File size: 11,639 Bytes
6efa67a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { t } from './i18n.js';
import { callGenericPopup, Popup, POPUP_TYPE } from './popup.js';
import { getFileExtension, sortMoments, timestampToMoment } from './utils.js';
import { displayPastChats, getRequestHeaders, importCharacterChat } from '/script.js';
import { importGroupChat } from './group-chats.js';

class BackupsBrowser {
    /** @type {HTMLElement} */
    #buttonElement;
    /** @type {HTMLElement} */
    #buttonChevronIcon;
    /** @type {HTMLElement} */
    #backupsListElement;
    /** @type {AbortController} */
    #loadingAbortController;
    /** @type {boolean} */
    #isOpen = false;

    get isOpen() {
        return this.#isOpen;
    }

    /**
     * View a backup file content.
     * @param {string} name File name of the backup to view.
     * @returns {Promise<void>}
     */
    async viewBackup(name) {
        const response = await fetch('/api/backups/chat/download', {
            method: 'POST',
            headers: getRequestHeaders(),
            body: JSON.stringify({ name: name }),
        });

        if (!response.ok) {
            toastr.error(t`Failed to download backup, try again later.`);
            console.error('Failed to download chat backup:', response.statusText);
            return;
        }

        try {
            /** @type {ChatMessage[]} */
            const parsedLines = [];
            const fileText = await response.text();
            fileText.split('\n').forEach(line => {
                try {
                    /** @type {ChatMessage} */
                    const lineData = JSON.parse(line);
                    if (lineData?.mes) {
                        parsedLines.push(lineData);
                    }
                } catch (error) {
                    console.error('Failed to parse chat backup line:', error);
                }
            });
            const textArea = document.createElement('textarea');
            textArea.classList.add('text_pole', 'monospace', 'textarea_compact', 'margin0', 'height100p');
            textArea.readOnly = true;
            textArea.value = parsedLines.map(l => `${l.name} [${timestampToMoment(l.send_date).format('lll')}]\n${l.mes}`).join('\n\n\n');
            await callGenericPopup(textArea, POPUP_TYPE.TEXT, '', { allowVerticalScrolling: true, large: true, wide: true });
        } catch (error) {
            console.error('Failed to parse chat backup content:', error);
            toastr.error(t`Failed to parse backup content.`);
            return;
        }
    }

    /**
     * Restore a backup by importing it.
     * @param {string} name File name of the backup to restore.
     * @returns {Promise<void>}
     */
    async restoreBackup(name) {
        const response = await fetch('/api/backups/chat/download', {
            method: 'POST',
            headers: getRequestHeaders(),
            body: JSON.stringify({ name: name }),
        });

        if (!response.ok) {
            toastr.error(t`Failed to download backup, try again later.`);
            console.error('Failed to download chat backup:', response.statusText);
            return;
        }

        const blob = await response.blob();
        const file = new File([blob], name, { type: 'application/octet-stream' });

        const extension = getFileExtension(file);

        if (extension !== 'jsonl') {
            toastr.warning(t`Only .jsonl files are supported for chat imports.`);
            return;
        }

        const context = SillyTavern.getContext();

        const formData = new FormData();
        formData.set('file_type', extension);
        formData.set('avatar', file);
        formData.set('avatar_url', context.characters[context.characterId]?.avatar || '');
        formData.set('user_name', context.name1);
        formData.set('character_name', context.name2);

        const importFn = context.groupId ? importGroupChat : importCharacterChat;
        const result = await importFn(formData, { refresh: false });

        if (result.length === 0) {
            toastr.error(t`Failed to import chat backup, try again later.`);
            return;
        }

        toastr.success(`Chat imported: ${result.join(', ')}`);
        await displayPastChats(result);
    }

    /**
     * Delete a backup file.
     * @param {string} name File name of the backup to delete.
     * @returns {Promise<boolean>} True if deleted, false otherwise.
     */
    async deleteBackup(name) {
        const confirm = await Popup.show.confirm(t`Are you sure?`);
        if (!confirm) {
            return false;
        }

        const response = await fetch('/api/backups/chat/delete', {
            method: 'POST',
            headers: getRequestHeaders(),
            body: JSON.stringify({ name: name }),
        });

        if (!response.ok) {
            toastr.error(t`Failed to delete backup, try again later.`);
            console.error('Failed to delete chat backup:', response.statusText);
            return false;
        }

        toastr.success(t`Backup deleted successfully.`);
        return true;
    }

    /**
     * Load backups and populate the list element.
     * @param {AbortSignal} signal Signal to abort loading.
     * @returns {Promise<void>}
     */
    async loadBackupsIntoList(signal) {
        if (!this.#backupsListElement) {
            return;
        }

        this.#backupsListElement.innerHTML = '';

        const response = await fetch('/api/backups/chat/get', {
            method: 'POST',
            headers: getRequestHeaders(),
            signal,
        });

        if (!response.ok) {
            console.error('Failed to load chat backups list:', response.statusText);
            return;
        }

        /** @type {import('../../src/endpoints/chats.js').ChatInfo[]} */
        const backupsList = await response.json();

        for (const backup of backupsList.sort((a, b) => sortMoments(timestampToMoment(a.last_mes), timestampToMoment(b.last_mes)))) {
            const listItem = document.createElement('div');
            listItem.classList.add('chatBackupsListItem');

            const backupName = document.createElement('div');
            backupName.textContent = backup.file_name;
            backupName.classList.add('chatBackupsListItemName');

            const backupInfo = document.createElement('div');
            backupInfo.classList.add('chatBackupsListItemInfo');
            backupInfo.textContent = `${timestampToMoment(backup.last_mes).format('lll')} (${backup.file_size}, ${backup.chat_items} 💬)`;

            const actionsList = document.createElement('div');
            actionsList.classList.add('chatBackupsListItemActions');

            const viewButton = document.createElement('div');
            viewButton.classList.add('right_menu_button', 'fa-solid', 'fa-eye');
            viewButton.title = t`View backup`;
            viewButton.addEventListener('click', async () => {
                await this.viewBackup(backup.file_name);
            });

            const restoreButton = document.createElement('div');
            restoreButton.classList.add('right_menu_button', 'fa-solid', 'fa-rotate-left');
            restoreButton.title = t`Restore backup`;
            restoreButton.addEventListener('click', async () => {
                await this.restoreBackup(backup.file_name);
            });

            const deleteButton = document.createElement('div');
            deleteButton.classList.add('right_menu_button', 'fa-solid', 'fa-trash');
            deleteButton.title = t`Delete backup`;
            deleteButton.addEventListener('click',async () => {
                const isDeleted = await this.deleteBackup(backup.file_name);
                if (isDeleted) {
                    listItem.remove();
                }
            });

            actionsList.appendChild(viewButton);
            actionsList.appendChild(restoreButton);
            actionsList.appendChild(deleteButton);

            listItem.appendChild(backupName);
            listItem.appendChild(backupInfo);
            listItem.appendChild(actionsList);

            this.#backupsListElement.appendChild(listItem);
        }
    }

    closeBackups() {
        if (!this.#isOpen) {
            return;
        }

        this.#isOpen = false;
        if (this.#buttonChevronIcon) {
            this.#buttonChevronIcon.classList.remove('fa-chevron-up');
            this.#buttonChevronIcon.classList.add('fa-chevron-down');
        }
        if (this.#backupsListElement) {
            this.#backupsListElement.classList.remove('open');
            this.#backupsListElement.innerHTML = '';
        }
        if (this.#loadingAbortController) {
            this.#loadingAbortController.abort();
            this.#loadingAbortController = null;
        }
    }

    openBackups() {
        if (this.#isOpen) {
            return;
        }

        this.#isOpen = true;
        if (this.#buttonChevronIcon) {
            this.#buttonChevronIcon.classList.remove('fa-chevron-down');
            this.#buttonChevronIcon.classList.add('fa-chevron-up');
        }
        if (this.#backupsListElement) {
            this.#backupsListElement.classList.add('open');
        }
        if (this.#loadingAbortController) {
            this.#loadingAbortController.abort();
            this.#loadingAbortController = null;
        }

        this.#loadingAbortController = new AbortController();
        this.loadBackupsIntoList(this.#loadingAbortController.signal);
    }

    renderButton() {
        if (this.#buttonElement) {
            return;
        }

        const sibling = document.getElementById('select_chat_search');
        if (!sibling) {
            console.error('Could not find sibling element for BackupsBrowser button');
            return;
        }

        const button = document.createElement('button');
        button.classList.add('menu_button', 'menu_button_icon');

        const buttonIcon = document.createElement('i');
        buttonIcon.classList.add('fa-solid', 'fa-box-open');

        const buttonText = document.createElement('span');
        buttonText.textContent = t`Backups`;
        buttonText.title = t`Browse chat backups`;

        const chevronIcon = document.createElement('i');
        chevronIcon.classList.add('fa-solid', 'fa-chevron-down', 'fa-sm');

        button.appendChild(buttonIcon);
        button.appendChild(buttonText);
        button.appendChild(chevronIcon);

        button.addEventListener('click', () => {
            if (this.#isOpen) {
                this.closeBackups();
            } else {
                this.openBackups();
            }
        });

        sibling.parentNode.insertBefore(button, sibling);

        this.#buttonElement = button;
        this.#buttonChevronIcon = chevronIcon;
    }

    renderBackupsList() {
        if (this.#backupsListElement) {
            return;
        }

        const sibling = document.getElementById('select_chat_div');
        if (!sibling) {
            console.error('Could not find sibling element for BackupsBrowser list');
            return;
        }

        const list = document.createElement('div');
        list.classList.add('chatBackupsList');

        sibling.parentNode.insertBefore(list, sibling);
        this.#backupsListElement = list;
    }
}

const backupsBrowser = new BackupsBrowser();

export function addChatBackupsBrowser() {
    backupsBrowser.renderButton();
    backupsBrowser.renderBackupsList();

    // Refresh the backups list if it's already open
    if (backupsBrowser.isOpen) {
        backupsBrowser.closeBackups();
        backupsBrowser.openBackups();
    }
}