-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathreloadmatic.js
970 lines (851 loc) · 31.5 KB
/
reloadmatic.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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
// Configuration format version
const CONFIG_VERSION = 1
// Conversion factor from seconds to minutes
const TIME_FACTOR = 1.0 / 60.0
// true if we can use session APIs from FF 57.0
const session57Available = (typeof browser.sessions.setTabValue === "function")
// true if we can use menu APIs from FF 60.0
const menu60Available = (typeof browser.menus.refresh === "function")
// Here we store all our data about tabs
var state = new Map()
// Here we store all pages for the "Remember" feature
var urlMemory = new Map();
// ID of the currently focused window
var CurrentWindowId = -1;
// ID of the currently active tab in the currently focused window
var CurrentTabId = -1;
// Here we store all user settings for the plugin
var Settings;
function objKey(tabId) {
return `tab-${tabId}-alarm`;
}
// Returns a default-initialized instance of the object
// that describes all add-on related properties of a
// browser tab.
function newTabProps(tabId) {
let ret = {
// User Settings
// ******************************
randomize: false, // whether "Randomize" is enabled
loadError: false, // whether there was an error in loading the page
smart: false, // whether "Smart timing" is enabled
onlyOnError: false, // whether "Only if unsuccessful" is enabled
stickyReload: false, // whether to keep reloading after page changes
nocache: false, // whether "Disable cache" is enabled
remember: false, // whether settings for this URL will be remembered
period: -1, // canonical autoreload interval
fixedUrl: undefined, // if set, a reload request will be made to this url
// Internal State
// ******************************
alarmName: objKey(tabId), // name of the alarm and key in collections
keepRefreshing: false, // true if periodic refresh should not be disabled
freezeUntil: 0, // time until we are not allowed to reload
tabId: tabId, // id of the tab we belong to
reqMethod: "GET", // HTTP method the page was retrieved with
postConfirmed: false, // true if user wants to resend POST data
scrollX: undefined, // Horizontal scroll position of page
scrollY: undefined, // Vertical scroll position of page
url: "", // Current or currently loading URL of tab,
reloadByAddon: false // true if the current reload was initiated by us
};
// Apply default user options
Object.keys(Settings.defaults).forEach(function (key, index) {
ret[key] = Settings.defaults[key];
});
return ret;
}
function getTabProps(tabId) {
let alarm_name = objKey(tabId)
if (state.has(alarm_name)) {
return state.get(alarm_name)
} else {
let obj = newTabProps(tabId)
state.set(alarm_name, obj)
return obj
}
}
// Free up resources we don't need anymore
browser.tabs.onRemoved.addListener((tabId, removeInfo) => {
let key = objKey(tabId)
browser.alarms.clear(key)
state.delete(key)
})
async function restartAlarm(obj) {
// If period is negative we are deleting the alarm
browser.alarms.clear(obj.alarmName)
if (obj.period < 0) {
obj.postConfirmed = false;
return browser.tabs.sendMessage(obj.tabId, {event: "timer-disabled"});
}
// Create new alarm
let period = obj.period
if (obj.randomize) {
let min = period * 0.5
let max = period * 1.5
period = Math.random() * (max - min + 1) + min
}
browser.alarms.create(obj.alarmName, { delayInMinutes: period * TIME_FACTOR });
return browser.tabs.sendMessage(obj.tabId, {event: "timer-enabled"});
}
async function applyTabProps(obj) {
let promises = [];
promises.push(refreshMenu());
promises.push(restartAlarm(obj));
if (session57Available) {
promises.push(browser.sessions.setTabValue(obj.tabId, "reloadmatic", obj));
}
return Promise.all(promises);
}
async function setTabPeriod(obj, period) {
// Determine if the tab is still open, and do not continue if closed
try {
await browser.tabs.get(obj.tabId);
}
catch (err) {
// Tab already closed.
return;
}
// If this page was requested using POST, make sure the user
// knows the risks and really wants to refresh
if ((obj.reqMethod != "GET") && (period != -1) && !obj.postConfirmed && !Settings.neverConfirmPost) {
let popupURL = browser.extension.getURL("pages/post-confirm.html");
let createData = {
type: "popup",
url: `${popupURL}?tabId=${obj.tabId}&period=${period}`,
width: 800,
height: 247
};
let win = await browser.windows.create(createData);
return browser.windows.update(win.id, { drawAttention: true });
}
// Custom interval
if (period == -2) {
let popupURL = browser.extension.getURL("pages/custom-interval.html");
let createData = {
type: "popup",
url: `${popupURL}?tabId=${obj.tabId}`,
width: 400,
height: 247
};
let win = await browser.windows.create(createData);
return browser.windows.update(win.id, { drawAttention: true });
}
// Set period truely
obj.period = period;
return Promise.all([applyTabProps(obj), rememberSet(obj)]);
}
async function rememberSet(obj) {
// We need the tab's URL
let tab;
try {
tab = await browser.tabs.get(obj.tabId);
} catch (err) {
// Tab already closed. Ignore.
return;
}
// Don't store anything on the computer in incognito mode
if (tab.incognito) {
return;
}
// We use only portions of the URL to generalize it to a certain page
// without protocol or query parameters
let url = parseUri(tab.url);
url = url.authority + url.path;
// Store (or delete)
if (obj.remember) {
urlMemory.set(url, clone(obj));
} else {
urlMemory.delete(url);
}
return browser.storage.local.set({
// We can only serialize Map objects "unpacked"
urlMemory: [...urlMemory]
});
}
function migratePropObj(newObj, oldObj) {
let tmp = clone(oldObj);
tmp.tabId = newObj.tabId;
tmp.alarmName = newObj.alarmName;
Object.keys(newObj).forEach(function (key, index) {
if (tmp.hasOwnProperty(key)) {
newObj[key] = tmp[key];
}
});
}
async function rememberGet(obj) {
return Promise.resolve().then(async function() {
// Reconstruct the URL as we did while saving
let tab = await browser.tabs.get(obj.tabId);
let url = parseUri(tab.url);
url = url.authority + url.path;
if (urlMemory.has(url)) {
// Load stored settings
migratePropObj(obj, urlMemory.get(url));
return true;
} else {
return false;
}
});
}
function clone(obj) {
return JSON.parse(JSON.stringify(obj));
}
async function deleteLastHistoryEntry(obj) {
// Delete old URL from history because our refresh
// will create a new history entry.
let items = await browser.history.search({ text: obj.url, maxResults: 1 });
if (items.length > 0) {
let visitTime = items[0].lastVisitTime
return browser.history.deleteRange({
startTime: visitTime-1,
endTime: visitTime+1
});
}
}
async function reloadTab(obj, forceNocache = false) {
return Promise.resolve().then(async function() {
let bypassCache = forceNocache || obj.nocache;
obj.reloadByAddon = true;
// Fixed URL reload
if (obj.fixedUrl != undefined) {
obj.keepRefreshing = true;
await deleteLastHistoryEntry(obj);
let msg = {
event: "reload-get",
url: obj.fixedUrl,
bypassCache: bypassCache
};
return browser.tabs.sendMessage(obj.tabId, msg);
// Reload with POST-data
} else if ((obj.reqMethod != "GET") && (obj.postConfirmed || Settings.neverConfirmPost)) {
obj.keepRefreshing = true;
await deleteLastHistoryEntry(obj);
let msg = {
event: "reload-post",
postData: obj.formData
};
return browser.tabs.sendMessage(obj.tabId, msg);
// Traditional GET-reload
} else {
return browser.tabs.reload(obj.tabId, { bypassCache: bypassCache });
}
});
}
async function reloadAllTabs() {
let tabs = await browser.tabs.query({windowId: CurrentWindowId});
let promises = [];
for (let tab of tabs) {
let obj = getTabProps(tab.id);
promises.push(reloadTab(obj));
}
return Promise.all(promises);
}
// Handle clicking on menu entries
browser.menus.onClicked.addListener(async function (info, tab) {
if (info.menuItemId === 'reloadmatic-mnu-settings') {
browser.runtime.openOptionsPage();
} else if (info.menuItemId === 'reloadmatic-mnu-faq') {
browser.tabs.create({
active: true,
url: browser.extension.getURL("pages/faq.html")
});
} else if (info.menuItemId === 'reloadmatic-mnu-amo') {
browser.tabs.create({
active: true,
url: "https://addons.mozilla.org/en-US/firefox/addon/reloadmatic/"
});
} else if (info.menuItemId === 'reloadmatic-mnu-support') {
browser.tabs.create({
active: true,
url: "https://github.com/pylorak/reloadmatic/issues"
});
}
if (tab.id == browser.tabs.TAB_ID_NONE) {
return
}
let obj = getTabProps(tab.id)
if (info.menuItemId === 'reloadmatic-mnu-period--1') {
setTabPeriod(obj, -1);
} else if (info.menuItemId === 'reloadmatic-mnu-period--2') {
setTabPeriod(obj, -2);
} else if (info.menuItemId.startsWith("reloadmatic-mnu-period")) {
setTabPeriod(obj, Number(info.menuItemId.split("-")[3]));
} else if (info.menuItemId === 'reloadmatic-mnu-randomize') {
obj.randomize = info.checked
rememberSet(obj);
} else if (info.menuItemId === 'reloadmatic-mnu-remember') {
obj.remember = info.checked
rememberSet(obj);
} else if (info.menuItemId === 'reloadmatic-mnu-disable-cache') {
obj.nocache = info.checked
rememberSet(obj);
} else if (info.menuItemId === 'reloadmatic-mnu-smart') {
obj.smart = info.checked
rememberSet(obj);
} else if (info.menuItemId === 'reloadmatic-mnu-sticky') {
obj.stickyReload = info.checked
rememberSet(obj);
} else if (info.menuItemId === 'reloadmatic-mnu-unsuccessful') {
obj.onlyOnError = info.checked
rememberSet(obj);
restartAlarm(obj);
} else if (info.menuItemId === 'reloadmatic-mnu-fix-url') {
if (obj.fixedUrl != undefined) {
obj.fixedUrl = undefined;
if (Settings.fixedUrlSetsStickyReload) {
obj.stickyReload = false;
}
if (!menu60Available) {
updateMenuForTab(obj.tabId);
}
} else {
let popupURL = browser.extension.getURL("pages/fix-url.html");
let createData = {
type: "popup",
url: `${popupURL}?tabId=${obj.tabId}`,
width: 800,
height: 247
};
let win = await browser.windows.create(createData);
browser.windows.update(win.id, { drawAttention: true });
}
} else if (info.menuItemId === 'reloadmatic-mnu-reload') {
reloadTab(obj, true);
} else if (info.menuItemId === 'reloadmatic-mnu-reload-all') {
reloadAllTabs();
} else if (info.menuItemId === 'reloadmatic-mnu-enable-all') {
browser.tabs.query({}).then((tabs) => {
for (let tab of tabs) {
let other = getTabProps(tab.id);
let oldOther = clone(other);
migratePropObj(other, obj);
other.postConfirmed = oldOther.postConfirmed;
setTabPeriod(other, other.period);
}
return;
})
.catch(console.log.bind(console));
} else if (info.menuItemId === 'reloadmatic-mnu-disable-all') {
browser.tabs.query({}).then((tabs) => {
for (let tab of tabs) {
let obj = getTabProps(tab.id);
setTabPeriod(obj, -1);
}
return;
})
.catch(console.log.bind(console));
}
if (session57Available) {
browser.sessions.setTabValue(tab.id, "reloadmatic", obj)
}
});
if (session57Available) {
browser.tabs.onCreated.addListener(async function(tab) {
let tabId = tab.id;
let obj = await browser.sessions.getTabValue(tabId, "reloadmatic");
if (obj) {
// Handle restoring settings for an old tab.
// Tab ID might have changed, so correct for that.
let alarm_name = objKey(tabId);
obj.tabId = tabId;
obj.alarmName = alarm_name;
obj.keepRefreshing = true;
state.set(alarm_name, obj);
return applyTabProps(obj);
}
});
}
browser.webRequest.onBeforeRequest.addListener((details) => {
let obj = getTabProps(details.tabId);
obj.reqMethod = details.method;
if ((obj.reqMethod != "GET") && details.requestBody) {
obj.formData = clone(details.requestBody.formData);
} else {
obj.formData = null;
}
if ((obj.reqMethod != "GET") && !obj.postConfirmed && !Settings.neverConfirmPost) {
// We just issued a POST-request,
// and the user didn't yet confirm this.
// So disable autoreloads.
if (obj.period != -1) {
obj.period = -1
applyTabProps(obj)
if (Settings.notifications.unconfirmedPost) {
browser.notifications.create(
"clickActivateTab-" + details.tabId,
{
"type": "basic",
"iconUrl": browser.extension.getURL("icon.svg"),
"title": "Timer disabled - POST page",
"message":
"Please reset timer in the affected\r\n"+
"tab and confirm if asked."
}
);
}
}
}
},
{ urls: ["<all_urls>"], types: ["main_frame"] },
["requestBody"]
);
browser.alarms.onAlarm.addListener((alarm) => {
let obj = state.get(alarm.name);
if (!obj.onlyOnError || obj.loadError) { // handling "Only if unsuccessful" feature
// Delay firing alarm until time is freezeUntil,
// fire otherwise.
let now = Date.now();
if (obj.smart && (obj.freezeUntil > now)) {
let deltaInSeconds = (obj.freezeUntil - now) / 1000;
browser.alarms.create(obj.alarmName, { delayInMinutes: deltaInSeconds * TIME_FACTOR });
} else {
reloadTab(obj);
} // smart
} // if onlyOnError ...
});
async function sendContentTabId(tabId) {
let msg = {
event: "set-tab-id",
tabId: tabId
}
return browser.tabs.sendMessage(tabId, msg)
}
browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (tabId == browser.tabs.TAB_ID_NONE) {
return;
}
let obj = getTabProps(tabId)
// Tell content-script what tab it is running in
sendContentTabId(tabId)
// Start or stop alarm based on page loading progress
if ('status' in changeInfo) {
if (changeInfo.status === 'complete') {
// Scroll page to same position as before reload
if (obj.reloadByAddon && (obj.scrollX != undefined)) {
let msg = {
event: "scroll",
scrollX: obj.scrollX,
scrollY: obj.scrollY
}
browser.tabs.sendMessage(tabId, msg)
}
obj.reloadByAddon = false;
// Start reload timer once page is completely loaded
restartAlarm(obj)
} else {
// Don't autoreload while page is being loaded
browser.alarms.clear(obj.alarmName)
}
}
// "Pinning sets Remember" option
if (Settings.pinSetsRemember && ('pinned' in changeInfo)) {
obj.remember = changeInfo.pinned;
rememberSet(obj);
refreshMenu();
}
});
browser.webNavigation.onCommitted.addListener(async function (details) {
// Remove alarm if tab navigated due to a user action
if (details.frameId == 0) {
let tabId = details.tabId
let obj = getTabProps(tabId)
let type = details.transitionType
let reloading = !((type != "auto_subframe") && (type != "reload"))
let cancelTimer = !reloading && !obj.keepRefreshing && !obj.stickyReload
if (!reloading) {
obj.remember = false;
}
if (cancelTimer) {
// On a user-initiated navigation,
// we cancel the timer and disable a fixed URL
obj.period = -1;
obj.fixedUrl = undefined;
await rememberGet(obj);
applyTabProps(obj);
if (Settings.notifications.navigateAway) {
browser.notifications.create(
"clickActivateTab-" + details.tabId,
{
"type": "basic",
"iconUrl": browser.extension.getURL("icon.svg"),
"title": "Timer disabled - you left the page",
"message":
"If you don't want this to happen again,\r\n"+
"enable the Sticky Reload option in the\r\n"+
"tab or make it default in the addon settings."
}
);
}
} else {
await rememberGet(obj);
applyTabProps(obj);
}
// If the URL changed, forget scroll position in tab
if (obj.url != details.url) {
obj.scrollX = undefined;
obj.scrollY = undefined;
obj.url = details.url;
}
}
});
browser.webNavigation.onCompleted.addListener((details) => {
// Remove alarm if tab navigated due to a user action
if (details.frameId == 0) {
let tabId = details.tabId
let obj = getTabProps(tabId)
obj.keepRefreshing = false
}
});
function freezeReload(tabId, duration) {
let obj = getTabProps(tabId)
obj.freezeUntil = Date.now() + duration
}
browser.runtime.onMessage.addListener((message) => {
if (message.event == "activity") {
// Delay a pending reload if there is activity
freezeReload(message.tabId, Settings.smartTiming.delaySecs*1000)
} else if (message.event == "typing-activity") {
// Delay a pending reload if there is activity, or cancel timer
// (based on settings)
if (Settings.smartTiming.typeReaction == "radSmartTimingTextDelay") {
freezeReload(message.tabId, Settings.smartTiming.delaySecs*1000)
} else {
let obj = getTabProps(message.tabId)
if (obj.period != -1)
{
setTabPeriod(obj, -1);
if (Settings.notifications.textInput) {
browser.notifications.create(
"clickActivateTab-" + message.tabId,
{
"type": "basic",
"iconUrl": browser.extension.getURL("icon.svg"),
"title": "Timer disabled - you are typing",
"message":
"If you wish to keep the timer enabled,\r\n"+
"disable Smart Timing or change its options\r\n"+
"in the addon settings."
}
);
}
}
}
} else if (message.event == "set-tab-interval") {
setTabPeriod(getTabProps(message.tabId), message.period);
} else if (message.event == "set-fixed-url") {
let obj = getTabProps(message.tabId);
obj.fixedUrl = message.url;
if (Settings.fixedUrlSetsStickyReload) {
obj.stickyReload = true;
}
if (!menu60Available) {
// Update menu for newly activated tab
updateMenuForTab(obj.tabId);
}
} else if (message.event == "scroll") {
// A page is telling us its scroll position
let obj = getTabProps(message.tabId)
obj.scrollX = message.arg1;
obj.scrollY = message.arg2;
}
})
browser.tabs.onActivated.addListener((info) => {
// Ignore event if this is not the currently focused window
if (info.windowId != CurrentWindowId) {
return;
}
CurrentTabId = info.tabId;
// Delay reload on activity
freezeReload(info.tabId, Settings.smartTiming.delaySecs*1000)
// If we are using FF60, we update the menu in its onShown().
// Otherwise we update it here.
if (!menu60Available) {
// Update menu for newly activated tab
updateMenuForTab(info.tabId);
}
})
browser.windows.onFocusChanged.addListener(async function(windowId) {
CurrentWindowId = windowId
let tabs = await browser.tabs.query({ windowId: CurrentWindowId, active: true });
if (tabs.length > 0) {
let tab = tabs[0];
CurrentTabId = tab.id;
freezeReload(tab.id, Settings.smartTiming.delaySecs*1000)
if (!menu60Available) { // In FF60, the menu's onShown() handles the update
return updateMenuForTab(tab.id)
}
}
})
/***********************************************
* Following functions used for "Only if unsuccessful" feature
***********************************************/
function webRequestError(responseDetails) {
let tabId = responseDetails.tabId
let obj = getTabProps(tabId)
obj.loadError = true
}
function webRequestComplete(responseDetails) {
let tabId = responseDetails.tabId
let obj = getTabProps(tabId)
obj.loadError = (responseDetails.statusCode >= 400)
}
browser.webRequest.onErrorOccurred.addListener(webRequestError, { urls: ["<all_urls>"], types: ["main_frame", "sub_frame"] })
browser.webRequest.onCompleted.addListener(webRequestComplete, { urls: ["<all_urls>"], types: ["main_frame", "sub_frame"] })
/***********************************************
* Following functions are used for updating the menu
***********************************************/
async function disablePeriodMenus() {
let promises = [];
for (let i = 0; i < num_periods / 2; i++) {
promises.push(
browser.menus.update(
`reloadmatic-mnu-period-${reload_periods[i * 2]}`,
{
checked: false,
title: reload_periods[i * 2 + 1]
}
)
);
}
return Promise.all(promises);
}
function formatInterval(total) {
let ret = ""
let h = Math.floor(total / 3600)
total -= h * 3600
let m = Math.floor(total / 60)
total -= m * 60
let s = total
if (h > 0) {
ret = `${ret} ${h}h`
}
if (m > 0) {
ret = `${ret} ${m}m`
}
if (s > 0) {
ret = `${ret} ${s}s`
}
if ((h != 0) && (m == 0) && (s == 0)) {
ret = ` ${h} hours`
} else if ((h == 0) && (m != 0) && (s == 0)) {
ret = ` ${m} minutes`
} else if ((h == 0) && (m == 0) && (s != 0)) {
ret = ` ${s} secs`
}
return ret
}
async function updateMenuForTab(tabId) {
let obj = getTabProps(tabId);
let promises = [];
promises.push(browser.menus.update("reloadmatic-mnu-randomize", { checked: obj.randomize }));
promises.push(browser.menus.update("reloadmatic-mnu-unsuccessful", { checked: obj.onlyOnError }));
promises.push(browser.menus.update("reloadmatic-mnu-smart", { checked: obj.smart }));
promises.push(browser.menus.update("reloadmatic-mnu-sticky", { checked: obj.stickyReload }));
promises.push(browser.menus.update("reloadmatic-mnu-disable-cache", { checked: obj.nocache }));
promises.push(browser.menus.update("reloadmatic-mnu-fix-url", { checked: obj.fixedUrl != undefined }));
// Enable/disable "Remember Page" based on incognito mode
promises.push(Promise.resolve().then(async function() {
let tab = await browser.tabs.get(tabId);
if (tab.incognito) {
return browser.menus.update("reloadmatic-mnu-remember", { checked: false, enabled: false });
} else {
return browser.menus.update("reloadmatic-mnu-remember", { checked: obj.remember, enabled: true });
}
}));
promises.push(Promise.resolve().then(async function() {
// Reset menu items representing periods
await disablePeriodMenus();
// Iterate through available presets to see if our setting
// corresponds to one of them or maybe it's a custom interval.
let custom = true;
for (let i = 0; i < num_periods / 2; i++) {
if (reload_periods[i * 2] === obj.period) {
custom = false;
break;
}
}
// Select the correct timer period menu option
if (custom) {
return promises.push(browser.menus.update(`reloadmatic-mnu-period--2`, { checked: true, title: `Custom:${formatInterval(obj.period)}` }));
} else {
return promises.push(browser.menus.update(`reloadmatic-mnu-period-${obj.period}`, { checked: true }));
}
}));
return Promise.all(promises);
}
async function refreshMenu() {
// In FF60, the menu's onShown() handles the update,
// in which case we have nothing to do here.
if (menu60Available) {
return;
}
return Promise.resolve().then(async function() {
// Get currently active tab (and window)
let tabs = await browser.tabs.query({ currentWindow: true, active: true });
let tab = tabs[0];
if ((CurrentWindowId == -1) || (CurrentTabId == -1)) {
CurrentWindowId = tab.windowId;
CurrentTabId = tab.id;
}
// Ignore update request if this is not the active tab
if ((CurrentWindowId != tab.windowId) || (CurrentTabId != tab.id)) {
return;
}
return updateMenuForTab(tab.id);
});
}
if (menu60Available) {
browser.menus.onShown.addListener(async function(info, tab) {
await updateMenuForTab(tab.id);
return browser.menus.refresh();
});
}
browser.runtime.onUpdateAvailable.addListener(async function(details) {
let upgradeInfo = {
version: CONFIG_VERSION,
state: [...state]
};
await browser.storage.local.set({ upgrade: upgradeInfo });
return browser.runtime.reload();
});
function GetDefaultSettings() {
return {
defaults: {
randomize: false,
onlyOnError: false,
smart: true,
stickyReload: false,
nocache: false
},
smartTiming: {
delaySecs: 5,
typeReaction: "radSmartTimingTextDisable"
},
notifications: {
unconfirmedPost: true,
navigateAway: false,
textInput: true
},
pinSetsRemember: true,
neverConfirmPost: false,
fixedUrlSetsStickyReload: true
};
}
async function LoadSettingsAsync() {
return Promise.resolve().then(async function() {
let results = await browser.storage.local.get("settings");
if (results && results.settings) {
let settings = results.settings;
// If saved settings has missing keys (for example we upgraded
// and new addon version supports more options), we migrate
// old settings into the new settings structure here.
let tmp = GetDefaultSettings();
Object.keys(tmp).forEach(function (key, index) {
if (settings.hasOwnProperty(key)) {
tmp[key] = settings[key];
}
});
// Done.
Settings = tmp;
} else {
// Error. Load defaults.
Settings = GetDefaultSettings();
}
return Settings;
});
}
function on_notification_clicked(notificationId) {
let tokens = notificationId.split("-");
let notifType = tokens[0];
let tabId = null;
if (tokens.length > 1) {
tabId = Number(tokens[1]);
}
if (notifType == "clickActivateTab")
{
// Activate tab
browser.tabs.update(tabId, {active: true});
// Activate the tab's window
browser.tabs.get(tabId).then((tab) => {
return browser.windows.update(tab.windowId, { focused: true });
})
.catch(console.log.bind(console));
}
}
async function on_addon_load() {
let createMenuPromise = createMenu();
let settingsPromise = LoadSettingsAsync();
browser.notifications.onClicked.addListener(on_notification_clicked);
let upgrading = false;
try {
let results = await browser.storage.local.get("upgrade");
if (results && results.upgrade) {
if (results.upgrade.version <= CONFIG_VERSION) {
let newState = new Map(results.upgrade.state)
for (var [key, obj] of newState) {
// Migrate settings from old version
let newObj = newTabProps(obj.tabId);
migratePropObj(newObj, obj);
state.set(newObj.alarmName, newObj);
}
upgrading = true;
}
}
}
catch (err) {
// Ignore errors from upgrade.
console.log(err);
}
// Remove stuff that we only needed for the upgrade
browser.storage.local.remove("upgrade");
// Load data for "Remember Page" function
try {
let results = await browser.storage.local.get("urlMemory");
if (results && results.urlMemory) {
urlMemory = new Map(results.urlMemory);
}
}
catch (err) {
// Ignore errors from upgrade.
}
await createMenuPromise;
await settingsPromise;
let promises = [];
let tabs = await browser.tabs.query({});
for (let tab of tabs) {
promises.push(Promise.resolve().then(async function() {
let obj = getTabProps(tab.id);
let rememberGetPromise = rememberGet(obj);
try
{
await browser.tabs.executeScript(tab.id,
{
file: "/content-script.js",
runAt: "document_start"
}
);
await sendContentTabId(tab.id);
}
catch (err) {
// Ignored on purpose
}
if (!upgrading) {
// Already loaded tabs might be using POST *sigh*
// We can't just use POST in this case
// because if the page is using GET, POSTing might
// be completely disallowed. So we'll fall back to
// browser reload, but say that the user has
// already confirmed POST. This way the browser
// might show a popup, but ReloadMatic will then
// see it was a POST, and at least won't ask a
// second time by itself.
obj.reqMethod = "GET";
obj.postConfirmed = true;
}
await rememberGetPromise;
return applyTabProps(obj);
}));
}
await Promise.all(promises);
}
on_addon_load().catch(console.log.bind(console));