File size: 5,963 Bytes
2717123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
// static/js/state.js

export let chatSessions = [];
export let activeChatId = null;
export let attachedFile = null;
export let isGenerating = false;
export let globalAbortController = null;
export let currentUploadXHR = null; // این متغیر دیگر برای آپلود استفاده نمی‌شود اما برای لغو پردازش فایل نگه داشته می‌شود
export let activeToolPrefix = null;
export let activeTool = null;

// *** START: ADDED FOR MESSAGE LIMIT ***
const DAILY_MESSAGE_LIMIT = 10;
const MESSAGE_LIMIT_KEY = 'alphaChatDailyLimit';

/**
 * Gets the current date as a formatted string (YYYY-MM-DD).
 * @returns {string} The formatted date string.
 */
function getTodayDateString() {
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

/**
 * Retrieves usage data from localStorage.
 * @returns {{count: number, date: string}} The usage data object.
 */
function getUsageData() {
    try {
        const saved = localStorage.getItem(MESSAGE_LIMIT_KEY);
        return saved ? JSON.parse(saved) : { count: 0, date: getTodayDateString() };
    } catch (e) {
        console.error("Failed to parse usage data from localStorage:", e);
        return { count: 0, date: getTodayDateString() };
    }
}

/**
 * Saves usage data to localStorage.
 * @param {{count: number, date: string}} data The usage data object to save.
 */
function saveUsageData(data) {
    try {
        localStorage.setItem(MESSAGE_LIMIT_KEY, JSON.stringify(data));
    } catch (e) {
        console.error("Failed to save usage data to localStorage:", e);
    }
}

/**
 * Checks if the daily message limit has been reached for a free user.
 * @param {boolean} isPremium - Whether the current user is premium.
 * @returns {boolean} - True if the limit is reached, otherwise false.
 */
export function isMessageLimitReached(isPremium) {
    if (isPremium) {
        return false; // Premium users have no limit.
    }

    let usageData = getUsageData();
    const today = getTodayDateString();

    if (usageData.date !== today) {
        // It's a new day, reset the counter.
        usageData = { count: 0, date: today };
        saveUsageData(usageData);
    }

    return usageData.count >= DAILY_MESSAGE_LIMIT;
}

/**
 * Increments the message count for a free user for the current day.
 * @param {boolean} isPremium - Whether the current user is premium.
 */
export function incrementMessageCount(isPremium) {
    if (isPremium) {
        return; // Don't track for premium users.
    }

    let usageData = getUsageData();
    const today = getTodayDateString();

    if (usageData.date !== today) {
        // If the day changed between the check and the increment, reset first.
        usageData = { count: 1, date: today };
    } else {
        usageData.count += 1;
    }

    saveUsageData(usageData);
}
// *** END: ADDED FOR MESSAGE LIMIT ***


export function setActiveTool(toolName) {
    activeTool = toolName;
}

export function getActiveTool() {
    return activeTool;
}

export function setActiveToolPrefix(prefix) {
    activeToolPrefix = prefix;
}

export function getActiveToolPrefix() {
    return activeToolPrefix;
}

export function setChatSessions(newSessions) {
    chatSessions = newSessions;
}

export function setActiveChatId(id) {
    activeChatId = id;
}

export function setAttachedFile(file) {
    attachedFile = file;
}

export function setGenerating(status) {
    isGenerating = status;
}

export function setGlobalAbortController(controller) {
    globalAbortController = controller;
}

export function setCurrentUploadXHR(xhr) {
    currentUploadXHR = xhr;
}

export function getActiveChat() {
    return chatSessions.find(s => s.id === activeChatId);
}

export function saveSessions() {
    try {
        const sessionsToSave = JSON.parse(JSON.stringify(chatSessions));
        
        sessionsToSave.forEach(session => {
            session.messages.forEach(message => {
                if (message.parts) {
                    message.parts.forEach(part => {
                        if (part.base64Data) {
                            delete part.base64Data;
                        }
                        if (part.blobUrl) {
                            delete part.blobUrl;
                        }
                    });
                }
            });
        });

        localStorage.setItem('alphaChatSessions', JSON.stringify(sessionsToSave));
    } catch (e) {
        console.error("Failed to save sessions to localStorage:", e);
    }
}

export function loadSessions() {
    try {
        const saved = localStorage.getItem('alphaChatSessions');
        chatSessions = saved ? JSON.parse(saved) : [];
        chatSessions.forEach(session => {
            if (session.showThoughts === undefined) {
                session.showThoughts = false;
            }
            // *** START: MODIFIED - افزودن فیلد جدید به پیام‌های قدیمی برای سازگاری ***
            session.messages.forEach(message => {
                if (message.role === 'assistant' && message.wasGeneratedWithThoughts === undefined) {
                    message.wasGeneratedWithThoughts = false; 
                }
            });
            // *** END: MODIFIED ***
        });
    } catch (e) {
        console.error("Failed to load sessions from localStorage:", e);
        chatSessions = [];
    }
}

export function findLastIndex(array, predicate) {
    for (let i = array.length - 1; i >= 0; i--) {
        if (predicate(array[i])) { return i; }
    }
    return -1;
}

export function deleteMessage(chatId, messageIndex) {
    const chat = chatSessions.find(s => s.id === chatId);
    if (chat && chat.messages[messageIndex]) {
        chat.messages.splice(messageIndex, 1);
        saveSessions();
    }
}