-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathbackground.js
More file actions
1052 lines (929 loc) · 41.8 KB
/
background.js
File metadata and controls
1052 lines (929 loc) · 41.8 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
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
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Universal background script for Manifest V2 (Firefox) and V3 (Chrome/Edge)
const isFirefox = typeof browser !== 'undefined';
const isManifestV3 = chrome.runtime.getManifest().manifest_version === 3;
const browserAPI = isFirefox ? browser : chrome;
const db = {
indexedDB: null,
addEvent: async (eventName) => {
let eventObject = {
"eventDate": new Date().toISOString(),
"event": eventName.toString(),
"currentState": (clock && clock.onABreak ? "break" : "streak")
};
let records = [eventObject];
if (db.indexedDB) {
const insert_transaction = db.indexedDB.transaction("activity", "readwrite");
const objectStore = insert_transaction.objectStore("activity");
return new Promise((resolve, reject) => {
insert_transaction.oncomplete = function () {
console.log("Insert done");
resolve(true);
}
insert_transaction.onerror = function (e) {
console.error("Problem inserting record");
console.error(e);
resolve(false);
}
records.forEach(record => {
let request = objectStore.add(record);
request.onsuccess = function () {
console.log("Added: ", record);
}
});
});
}
},
createDB: () => {
return new Promise((resolve, reject) => {
const indexedDB = isManifestV3 ? self.indexedDB : window.indexedDB;
const request = indexedDB.open('stats');
request.onerror = function (event) {
console.log("Problem opening DB.");
reject(event);
}
request.onupgradeneeded = function (event) {
db.indexedDB = event.target.result;
let objectStore = db.indexedDB.createObjectStore('activity', {
keyPath: 'eventDate'
});
objectStore.transaction.oncomplete = function (event) {
console.log("ObjectStore Created.");
}
}
request.onsuccess = function (event) {
db.indexedDB = event.target.result;
console.log("DB opened");
db.addEvent("loaded");
db.indexedDB.onerror = (event) => {
console.error("Failed to open DB")
}
resolve(db.indexedDB);
}
});
},
getStats: () => {
if (db.indexedDB) {
const read_transaction = db.indexedDB.transaction("activity", "readonly");
const objectStore = read_transaction.objectStore("activity");
return new Promise((resolve, reject) => {
read_transaction.oncomplete = function () {
console.log("Get transaction complete");
}
read_transaction.onerror = function () {
console.error("Problem getting records")
reject();
}
let request = objectStore.getAll();
request.onsuccess = function (event) {
resolve(event.target.result);
}
});
}
}
}
const clock = {
seconds: 1800, // Default to 30 minutes
timeStarted: 0,
alarmAt: 0,
onABreak: false,
ticking: false,
paused: false,
streakTimer: 30,
pauseTimer: 5,
inARow: 0,
ring: null,
volume: 100,
showMinutes: false,
loopDisabled: false,
useAdvancedTimers: false,
soundEnabled: true,
advancedTimers: [30, 5],
advancedTimersIndex: 0,
customSound: false,
customSoundData: "",
muteOtherTabs: false,
initialized: false,
updateBadge: async (minutes) => {
let color;
let title;
if (clock.paused) {
color = "lightskyblue";
title = "paused";
} else if (clock.onABreak) {
color = "green";
title = "on a break";
} else {
color = "darkred";
title = "on a streak";
}
const actionAPI = isManifestV3 ? browserAPI.action : browserAPI.browserAction;
if (!clock.showMinutes) {
try {
await actionAPI.setBadgeText({ "text": "0" });
if (actionAPI.setBadgeTextColor) {
await actionAPI.setBadgeTextColor({ "color": color });
}
} catch (e) {
await actionAPI.setBadgeText({ "text": " " });
}
} else {
await actionAPI.setBadgeText({ "text": minutes.toString() });
try {
if (actionAPI.setBadgeTextColor) {
await actionAPI.setBadgeTextColor({ "color": "white" });
}
} catch (e) { }
}
await actionAPI.setBadgeBackgroundColor({ "color": color });
await actionAPI.setTitle({ "title": title });
return true;
},
start: async () => {
clock.ticking = true;
clock.timeStarted = Date.now();
let timer = 0;
if (clock.useAdvancedTimers) {
// Validate advanced timers array
if (!clock.advancedTimers || !Array.isArray(clock.advancedTimers) || clock.advancedTimers.length === 0) {
console.warn("Invalid advancedTimers, using default");
clock.advancedTimers = [30, 5];
clock.advancedTimersIndex = 0;
}
// Ensure index is valid
if (clock.advancedTimersIndex >= clock.advancedTimers.length) {
clock.advancedTimersIndex = 0;
}
timer = clock.advancedTimers[clock.advancedTimersIndex];
// Validate the timer value
if (isNaN(timer) || timer <= 0) {
console.warn("Invalid timer value:", timer, "using default 30");
timer = 30;
}
clock.advancedTimersIndex++;
} else {
timer = clock.streakTimer;
// Validate streak timer
if (isNaN(timer) || timer <= 0) {
console.warn("Invalid streakTimer:", timer, "using default 30");
timer = 30;
clock.streakTimer = 30;
}
}
console.log("Starting timer with duration:", timer, "minutes");
clock.alarmAt = clock.timeStarted + (timer * 60000);
clock.seconds = timer * 60;
clock.paused = false;
clock.onABreak = false;
await clock.updateBadge(timer);
await browserAPI.alarms.create("alarm", { "when": clock.alarmAt });
await browserAPI.alarms.clear("minutes");
await browserAPI.alarms.create("minutes", { "delayInMinutes": 1, "periodInMinutes": 1 });
await clock.saveState();
db.addEvent("started");
return true;
},
reset: async () => {
// Track actual elapsed streak minutes if resetting during an active streak
if (clock.ticking && !clock.onABreak) {
const elapsedMinutes = clock.getElapsedStreakMinutes();
if (elapsedMinutes > 0) {
await clock.addDailyStreakMinutes(elapsedMinutes);
}
}
clock.ticking = false;
clock.paused = false;
if (clock.useAdvancedTimers) {
clock.seconds = clock.advancedTimers[0] * 60;
} else {
clock.seconds = clock.streakTimer * 60;
}
clock.onABreak = false;
clock.advancedTimersIndex = 0;
clock.inARow = 0;
const actionAPI = isManifestV3 ? browserAPI.action : browserAPI.browserAction;
await actionAPI.setBadgeText({ "text": "" });
await actionAPI.setBadgeBackgroundColor({ "color": "darkred" });
await actionAPI.setTitle({ title: "not ticking" });
await browserAPI.alarms.clear("alarm");
await browserAPI.alarms.clear("minutes");
await clock.saveState();
db.addEvent("stopped");
return true;
},
pause: async () => {
if (!clock.ticking) { return false; }
clock.paused = !clock.paused;
if (clock.paused) {
clock.seconds = Math.floor((clock.alarmAt - Date.now()) / 1000);
await browserAPI.alarms.clear("alarm");
await browserAPI.alarms.clear("minutes");
db.addEvent("paused");
} else if (!clock.paused) {
clock.alarmAt = Date.now() + (clock.seconds * 1000);
await browserAPI.alarms.create("alarm", { "when": clock.alarmAt });
await browserAPI.alarms.create("minutes", { "delayInMinutes": 1, "periodInMinutes": 1 });
db.addEvent("unpaused");
}
await clock.updateBadge(Math.round(clock.seconds / 60));
await clock.saveState();
return true;
},
addMinute: async (minutes) => {
if (!clock.ticking) { return false; }
// Calculate current remaining seconds
let currentSeconds;
if (clock.paused) {
currentSeconds = clock.seconds;
} else {
currentSeconds = Math.floor((clock.alarmAt - Date.now()) / 1000);
}
// If trying to remove time and there's 1 minute or less left, don't allow it
if (minutes < 0 && currentSeconds <= 60) {
console.log("Cannot remove time: 1 minute or less remaining");
return false;
}
// Add the specified minutes (can be positive or negative)
const additionalSeconds = minutes * 60;
if (clock.paused) {
// If paused, just update the seconds directly
clock.seconds = Math.max(1, clock.seconds + additionalSeconds);
} else {
// If running, update the alarm time
clock.alarmAt = Math.max(Date.now() + 1000, clock.alarmAt + (additionalSeconds * 1000));
clock.seconds = Math.floor((clock.alarmAt - Date.now()) / 1000);
// Update the alarms with new time
await browserAPI.alarms.clear("alarm");
await browserAPI.alarms.create("alarm", { "when": clock.alarmAt });
}
// Update badge and save state
await clock.updateBadge(Math.round(clock.seconds / 60));
await clock.saveState();
// Log the event
db.addEvent(minutes > 0 ? "time_added" : "time_removed");
return true;
},
// Daily streak minutes tracking
addDailyStreakMinutes: async (minutes) => {
const today = new Date().toISOString().split('T')[0]; // Get yyyy-mm-dd format
try {
// Get current daily streak data from storage
const result = await browserAPI.storage.local.get(['dailyStreakMinutes']);
let dailyData = result.dailyStreakMinutes || {};
// Initialize today's count if it doesn't exist
if (!dailyData[today]) {
dailyData[today] = 0;
}
// Add the minutes to today's total
dailyData[today] += minutes;
// Clean up old entries (keep only last 30 days)
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
const thirtyDaysAgoISO = thirtyDaysAgo.toISOString().split('T')[0];
Object.keys(dailyData).forEach(dateKey => {
if (dateKey < thirtyDaysAgoISO) {
delete dailyData[dateKey];
}
});
// Save back to storage
await browserAPI.storage.local.set({ dailyStreakMinutes: dailyData });
console.log(`Added ${minutes} streak minutes for ${today}. Total: ${dailyData[today]}`);
} catch (e) {
console.warn("Could not save daily streak minutes:", e);
}
},
getDailyStreakMinutes: async () => {
const today = new Date().toISOString().split('T')[0]; // Get yyyy-mm-dd format
try {
const result = await browserAPI.storage.local.get(['dailyStreakMinutes']);
const dailyData = result.dailyStreakMinutes || {};
return dailyData[today] || 0;
} catch (e) {
console.warn("Could not get daily streak minutes:", e);
return 0;
}
},
// Calculate actual elapsed time in current streak
getElapsedStreakMinutes: () => {
if (!clock.ticking || clock.onABreak) {
return 0;
}
let elapsedSeconds;
if (clock.paused) {
// If paused, calculate based on original duration minus remaining seconds
elapsedSeconds = (clock.streakTimer * 60) - clock.seconds;
} else {
// If running, calculate based on alarm time
const remainingSeconds = Math.floor((clock.alarmAt - Date.now()) / 1000);
elapsedSeconds = (clock.streakTimer * 60) - remainingSeconds;
}
// Ensure we don't return negative values
elapsedSeconds = Math.max(0, elapsedSeconds);
// Convert to minutes and round down
return Math.floor(elapsedSeconds / 60);
},
getStreakHistory: async () => {
try {
const result = await browserAPI.storage.local.get(['dailyStreakMinutes']);
const dailyData = result.dailyStreakMinutes || {};
// Generate last 30 days and filter out days with no data
const history = [];
const today = new Date();
for (let i = 0; i <= 29; i++) {
const date = new Date(today);
date.setDate(date.getDate() - i);
const dateKey = date.toISOString().split('T')[0]; // yyyy-mm-dd format
const minutes = dailyData[dateKey] || 0;
// Only include days with data (minutes > 0)
if (minutes > 0) {
history.push({
date: dateKey,
shortDate: date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }),
minutes: minutes,
isToday: i === 0
});
}
}
return history;
} catch (e) {
console.warn("Could not get streak history:", e);
return [];
}
},
getCurrentState: async () => {
if (clock.ticking && !clock.paused) {
clock.seconds = Math.floor((clock.alarmAt - Date.now()) / 1000);
}
// If not ticking and seconds is 0, set it to the streak timer duration
if (!clock.ticking && (!clock.seconds || clock.seconds === 0)) {
clock.seconds = (clock.streakTimer || 30) * 60;
}
// Get daily streak minutes
const dailyStreakMinutes = await clock.getDailyStreakMinutes();
// Ensure all values are valid
return {
"seconds": clock.seconds || (clock.streakTimer || 30) * 60,
"paused": clock.paused || false,
"onABreak": clock.onABreak || false,
"ticking": clock.ticking || false,
"streakTimer": clock.streakTimer || 30,
"pauseTimer": clock.pauseTimer || 5,
"advancedTimers": clock.advancedTimers || [30, 5],
"useAdvancedTimers": clock.useAdvancedTimers || false,
"loopDisabled": clock.loopDisabled || false,
"alarmAt": clock.alarmAt || 0,
"inARow": clock.inARow || 0,
"dailyStreakMinutes": dailyStreakMinutes || 0
};
},
loadOptions: async () => {
try {
const result = await browserAPI.storage.local.get([
'volume', 'showMinutes', 'loopDisabled',
'useAdvancedTimers', 'soundEnabled', 'customSoundData', 'customSound', 'advancedTimers', 'muteOtherTabs'
]);
clock.volume = result.volume !== undefined ? result.volume : 100;
clock.showMinutes = result.showMinutes !== undefined ? result.showMinutes : true;
clock.loopDisabled = result.loopDisabled !== undefined ? result.loopDisabled : false;
clock.useAdvancedTimers = result.useAdvancedTimers !== undefined ? result.useAdvancedTimers : false;
clock.soundEnabled = result.soundEnabled !== undefined ? result.soundEnabled : true;
clock.customSoundData = result.customSoundData || "";
clock.customSound = result.customSound !== undefined ? result.customSound : false;
clock.advancedTimers = result.advancedTimers || [30, 5];
clock.muteOtherTabs = result.muteOtherTabs !== undefined ? result.muteOtherTabs : false;
} catch (e) {
console.warn("could not load options from storage, trying localStorage: " + e);
// Fallback to localStorage for compatibility
if (typeof localStorage !== 'undefined') {
clock.volume = localStorage.volume || 100;
clock.showMinutes = (localStorage.showMinutes === true || localStorage.showMinutes === "true" || localStorage.showMinutes === undefined);
clock.loopDisabled = (localStorage.loopDisabled === true || localStorage.loopDisabled === "true");
clock.useAdvancedTimers = (localStorage.useAdvancedTimers === true || localStorage.useAdvancedTimers === "true");
clock.soundEnabled = (localStorage.soundEnabled === undefined || localStorage.soundEnabled === true || localStorage.soundEnabled === "true");
clock.customSoundData = localStorage.customSoundData || "";
clock.customSound = (clock.customSoundData !== "" && (localStorage.customSound === true || localStorage.customSound === "true"));
clock.muteOtherTabs = (localStorage.muteOtherTabs === true || localStorage.muteOtherTabs === "true");
try {
clock.advancedTimers = JSON.parse(localStorage.advancedTimers);
} catch (e) {
clock.advancedTimers = [30, 5];
}
}
}
},
saveState: async () => {
try {
await browserAPI.storage.local.set({
clockState: {
seconds: clock.seconds,
timeStarted: clock.timeStarted,
alarmAt: clock.alarmAt,
onABreak: clock.onABreak,
ticking: clock.ticking,
paused: clock.paused,
streakTimer: clock.streakTimer,
pauseTimer: clock.pauseTimer,
inARow: clock.inARow,
advancedTimersIndex: clock.advancedTimersIndex
}
});
} catch (e) {
console.warn("could not save state: " + e);
}
},
loadState: async () => {
try {
const result = await browserAPI.storage.local.get(['clockState']);
if (result.clockState) {
const state = result.clockState;
clock.seconds = state.seconds || 0;
clock.timeStarted = state.timeStarted || 0;
clock.alarmAt = state.alarmAt || 0;
clock.onABreak = state.onABreak || false;
clock.ticking = state.ticking || false;
clock.paused = state.paused || false;
clock.streakTimer = state.streakTimer || 30;
clock.pauseTimer = state.pauseTimer || 5;
clock.inARow = state.inARow || 0;
clock.advancedTimersIndex = state.advancedTimersIndex || 0;
// If we were ticking and not paused, restore the timer state
if (clock.ticking && !clock.paused && clock.alarmAt > 0) {
const now = Date.now();
if (clock.alarmAt > now) {
// Timer is still running, update seconds to current remaining time
clock.seconds = Math.floor((clock.alarmAt - now) / 1000);
// Restore the badge
await clock.updateBadge(Math.round(clock.seconds / 60));
// Ensure minute alarm is running for badge updates
await browserAPI.alarms.clear("minutes");
await browserAPI.alarms.create("minutes", { "delayInMinutes": 1, "periodInMinutes": 1 });
} else {
// Timer should have already fired, but background script was killed
console.log("Timer expired while background script was inactive, triggering alarm");
await clock.alarm();
}
}
}
} catch (e) {
console.warn("could not load state: " + e);
}
},
offscreenReady: false,
audioQueue: [],
ensureOffscreenDocument: async () => {
if (isManifestV3 && !isFirefox && !clock.offscreenReady) {
try {
// Check if offscreen document already exists
const existingContexts = await chrome.runtime.getContexts({
contextTypes: ['OFFSCREEN_DOCUMENT']
});
if (existingContexts.length === 0) {
await chrome.offscreen.createDocument({
url: 'offscreen.html',
reasons: ['AUDIO_PLAYBACK'],
justification: 'Play notification sound for pomodoro timer'
});
}
clock.offscreenReady = true;
console.log("Offscreen document ready");
} catch (e) {
console.warn("Could not create offscreen document: " + e);
clock.offscreenReady = false;
}
}
},
muteAllOtherTabs: async () => {
// Check if we have tabs permission
const hasPermission = await browserAPI.permissions.contains({ permissions: ['tabs'] });
if (!hasPermission || !clock.muteOtherTabs) {
return [];
}
try {
const tabs = await browserAPI.tabs.query({ audible: true });
const mutedTabs = [];
for (const tab of tabs) {
if (!tab.mutedInfo.muted) {
await browserAPI.tabs.update(tab.id, { muted: true });
mutedTabs.push(tab.id);
console.log(`Muted tab ${tab.id}`);
}
}
return mutedTabs;
} catch (e) {
console.warn("Could not mute tabs: " + e);
return [];
}
},
unmuteTabsById: async (tabIds) => {
if (!tabIds || tabIds.length === 0) {
return;
}
try {
for (const tabId of tabIds) {
try {
await browserAPI.tabs.update(tabId, { muted: false });
console.log(`Unmuted tab ${tabId}`);
} catch (e) {
// Tab might have been closed, ignore error
console.warn(`Could not unmute tab ${tabId}: ` + e);
}
}
} catch (e) {
console.warn("Error unmuting tabs: " + e);
}
},
playNotificationSound: async () => {
// Check if sound is enabled
if (!clock.soundEnabled) {
console.log("Notification sound is disabled, skipping audio");
return;
}
// Mute other tabs if feature is enabled
const mutedTabs = await clock.muteAllOtherTabs();
try {
if (isManifestV3 && !isFirefox) {
// Ensure offscreen document is ready
await clock.ensureOffscreenDocument();
if (clock.offscreenReady) {
// Send message with muted tabs for unmuting after sound ends
chrome.runtime.sendMessage({
type: 'PLAY_SOUND',
soundData: clock.customSound ? clock.customSoundData : null,
volume: clock.volume / 100,
mutedTabs: mutedTabs
}).catch((e) => {
console.warn("Could not send audio message: " + e);
// Unmute tabs if message failed
if (mutedTabs.length > 0) {
clock.unmuteTabsById(mutedTabs);
}
});
} else {
console.warn("Offscreen document not ready, skipping audio");
// Unmute tabs immediately if we can't play sound
if (mutedTabs.length > 0) {
await clock.unmuteTabsById(mutedTabs);
}
}
} else {
// Use direct audio element for Firefox and Manifest V2
// Add fallback for browsers where Audio is not available in service worker context
try {
if (!clock.ring) {
// Check if Audio constructor is available
if (typeof Audio !== 'undefined') {
clock.ring = new Audio();
clock.ring.preload = 'auto';
} else {
throw new Error("Audio constructor not available in service worker context");
}
}
const soundSrc = (clock.customSound && clock.customSoundData)
? clock.customSoundData
: "sound/bell-ringing-02.mp3";
// Only change src if different to avoid reloading
if (clock.ring.src !== soundSrc) {
clock.ring.src = soundSrc;
}
clock.ring.volume = clock.volume / 100;
// Set up onended handler to unmute tabs when sound actually finishes
clock.ring.onended = () => {
if (mutedTabs.length > 0) {
clock.unmuteTabsById(mutedTabs);
}
};
// Play without awaiting to avoid blocking
clock.ring.play().catch((e) => {
console.warn("Could not play audio: " + e);
// Unmute tabs if playback failed
if (mutedTabs.length > 0) {
clock.unmuteTabsById(mutedTabs);
}
});
} catch (audioError) {
console.warn("Audio fallback failed, trying offscreen document approach: " + audioError);
// Fallback: Try to use offscreen document even for non-Manifest V3
try {
await clock.ensureOffscreenDocument();
if (clock.offscreenReady) {
chrome.runtime.sendMessage({
type: 'PLAY_SOUND',
soundData: clock.customSound ? clock.customSoundData : null,
volume: clock.volume / 100,
mutedTabs: mutedTabs
}).catch((e) => {
console.warn("Could not send audio message to offscreen: " + e);
// Final fallback: just unmute tabs
if (mutedTabs.length > 0) {
clock.unmuteTabsById(mutedTabs);
}
});
} else {
console.warn("All audio methods failed, skipping sound");
// Unmute tabs immediately if we can't play sound
if (mutedTabs.length > 0) {
await clock.unmuteTabsById(mutedTabs);
}
}
} catch (offscreenError) {
console.warn("Offscreen fallback also failed: " + offscreenError);
// Final cleanup
if (mutedTabs.length > 0) {
await clock.unmuteTabsById(mutedTabs);
}
}
}
}
} catch (e) {
console.warn("Could not play notification sound: " + e);
// Ensure tabs are unmuted even if there's an error
if (mutedTabs.length > 0) {
await clock.unmuteTabsById(mutedTabs);
}
}
},
alarm: async (alarmOrSkip) => {
await clock.loadOptions();
if (!clock.ticking || clock.paused) {
return true;
}
// Check if this is a skip call (boolean) or an actual alarm object
const isSkip = typeof alarmOrSkip === 'boolean' && alarmOrSkip === true;
const alarm = isSkip ? null : alarmOrSkip;
console.log("Alarm fired - isSkip:", isSkip, "loopDisabled:", clock.loopDisabled, "onABreak:", clock.onABreak, "alarm name:", alarm?.name);
const actionAPI = isManifestV3 ? browserAPI.action : browserAPI.browserAction;
if (alarm && alarm.name === "minutes" && clock.showMinutes) {
clock.seconds = Math.floor((clock.alarmAt - Date.now()) / 1000);
let remaining = Math.round(clock.seconds / 60);
await actionAPI.setBadgeText({ "text": remaining.toString() });
} else if (!alarm || alarm.name !== "minutes") {
// looping is disabled, stop now (but only after a work streak, not a break)
if (clock.loopDisabled && !clock.onABreak) {
console.log("Single streak mode: stopping after work streak completion");
// Track streak minutes for today
if (isSkip) {
// For skip: track actual elapsed time
const elapsedMinutes = clock.getElapsedStreakMinutes();
if (elapsedMinutes > 0) {
await clock.addDailyStreakMinutes(elapsedMinutes);
}
} else {
// For natural completion: track full streak duration
await clock.addDailyStreakMinutes(clock.streakTimer);
}
// Play notification sound
if (clock.soundEnabled) {
clock.playNotificationSound();
}
try {
let text = ("Good, another " + clock.streakTimer + " minutes streak done!");
let notifDetail = {
type: "basic",
title: "Ding!",
iconUrl: "icons/clock-48.png",
message: text
};
await browserAPI.notifications.create(notifDetail);
console.log("Single streak notification created:", text);
} catch (e) {
console.warn("could not display notification: " + e);
}
console.log("Resetting timer after single streak completion");
await clock.reset();
return true;
}
console.log("Not in single streak mode or on a break, continuing with normal cycle");
if (!clock.onABreak) {
clock.inARow++;
// Track streak minutes for today
if (isSkip) {
// For skip: track actual elapsed time
const elapsedMinutes = clock.getElapsedStreakMinutes();
if (elapsedMinutes > 0) {
await clock.addDailyStreakMinutes(elapsedMinutes);
}
} else {
// For natural completion: track full streak duration
await clock.addDailyStreakMinutes(clock.streakTimer);
}
}
clock.onABreak = !clock.onABreak;
db.addEvent("switched");
// Play notification sound (don't await to avoid delays)
clock.playNotificationSound();
let minutes;
if (clock.useAdvancedTimers
&& clock.advancedTimers
&& clock.advancedTimers.length > 0) {
if (clock.advancedTimersIndex >= clock.advancedTimers.length) {
// at the end of the array
clock.advancedTimersIndex = 0;
clock.onABreak = false;
}
minutes = (clock.advancedTimers[clock.advancedTimersIndex] ? clock.advancedTimers[clock.advancedTimersIndex] : 1);
clock.advancedTimersIndex++;
} else {
minutes = (clock.onABreak ? clock.pauseTimer : clock.streakTimer);
}
clock.seconds = minutes * 60;
clock.timeStarted = Date.now();
clock.alarmAt = clock.timeStarted + (clock.seconds * 1000);
await clock.updateBadge(minutes);
await browserAPI.alarms.clear("alarm");
await browserAPI.alarms.create("alarm", { "when": clock.alarmAt });
await browserAPI.alarms.clear("minutes");
await browserAPI.alarms.create("minutes", { "delayInMinutes": 1, "periodInMinutes": 1 });
await clock.saveState();
try {
let text = (clock.onABreak ? "Time for a " + minutes + " min break" : "Ready for a new " + minutes + " min streak?");
let notifDetail = {
type: "basic",
title: "Ding!",
iconUrl: "icons/clock-48.png",
message: text
};
await browserAPI.notifications.create(notifDetail);
} catch (e) {
console.warn("could not display notification: " + e);
}
}
return true;
}
};
// Load saved timer settings from storage
const loadTimerSettings = async () => {
try {
const result = await browserAPI.storage.local.get(['streakTimer', 'pauseTimer', 'advancedTimers']);
clock.streakTimer = result.streakTimer || 30;
clock.seconds = clock.streakTimer * 60;
clock.pauseTimer = result.pauseTimer || 5;
clock.advancedTimers = result.advancedTimers || [30, 5];
} catch (e) {
console.warn("could not load timer settings from storage, trying localStorage: " + e);
// Fallback to localStorage
if (typeof localStorage !== 'undefined') {
clock.streakTimer = 30;
if (parseInt(localStorage.streakTimer)) {
clock.streakTimer = parseInt(localStorage.streakTimer);
clock.seconds = clock.streakTimer * 60;
}
clock.pauseTimer = 5;
if (parseInt(localStorage.pauseTimer)) {
clock.pauseTimer = parseInt(localStorage.pauseTimer);
}
clock.advancedTimers = [30, 5];
if (localStorage.advancedTimers) {
try {
clock.advancedTimers = JSON.parse(localStorage.advancedTimers);
} catch (e) {
console.error("Unable to parse the localStorage value for advancedTimers");
console.error(e);
}
}
}
}
};
/**
* Message listener
* @param {Object} message message received
*/
const msgListener = (message, sender, sendResponse) => {
console.log("received message from browser action: " + JSON.stringify(message));
// Handle async operations with proper response handling
const handleAsync = async () => {
// Ensure background script is fully initialized before handling any messages
if (!clock.initialized) {
console.log("Background script not initialized, initializing now...");
await initializeBackgroundScript();
}
// Handle unmute request from offscreen document
if (message.type === 'UNMUTE_TABS' && message.mutedTabs) {
await clock.unmuteTabsById(message.mutedTabs);
sendResponse({ success: true });
return;
}
if (message && ((message.streakTimer && message.pauseTimer) || message.advancedTimers || message.loopDisabled !== undefined)) {
// Validate and set streak timer
if (message.streakTimer && !isNaN(message.streakTimer) && message.streakTimer > 0) {
clock.streakTimer = message.streakTimer;
}
// Validate and set pause timer
if (message.pauseTimer && !isNaN(message.pauseTimer) && message.pauseTimer > 0) {
clock.pauseTimer = message.pauseTimer;
}
// Set loopDisabled setting
if (message.loopDisabled !== undefined) {
clock.loopDisabled = message.loopDisabled;
}
// Validate and set advanced timers
if (message.advancedTimers && Array.isArray(message.advancedTimers)) {
// Filter out invalid values
const validTimers = message.advancedTimers.filter(timer =>
!isNaN(timer) && timer > 0
);
if (validTimers.length > 0) {
clock.advancedTimers = validTimers;
} else {
console.warn("No valid timers in advancedTimers, keeping current:", clock.advancedTimers);
}
}
try {
await browserAPI.storage.local.set({
streakTimer: clock.streakTimer,
pauseTimer: clock.pauseTimer,
advancedTimers: clock.advancedTimers
});
} catch (e) {
console.warn("could not save timer settings to storage, trying localStorage: " + e);
// Fallback to localStorage
if (typeof localStorage !== 'undefined') {
localStorage.streakTimer = clock.streakTimer;
localStorage.pauseTimer = clock.pauseTimer;
localStorage.advancedTimers = JSON.stringify(clock.advancedTimers);
}
}
}
if (message.command === "getCurrentState") {
const state = await clock.getCurrentState();
sendResponse(state);
} else if (message.command === "start") {
await clock.start();
sendResponse(true);
} else if (message.command === "skip") {
await clock.alarm(true); // Pass true to indicate this is a skip
sendResponse(true);
} else if (message.command === "reset") {
await clock.reset();
sendResponse(true);
} else if (message.command === "pause") {
await clock.pause();
sendResponse(true);
} else if (message.command === "addMinute") {
await clock.addMinute(message.minutes);
sendResponse(true);
} else if (message.command === "getStats") {
const stats = await db.getStats();
sendResponse(stats);
} else if (message.command === "getStreakHistory") {
const history = await clock.getStreakHistory();
sendResponse(history);
}
};
// Execute async operations
handleAsync().catch((error) => {
console.error("Message handler error:", error);
sendResponse(false);
});
return true; // Keep message channel open for async response
};
// Initialize background script
browserAPI.runtime.onMessage.addListener(msgListener);
browserAPI.alarms.onAlarm.addListener(clock.alarm);
browserAPI.storage.onChanged.addListener(clock.loadOptions);
// Check for version updates and show news if needed
const checkForUpdates = async () => {
try {
const manifest = chrome.runtime.getManifest ? chrome.runtime.getManifest() : browser.runtime.getManifest();
const currentVersion = manifest.version;