aboutsummaryrefslogtreecommitdiff
path: root/ext/bg/js/settings/backup.js
blob: 57963cec4670d6f898b8baddc4015e3b8eca1753 (plain)
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
/*
 * Copyright (C) 2019-2020  Yomichan Authors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

/* global
 * OptionsUtil
 * api
 */

class SettingsBackup {
    constructor(settingsController) {
        this._settingsController = settingsController;
        this._settingsExportToken = null;
        this._settingsExportRevoke = null;
        this._currentVersion = 0;
    }

    prepare() {
        document.querySelector('#settings-export').addEventListener('click', this._onSettingsExportClick.bind(this), false);
        document.querySelector('#settings-import').addEventListener('click', this._onSettingsImportClick.bind(this), false);
        document.querySelector('#settings-import-file').addEventListener('change', this._onSettingsImportFileChange.bind(this), false);
        document.querySelector('#settings-reset').addEventListener('click', this._onSettingsResetClick.bind(this), false);
        document.querySelector('#settings-reset-modal-confirm').addEventListener('click', this._onSettingsResetConfirmClick.bind(this), false);
    }

    // Private

    _getSettingsExportDateString(date, dateSeparator, dateTimeSeparator, timeSeparator, resolution) {
        const values = [
            date.getUTCFullYear().toString(),
            dateSeparator,
            (date.getUTCMonth() + 1).toString().padStart(2, '0'),
            dateSeparator,
            date.getUTCDate().toString().padStart(2, '0'),
            dateTimeSeparator,
            date.getUTCHours().toString().padStart(2, '0'),
            timeSeparator,
            date.getUTCMinutes().toString().padStart(2, '0'),
            timeSeparator,
            date.getUTCSeconds().toString().padStart(2, '0')
        ];
        return values.slice(0, resolution * 2 - 1).join('');
    }

    async _getSettingsExportData(date) {
        const optionsFull = await this._settingsController.getOptionsFull();
        const environment = await api.getEnvironmentInfo();
        const fieldTemplatesDefault = await api.getDefaultAnkiFieldTemplates();

        // Format options
        for (const {options} of optionsFull.profiles) {
            if (options.anki.fieldTemplates === fieldTemplatesDefault || !options.anki.fieldTemplates) {
                delete options.anki.fieldTemplates; // Default
            }
        }

        const data = {
            version: this._currentVersion,
            date: this._getSettingsExportDateString(date, '-', ' ', ':', 6),
            url: chrome.runtime.getURL('/'),
            manifest: chrome.runtime.getManifest(),
            environment,
            userAgent: navigator.userAgent,
            options: optionsFull
        };

        return data;
    }

    _saveBlob(blob, fileName) {
        if (typeof navigator === 'object' && typeof navigator.msSaveBlob === 'function') {
            if (navigator.msSaveBlob(blob)) {
                return;
            }
        }

        const blobUrl = URL.createObjectURL(blob);

        const a = document.createElement('a');
        a.href = blobUrl;
        a.download = fileName;
        a.rel = 'noopener';
        a.target = '_blank';

        const revoke = () => {
            URL.revokeObjectURL(blobUrl);
            a.href = '';
            this._settingsExportRevoke = null;
        };
        this._settingsExportRevoke = revoke;

        a.dispatchEvent(new MouseEvent('click'));
        setTimeout(revoke, 60000);
    }

    async _onSettingsExportClick() {
        if (this._settingsExportRevoke !== null) {
            this._settingsExportRevoke();
            this._settingsExportRevoke = null;
        }

        const date = new Date(Date.now());

        const token = {};
        this._settingsExportToken = token;
        const data = await this._getSettingsExportData(date);
        if (this._settingsExportToken !== token) {
            // A new export has been started
            return;
        }
        this._settingsExportToken = null;

        const fileName = `yomichan-settings-${this._getSettingsExportDateString(date, '-', '-', '-', 6)}.json`;
        const blob = new Blob([JSON.stringify(data, null, 4)], {type: 'application/json'});
        this._saveBlob(blob, fileName);
    }

    _readFileArrayBuffer(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = () => resolve(reader.result);
            reader.onerror = () => reject(reader.error);
            reader.readAsArrayBuffer(file);
        });
    }

    // Importing

    async _settingsImportSetOptionsFull(optionsFull) {
        await this._settingsController.setAllSettings(optionsFull);
    }

    _showSettingsImportError(error) {
        yomichan.logError(error);
        document.querySelector('#settings-import-error-modal-message').textContent = `${error}`;
        $('#settings-import-error-modal').modal('show');
    }

    async _showSettingsImportWarnings(warnings) {
        const modalNode = $('#settings-import-warning-modal');
        const buttons = document.querySelectorAll('.settings-import-warning-modal-import-button');
        const messageContainer = document.querySelector('#settings-import-warning-modal-message');
        if (modalNode.length === 0 || buttons.length === 0 || messageContainer === null) {
            return {result: false};
        }

        // Set message
        const fragment = document.createDocumentFragment();
        for (const warning of warnings) {
            const node = document.createElement('li');
            node.textContent = `${warning}`;
            fragment.appendChild(node);
        }
        messageContainer.textContent = '';
        messageContainer.appendChild(fragment);

        // Show modal
        modalNode.modal('show');

        // Wait for modal to close
        return new Promise((resolve) => {
            const onButtonClick = (e) => {
                e.preventDefault();
                complete({
                    result: true,
                    sanitize: e.currentTarget.dataset.importSanitize === 'true'
                });
                modalNode.modal('hide');
            };
            const onModalHide = () => {
                complete({result: false});
            };

            let completed = false;
            const complete = (result) => {
                if (completed) { return; }
                completed = true;

                modalNode.off('hide.bs.modal', onModalHide);
                for (const button of buttons) {
                    button.removeEventListener('click', onButtonClick, false);
                }

                resolve(result);
            };

            // Hook events
            modalNode.on('hide.bs.modal', onModalHide);
            for (const button of buttons) {
                button.addEventListener('click', onButtonClick, false);
            }
        });
    }

    _isLocalhostUrl(urlString) {
        try {
            const url = new URL(urlString);
            switch (url.hostname.toLowerCase()) {
                case 'localhost':
                case '127.0.0.1':
                case '[::1]':
                    switch (url.protocol.toLowerCase()) {
                        case 'http:':
                        case 'https:':
                            return true;
                    }
                    break;
            }
        } catch (e) {
            // NOP
        }
        return false;
    }

    _settingsImportSanitizeProfileOptions(options, dryRun) {
        const warnings = [];

        const anki = options.anki;
        if (isObject(anki)) {
            const fieldTemplates = anki.fieldTemplates;
            if (typeof fieldTemplates === 'string') {
                warnings.push('anki.fieldTemplates contains a non-default value');
                if (!dryRun) {
                    delete anki.fieldTemplates;
                }
            }
            const server = anki.server;
            if (typeof server === 'string' && server.length > 0 && !this._isLocalhostUrl(server)) {
                warnings.push('anki.server uses a non-localhost URL');
                if (!dryRun) {
                    delete anki.server;
                }
            }
        }

        const audio = options.audio;
        if (isObject(audio)) {
            const customSourceUrl = audio.customSourceUrl;
            if (typeof customSourceUrl === 'string' && customSourceUrl.length > 0 && !this._isLocalhostUrl(customSourceUrl)) {
                warnings.push('audio.customSourceUrl uses a non-localhost URL');
                if (!dryRun) {
                    delete audio.customSourceUrl;
                }
            }
        }

        return warnings;
    }

    _settingsImportSanitizeOptions(optionsFull, dryRun) {
        const warnings = new Set();

        const profiles = optionsFull.profiles;
        if (Array.isArray(profiles)) {
            for (const profile of profiles) {
                if (!isObject(profile)) { continue; }
                const options = profile.options;
                if (!isObject(options)) { continue; }

                const warnings2 = this._settingsImportSanitizeProfileOptions(options, dryRun);
                for (const warning of warnings2) {
                    warnings.add(warning);
                }
            }
        }

        return warnings;
    }

    _utf8Decode(arrayBuffer) {
        try {
            return new TextDecoder('utf-8').decode(arrayBuffer);
        } catch (e) {
            const binaryString = String.fromCharCode.apply(null, new Uint8Array(arrayBuffer));
            return decodeURIComponent(escape(binaryString));
        }
    }

    async _importSettingsFile(file) {
        const dataString = this._utf8Decode(await this._readFileArrayBuffer(file));
        const data = JSON.parse(dataString);

        // Type check
        if (!isObject(data)) {
            throw new Error(`Invalid data type: ${typeof data}`);
        }

        // Version check
        const version = data.version;
        if (!(
            typeof version === 'number' &&
            Number.isFinite(version) &&
            version === Math.floor(version)
        )) {
            throw new Error(`Invalid version: ${version}`);
        }

        if (!(
            version >= 0 &&
            version <= this._currentVersion
        )) {
            throw new Error(`Unsupported version: ${version}`);
        }

        // Verify options exists
        let optionsFull = data.options;
        if (!isObject(optionsFull)) {
            throw new Error(`Invalid options type: ${typeof optionsFull}`);
        }

        // Upgrade options
        optionsFull = await OptionsUtil.update(optionsFull);

        // Check for warnings
        const sanitizationWarnings = this._settingsImportSanitizeOptions(optionsFull, true);

        // Show sanitization warnings
        if (sanitizationWarnings.size > 0) {
            const {result, sanitize} = await this._showSettingsImportWarnings(sanitizationWarnings);
            if (!result) { return; }

            if (sanitize !== false) {
                this._settingsImportSanitizeOptions(optionsFull, false);
            }
        }

        // Assign options
        await this._settingsImportSetOptionsFull(optionsFull);
    }

    _onSettingsImportClick() {
        document.querySelector('#settings-import-file').click();
    }

    async _onSettingsImportFileChange(e) {
        const files = e.target.files;
        if (files.length === 0) { return; }

        const file = files[0];
        e.target.value = null;
        try {
            await this._importSettingsFile(file);
        } catch (error) {
            this._showSettingsImportError(error);
        }
    }

    // Resetting

    _onSettingsResetClick() {
        $('#settings-reset-modal').modal('show');
    }

    async _onSettingsResetConfirmClick() {
        $('#settings-reset-modal').modal('hide');

        // Get default options
        const optionsFull = await OptionsUtil.getDefault();

        // Assign options
        await this._settingsImportSetOptionsFull(optionsFull);
    }
}