forked from darkreader/darkreader
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuser-storage.ts
More file actions
230 lines (205 loc) · 9.19 KB
/
Copy pathuser-storage.ts
File metadata and controls
230 lines (205 loc) · 9.19 KB
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
import {DEFAULT_SETTINGS, DEFAULT_THEME} from '../defaults';
import {debounce} from '../utils/debounce';
import {isURLMatched} from '../utils/url';
import type {UserSettings} from '../definitions';
import {readSyncStorage, readLocalStorage, writeSyncStorage, writeLocalStorage, removeSyncStorage, removeLocalStorage} from './utils/extension-api';
import {logWarn} from './utils/log';
import {PromiseBarrier} from '../utils/promise-barrier';
import {validateSettings} from '../utils/validation';
const SAVE_TIMEOUT = 1000;
export default class UserStorage {
private static loadBarrier: PromiseBarrier<UserSettings, void>;
private static saveStorageBarrier: PromiseBarrier<void, void> | null;
static settings: Readonly<UserSettings>;
static async loadSettings(): Promise<void> {
if (!UserStorage.settings) {
UserStorage.settings = await UserStorage.loadSettingsFromStorage();
}
}
private static fillDefaults(settings: UserSettings) {
settings.theme = {...DEFAULT_THEME, ...settings.theme};
settings.time = {...DEFAULT_SETTINGS.time, ...settings.time};
settings.presets.forEach((preset) => {
preset.theme = {...DEFAULT_THEME, ...preset.theme};
});
settings.customThemes.forEach((site) => {
site.theme = {...DEFAULT_THEME, ...site.theme};
});
if (settings.customThemes.length === 0) {
settings.customThemes = DEFAULT_SETTINGS.customThemes;
}
}
// migrateAutomationSettings migrates old automation settings to the new interface.
// It will move settings.automation & settings.automationBehavior into,
// settings.automation = { enabled, mode, behavior }.
// Remove this over two years(mid-2024).
// This won't always work, because browsers can decide to instead use the default settings
// when they notice a different type being requested for automation, in that case it's a data-loss
// and not something we can encounter for, except for doing always two extra requests to explicitly
// check for this case which is inefficient usage of requesting storage.
private static migrateAutomationSettings(settings: UserSettings): void {
if (typeof settings.automation === 'string') {
const automationMode = settings.automation;
const automationBehavior: UserSettings['automation']['behavior'] = (settings as any).automationBehaviour;
if (settings.automation === '') {
settings.automation = {
enabled: false,
mode: automationMode,
behavior: automationBehavior,
};
} else {
settings.automation = {
enabled: true,
mode: automationMode,
behavior: automationBehavior,
};
}
delete (settings as any).automationBehaviour;
}
}
private static migrateSiteListsV2(deprecated: any): Partial<UserSettings> {
const settings: Partial<UserSettings> = {};
settings.enabledByDefault = !deprecated.applyToListedOnly;
if (settings.enabledByDefault) {
settings.disabledFor = deprecated.siteList ?? [];
settings.enabledFor = deprecated.siteListEnabled ?? [];
} else {
settings.disabledFor = [];
settings.enabledFor = deprecated.siteList ?? [];
}
return settings;
}
private static async loadSettingsFromStorage(): Promise<UserSettings> {
if (UserStorage.loadBarrier) {
return await UserStorage.loadBarrier.entry();
}
UserStorage.loadBarrier = new PromiseBarrier();
let local = await readLocalStorage(DEFAULT_SETTINGS);
if (local.schemeVersion < 2) {
const sync = await readSyncStorage({schemeVersion: 0});
if (!sync || sync.schemeVersion < 2) {
const deprecatedDefaults = {
siteList: [],
siteListEnabled: [],
applyToListedOnly: false,
};
const localDeprecated = await readLocalStorage(deprecatedDefaults);
const localTransformed = UserStorage.migrateSiteListsV2(localDeprecated);
await writeLocalStorage({schemeVersion: 2, ...localTransformed});
await removeLocalStorage(Object.keys(deprecatedDefaults));
const syncDeprecated = await readSyncStorage(deprecatedDefaults);
const syncTransformed = UserStorage.migrateSiteListsV2(syncDeprecated);
await writeSyncStorage({schemeVersion: 2, ...syncTransformed});
await removeSyncStorage(Object.keys(deprecatedDefaults));
local = await readLocalStorage(DEFAULT_SETTINGS);
}
}
const {errors: localCfgErrors} = validateSettings(local);
localCfgErrors.forEach((err) => logWarn(err));
if (local.syncSettings == null) {
local.syncSettings = DEFAULT_SETTINGS.syncSettings;
}
if (!local.syncSettings) {
UserStorage.migrateAutomationSettings(local);
UserStorage.fillDefaults(local);
UserStorage.loadBarrier.resolve(local);
return local;
}
const $sync = await readSyncStorage(DEFAULT_SETTINGS);
if (!$sync) {
logWarn('Sync settings are missing');
local.syncSettings = false;
UserStorage.set({syncSettings: false});
UserStorage.saveSyncSetting(false);
UserStorage.loadBarrier.resolve(local);
return local;
}
const {errors: syncCfgErrors} = validateSettings($sync);
syncCfgErrors.forEach((err) => logWarn(err));
UserStorage.migrateAutomationSettings($sync);
UserStorage.fillDefaults($sync);
UserStorage.loadBarrier.resolve($sync);
return $sync;
}
static async saveSettings(): Promise<void> {
if (!UserStorage.settings) {
// This path is never taken because Extension always calls UserStorage.loadSettings()
// before calling UserStorage.saveSettings().
logWarn('Could not save settings into storage because the settings are missing.');
return;
}
await UserStorage.saveSettingsIntoStorage();
}
static async saveSyncSetting(sync: boolean): Promise<void> {
const obj = {syncSettings: sync};
await writeLocalStorage(obj);
try {
await writeSyncStorage(obj);
} catch (err) {
logWarn('Settings synchronization was disabled due to error:', chrome.runtime.lastError);
UserStorage.set({syncSettings: false});
}
}
private static saveSettingsIntoStorage = debounce(SAVE_TIMEOUT, async () => {
if (UserStorage.saveStorageBarrier) {
await UserStorage.saveStorageBarrier.entry();
return;
}
UserStorage.saveStorageBarrier = new PromiseBarrier();
const settings = UserStorage.settings;
if (settings.syncSettings) {
try {
await writeSyncStorage(settings);
} catch (err) {
logWarn('Settings synchronization was disabled due to error:', chrome.runtime.lastError);
UserStorage.set({syncSettings: false});
await UserStorage.saveSyncSetting(false);
await writeLocalStorage(settings);
}
} else {
await writeLocalStorage(settings);
}
UserStorage.saveStorageBarrier.resolve();
UserStorage.saveStorageBarrier = null;
});
static set($settings: Partial<UserSettings>): void {
if (!UserStorage.settings) {
// This path is never taken because Extension always calls UserStorage.loadSettings()
// before calling UserStorage.set().
logWarn('Could not modify settings because the settings are missing.');
return;
}
const filterSiteList = (siteList: string[]) => {
if (!Array.isArray(siteList)) {
const list: string[] = [];
for (const key in (siteList as string[])) {
const index = Number(key);
if (!isNaN(index)) {
list[index] = siteList[key];
}
}
siteList = list;
}
return siteList.filter((pattern) => {
let isOK = false;
try {
isURLMatched('https://google.com/', pattern);
isURLMatched('[::1]:1337', pattern);
isOK = true;
} catch (err) {
logWarn(`Pattern "${pattern}" excluded`);
}
return isOK && pattern !== '/';
});
};
const {enabledFor, disabledFor} = $settings;
const updatedSettings = {...UserStorage.settings, ...$settings};
if (enabledFor) {
updatedSettings.enabledFor = filterSiteList(enabledFor);
}
if (disabledFor) {
updatedSettings.disabledFor = filterSiteList(disabledFor);
}
UserStorage.settings = updatedSettings;
}
}