-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathConfigs.js
317 lines (291 loc) · 8.92 KB
/
Configs.js
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
/*
license: The MIT License, Copyright (c) 2016-2018 YUKI "Piro" Hiroshi
original:
http://github.com/piroor/webextensions-lib-configs
*/
'use strict';
// eslint-disable-next-line no-unused-vars
class Configs {
constructor(
defaults,
{ logging, logger, localKeys, syncKeys } = { syncKeys: [], logger: null }
) {
this.$defaultLockedKeys = [];
for (const key of Object.keys(defaults)) {
if (!key.endsWith(':locked'))
continue;
if (defaults[key])
this.$defaultLockedKeys.push(key.replace(/:locked$/, ''));
delete defaults[key];
}
this.$default = defaults;
this.$logging = logging || false;
this.$logs = [];
this.$logger = logger;
this._locked = new Set();
this._lastValues = {};
this._updating = new Map();
this._observers = new Set();
this._syncKeys = localKeys ?
Object.keys(defaults).filter(x => !localKeys.includes(x)) :
(syncKeys || []);
this.$loaded = this._load();
}
async $reset() {
this._applyValues(this.$default);
}
$addObserver(observer) {
if (!this._observers.has(observer))
this._observers.add(observer);
}
$removeObserver(observer) {
this._observers.delete(observer);
}
_log(message, ...args) {
message = `Configs[${location.href}] ${message}`;
this.$logs = this.$logs.slice(-1000);
if (!this.$logging)
return;
if (typeof this.$logger === 'function')
this.$logger(message, ...args);
else
console.log(message, ...args);
}
_load() {
return this.$_promisedLoad ||
(this.$_promisedLoad = this._tryLoad());
}
async _tryLoad() {
this._log('load');
this._applyValues(this.$default);
let values;
try {
this._log(`load: try load from storage on ${location.href}`);
const [localValues, managedValues, lockedKeys] = await Promise.all([
(async () => {
try {
const localValues = await browser.storage.local.get(null); // keys must be "null" to get only stored values
this._log('load: successfully loaded local storage');
return localValues;
}
catch(e) {
this._log('load: failed to load local storage: ', String(e));
}
return {};
})(),
(async () => {
if (!browser.storage.managed) {
this._log('load: skip managed storage');
return null;
}
let resolved = false;
return new Promise((resolve, _reject) => {
browser.storage.managed.get().then(managedValues => {
if (resolved)
return;
resolved = true;
this._log('load: successfully loaded managed storage');
resolve(managedValues || null);
}).catch(error => {
if (resolved)
return;
resolved = true;
this._log('load: failed to load managed storage: ', String(error));
resolve(null);
});
// storage.managed.get() fails on options page in Thunderbird.
// The problem should be fixed by Thunderbird side.
if (window.messenger) {
setTimeout(() => {
if (resolved)
return;
resolved = true;
this._log('load: failed to load managed storage: timeout');
resolve(null);
}, 250);
}
});
})(),
(async () => {
try {
const lockedKeys = await browser.runtime.sendMessage({
type: 'Configs:getLockedKeys'
});
this._log('load: successfully synchronized locked state');
return lockedKeys || [];
}
catch(e) {
this._log('load: failed to synchronize locked state: ', String(e));
}
return [];
})()
]);
this._log(`load: loaded:`, { localValues, managedValues, lockedKeys });
lockedKeys.push(...this.$defaultLockedKeys);
const lockedValues = {};
for (const key of this.$defaultLockedKeys) {
lockedValues[key] = this.$default[key];
}
if (managedValues) {
const unlockedKeys = new Set();
for (const key of Object.keys(managedValues)) {
if (!key.endsWith(':locked'))
continue;
if (!managedValues[key])
unlockedKeys.add(key.replace(/:locked$/, ''));
delete managedValues[key];
}
const lockedManagedKeys = Object.keys(managedValues).filter(key => !unlockedKeys.has(key));
lockedKeys.push(...lockedManagedKeys);
for (const key of lockedManagedKeys) {
lockedValues[key] = managedValues[key];
}
}
values = { ...(managedValues || {}), ...(localValues || {}), ...lockedValues };
this._applyValues(values);
this._log('load: values are applied');
for (const key of new Set(lockedKeys)) {
this._updateLocked(key, true);
}
this._log('load: locked state is applied');
browser.storage.onChanged.addListener(this._onChanged.bind(this));
if (this._syncKeys || this._syncKeys.length > 0) {
try {
browser.storage.sync.get(this._syncKeys).then(syncedValues => {
this._log('load: successfully loaded sync storage');
if (!syncedValues)
return;
for (const key of Object.keys(syncedValues)) {
this[key] = syncedValues[key];
}
});
}
catch(e) {
this._log('load: failed to read sync storage: ', String(e));
return null;
}
}
browser.runtime.onMessage.addListener(this._onMessage.bind(this));
return values;
}
catch(e) {
this._log('load: fatal error: ', e, e.stack);
throw e;
}
}
_applyValues(values) {
for (const [key, value] of Object.entries(values)) {
if (this._locked.has(key))
continue;
this._lastValues[key] = value;
if (key in this)
continue;
Object.defineProperty(this, key, {
get: () => this._lastValues[key],
set: (value) => this._setValue(key, value)
});
}
}
_setValue(key, value) {
if (this._locked.has(key)) {
this._log(`warning: ${key} is locked and not updated`);
return value;
}
if (JSON.stringify(value) == JSON.stringify(this._lastValues[key]))
return value;
this._log(`set: ${key} = ${value}`);
this._lastValues[key] = value;
const update = {};
update[key] = value;
try {
this._updating.set(key, value);
browser.storage.local.set(update).then(() => {
this._log('successfully saved', update);
setTimeout(() => {
if (!this._updating.has(key))
return;
// failsafe: on Thunderbird updates sometimes won't be notified to the page itself.
const changes = {};
changes[key] = {
oldValue: this[key],
newValue: value
};
this._onChanged(changes);
}, 250);
});
}
catch(e) {
this._log('save: failed', e);
}
try {
if (this._syncKeys.includes(key))
browser.storage.sync.set(update).then(() => {
this._log('successfully synced', update);
});
}
catch(e) {
this._log('sync: failed', e);
}
return value;
}
$lock(key) {
this._log('locking: ' + key);
this._updateLocked(key, true);
}
$unlock(key) {
this._log('unlocking: ' + key);
this._updateLocked(key, false);
}
$isLocked(key) {
return this._locked.has(key);
}
_updateLocked(key, locked, { broadcast } = {}) {
if (locked) {
this._locked.add(key);
}
else {
this._locked.delete(key);
}
if (browser.runtime &&
broadcast !== false) {
try {
browser.runtime.sendMessage({
type: 'Configs:updateLocked',
key: key,
locked: this._locked.has(key)
}).catch(_error => {});
}
catch(_error) {
}
}
}
_onMessage(message, sender) {
if (!message ||
typeof message.type != 'string')
return;
this._log(`onMessage: ${message.type}`, message, sender);
switch (message.type) {
case 'Configs:getLockedKeys':
return Promise.resolve(Array.from(this._locked.values()));
case 'Configs:updateLocked':
this._updateLocked(message.key, message.locked, { broadcast: false });
break;
}
}
_onChanged(changes) {
this._log('_onChanged', changes);
for (const [key, change] of Object.entries(changes)) {
this._lastValues[key] = change.newValue;
this.$notifyToObservers(key);
}
}
$notifyToObservers(key) {
this._updating.delete(key);
for (const observer of this._observers) {
if (typeof observer === 'function')
observer(key);
else if (observer && typeof observer.onChangeConfig === 'function')
observer.onChangeConfig(key);
}
}
};