-
Notifications
You must be signed in to change notification settings - Fork 2
/
background-script.js
487 lines (433 loc) · 14.4 KB
/
background-script.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
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
'use strict';
const BMU = function(){
this.scannedBookmarks = null;
this.State = function(){
this.from = null;
this.to = null;
this.isValid = function(){ return !(this.from === null || this.from === undefined || this.to === null || this.to === undefined) }
this.clear = function(){ return !(this.from = this.to = null) }
};
this.operations = {
running:null,
progress: {
current:null,
target:null,
get : ()=> {
let prog = this.operations.progress;
return (!prog.current || !prog.target) ? 0 : Math.ceil(100*(prog.current/prog.target))
}
},
type:null,
operands: {
url: new this.State(),
title: new this.State(),
clear: function(){this.url.clear() && this.title.clear()}
}
};
this.debug = true;
this.print = (message) => { this.debug && console.log(message) };
this.sRegexp = function(a,rv){
if(typeof a === "string" && a.length > 0){
try{
let s = new RegExp(a);
return s
}catch(e){
rv.ok = false;
rv.message = "invalid regular expression"
}
}
return null
}
this.initializeOperation = function(ARGS,rv){
const OPS = this.operations.operands;
const STR = (a)=>{return typeof a === "string" ? a : null};
switch(ARGS.type){
case "protocol":
this.operations.type = "protocol";
OPS.url.from = STR(ARGS.fromDomain);
OPS.url.to = null;
OPS.title.from = null;
OPS.title.to = null;
break;
case "domain":
this.operations.type = "domain";
OPS.url.from = STR(ARGS.fromDomain);
OPS.url.to = STR(ARGS.toDomain) || null; // collapse to null if empty string
OPS.title.from = null;
OPS.title.to = null;
rv.ok = (OPS.url.isValid());
if(!rv.ok){
rv.message = "input or output domain is not defined"
}
break;
case "regexp":
this.operations.type = "regexp";
OPS.url.from = this.sRegexp(ARGS.fromDomain,rv);
OPS.title.from = this.sRegexp(ARGS.fromTitle,rv);
OPS.url.to = STR(ARGS.toDomain);
OPS.title.to = STR(ARGS.toTitle);
rv.ok = (OPS.url.isValid() || OPS.title.isValid());
if(!rv.ok){
rv.message += ";input or output operand is not defined"
}
break;
default:
rv.message = "unknown scan type";
rv.ok = false;
}
return rv
}
this.isOpValid = function(obj){
let initOps = this.operations;
let rv = {ok:false};
if(initOps.running){
rv.message = `${initOps.running} is running`;
}
switch(obj.operation){
case "scan":
rv.ok = !rv.message;
if(rv.ok){
this.initializeOperation(obj.properties,rv)
}
break;
case "status":
rv.ok = true;
rv.busy = !!rv.message;
rv.progress = `${initOps.progress.get()}%`;
break;
case "update":
rv.ok = !initOps.running;
if(rv.ok){
if(!this.scannedBookmarks || this.scannedBookmarks.length === 0){
rv.ok = false;
rv.message = "no scanned bookmarks to update";
break;
}
if(initOps.type === "domain"){
rv.ok = (initOps.operands.url.isValid());
if(!rv.ok){
rv.message = "input or output domain is not defined"
}
}else if(initOps.type === "regexp"){
rv.ok = (initOps.operands.url.isValid() || initOps.operands.title.isValid());
if(!rv.ok){
rv.message = "missing argument for replace operation"
}
}
}
break;
case "list":
rv.ok = !initOps.running;
if(rv.ok){
if(!this.scannedBookmarks){
rv.ok = false;
rv.message = "Bookmarks haven't been scanned yet";
}
}
break;
case "reset":
rv.ok = !initOps.running;
break;
default:
this.print(`Error determining op ${obj.operation}`)
rv.message = "unknown op"
break;
}
return rv
}
this.messageHandler = function(request,sender,sendResponse){
if(sender.id != browser.runtime.id || sender.envType != "addon_child" || !request.operation){
return
}
let result = this.isOpValid(request);
switch(request.operation){
case "scan":
this.print("received scan request");
sendResponse(result);
result.ok && this.scan(request.properties);
break;
case "status":
this.print("received status query");
sendResponse(result);
break;
case "update":
this.print("received update request");
sendResponse(result);
result.ok && this.update(request.excludes,request.allowUrlFixup);
break;
case "list":
this.print("received scanned list request");
sendResponse(result);
result.ok && this.createBookmarkList();
break;
case "reset":
this.print("received reset request");
result.ok && this.reset();
break;
default:
this.print("received some random request");
return
}
};
this.createBookmarkList = async function(){
const BM = function(bm,r,includeReplacement){
const o = { id: bm.id };
if(r.url[0] && typeof r.url[1] === "string"){
o.url = { "match": bm.url };
if(includeReplacement){
o.url.replacement = bm.url.replace(r.url[0],r.url[1]);
}
}
if(r.title[0] && typeof r.title[1] === "string"){
o.title = { "match": bm.title };
if(includeReplacement){
o.title.replacement = bm.title.replace(r.title[0],r.title[1]);
}
}
return o
}
if(this.operations.running || !this.scannedBookmarks){
return
}
this.operations.running = "listing";
let bookmarks = this.scannedBookmarks;
let list = [];
const END = bookmarks.length;
const REPLACER = this.getReplacers();
END && list.push(BM(bookmarks[0],REPLACER,true));
let idx = 1;
while(idx < END){
list.push(BM(bookmarks[idx],REPLACER,true))
idx++
}
if (bookmarks.length > END){
list.push({note:`--- and ${bookmarks.length - END} more ---`});
}
this.operations.running = null;
browser.runtime.sendMessage({
type:"list",
operation:this.operations.type,
list:list
});
};
this.parseDomain = function(url){
let start = url.indexOf("//") + 2;
let end = url.indexOf("/",start);
if(start > 0 && end > start){
return url.slice(start,end)
}else{
return url.slice(start)
}
};
this.isBookmarkATarget = function(node,ref){
let rv = false;
let queries = {
url: this.operations.operands.url.from,
title: this.operations.operands.title.from
}; // This has been set earlier by this.isOpValid()
switch(ref.options.type){
case "protocol":
return (/^http:/).test(node.url) && (queries.url === null || this.parseDomain(node.url).endsWith(queries.url))
break;
case "domain":
return this.parseDomain(node.url).endsWith(queries.url);
break;
case "regexp":
return queries.url ? queries.url.test(node.url) : queries.title ? queries.title.test(node.title) : false
default:
break;
}
return rv
}
this.traverseBookmarkTree = async function(tree,ref){
// skip scanning if operation is not supported
if(ref.options.type != "protocol" && ref.options.type != "domain" && ref.options.type != "regexp"){
console.error("error traversing")
return ref
}
for(let node of tree.children){
if(node.children){
this.traverseBookmarkTree(node,ref);
}else if(node.type === "bookmark"){
if( this.isBookmarkATarget(node,ref) ){
ref.collection.push(node);
}
}
}
return ref;
}
this.scan = async function(options){
this.operations.running = "scan";
(function(){
return new Promise((resolve,reject) => {
browser.bookmarks.getTree().then(
(success) => resolve(this.traverseBookmarkTree(success[0],{collection:[],options:options})),
(error) => reject("for reasons")
);
});
}).bind(this)()
.then(
(bookmarks)=>(this.scannedBookmarks = bookmarks.collection),
(error)=>(this.scannedBookmarks = null)
)
.finally(()=>{
this.operations.running = null;
browser.runtime.sendMessage({
type: "scan",
success: !(this.scannedBookmarks===null),
length: this.scannedBookmarks?this.scannedBookmarks.length:0,
domain: options.fromDomain
});
})
}
this.reset = function(force){
this.print("resetting...");
if(force || !this.operations.running){
this.operations.progress.current = null;
this.operations.progress.target = null;
this.scannedBookmarks = null
this.operations.type = null;
this.operations.operands.clear();
}else{
this.print(`reset was ignored due to pending ${this.running} operation`)
}
}
this.isValidURL = function(url,hasNoBackslash){
let rv = true;
function tryMakeUrl(base){
try{
return new URL(base)
}catch(e){
return null
}
}
try{
let d = tryMakeUrl(url) || tryMakeUrl(decodeURIComponent(url));
rv = !d.host.startsWith(".")
&& !d.host.endsWith(".")
&& d.host.indexOf("..") === -1
&& !d.pathname.startsWith("//");
}catch(e){
rv = false
}
return rv && (!hasNoBackslash || url.indexOf("\\") === -1)
}
this.getReplacers = function(){
let rv = {url:new Array(2),title:new Array(2)};
switch(this.operations.type){
case "protocol":
rv.url[0] = /^http:/;
rv.url[1] = "https:";
break;
case "regexp":
rv.title[0] = this.operations.operands.title.from;
rv.title[1] = this.operations.operands.title.to;
case "domain":
rv.url[0] = this.operations.operands.url.from;
rv.url[1] = this.operations.operands.url.to;
break;
}
return rv
}
this.reformatUrl = function(url,index){
try{
return decodeURIComponent(url.slice(0,index)) + url.slice(index)
}catch(e){
// this will intentionally cause bookmarks.update() to fail
return null
}
}
this.update = async function(excludes,allowfixup){
if(this.scannedBookmarks === null){
return
}
this.operations.running = "update";
this.operations.progress.target = this.scannedBookmarks.length;
const IS_DOMAIN_OR_REGEXP = (this.operations.type === "domain" || this.operations.type === "regexp");
let replacer = this.getReplacers();
// This is necessary to get around an issue when Promise.all may resolve too fast is all bookmarks fail to update, which in turn confuses the popup ui.
let bookmarkPromises = [new Promise((resolve)=>(setTimeout(()=>(resolve(1)),100)))];
const CHANGES = {};
CHANGES.url = replacer.url[0] && (this.operations.type === "regexp" || replacer.url[1]);
CHANGES.title = this.operations.type === "regexp" && replacer.title[0] && (typeof replacer.title[1] === "string") ;
let exclusions = 0;
let failures = [];
let success = false;
for(let bm of this.scannedBookmarks){
if(excludes.includes(bm.id)){
this.operations.progress.current++;
exclusions++;
continue
}
let newProps = {};
let failedURL;
if(CHANGES.url){
newProps.url = bm.url.replace(replacer.url[0],replacer.url[1]);
if(IS_DOMAIN_OR_REGEXP && !this.isValidURL(newProps.url,bm.url.indexOf("\\" === -1))){
failedURL = newProps.url;
delete newProps.url
}
}
if(CHANGES.title){
newProps.title = bm.title.replace(replacer.title[0],replacer.title[1]);
}
if(newProps.url || newProps.title){
const ID = bm.id;
// This path should handle an outcome where the resulting url is in
// in encoded form and thus invalid. If such a scenario were to happen
// then it's very likely that the url does not have a ":" in it
// so use that as a simple detecting mechanism. Moreso, should
// such a scenario occur, then it is likely that the correct url
// was part of a query parameter
if(allowfixup && newProps.url.indexOf(":") === -1){
let queryIndex = newProps.url.indexOf("?");
if(queryIndex > -1){
newProps.url = this.reformatUrl(newProps.url,queryIndex);
}else{
newProps.url = this.reformatUrl(newProps.url,newProps.url.length);
}
}
let updating = browser.bookmarks.update(ID,newProps);
// This error should only happen if the bookmark to be updated is no longer available when the update is being run but it was available when scanning
updating
.catch((e)=>(failures.push({error:e.message}),true))
.finally(()=>(this.operations.progress.current++));
bookmarkPromises.push(updating);
}else{
failures.push({error:`invalid url: ${failedURL}`});
this.operations.progress.current++
}
}
Promise.allSettled(bookmarkPromises)
.then(()=>{ success = true })
// If we end up in this catch it implies error in the script
.catch((e)=>{ console.error(e) })
.then(()=>{
browser.runtime.sendMessage({
type: "update",
success: (success && !failures.length),
length: this.operations.progress.current - exclusions,
failures: failures.length?failures:null
});
this.operations.running = null;
// reset() takes one "force" argument to fully reset status so we can recover from hard errors
// note - success will be true if bookmark couldn't be updated due to no matching id
this.reset(!success);
})
}
browser.runtime.onMessage.addListener(this.messageHandler.bind(this));
};
let engine = null;
async function switchToOrOpenTab(){
let views = await browser.extension.getViews({type:"tab"});
if(!views.length){
if(!engine){
engine = new BMU();
}
browser.tabs.create({url:"ui.html"})
}else{
let aTab = await views[0].browser.tabs.getCurrent()
browser.tabs.update(aTab.id,{active:true})
}
}
browser.browserAction.onClicked.addListener(switchToOrOpenTab)