Repository navigation
Expand file tree
/
Copy pathserviceWorker.js
More file actions
1428 lines (1223 loc) · 60.3 KB
/
Copy pathserviceWorker.js
File metadata and controls
1428 lines (1223 loc) · 60.3 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
self.importScripts('js/praytimes.js', 'js/functions.js', 'js/quran-shared.js', 'js/quran-surahs.js');
chrome.runtime.onInstalled.addListener(async () => { await start() });
chrome.runtime.onStartup.addListener(async () => { await run('onStartUp') });
chrome.alarms.onAlarm.addListener(async (alarm) => { await run('via alarm:' + alarm.name + ' at ' + Date.now()) }); /* every minute */
self.addEventListener('message', async (msg) => {
if ('goGoRun' in msg.data) {
await run('run via message')
}
else if ('endAdhanCall' in msg.data) {
await endAdhanCall();
}
else if ('quranToggle' in msg.data) {
await quranToggle();
}
else if ('quranSelectSurah' in msg.data) { /* pick a surah from the list — cue it up, don't play */
quranErrorStreak = 0;
await quranSelectSurah(msg.data.quranSelectSurah);
}
else if ('quranNext' in msg.data) {
quranErrorStreak = 0;
await quranStep(1);
}
else if ('quranPrev' in msg.data) {
quranErrorStreak = 0;
await quranStep(-1);
}
else if ('quranSeek' in msg.data) { /* drag the progress bar */
await quranSeek(msg.data.quranSeek);
}
else if ('quranReload' in msg.data) { /* reciter changed → stop (new reciter loads on next play) */
await quranReload();
}
else if ('quranStop' in msg.data) {
await quranStopAll();
}
else if ('quranPauseOnly' in msg.data) { /* previewing an adhan sound in settings interrupts Qur'an playback */
await quranPauseOnly();
}
else if ('quranSetVolume' in msg.data) {
await quranSetVolume(msg.data.quranSetVolume);
}
});
/* Offscreen player (js/quran.js) → SW. It uses chrome.runtime.sendMessage (not
serviceWorker.controller.postMessage) because that reliably wakes a stopped MV3 service
worker; otherwise `quranEnded` was dropped on longer surahs (no advance / auto-complete).
Return true + sendResponse keeps the worker alive until the async handler finishes. */
/* TEMP TRACE (remove after debugging long-surah completion): throttle progress logs so the
console shows pings still arriving + position advancing, without flooding. */
let quranDbgLastProg = 0;
function quranDbg(m) { try { console.log('[qdbg] ' + m + ' @' + new Date().toLocaleTimeString()); } catch (e) { } }
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (!msg || typeof msg !== 'object') return;
if ('quranDbg' in msg) { quranDbg('OFFSCREEN ' + msg.quranDbg); return; }
if ('quranEnded' in msg) { quranDbg('SW recv quranEnded'); quranAdvance().catch((e) => quranDbg('SW quranAdvance ERROR ' + e)).finally(() => { try { sendResponse({}); } catch (e) { } }); return true; }
if ('quranError' in msg) { quranHandleError().finally(() => { try { sendResponse({}); } catch (e) { } }); return true; }
if ('quranProgress' in msg) {
const p = msg.quranProgress || {};
const now = Date.now();
if (now - quranDbgLastProg >= 15000) { quranDbgLastProg = now; quranDbg('SW recv progress surah=' + p.surah + ' t=' + (p.currentTime || 0).toFixed(0) + '/' + (p.duration || 0).toFixed(0) + ' playing=' + p.isPlaying); }
quranPersistProgress(p).finally(() => { try { sendResponse({}); } catch (e) { } }); return true;
}
});
let appData = {};
let adhanStatus = {};
let currentVakit;
let currentTime;
let currentTimeString;
let prayerTimes;
let hijriCurrentTime;
let hijriDate;
let nextVakit;
let totalMinutesInVakit;
let remainingMinutesInVakit;
let aroundTheClock;
let iconColor;
let badgeBackgroundColor;
let iconTextColor;
let clockFaceVakit;
let quranPlaying = false; /* true while a surah is playing → toolbar icon becomes the pause button */
let quranPlayingSurah = 1; /* current surah number, for the "now playing" tooltip */
const r = 160;
const ir = 12;
const iconSize = 128;
const colors = { black: '#212529', silver: 'whitesmoke', tomato: '#F20031', gray: '#2E3338' };
const QURAN_GREEN = '#22c55e'; /* the pause bars drawn on the toolbar icon while the Qur'an plays */
const ADHAN_RED = colors.tomato; /* the pause bars drawn on the toolbar icon while an adhan/alarm calls (matches the red #stopAdhanDiv stop button) */
const ctx = new OffscreenCanvas(470, 470).getContext("2d", { alpha: true, willReadFrequently: true });
const itx = new OffscreenCanvas(iconSize, iconSize).getContext("2d", { alpha: true, willReadFrequently: true });
const btx = new OffscreenCanvas(iconSize, iconSize).getContext("2d", { alpha: true, willReadFrequently: true });
const ptx = new OffscreenCanvas(iconSize, iconSize).getContext("2d", { alpha: true, willReadFrequently: true }); /* Qur'an "pause" toolbar icon */
const defaultAdhanSettings = { fajr: 12, dhuhr: 7, asr: 3, maghrib: 6, isha: 1 };
async function run(info) {
appData = (await chrome.storage.local.get(['appData'])).appData;
if (!appData) {
return start();
}
let asResult = await chrome.storage.local.get(['adhanStatus']);
if (asResult.adhanStatus)
adhanStatus = asResult.adhanStatus;
/* Sync the Qur'an-playing flag from storage so the toolbar icon is correct even after the
service worker was suspended while the offscreen player kept playing. */
let qsResult = await chrome.storage.local.get(['quranState']);
quranPlaying = !!(qsResult.quranState && qsResult.quranState.isPlaying);
quranPlayingSurah = (qsResult.quranState && qsResult.quranState.currentSurah) || 1;
/* in case all chrome windows are closed during an adhan call */
let isOffscreenDocAvailable = await offScreenDocumentAvailable();
if (adhanStatus.isBeingCalled && !isOffscreenDocAvailable) {
adhanStatus.isBeingCalled = false;
await chrome.storage.local.set({ 'adhanStatus': adhanStatus });
}
/* If quranState says it was playing (or waiting to resume after an adhan) but there is no
offscreen document, that audio can't actually be running — the doc is destroyed on
reload/update or browser restart while quranState persists. Clear the stale flags so the
toolbar icon isn't stuck on pause and no spurious resume fires after the next adhan. */
if (!isOffscreenDocAvailable && qsResult.quranState &&
(qsResult.quranState.isPlaying || qsResult.quranState.wasPlayingBeforeAdhan)) {
quranPlaying = false;
const staleState = qsResult.quranState;
staleState.isPlaying = false;
staleState.wasPlayingBeforeAdhan = false;
await chrome.storage.local.set({ quranState: staleState });
}
let lastRunMS = new Date().getTime() - (appData.lastRun ?? 0);
if (lastRunMS < 700 && info && info.indexOf('alarm') > 0) { return }
populateVakitsAndVars();
clearCanvas(ctx);
updateClock(ctx, r);
clearCanvas(itx);
updateIcon(itx, ir * iconSize / 38);
clearCanvas(btx);
updateBar(btx, ir * iconSize / 38);
extensionOps();
}
async function start() {
let i18nValues = {};
let navLang = navigator.language;
let lang = languages.some(f => f.code == navLang) ? navLang : 'en';
appData = (await chrome.storage.local.get(['appData'])).appData ?? (await chrome.storage.local.get(['appSettings'])).appSettings;
await chrome.storage.local.remove('appSettings');
await chrome.storage.local.set({ 'appData': appData }); /* temp renaming fix, remove later */
if (appData && appData.i18n) {
let lc = appData.i18n.languageCode;
lang = (languages.some(f => f.code == lc)) ? lc : 'en';
}
const response = await fetch(`../_locales/${lang}/messages.json`);
if (!response.ok) {
throw new Error(`Failed to fetch language messages: ${response.status} ${response.statusText}`);
}
const data = await response.json();
Object.entries(data).forEach(([key, value]) => { i18nValues[key] = value.message });
await initUser(i18nValues, appData);
}
async function initUser(i18nValues, appData) {
try {
if (appData) {
/* existing user: new version */
appData.settings ??= {
address: appData.address,
calculationMethod: appData.calculationMethod,
lat: appData.lat,
lng: appData.lng,
timeZoneID: appData.timeZoneID,
timeFormat: appData.timeFormat,
iconStyle: appData.iconStyle,
desktopNotifications: appData.desktopNotifications,
adhans: appData.adhans,
vakitOffsets: appData.vakitOffsets,
areAdhansEnabled: appData.areAdhansEnabled,
hanafiAsr: appData.hanafiAsr,
showImsak: appData.showImsak,
showDuha: appData.showDuha,
showMidnight: appData.showMidnight,
volume: appData.volume,
hijriDateOffset: appData.hijriDateOffset
};
delete appData.address;
delete appData.calculationMethod;
delete appData.lat;
delete appData.lng;
delete appData.timeZoneID;
delete appData.timeFormat;
delete appData.iconStyle;
delete appData.desktopNotifications;
delete appData.adhans;
delete appData.vakitOffsets;
delete appData.areAdhansEnabled;
delete appData.hanafiAsr;
delete appData.showImsak;
delete appData.showDuha;
delete appData.showMidnight;
delete appData.volume;
delete appData.hijriDateOffset;
delete appData.r;
appData.i18n = i18nValues;
if (!appData.settings.adhans) {
appData.settings.adhans = defaultAdhanSettings;
}
if (!appData.settings.areAdhansEnabled) {
appData.settings.areAdhansEnabled = false;
}
if (!appData.settings.hanafiAsr) {
appData.settings.hanafiAsr = false;
}
if (!appData.settings.volume) {
appData.settings.volume = 5;
}
if (!appData.settings.alarms) {
appData.settings.alarms = [];
}
if (!appData.settings.naflAlarms) {
appData.settings.naflAlarms = [];
}
if (!appData.settings.calcAngleFixApplied) {
appData.settings.calcAngleFixApplied = true;
if (calcAngleUpdatedMethods.includes(appData.settings.calculationMethod)) {
appData.settings.vakitOffsets = {};
await chrome.storage.local.set({ calcAngleNotice: { method: appData.settings.calculationMethod } });
}
}
await chrome.storage.local.set({ 'appData': appData });
await initAlarm();
}
else {
/* new user: first installation */
const response = await fetch('https://smartazanclock.com/iplocation', { method: 'POST' });
if (!response.ok) {
throw new Error(`Failed to fetch IP location: ${response.status} ${response.statusText}`);
}
const data = await response.json();
let settings = {
address: data.address,
calculationMethod: i18nValues.defaultMethod,
lat: data.lat,
lng: data.lng,
timeZoneID: data.timeZoneID,
timeFormat: 12,
iconStyle: 'badge',
desktopNotifications: true,
adhans: defaultAdhanSettings,
areAdhansEnabled: false,
hanafiAsr: false,
showImsak: false,
showDuha: false,
showMidnight: false,
volume: 5,
calcAngleFixApplied: true,
alarms: [],
naflAlarms: []
}
let appData = {
settings: settings,
i18n: i18nValues,
};
await chrome.storage.local.set({ 'appData': appData });
}
} catch (error) {
await initDefaultUser(i18nValues);
}
await initAlarm();
}
async function initDefaultUser(i18nValues) {
let appData = { i18n: i18nValues, settings: {} };
appData.settings.address = "Al-Masjid An-Nabawi"; /* صلى الله عليه وعلى آله وسلم */
appData.settings.lat = 24.4672105;
appData.settings.lng = 39.611131;
appData.settings.timeZoneID = "Asia/Riyadh";
appData.settings.calculationMethod = 'Makkah';
appData.settings.iconStyle = 'badge';
appData.settings.desktopNotifications = true;
appData.settings.hanafiAsr = false;
appData.settings.showImsak = false;
appData.settings.showDuha = false;
appData.settings.showMidnight = false;
appData.settings.adhans = defaultAdhanSettings;
appData.settings.areAdhansEnabled = false;
appData.settings.volume = 5;
appData.settings.calcAngleFixApplied = true;
appData.settings.alarms = [];
appData.settings.naflAlarms = [];
await chrome.storage.local.set({ 'appData': appData });
}
/* TEMP (testing only — delete before release): clear the one-time calc-angle
migration guard and re-run it. Call from the service worker console: resetCalcAngleFix() */
async function resetCalcAngleFix() {
const stored = (await chrome.storage.local.get('appData')).appData;
if (stored && stored.settings) delete stored.settings.calcAngleFixApplied;
await chrome.storage.local.set({ 'appData': stored });
await chrome.storage.local.remove('calcAngleNotice');
await start();
const after = await chrome.storage.local.get(['appData', 'calcAngleNotice']);
console.log('resetCalcAngleFix:', {
method: after.appData && after.appData.settings && after.appData.settings.calculationMethod,
calcAngleFixApplied: after.appData && after.appData.settings && after.appData.settings.calcAngleFixApplied,
vakitOffsets: after.appData && after.appData.settings && after.appData.settings.vakitOffsets,
calcAngleNotice: after.calcAngleNotice
});
return after;
}
async function initAlarm() {
run('onInstall');
let w = new Date();
w.setMinutes(w.getMinutes() + 1);
w.setSeconds(0);
w.setMilliseconds(0);
await chrome.alarms.create('everyMinute', { periodInMinutes: 1, when: Date.parse(w) });
}
function clearCanvas(canvas) {
canvas.save();
canvas.translate(0, 0);
canvas.clearRect(0, 0, canvas.canvas.width, canvas.canvas.height);
canvas.restore();
return this;
}
function populateVakitsAndVars() {
/* get prayer times */
prayTimes.setMethod(appData.settings.calculationMethod);
if (appData.settings.hanafiAsr)
prayTimes.adjust({ asr: 'Hanafi' });
else
prayTimes.adjust({ asr: 'Standard' });
let baseTuneValues = { imsak: 0, sunrise: 0, duha: 0, duhaend: 0, fajr: 0, dhuhr: 0, asr: 0, maghrib: 0, isha: 0 }
let methodDefaultTuneValues = methods.find(f => f.id == appData.settings.calculationMethod).methodOffsets;
tuneValues = { ...baseTuneValues, ...methodDefaultTuneValues }
if (appData.settings.vakitOffsets) {
if (appData.settings.vakitOffsets.imsak)
tuneValues.imsak += appData.settings.vakitOffsets.imsak;
if (appData.settings.vakitOffsets.fajr)
tuneValues.fajr += appData.settings.vakitOffsets.fajr;
if (appData.settings.vakitOffsets.duha)
tuneValues.duha += appData.settings.vakitOffsets.duha;
if (appData.settings.vakitOffsets.duhaend)
tuneValues.duhaend += appData.settings.vakitOffsets.duhaend;
if (appData.settings.vakitOffsets.dhuhr)
tuneValues.dhuhr += appData.settings.vakitOffsets.dhuhr;
if (appData.settings.vakitOffsets.asr)
tuneValues.asr += appData.settings.vakitOffsets.asr;
if (appData.settings.vakitOffsets.maghrib)
tuneValues.maghrib += appData.settings.vakitOffsets.maghrib;
if (appData.settings.vakitOffsets.isha)
tuneValues.isha += appData.settings.vakitOffsets.isha;
}
prayTimes.tune({ imsak: tuneValues.imsak, fajr: tuneValues.fajr, sunrise: tuneValues.sunrise, duha: tuneValues.duha, duhaend: tuneValues.duhaend, dhuhr: tuneValues.dhuhr, asr: tuneValues.asr, maghrib: tuneValues.maghrib, isha: tuneValues.isha });
currentTime = new Date(new Date().toLocaleString("en-US", { timeZone: appData.settings.timeZoneID }));
currentTimeString = currentTime.getHours() + ':' + fillInZeros(currentTime.getMinutes());
prayerTimes = prayTimes.getTimes(currentTime, [appData.settings.lat, appData.settings.lng, 0], getOffsetHoursFromTimeZone(appData.settings.timeZoneID), 0, '24h');
appData.timeNow24 = currentTimeString;
appData.timeNow = format12(currentTimeString);
appData.fajrAngle = prayTimes.getDefaults()[appData.settings.calculationMethod].params.fajr;
if (appData.fajrAngle.toString().indexOf('min') < 0)
appData.fajrAngle += '°';
appData.ishaAngle = prayTimes.getDefaults()[appData.settings.calculationMethod].params.isha;
if (appData.ishaAngle.toString().indexOf('min') < 0)
appData.ishaAngle += '°';
hijriCurrentTime = new Date(currentTime);
if (appData.settings.hijriDateOffset)
hijriCurrentTime = addDaysToDate(hijriCurrentTime, appData.settings.hijriDateOffset);
hijriDate = new Intl.DateTimeFormat((appData.i18n.languageCode ?? navigator.language), { calendar: 'islamic-umalqura', day: 'numeric', month: 'long', year: 'numeric' }).format(hijriCurrentTime);
let aVakits = [];
let vakits = [];
imsakVakit = new Vakit('Imsak', getPrayerTime('imsak'), getPrayerTime('fajr'), currentTimeString, appData.settings.timeFormat);
fajrVakit = new Vakit('Fajr', getPrayerTime('fajr'), getPrayerTime('sunrise'), currentTimeString, appData.settings.timeFormat);
sunriseDuhaVakit = new Vakit('Sunrise', getPrayerTime('sunrise'), getPrayerTime('duha'), currentTimeString, appData.settings.timeFormat);
sunriseDhuhrVakit = new Vakit('Sunrise', getPrayerTime('sunrise'), getPrayerTime('dhuhr'), currentTimeString, appData.settings.timeFormat);
duhaVakit = new Vakit('Duha', getPrayerTime('duha'), getPrayerTime('duhaend'), currentTimeString, appData.settings.timeFormat);
duhaendVakit = new Vakit('Duhaend', getPrayerTime('duhaend'), getPrayerTime('dhuhr'), currentTimeString, appData.settings.timeFormat);
dhuhrVakit = new Vakit('Dhuhr', getPrayerTime('dhuhr'), getPrayerTime('asr'), currentTimeString, appData.settings.timeFormat);
asrVakit = new Vakit('Asr', getPrayerTime('asr'), getPrayerTime('maghrib'), currentTimeString, appData.settings.timeFormat);
maghribVakit = new Vakit('Maghrib', getPrayerTime('maghrib'), getPrayerTime('isha'), currentTimeString, appData.settings.timeFormat);
ishaImsakVakit = new Vakit('Isha', getPrayerTime('isha'), getPrayerTime('imsak'), currentTimeString, appData.settings.timeFormat);
ishaFajrVakit = new Vakit('Isha', getPrayerTime('isha'), getPrayerTime('fajr'), currentTimeString, appData.settings.timeFormat);
ishaMidnightVakit = new Vakit('Isha', getPrayerTime('isha'), getPrayerTime('midnight'), currentTimeString, appData.settings.timeFormat);
midnightFajrVakit = new Vakit('Midnight', getPrayerTime('midnight'), getPrayerTime('fajr'), currentTimeString, appData.settings.timeFormat);
midnightImsakVakit = new Vakit('Midnight', getPrayerTime('midnight'), getPrayerTime('imsak'), currentTimeString, appData.settings.timeFormat);
aVakits.push(imsakVakit);
aVakits.push(fajrVakit);
aVakits.push(sunriseDuhaVakit);
aVakits.push(duhaVakit);
aVakits.push(duhaendVakit);
aVakits.push(dhuhrVakit);
aVakits.push(asrVakit);
aVakits.push(maghribVakit);
aVakits.push(ishaMidnightVakit);
aVakits.push(midnightImsakVakit);
if (appData.settings.showImsak) {
vakits.push(imsakVakit);
}
vakits.push(new Vakit('Fajr', getPrayerTime('fajr'), getPrayerTime('sunrise'), currentTimeString, appData.settings.timeFormat));
if (appData.settings.showDuha) {
vakits.push(sunriseDuhaVakit);
vakits.push(duhaVakit);
vakits.push(duhaendVakit);
}
else {
vakits.push(sunriseDhuhrVakit);
}
vakits.push(dhuhrVakit);
vakits.push(asrVakit);
vakits.push(maghribVakit);
if (appData.settings.showMidnight) {
vakits.push(ishaMidnightVakit);
if (appData.settings.showImsak)
vakits.push(midnightImsakVakit);
else
vakits.push(midnightFajrVakit);
}
else {
if (appData.settings.showImsak)
vakits.push(ishaImsakVakit);
else
vakits.push(ishaFajrVakit);
}
let cvi = vakits.findIndex(a => a.isCurrentVakit);
currentVakit = vakits[cvi];
nextVakit = vakits[(cvi + 1) % vakits.length];
cavi = aVakits.findIndex(a => a.isCurrentVakit);
currentAllVakit = aVakits[cavi];
appData.currentVakitAdhanAudioID = appData.settings.adhans[currentVakit.name.toLowerCase()] ?? 0;
totalMinutesInVakit = diffMinutesBetweenTimes(currentVakit.time24, nextVakit.time24);
aroundTheClock = totalMinutesInVakit >= 720;
remainingMinutesInVakit = diffMinutesBetweenTimes(currentTimeString, nextVakit.time24);
appData.isLastHour = false;
if (remainingMinutesInVakit <= 60)
appData.isLastHour = true;
appData.lastHourHilite = appData.lastHourHilite ?? 1;
if (appData.isLastHour && appData.lastHourHilite == 1) {
iconColor = colors.tomato;
badgeBackgroundColor = colors.tomato;
iconTextColor = colors.silver;
}
else {
iconColor = colors.silver;
badgeBackgroundColor = colors.gray;
iconTextColor = colors.gray;
}
clockFaceVakit = appData.i18n[currentVakit.name.toLowerCase() + 'Text'];
if (currentVakit.name === "Duhaend")
clockFaceVakit = "";
if (currentVakit.name === "Sunrise" && currentAllVakit.name !== "Sunrise")
clockFaceVakit = "";
if (currentVakit.name === "Midnight")
clockFaceVakit = appData.i18n['ishaText'];
if (appData.i18n.languageCode == "en" && clockFaceVakit)
clockFaceVakit = clockFaceVakit.toUpperCase();
let appVakits = [];
for (let i = 0; i < vakits.length; i++) {
appVakits.push(vakits[i]);
}
let allVakits = [];
for (let i = 0; i < aVakits.length; i++) {
allVakits.push(aVakits[i]);
}
appData.isJumua = false;
if (currentTime.getDay() === 5)
appData.isJumua = true;
appData.appVakits = appVakits;
appData.allVakits = allVakits;
return this;
}
function updateIcon(canvas, r) {
canvas.save();
canvas.translate(canvas.canvas.width * 0.5, canvas.canvas.height * 0.5);
fillCircle(canvas, r * 1.5, 0, 0, iconColor);
if (aroundTheClock) {
drawArc(canvas, 0, 2 * Math.PI + Math.PI / 40, r * 1.05, r / 3, iconTextColor);
drawHand(canvas, nextVakit.startAngle12, r * 0.9, r * 1.13, r / 4, iconColor);
}
else {
drawArc(canvas, currentVakit.startAngle12, currentVakit.endAngle12, r * 1.05, r / 3, iconTextColor);
}
drawArrow(canvas, hoursToRadians(hours12(currentTime.getHours()) * 60 + currentTime.getMinutes()), 0, r * 0.21, r * 0.81, iconTextColor);
fillCircle(canvas, r * 0.19, 0, 0, iconTextColor);
canvas.restore();
return this;
}
function updateClock(canvas, r) {
canvas.save();
let arcLineWidth = r / 15;
canvas.translate(canvas.canvas.width * 0.5, canvas.canvas.height * 0.5);
/*
if (currentVakit.name == 'Sunrise' || currentVakit.name == 'Duha' || currentVakit.name == 'Duhaend') {
drawArc(canvas, sunriseDhuhrVakit.startAngle12, sunriseDhuhrVakit.endAngle12, r * 1.19, arcLineWidth, colors.gray);
}
*/
if (aroundTheClock) {
drawArc(canvas, 0, 2 * Math.PI + Math.PI / 40, r * 1.19, arcLineWidth, colors.silver);
drawHand(canvas, nextVakit.startAngle12, r * 1.15, r * 1.22, arcLineWidth / 1.7, colors.gray);
}
else {
drawArc(canvas, currentVakit.startAngle12, currentVakit.endAngle12, r * 1.19, arcLineWidth, colors.silver);
}
if (currentVakit.name === 'Isha' || currentVakit.name === 'Midnight') {
if (!appData.settings.showImsak)
drawArc(canvas, ishaFajrVakit.startAngle12, ishaFajrVakit.endAngle12, r * 1.19, arcLineWidth, colors.silver);
else
drawArc(canvas, ishaImsakVakit.startAngle12, ishaImsakVakit.endAngle12, r * 1.19, arcLineWidth, colors.silver);
let fractionTextSize = r * 0.13;
let totalMinutesInIsha = diffMinutesBetweenTimes(getPrayerTime('maghrib'), getPrayerTime('fajr'));
let oneThird = totalMinutesInIsha / 3;
let twoThird = oneThird * 2;
appData.twoThirdTime = addMinutesToTime(getPrayerTime('maghrib'), twoThird);
if (appData.settings.timeFormat === 12)
appData.twoThirdTime = format12(appData.twoThirdTime)
let midnightRadians = timeToRadians(getPrayerTime('midnight'), 12);
drawHand(canvas, midnightRadians, r * 1.15, r * 1.22, arcLineWidth / 1.7, colors.gray);
printAt(canvas, '1/2', fractionTextSize, colors.silver, r, midnightRadians);
let oneThirdRadians = timeToRadians(getPrayerTime('maghrib'), 12) + oneThird * 2 * Math.PI / 720;
drawHand(canvas, oneThirdRadians, r * 1.15, r * 1.22, arcLineWidth / 1.7, colors.gray);
printAt(canvas, '1/3', fractionTextSize, colors.silver, r, oneThirdRadians);
let twoThirdRadians = timeToRadians(getPrayerTime('maghrib'), 12) + twoThird * 2 * Math.PI / 720;
drawHand(canvas, twoThirdRadians, r * 1.15, r * 1.22, arcLineWidth / 1.7, colors.gray);
printAt(canvas, '2/3', fractionTextSize, colors.silver, r, twoThirdRadians);
}
markAlarms(canvas, r);
let hourRadians = hoursToRadians(hours12(currentTime.getHours()) * 60 + currentTime.getMinutes());
let minuteRadians = minutesToRadians(currentTime.getMinutes());
let secondRadians = secondsToRadians(currentTime.getSeconds());
drawHand(canvas, hourRadians, -r * 0.05, r * 0.7, arcLineWidth, colors.silver);
drawHand(canvas, minuteRadians, -r * 0.05, r * 1.05, arcLineWidth, colors.silver);
drawHand(canvas, secondRadians, -r * 0.1, r * 1.1, arcLineWidth / 4, colors.silver);
fillCircle(canvas, r * 0.02, 0, 0, colors.gray);
drawNumbers12(canvas, r * 1.01, colors.silver);
if (clockFaceVakit) {
let topHands = handOnTop(hourRadians) || handOnTop(minuteRadians);
let bottomHands = handOnBottom(hourRadians) || handOnBottom(minuteRadians);
if (topHands && !bottomHands)
print(canvas, clockFaceVakit, 27, colors.silver, r * 0.5);
else
print(canvas, clockFaceVakit, 27, colors.silver, -r * 0.5);
}
canvas.restore();
return this;
}
function updateBar(canvas, r) {
let barColor = iconColor;
if (appData.isLastHour && appData.lastHourHilite == 1) {
barColor = colors.tomato;
}
let scale = canvas.canvas.width / 38;
let iWidth = 38 * scale;
let iHeight = 16 * scale;
let borderPadding = 1.8 * scale;
let actualWidth = iWidth - 2 * borderPadding;
let actualHeight = iHeight - 2 * borderPadding;
let remainingWidth = remainingMinutesInVakit * (actualWidth - 2 * borderPadding) / totalMinutesInVakit;
if (remainingWidth < 4)
remainingWidth = 4;
canvas.save();
canvas.beginPath();
canvas.rect(0, 0, iWidth, iHeight);
canvas.fillStyle = colors.silver;
canvas.fill();
canvas.restore();
canvas.save();
canvas.beginPath();
canvas.rect(borderPadding, borderPadding, actualWidth, actualHeight);
canvas.fillStyle = colors.gray;
canvas.fill();
canvas.restore();
canvas.save();
canvas.beginPath();
canvas.rect(borderPadding * 2, borderPadding * 2, remainingWidth, actualHeight - 2 * borderPadding);
canvas.fillStyle = barColor;
canvas.fill();
canvas.restore();
canvas.save();
canvas.translate(canvas.canvas.width * 0.5, canvas.canvas.height * 0.5);
print(canvas, currentVakit.nextVakitIn, r * 1.1, colors.silver, r * 0.85);
canvas.restore();
return this;
}
/* Create a desktop notification.
On macOS, Chrome hands the notification to the system Notification Center,
which silently drops the rich "image" type WITHOUT setting
chrome.runtime.lastError — so an image notification simply never appears and
no error-based fallback can catch it. Use a plain "basic" notification on
macOS; keep the image (with a basic fallback) on Windows/Linux where it
renders correctly. */
function showNotification(id, title, message) {
chrome.notifications.clear(id);
let base = { iconUrl: 'images/icons/128.png', title: title, message: message };
if (navigator.userAgent.includes('Macintosh')) {
chrome.notifications.create(id, Object.assign({ type: 'basic' }, base));
return;
}
chrome.notifications.create(id, Object.assign({ type: 'image', imageUrl: 'images/notification.jpg' }, base), () => {
if (chrome.runtime.lastError)
chrome.notifications.create(id, Object.assign({ type: 'basic' }, base));
});
}
/* The popup calls run() every second; clearing and re-setting the badge on each run made it
visibly flicker. Only touch the badge when its text or color actually changes. */
let lastBadgeText = null;
let lastBadgeColor = null;
function setBadge(text, color) {
if (text !== lastBadgeText) {
chrome.action.setBadgeText({ 'text': text });
lastBadgeText = text;
}
if (text && color !== lastBadgeColor) {
chrome.action.setBadgeBackgroundColor({ 'color': color });
lastBadgeColor = color;
}
}
function extensionOps() {
let isRamadan = false;
let enHijriDate = new Intl.DateTimeFormat('en', { calendar: 'islamic-umalqura', day: 'numeric', month: 'long', year: 'numeric' }).format(hijriCurrentTime);
if (enHijriDate.indexOf('Ramadan') >= 0)
isRamadan = true;
let elapsedText = appData.i18n.elapsedTimeTitle + ' ' + diffBetweenTimes(currentVakit.time24, currentTimeString);
let nextText = currentVakit.nextVakitIn;
let nextTextTitle = appData.i18n.nextTextTitle;
if (isRamadan && currentVakit.name === 'Asr')
nextTextTitle = appData.i18n.remainingForIftarTitle;
appData.iconColor = iconColor;
appData.iconTextColor = iconTextColor;
appData.todaysDate = new Date().toLocaleString((appData.i18n.languageCode ?? navigator.language), { timeZone: appData.settings.timeZoneID, weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
appData.todaysDateArabic = hijriDate;
if (currentTimeString === currentVakit.time24 && appData.settings.desktopNotifications) {
chrome.storage.local.get(['lastAlert'], (result) => {
let lastAlertString = currentVakit.name + (new Date().toLocaleString("en-US", { day: 'numeric', month: 'numeric', year: 'numeric', minute: '2-digit' })).replace(/[\/, ]/g, '-');
if (result.lastAlert && result.lastAlert === lastAlertString) {
/* already alerted for this vakit */
}
else {
chrome.storage.local.set({ 'lastAlert': lastAlertString });
showNotification('notification', nextText, appData.settings.address);
}
});
}
chrome.action.setTitle({ title: (clockFaceVakit ? '[' + clockFaceVakit + '] ' : '') + nextTextTitle + ' ' + nextText + ' -> ' + appData.i18n[nextVakit.name.toLowerCase() + 'Text'] });
if (currentTimeString === currentVakit.time24) {
callAdhan();
nextTextTitle = appData.i18n.azanTimeTitle;
if (currentVakit.name === 'Imsak' || currentVakit.name === 'Sunrise' || currentVakit.name === 'Duha' || currentVakit.name === 'Duhaend' || currentVakit.name === 'Midnight')
nextTextTitle = ' ';
if (currentVakit.name !== 'Duhaend') {
nextText = appData.i18n[currentVakit.name.toLowerCase() + 'Text'];
chrome.action.setTitle({ title: nextText });
}
}
/* While playing, name the current surah on hover instead of the prayer countdown (which stays
on the icon's corner badge). */
if (quranPlaying)
chrome.action.setTitle({ title: quranNowPlayingTitle() });
checkAlarms();
if (nextText.length < 4)
nextText = ' ' + nextText + ' ';
if (adhanStatus.isBeingCalled) {
/* An adhan or alarm is calling: the whole toolbar icon becomes red pause bars — the same
treatment as the green Qur'an icon below, but red to match the red stop-adhan button
(#stopAdhanDiv) in the popup, so it's obvious where the audio is coming from (click it to
open the popup and stop it). Checked before quranPlaying because an adhan pauses the
Qur'an; the prayer countdown stays in Chrome's native corner badge as usual. */
chrome.action.setIcon({ imageData: { [iconSize]: pauseIconData(ADHAN_RED) } });
setBadge(nextText, badgeBackgroundColor);
}
else if (quranPlaying) {
/* Qur'an is playing: the whole toolbar icon becomes green pause bars so it's obvious where
the audio is coming from (click it to open the popup for surah + time left). The prayer
countdown is kept as Chrome's native corner badge — rendered crisply, unlike text baked
into a 16px icon — so both icon styles still show the time while playing. The badge keeps
the normal badge background (dark gray, or tomato in the last hour) for consistency. */
chrome.action.setIcon({ imageData: { [iconSize]: pauseIconData(QURAN_GREEN) } });
setBadge(nextText, badgeBackgroundColor);
}
else if (appData.settings.iconStyle === "badge") {
setBadge(nextText, badgeBackgroundColor);
chrome.action.setIcon({ imageData: { [iconSize]: btx.getImageData(0, 0, iconSize, iconSize) } });
}
else {
setBadge('', badgeBackgroundColor);
chrome.action.setIcon({ imageData: { [iconSize]: itx.getImageData(0, 0, iconSize, iconSize) } });
}
appData.nextText = nextText;
appData.nextTextTitle = nextTextTitle;
appData.elapsedText = elapsedText;
appData.settings.iconStyle = appData.settings.iconStyle ?? "badge";
appData.remainingForIftar = null;
if (isRamadan && currentVakit.name !== 'Asr' && currentVakit.name !== 'Maghrib' && currentVakit.name !== 'Isha' && currentVakit.name !== 'Midnight')
appData.remainingForIftar = appData.i18n.remainingForIftarTitle + ' ' + diffBetweenTimes(currentTimeString, getPrayerTime('maghrib'));
itx.canvas.convertToBlob().then((blob) => {
let reader1 = new FileReader();
reader1.readAsDataURL(blob);
reader1.onloadend = () => {
appData.icon = reader1.result;
btx.canvas.convertToBlob().then((blob) => {
let reader2 = new FileReader();
reader2.readAsDataURL(blob);
reader2.onloadend = () => {
appData.bar = reader2.result;
ctx.canvas.convertToBlob().then((blob) => {
let reader3 = new FileReader();
reader3.readAsDataURL(blob);
reader3.onloadend = () => {
appData.clock = reader3.result;
appData.lastRun = new Date().getTime();
chrome.storage.local.set({ 'appData': appData }, function () {
chrome.runtime.sendMessage({ runApp: true }, function (response) {
if (!chrome.runtime.lastError) {
/* msg is received */
}
else {
/* popup not open to receive the msg */
}
});
});
}
});
}
});
}
});
return true;
}
function getPrayerTime(vakit) { return prayerTimes[vakit].replace(/^0/, ''); }
function print(canvas, text, size, color, y) {
canvas.save();
if (!y)
y = 0;
canvas.font = 'bold ' + Math.floor(size) + 'px Arial';
canvas.fillStyle = color;
canvas.textBaseline = "middle";
canvas.textAlign = 'center';
canvas.fillText(text, 0, y);
canvas.restore();
}
function printAt(canvas, text, size, color, r, angle) {
canvas.save();
canvas.textBaseline = "middle";
canvas.fillStyle = color;
canvas.textAlign = "center";
canvas.font = size + "px Arial";
let ang = angle - Math.PI / 2;
canvas.rotate(ang);
canvas.translate(0, r);
canvas.rotate(-ang);
canvas.fillText(text, 0, 0);
canvas.restore();
}
function drawArc(canvas, startAngle, endAngle, radius, lineWidth, color) {
canvas.save();
canvas.beginPath();
canvas.arc(0, 0, radius, startAngle, endAngle, false);
canvas.lineWidth = lineWidth;
canvas.lineCap = "butt";
canvas.strokeStyle = color;
canvas.stroke();
canvas.restore();
}
function drawNumbers12(canvas, r, color) {
let p;
for (let n = 0; n < 12; n++) {
canvas.save();
canvas.textBaseline = "middle";
canvas.fillStyle = color;
canvas.textAlign = "center";
canvas.font = "bold " + r * 0.15 + "px Arial";
let ang = n * Math.PI / 6 - Math.PI;
canvas.rotate(ang);
canvas.translate(0, r * 1.35);
canvas.rotate(-ang);
p = n;
if (n === 0)
p = 12;
canvas.fillText(p, 0, 0);
canvas.restore();
}
for (let m = 0; m < 144; m++) {
canvas.save();
canvas.textBaseline = "middle";
canvas.fillStyle = color;
canvas.textAlign = "center";
let ang = m * Math.PI / 30;
canvas.rotate(ang);
canvas.translate(0, r * 1.29);
if (m % 5 !== 0) {
canvas.font = r * 0.19 + "px Arial";
canvas.fillText(".", 0, 0);
}
canvas.restore();
}
}
function fillCircle(canvas, r, x, y, color) {
canvas.save();
canvas.beginPath();
canvas.arc(x, y, r, 0, Math.PI * 2);
canvas.fillStyle = color;
canvas.fill();
canvas.restore();
}
function drawHand(canvas, angle, from, to, lineWidth, color) {
canvas.save();
canvas.beginPath();
canvas.rotate(angle);
canvas.moveTo(from, 0);
canvas.lineTo(to, 0);
canvas.lineWidth = lineWidth;
canvas.strokeStyle = color;
canvas.lineCap = "round";
canvas.stroke();
canvas.restore();
}
function drawArrow(canvas, angle, x, width, height, color) {
canvas.save();
canvas.beginPath();
canvas.rotate(angle);
canvas.moveTo(x, -width);
canvas.lineTo(x, width);
canvas.lineTo(x + height, 0);
canvas.fillStyle = color;
canvas.fill();
canvas.restore();
}
/* Minutes from now until this alarm next actually rings, honoring its frequency
(E = every day, W = weekdays). Returns Infinity if it never fires. */
function minutesUntilNextAlarm(a) {
let nowMinutes = currentTime.getHours() * 60 + currentTime.getMinutes();
let parts = a.time.split(':');
let alarmMinutes = parts[0] * 60 + parts[1] * 1;
let today = currentTime.getDay(); /* 0=Sun .. 6=Sat */
for (let d = 0; d <= 7; d++) {
let weekday = (today + d) % 7;
let fires = (a.frequency === 'E') || (a.frequency === 'W' && weekday > 0 && weekday < 6);
if (!fires)
continue;
let delta = d * 1440 + alarmMinutes - nowMinutes;
if (delta >= 0)
return delta;
}
return Infinity;
}
function markAlarms(canvas, r) {
let alarms = appData.settings.alarms || [];
let naflAlarms = appData.settings.naflAlarms || [];
if (alarms.length === 0 && naflAlarms.length === 0)
return;
let markerRadius = r * 1.19;
/* The clock face is a 12h dial, so a 9:30am and a 9:30pm alarm would land on
the exact same spot. Only show the dot while the alarm is the next thing due
within 12h, so its position always matches when it will actually ring. */
alarms.forEach((a) => {
if (minutesUntilNextAlarm(a) <= 720)