File size: 13,846 Bytes
519a20c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import { getRequestHeaders } from '../script.js';
import { t } from './i18n.js';
import { callGenericPopup, Popup, POPUP_TYPE } from './popup.js';
import { renderTemplateAsync } from './templates.js';
import { humanFileSize, timestampToMoment } from './utils.js';

/**
 * @typedef {object} DataMaidReportResult
 * @property {import('../../src/endpoints/data-maid.js').DataMaidSanitizedReport} report - The sanitized report of the Data Maid.
 * @property {string} token - The token to use for the Data Maid report.
 */

/**
 * Data Maid Dialog class for managing the cleanup dialog interface.
 */
class DataMaidDialog {
    constructor() {
        this.token = null;
        this.container = null;
        this.isScanning = false;

        this.DATA_MAID_CATEGORIES = {
            files: {
                name: t`Files`,
                description: t`Files that are not associated with chat messages or Data Bank. WILL DELETE MANUAL UPLOADS!`,
            },
            images: {
                name: t`Images`,
                description: t`Images that are not associated with chat messages. WILL DELETE MANUAL UPLOADS!`,
            },
            chats: {
                name: t`Chats`,
                description: t`Chat files associated with deleted characters.`,
            },
            groupChats: {
                name: t`Group Chats`,
                description: t`Chat files associated with deleted groups.`,
            },
            avatarThumbnails: {
                name: t`Avatar Thumbnails`,
                description: t`Thumbnails for avatars of missing or deleted characters.`,
            },
            backgroundThumbnails: {
                name: t`Background Thumbnails`,
                description: t`Thumbnails for missing or deleted backgrounds.`,
            },
            chatBackups: {
                name: t`Chat Backups`,
                description: t`Automatically generated chat backups.`,
            },
            settingsBackups: {
                name: t`Settings Backups`,
                description: t`Automatically generated settings backups.`,
            },
        };
    }

    /**
     * Returns a promise that resolves to the Data Maid report.
     * @returns {Promise<DataMaidReportResult>}
     * @private
     */
    async getReport() {
        const response = await fetch('/api/data-maid/report', {
            method: 'POST',
            headers: getRequestHeaders(),
        });

        if (!response.ok) {
            throw new Error(`Error fetching Data Maid report: ${response.statusText}`);
        }

        return await response.json();
    }

    /**
     * Finalizes the Data Maid process by sending a request to the server.
     * @returns {Promise<void>}
     * @private
     */
    async finalize() {
        const response = await fetch('/api/data-maid/finalize', {
            method: 'POST',
            headers: getRequestHeaders(),
            body: JSON.stringify({ token: this.token }),
        });

        if (!response.ok) {
            throw new Error(`Error finalizing Data Maid: ${response.statusText}`);
        }
    }

    /**
     * Sets up the dialog UI elements and event listeners.
     * @private
     */
    async setupDialogUI() {
        const template = await renderTemplateAsync('dataMaidDialog');
        this.container = document.createElement('div');
        this.container.classList.add('dataMaidDialogContainer');
        this.container.innerHTML = template;

        const startButton = this.container.querySelector('.dataMaidStartButton');
        startButton.addEventListener('click', () => this.handleScanClick());
    }

    /**
     * Handles the scan button click event.
     * @private
     */
    async handleScanClick() {
        if (this.isScanning) {
            toastr.warning(t`The scan is already running. Please wait for it to finish.`);
            return;
        }

        try {
            const resultsList = this.container.querySelector('.dataMaidResultsList');
            resultsList.innerHTML = '';
            this.showSpinner();
            this.isScanning = true;

            const report = await this.getReport();

            this.hideSpinner();
            await this.renderReport(report, resultsList);
            this.token = report.token;
        } catch (error) {
            this.hideSpinner();
            toastr.error(t`An error has occurred. Check the console for details.`);
            console.error('Error generating Data Maid report:', error);
        } finally {
            this.isScanning = false;
        }
    }

    /**
     * Shows the loading spinner and hides the placeholder.
     * @private
     */
    showSpinner() {
        const spinner = this.container.querySelector('.dataMaidSpinner');
        const placeholder = this.container.querySelector('.dataMaidPlaceholder');
        placeholder.classList.add('displayNone');
        spinner.classList.remove('displayNone');
    }

    /**
     * Hides the loading spinner.
     * @private
     */
    hideSpinner() {
        const spinner = this.container.querySelector('.dataMaidSpinner');
        spinner.classList.add('displayNone');
    }

    /**
     * Renders the Data Maid report into the results list.
     * @param {DataMaidReportResult} report
     * @param {Element} resultsList
     * @private
     */
    async renderReport(report, resultsList) {
        for (const [prop, data] of Object.entries(this.DATA_MAID_CATEGORIES)) {
            const category = await this.renderCategory(prop, data.name, data.description, report.report[prop]);
            if (!category) {
                continue;
            }
            resultsList.appendChild(category);
        }
        this.displayEmptyPlaceholder();
    }

    /**
     * Displays a placeholder message if no items are found in the results list.
     * @private
     */
    displayEmptyPlaceholder() {
        const resultsList = this.container.querySelector('.dataMaidResultsList');
        if (resultsList.children.length === 0) {
            const placeholder = this.container.querySelector('.dataMaidPlaceholder');
            placeholder.classList.remove('displayNone');
            placeholder.textContent = t`No items found to clean up. Come back later!`;
        }
    }

    /**
     * Renders a single Data Maid category into a DOM element.
     * @param {string} prop Property name for the category
     * @param {string} name Name of the category
     * @param {string} description Description of the category
     * @param {import('../../src/endpoints/data-maid.js').DataMaidSanitizedRecord[]} items List of items in the category
     * @return {Promise<Element|null>} A promise that resolves to a DOM element containing the rendered category
     * @private
     */
    async renderCategory(prop, name, description, items) {
        if (!Array.isArray(items) || items.length === 0) {
            return null;
        }

        const viewModel = {
            name: name,
            description: description,
            totalSize: humanFileSize(items.reduce((sum, item) => sum + item.size, 0)),
            totalItems: items.length,
            items: items.sort((a, b) => b.mtime - a.mtime).map(item => ({
                ...item,
                size: humanFileSize(item.size),
                date: timestampToMoment(item.mtime).format('L LT'),
            })),
        };

        const template = await renderTemplateAsync('dataMaidCategory', viewModel);
        const categoryElement = document.createElement('div');
        categoryElement.innerHTML = template;
        categoryElement.querySelectorAll('.dataMaidItemView').forEach(button => {
            button.addEventListener('click', async () => {
                const item = button.closest('.dataMaidItem');
                const hash = item?.getAttribute('data-hash');
                if (hash) {
                    await this.view(prop, hash);
                }
            });
        });
        categoryElement.querySelectorAll('.dataMaidItemDownload').forEach(button => {
            button.addEventListener('click', async () => {
                const item = button.closest('.dataMaidItem');
                const hash = item?.getAttribute('data-hash');
                if (hash) {
                    await this.download(items, hash);
                }
            });
        });
        categoryElement.querySelectorAll('.dataMaidDeleteAll').forEach(button => {
            button.addEventListener('click', async (event) => {
                event.stopPropagation();
                const confirm = await Popup.show.confirm(t`Are you sure?`, t`This will permanently delete all files in this category. THIS CANNOT BE UNDONE!`);
                if (!confirm) {
                    return;
                }

                const hashes = items.map(item => item.hash).filter(hash => hash);
                await this.delete(hashes);

                categoryElement.remove();
                this.displayEmptyPlaceholder();
            });

        });
        categoryElement.querySelectorAll('.dataMaidItemDelete').forEach(button => {
            button.addEventListener('click', async () => {
                const item = button.closest('.dataMaidItem');
                const hash = item?.getAttribute('data-hash');
                if (hash) {
                    const confirm = await Popup.show.confirm(t`Are you sure?`, t`This will permanently delete the file. THIS CANNOT BE UNDONE!`);
                    if (!confirm) {
                        return;
                    }
                    if (await this.delete([hash])) {
                        item.remove();
                        items.splice(items.findIndex(i => i.hash === hash), 1);
                        if (items.length === 0) {
                            categoryElement.remove();
                            this.displayEmptyPlaceholder();
                        }
                    }
                }
            });
        });
        return categoryElement;
    }

    /**
     * Constructs the URL for viewing an item by its hash.
     * @param {string} hash Hash of the item to view
     * @returns {string} URL to view the item
     * @private
     */
    getViewUrl(hash) {
        return `/api/data-maid/view?hash=${encodeURIComponent(hash)}&token=${encodeURIComponent(this.token)}`;
    }

    /**
     * Downloads an item by its hash.
     * @param {import('../../src/endpoints/data-maid.js').DataMaidSanitizedRecord[]} items List of items in the category
     * @param {string} hash Hash of the item to download
     * @private
     */
    async download(items, hash) {
        const item = items.find(i => i.hash === hash);
        if (!item) {
            return;
        }
        const url = this.getViewUrl(hash);
        const a = document.createElement('a');
        a.href = url;
        a.download = item?.name || hash;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }

    /**
     * Opens the item view for a specific hash.
     * @param {string} prop Property name for the category
     * @param {string} hash Item hash to view
     * @private
     */
    async view(prop, hash) {
        const url = this.getViewUrl(hash);
        const isImage = ['images', 'avatarThumbnails', 'backgroundThumbnails'].includes(prop);
        const element = isImage
            ? await this.getViewElement(url)
            : await this.getTextViewElement(url);
        await callGenericPopup(element, POPUP_TYPE.DISPLAY, '', { large: true, wide: true });
    }

    /**
     * Deletes an item by its file path hash.
     * @param {string[]} hashes Hashes of items to delete
     * @return {Promise<boolean>} True if the deletion was successful, false otherwise
     * @private
     */
    async delete(hashes) {
        try {
            const response = await fetch('/api/data-maid/delete', {
                method: 'POST',
                headers: getRequestHeaders(),
                body: JSON.stringify({ hashes: hashes, token: this.token }),
            });

            if (!response.ok) {
                throw new Error(`Error deleting item: ${response.statusText}`);
            }

            return true;
        } catch (error) {
            console.error('Error deleting item:', error);
            return false;
        }
    }

    /**
     * Gets an image element for viewing images.
     * @param {string} url View URL
     * @returns {Promise<HTMLElement>} Image element
     * @private
     */
    async getViewElement(url) {
        const img = document.createElement('img');
        img.src = url;
        img.classList.add('dataMaidImageView');
        return img;
    }

    /**
     * Gets an iframe element for viewing text content.
     * @param {string} url View URL
     * @returns {Promise<HTMLTextAreaElement>} Frame element
     * @private
     */
    async getTextViewElement(url) {
        const response = await fetch(url);
        const text = await response.text();
        const element = document.createElement('textarea');
        element.classList.add('dataMaidTextView');
        element.readOnly = true;
        element.textContent = text;
        return element;
    }

    /**
     * Opens the Data Maid dialog and handles the interaction.
     */
    async open() {
        await this.setupDialogUI();
        await callGenericPopup(this.container, POPUP_TYPE.TEXT, '', { wide: true, large: true });

        if (this.token) {
            await this.finalize();
        }
    }
}

export function initDataMaid() {
    const dataMaidButton = document.getElementById('data_maid_button');
    if (!dataMaidButton) {
        console.warn('Data Maid button not found');
        return;
    }

    dataMaidButton.addEventListener('click', () => new DataMaidDialog().open());
}