-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
304 lines (256 loc) · 8.95 KB
/
background.js
File metadata and controls
304 lines (256 loc) · 8.95 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
/* ========================================
RAMADAN MODE - Background Service Worker
Handles prayer notifications + Adhan audio
======================================== */
// Track which prayers already notified today (avoid duplicates)
let notifiedToday = {};
// Reset notified list at midnight
chrome.alarms.create('resetNotified', { periodInMinutes: 60 });
// Check prayer times every 30 seconds for accuracy
chrome.alarms.create('checkPrayer', { periodInMinutes: 0.5 });
chrome.alarms.onAlarm.addListener(async (alarm) => {
if (alarm.name === 'checkPrayer') {
await checkNextPrayer();
}
if (alarm.name === 'updateBadge') {
await updateBadge();
}
if (alarm.name === 'resetNotified') {
const now = new Date();
if (now.getHours() === 0 && now.getMinutes() < 60) {
notifiedToday = {};
}
}
});
// ==================== Offscreen document for audio ====================
let offscreenCreated = false;
async function ensureOffscreen() {
if (offscreenCreated) return;
try {
const existing = await chrome.offscreen.hasDocument();
if (existing) {
offscreenCreated = true;
return;
}
} catch {}
try {
await chrome.offscreen.createDocument({
url: 'offscreen.html',
reasons: ['AUDIO_PLAYBACK'],
justification: 'Playing Adhan audio at prayer time'
});
offscreenCreated = true;
} catch (err) {
console.error('Offscreen create error:', err);
}
}
// Safe message sender - won't throw if no receiver
function safeSendMessage(msg) {
try {
chrome.runtime.sendMessage(msg).catch(() => {});
} catch {}
}
async function playAdhan(volume = 0.8) {
await ensureOffscreen();
safeSendMessage({ action: 'playAdhan', volume });
}
function stopAdhanAudio() {
// Only sends stop to offscreen doc - does NOT re-trigger onMessage
safeSendMessage({ action: 'stopAdhan' });
}
function clearAdhanState() {
stopAdhanAudio();
chrome.storage.local.remove('adhanPlaying');
safeSendMessage({ action: 'adhanStopped' });
}
// Stop adhan when notification is clicked
chrome.notifications.onClicked.addListener((notifId) => {
if (notifId.startsWith('prayer-')) {
clearAdhanState();
chrome.notifications.clear(notifId);
}
});
// Stop adhan when notification is closed
chrome.notifications.onClosed.addListener((notifId) => {
if (notifId.startsWith('prayer-')) {
clearAdhanState();
}
});
// Listen for messages from popup (stopAdhan request)
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.action === 'adhanFinished') {
chrome.storage.local.remove('adhanPlaying');
safeSendMessage({ action: 'adhanStopped' });
}
if (msg.action === 'stopAdhanFromPopup') {
clearAdhanState();
chrome.notifications.getAll((notifs) => {
for (const id of Object.keys(notifs)) {
if (id.startsWith('prayer-')) chrome.notifications.clear(id);
}
});
}
});
// ==================== Prayer time check ====================
// Cache prayer times to avoid hitting the API every 30 seconds
let cachedTimings = null;
let cachedDate = null;
async function getPrayerTimings(settings) {
const now = new Date();
const todayStr = `${now.getFullYear()}-${now.getMonth()}-${now.getDate()}`;
// Return cache if same day
if (cachedTimings && cachedDate === todayStr) {
return cachedTimings;
}
const dd = now.getDate();
const mm = now.getMonth() + 1;
const yyyy = now.getFullYear();
let url;
if (settings.latitude && settings.longitude) {
url = `https://api.aladhan.com/v1/timings/${dd}-${mm}-${yyyy}?latitude=${settings.latitude}&longitude=${settings.longitude}&method=${settings.method || 5}`;
} else {
url = `https://api.aladhan.com/v1/timingsByCity/${dd}-${mm}-${yyyy}?city=${encodeURIComponent(settings.city || 'Paris')}&country=${settings.country || 'FR'}&method=${settings.method || 5}`;
}
const res = await fetch(url);
const result = await res.json();
if (result.code === 200) {
cachedTimings = result.data.timings;
cachedDate = todayStr;
return cachedTimings;
}
return null;
}
async function checkNextPrayer() {
try {
const data = await chrome.storage.local.get('ramadanSettings');
const settings = data.ramadanSettings;
if (!settings || !settings.notifications) return;
const timings = await getPrayerTimings(settings);
if (!timings) return;
const prayers = ['Fajr', 'Dhuhr', 'Asr', 'Maghrib', 'Isha'];
const prayerNamesAr = {
Fajr: 'الفجر',
Dhuhr: 'الظهر',
Asr: 'العصر',
Maghrib: 'المغرب',
Isha: 'العشاء'
};
const prayerNamesFr = {
Fajr: 'Fajr (Sobh)',
Dhuhr: 'Dhuhr',
Asr: 'Asr',
Maghrib: 'Maghrib',
Isha: 'Isha'
};
const now = new Date();
const currentMinutes = now.getHours() * 60 + now.getMinutes();
for (const prayer of prayers) {
const [h, m] = timings[prayer].split(':').map(Number);
const prayerMinutes = h * 60 + m;
// Already notified for this prayer today
if (notifiedToday[prayer]) continue;
// Notify if current time matches prayer time (within 1 min window)
if (currentMinutes >= prayerMinutes && currentMinutes <= prayerMinutes + 1) {
const isAr = settings.lang === 'ar';
let title, message;
if (prayer === 'Maghrib') {
title = isAr ? 'حان وقت المغرب - الإفطار 🍽️' : 'Adhan Maghrib - Iftar 🍽️';
message = isAr
? 'اللهم إني لك صمت وعلى رزقك أفطرت'
: 'Allahumma inni laka sumtu wa \'ala rizqika aftartu';
} else if (prayer === 'Fajr') {
title = isAr ? 'حان وقت الفجر - السحور 🌙' : 'Adhan Fajr - Fin du Suhoor 🌙';
message = isAr
? `صلاة ${prayerNamesAr[prayer]} - ${timings[prayer]}`
: `Prière de ${prayerNamesFr[prayer]} - ${timings[prayer]}`;
} else {
title = isAr ? `حان وقت ${prayerNamesAr[prayer]}` : `Adhan ${prayerNamesFr[prayer]}`;
message = isAr
? `حي على الصلاة - ${timings[prayer]}`
: `Hayya 'ala as-salat - ${timings[prayer]}`;
}
// Show notification
chrome.notifications.create(`prayer-${prayer}`, {
type: 'basic',
iconUrl: 'icons/icon128.png',
title: title,
message: message,
priority: 2,
requireInteraction: true
});
// Play adhan audio
const adhanVolume = settings.adhanVolume ?? 0.8;
await playAdhan(adhanVolume);
// Store adhan state so popup can show overlay when opened
chrome.storage.local.set({
adhanPlaying: { prayer: prayer, time: timings[prayer], startedAt: Date.now() }
});
// Notify popup if it's already open
safeSendMessage({
action: 'adhanStarted',
prayer: prayer,
time: timings[prayer]
});
// Mark as notified
notifiedToday[prayer] = true;
break;
}
}
} catch (err) {
console.error('Background check error:', err);
}
}
// ==================== Badge Countdown ====================
async function updateBadge() {
try {
const data = await chrome.storage.local.get('ramadanSettings');
const settings = data.ramadanSettings;
if (!settings) return;
const timings = await getPrayerTimings(settings);
if (!timings) return;
const prayers = ['Fajr', 'Sunrise', 'Dhuhr', 'Asr', 'Maghrib', 'Isha'];
const now = new Date();
let nextPrayerTime = null;
for (const key of prayers) {
const [h, m] = timings[key].split(':').map(Number);
const prayerDate = new Date(now);
prayerDate.setHours(h, m, 0, 0);
if (prayerDate > now) {
nextPrayerTime = prayerDate;
break;
}
}
if (!nextPrayerTime) {
// Next is Fajr tomorrow
const [h, m] = timings.Fajr.split(':').map(Number);
nextPrayerTime = new Date(now);
nextPrayerTime.setDate(nextPrayerTime.getDate() + 1);
nextPrayerTime.setHours(h, m, 0, 0);
}
const diff = nextPrayerTime - now;
const totalMins = Math.ceil(diff / 60000);
const hours = Math.floor(totalMins / 60);
const mins = totalMins % 60;
// Format: "1:23" or "45m" if less than 1 hour
const badgeText = hours > 0 ? `${hours}:${String(mins).padStart(2, '0')}` : `${mins}m`;
chrome.action.setBadgeText({ text: badgeText });
chrome.action.setBadgeBackgroundColor({ color: '#d4af37' });
chrome.action.setBadgeTextColor({ color: '#000000' });
} catch (err) {
// Silent fail - badge is not critical
}
}
// Update badge every minute
chrome.alarms.create('updateBadge', { periodInMinutes: 1 });
// ==================== Init ====================
chrome.runtime.onInstalled.addListener(() => {
console.log('Ramadan Mode installed! 🌙');
checkNextPrayer();
updateBadge();
});
// Also check on startup
chrome.runtime.onStartup.addListener(() => {
notifiedToday = {};
checkNextPrayer();
updateBadge();
});