File size: 13,420 Bytes
9de864e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import crypto from 'crypto';
import { logInfo, logError, logDebug } from '../logger/index.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const HISTORY_DIR = path.join(__dirname, '..', '..', 'session', 'history');

const MAX_HISTORY_LENGTH = 100;

export function initHistoryDirectory() {
    if (!fs.existsSync(HISTORY_DIR)) {
        fs.mkdirSync(HISTORY_DIR, { recursive: true });
        logInfo(`Создана директория для истории чатов: ${HISTORY_DIR}`);
    }
}

export function generateChatId() {
    return crypto.randomUUID();
}

export function createChat(chatName) {
    const chatId = generateChatId();
    const chatInfo = {
        id: chatId,
        name: chatName || `Новый чат ${new Date().toLocaleString()}`,
        created: Date.now(),
        messages: []
    };
    saveHistory(chatId, chatInfo);
    logInfo(`Создан новый чат [${chatId}] с именем "${chatInfo.name}"`);
    return chatId;
}

function getHistoryFilePath(chatId) {
    return path.join(HISTORY_DIR, `${chatId}.json`);
}

export function saveHistory(chatId, data) {
    try {
        initHistoryDirectory();
        const historyFilePath = getHistoryFilePath(chatId);
        fs.writeFileSync(historyFilePath, JSON.stringify(data, null, 2), 'utf8');
        logDebug(`История чата ${chatId} успешно сохранена`);
        return true;
    } catch (error) {
        logError(`Ошибка при сохранении истории чата ${chatId}`, error);
        return false;
    }
}

export function loadHistory(chatId) {
    try {
        const historyFilePath = getHistoryFilePath(chatId);
        if (fs.existsSync(historyFilePath)) {
            const rawData = fs.readFileSync(historyFilePath, 'utf8');
            logDebug(`Данные чата ${chatId} успешно загружены`);

            let data;
            try {
                data = JSON.parse(rawData);
                logDebug(`Данные чата ${chatId} успешно распарсены`);
            } catch (parseErr) {
                logError(`Ошибка при парсинге данных чата ${chatId}`, parseErr);
                return {
                    id: chatId,
                    name: `Восстановленный чат ${new Date().toLocaleString()}`,
                    created: Date.now(),
                    messages: []
                };
            }

            // Поддержка обратной совместимости со старым форматом
            if (Array.isArray(data)) {
                logDebug(`Чат ${chatId} использует устаревший формат, выполняется конвертация`);
                return {
                    id: chatId,
                    name: `Чат от ${new Date().toLocaleString()}`,
                    created: Date.now(),
                    messages: data,
                    wasConverted: true
                };
            }

            // Проверяем наличие обязательных полей
            if (!data.messages) {
                logInfo(`Чат ${chatId} не содержит сообщений, инициализируем пустой массив`);
                data.messages = [];
            }

            if (!data.name) {
                data.name = `Чат ${chatId.substring(0, 6)}`;
            }

            if (!data.created) {
                data.created = Date.now();
            }

            if (!data.id) {
                data.id = chatId;
            }

            return data;
        } else {
            logInfo(`Файл истории для чата ${chatId} не найден`);
        }
    } catch (error) {
        logError(`Ошибка при загрузке истории чата ${chatId}`, error);
    }

    // Если не удалось загрузить, создаем новые данные
    logInfo(`Создаем новую историю для чата ${chatId}`);
    return {
        id: chatId,
        name: `Новый чат ${new Date().toLocaleString()}`,
        created: Date.now(),
        messages: []
    };
}

export function chatExists(chatId) {
    const historyFilePath = getHistoryFilePath(chatId);
    const exists = fs.existsSync(historyFilePath);
    logDebug(`Проверка существования чата ${chatId}: ${exists ? 'найден' : 'не найден'}`);
    return exists;
}

export function renameChat(chatId, newName) {
    try {
        if (!chatExists(chatId)) {
            logError(`Попытка переименовать несуществующий чат ${chatId}`);
            return false;
        }

        const chatData = loadHistory(chatId);
        const oldName = chatData.name;
        chatData.name = newName;
        const success = saveHistory(chatId, chatData);
        if (success) {
            logInfo(`Чат ${chatId} переименован: "${oldName}" -> "${newName}"`);
        } else {
            logError(`Не удалось переименовать чат ${chatId}`);
        }
        return success;
    } catch (error) {
        logError(`Ошибка при переименовании чата ${chatId}`, error);
        return false;
    }
}

export function addUserMessage(chatId, content) {
    const timestamp = Math.floor(Date.now() / 1000);
    const messageId = crypto.randomUUID();

    // Определяем тип содержимого и его длину для логирования
    let contentDesc;
    if (Array.isArray(content)) {
        // Составное сообщение (текст + изображения)
        const textParts = content.filter(item => item.type === 'text');
        const imageParts = content.filter(item => item.type === 'image');
        const fileParts = content.filter(item => item.type === 'file');

        contentDesc = `составное сообщение (${textParts.length} текст., ${imageParts.length} изобр., ${fileParts.length} файл.)`;
    } else if (typeof content === 'object' && content !== null) {
        contentDesc = 'объект-сообщение';
    } else {
        contentDesc = `текст длиной ${String(content).length}`;
    }

    const message = {
        id: messageId,
        role: "user",
        content: content,
        timestamp: timestamp,
        chat_type: "t2t"
    };

    logInfo(`Добавление сообщения пользователя в чат ${chatId}: ${contentDesc}`);
    return addMessageToHistory(chatId, message);
}

export function addAssistantMessage(chatId, content, info = {}) {
    const timestamp = Math.floor(Date.now() / 1000);
    const messageId = crypto.randomUUID();

    const message = {
        id: messageId,
        role: "assistant",
        content: content,
        timestamp: timestamp,
        info: info,
        chat_type: "t2t"
    };

    logInfo(`Добавление ответа ассистента в чат ${chatId}, длина: ${content.length}`);
    return addMessageToHistory(chatId, message);
}

function addMessageToHistory(chatId, message) {
    try {
        let chatData = loadHistory(chatId);

        if (chatData.messages.length >= MAX_HISTORY_LENGTH) {
            logInfo(`Чат ${chatId} достиг максимальной длины (${MAX_HISTORY_LENGTH}), удаляем старые сообщения`);
            chatData.messages = [chatData.messages[0], ...chatData.messages.slice(chatData.messages.length - MAX_HISTORY_LENGTH + 2)];
        }

        chatData.messages.push(message);
        saveHistory(chatId, chatData);
        logDebug(`Сообщение ${message.id} успешно добавлено в чат ${chatId}`);

        return message.id;
    } catch (error) {
        logError(`Ошибка при добавлении сообщения в историю чата ${chatId}`, error);
        return null;
    }
}

export function getAllChats() {
    try {
        initHistoryDirectory();
        const files = fs.readdirSync(HISTORY_DIR);
        logDebug(`Получен список файлов чатов: ${files.length} файлов`);

        let convertedCount = 0;
        const chats = files
            .filter(file => file.endsWith('.json'))
            .map(file => {
                const chatId = file.replace('.json', '');
                const chatData = loadHistory(chatId);

                if (chatData.wasConverted) {
                    convertedCount++;
                }

                return {
                    id: chatId,
                    name: chatData.name || `Чат ${chatId.substring(0, 6)}`,
                    created: chatData.created || 0,
                    messageCount: chatData.messages ? chatData.messages.length : 0,
                    userMessageCount: chatData.messages ?
                        chatData.messages.filter(m => m.role === 'user').length : 0
                };
            });

        if (convertedCount > 0) {
            logInfo(`Конвертировано ${convertedCount} чатов из устаревшего формата`);
        }

        logInfo(`Обработано ${chats.length} чатов`);
        return chats.sort((a, b) => b.created - a.created);
    } catch (error) {
        logError('Ошибка при получении списка чатов', error);
        return [];
    }
}

export function deleteChat(chatId) {
    try {
        const historyFilePath = getHistoryFilePath(chatId);
        if (fs.existsSync(historyFilePath)) {
            fs.unlinkSync(historyFilePath);
            logInfo(`Чат ${chatId} успешно удален`);
            return true;
        } else {
            logError(`Попытка удаления несуществующего чата ${chatId}`);
        }
    } catch (error) {
        logError(`Ошибка при удалении чата ${chatId}`, error);
    }
    return false;
}

export function deleteChatsAutomatically(criteria = {}) {
    try {
        const { olderThan, userMessageCountLessThan, messageCountLessThan, maxChats } = criteria;
        logInfo(`Автоудаление чатов с критериями: ${JSON.stringify(criteria)}`);

        const chats = getAllChats();
        logInfo(`Найдено ${chats.length} чатов для проверки`);

        let chatsToDelete = [...chats];

        // Фильтрация по возрасту (в миллисекундах)
        if (olderThan) {
            const cutoffTime = Date.now() - olderThan;
            const oldChatsCount = chatsToDelete.filter(chat => chat.created < cutoffTime).length;
            logInfo(`Чатов старше ${olderThan}мс (${new Date(cutoffTime).toLocaleString()}): ${oldChatsCount}`);
            chatsToDelete = chatsToDelete.filter(chat => chat.created < cutoffTime);
        }

        if (userMessageCountLessThan !== undefined) {
            const lowUserMsgChatsCount = chatsToDelete.filter(chat =>
                chat.userMessageCount < userMessageCountLessThan).length;
            logInfo(`Чатов с менее чем ${userMessageCountLessThan} сообщений пользователя: ${lowUserMsgChatsCount}`);
            chatsToDelete = chatsToDelete.filter(chat =>
                chat.userMessageCount < userMessageCountLessThan);
        }

        if (messageCountLessThan !== undefined) {
            const lowMsgChatsCount = chatsToDelete.filter(chat =>
                chat.messageCount < messageCountLessThan).length;
            logInfo(`Чатов с менее чем ${messageCountLessThan} сообщений всего: ${lowMsgChatsCount}`);
            chatsToDelete = chatsToDelete.filter(chat =>
                chat.messageCount < messageCountLessThan);
        }

        if (maxChats && chats.length > maxChats) {
            logInfo(`Общее количество чатов (${chats.length}) превышает лимит (${maxChats}), удаляем старые чаты`);
            const sortedChats = [...chats].sort((a, b) => a.created - b.created);
            const oldestChats = sortedChats.slice(0, chats.length - maxChats);

            oldestChats.forEach(chat => {
                if (!chatsToDelete.some(c => c.id === chat.id)) {
                    chatsToDelete.push(chat);
                }
            });
        }

        // Удаление выбранных чатов
        const deletedChats = [];
        logInfo(`Найдено ${chatsToDelete.length} чатов для удаления`);

        for (const chat of chatsToDelete) {
            if (deleteChat(chat.id)) {
                deletedChats.push(chat.id);
            }
        }

        logInfo(`Удалено ${deletedChats.length} чатов`);
        return {
            success: true,
            deletedCount: deletedChats.length,
            deletedChats
        };
    } catch (error) {
        logError('Ошибка при автоматическом удалении чатов', error);
        return {
            success: false,
            error: error.message
        };
    }
}