-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
992 lines (857 loc) · 37.2 KB
/
Copy pathbackground.js
File metadata and controls
992 lines (857 loc) · 37.2 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
// Nirvanify Background Service Worker
// Handles session management, timers, notifications, and cross-tab coordination
// MV3 background service worker (module)
// Implements session-based blocking: when an active study session is running,
// any navigation to a site listed in the session's block sets is intercepted
// and redirected to the intervention page with the configured intervention.
// Minimal IndexedDB KV helpers (reuse project module)
import { idbGet, idbSet } from "./components/storage/idb-kv.js";
import { loadAllSessions } from './classes/session/storage.js';
// Analytics recorders
import { recordBlockEvent, recordFocusMs, recordOverrideStart, recordOverrideUsage, recordSessionCompleted } from './components/storage/analytics-storage.js';
const ACTIVE_SESSION_KEY = "nv_active_session";
const SESSIONS_KEY = "nv_sessions"; // canonical map (snake_case)
const BLOCKSETS_KEY = "nv_blocksets"; // one-indexed array
const INTERVENTIONS_KEY = "nv_interventions"; // id -> intervention object
const OVERRIDE_KEY = "nv_override_active"; // { ends_at: ms, reason?: string }
const OVERRIDE_RUNTIME_KEY = "nv_override_runtime"; // { started_at:number, ends_at:number }
const STRICT_MODE_KEY = "nv_strict_mode"; // boolean
const DEBUG_MODE_KEY = "nv_debug_mode"; // boolean
const ALLOWANCE_USAGE_KEY = "nv_allowance_usage_v1"; // { [blocksetId]: [{start:number,end:number}] }
const BLOCKSET_OVERRIDES_KEY = "nv_blockset_overrides_v1"; // { [blocksetId]: number(ends_at) }
// Debounce/guard to avoid redirect loops per tab
const processingTabs = new Set();
function getExtUrl(path) { return chrome.runtime.getURL(path.replace(/^\//, "")); }
function isExtensionUrl(url) {
try { return new URL(url).origin === new URL(getExtUrl("/"))?.origin; } catch { return false; }
}
function hostname(url) { try { return new URL(url).hostname; } catch { return ""; } }
function domainMatches(host, domain) {
if (!host || !domain) return false;
const h = String(host).toLowerCase();
const d = String(domain).toLowerCase().replace(/^\*\.?/, "");
if (h === d) return true;
return h.endsWith("." + d);
}
function toKebab(s) { return String(s || "").replace(/_/g, "-"); }
async function loadActiveSession() {
const st = await idbGet(ACTIVE_SESSION_KEY);
return st || { status: "idle" };
}
// Prefer canonical loader so we get correct shape and defaults/migrations applied
async function loadSessionsMap() {
try {
const map = await loadAllSessions();
if (map && typeof map === 'object') return map;
} catch { }
const raw = await idbGet(SESSIONS_KEY);
// Fallback: if an array slipped into canonical key, convert to id->obj map
if (Array.isArray(raw)) {
const m = {};
for (const it of raw) { if (it && it.id) m[it.id] = it; }
return m;
}
return raw || {};
}
async function loadBlocksetsArray() { return (await idbGet(BLOCKSETS_KEY)) || []; }
async function loadInterventionsMap() { return (await idbGet(INTERVENTIONS_KEY)) || {}; }
async function resolveMatch(url) {
// 0) Global override
// If a global override is active, skip blocking
try {
const ov = await idbGet(OVERRIDE_KEY);
if (ov && ov.ends_at && ov.ends_at > Date.now()) return null;
} catch { }
// 1) Check any "always"-active blocksets regardless of session
const blocksets = await loadBlocksetsArray(); // one-indexed
const alwaysHit = await matchFromBlocksets(url, blocksets, (bs) => {
const act = bs?.additional_settings?.activatedWhen;
return act === 'always';
});
if (alwaysHit) return alwaysHit;
// 2) Only when a session is running for session-scoped sets
const active = await loadActiveSession();
if (!active || active.status !== "running") return null;
// 3) Load session config to know which block sets apply
const sessions = await loadSessionsMap();
const session = sessions?.[active.session_id];
if (!session) return null;
const ids = Array.isArray(session.block_sets) ? session.block_sets : (Array.isArray(session.blockSets) ? session.blockSets : []);
if (!ids.length) return null;
const host = hostname(url);
if (!host) return null;
// 4) Load blocksets and try to match domain + schedule
let matched = null;
for (const id of ids) {
const bs = blocksets?.[id];
if (!bs || !Array.isArray(bs.website_list)) continue;
if (bs?.additional_settings?.activatedWhen && bs.additional_settings.activatedWhen !== 'study_session_only') {
// if configured as always-only, skip here (already matched in always phase)
}
const hit = await shouldBlockForBlockset(url, bs);
if (hit) { matched = { blockset: bs, id }; break; }
}
if (!matched) return null;
// 4) Resolve intervention
const intrId = matched.blockset.intervention;
if (!intrId) return null;
const intrMap = await loadInterventionsMap();
const intr = intrMap[intrId];
// If not found, still navigate with type by guessing from id (e.g., *_default)
let type = intr?.type || (String(intrId).includes("soft") ? "soft_block" : String(intrId).includes("hard") ? "hard_block" : "soft_block");
// Strict mode escalation
try {
const strict = await idbGet(STRICT_MODE_KEY);
if (strict && type === 'soft_block') type = 'hard_block';
} catch { }
return { type, iid: intrId };
}
/**
* Compute allowance info for a given blockset at the current time.
* Returns { minutes, hours, remainingMs, endsAt }
*/
async function computeAllowanceInfoForBlockset(blockset) {
const minutes = Number(blockset?.hourly_allowance?.minutes) || 0;
const hours = Number(blockset?.hourly_allowance?.hour_range) || 0;
const now = Date.now();
const allowanceMs = Math.max(0, minutes) * 60 * 1000;
const windowMs = Math.max(0, hours) * 60 * 60 * 1000;
const overrides = (await idbGet(BLOCKSET_OVERRIDES_KEY)) || {};
const endsAt = overrides?.[blockset?.id] || 0;
if (!minutes || !hours) {
return { minutes, hours, remainingMs: 0, endsAt };
}
const usageMap = (await idbGet(ALLOWANCE_USAGE_KEY)) || {};
const events = Array.isArray(usageMap[blockset.id]) ? usageMap[blockset.id] : [];
const windowStart = now - windowMs;
let usedMs = 0;
for (const ev of events) {
if (!ev || typeof ev.start !== 'number' || typeof ev.end !== 'number') continue;
if (ev.end <= windowStart) continue; // outside window
const a = Math.max(windowStart, ev.start);
const b = Math.min(now, ev.end);
if (b > a) usedMs += (b - a);
}
const remainingMs = Math.max(0, allowanceMs - usedMs);
return { minutes, hours, remainingMs, endsAt };
}
/**
* Find the first matching blockset for a given URL and return
* { blockset, info } where info is from computeAllowanceInfoForBlockset.
*/
async function findAllowanceForUrl(url) {
const host = hostname(url);
if (!host) return null;
const blocksets = await loadBlocksetsArray();
for (let i = 1; i < (blocksets?.length || 0); i++) {
const bs = blocksets?.[i];
if (!bs || !Array.isArray(bs.website_list)) continue;
if (!bs.hourly_allowance) continue;
const listed = bs.website_list.some(d => domainMatches(host, String(d)));
if (!listed) continue;
// If a schedule exists, ensure it's active now to consider allowance
if (!withinSchedule(bs.block_schedule)) continue;
const info = await computeAllowanceInfoForBlockset(bs);
return { blockset: bs, info };
}
return null;
}
/**
* Start (opt-in) allowance usage for a blockset by recording an event and
* setting a per-blockset override until allowance expiry.
* Returns { grantedMs, endsAt } or throws when not possible.
*/
async function startAllowanceForBlockset(blocksetId) {
const blocksets = await loadBlocksetsArray();
const bs = blocksets?.[blocksetId];
if (!bs) throw new Error('Invalid blockset');
const { minutes, hours } = bs?.hourly_allowance || {};
const min = Number(minutes) || 0;
const hr = Number(hours || bs?.hourly_allowance?.hour_range) || 0;
if (!min || !hr) throw new Error('No allowance available');
const now = Date.now();
const allowanceMs = min * 60 * 1000;
const windowMs = hr * 60 * 60 * 1000;
const usageMap = (await idbGet(ALLOWANCE_USAGE_KEY)) || {};
const overrides = (await idbGet(BLOCKSET_OVERRIDES_KEY)) || {};
const events = Array.isArray(usageMap[blocksetId]) ? usageMap[blocksetId] : [];
const windowStart = now - windowMs;
let usedMs = 0;
const pruned = [];
for (const ev of events) {
if (!ev || typeof ev.start !== 'number' || typeof ev.end !== 'number') continue;
if (ev.end <= windowStart) continue;
pruned.push(ev);
const a = Math.max(windowStart, ev.start);
const b = Math.min(now, ev.end);
if (b > a) usedMs += (b - a);
}
const remainingMs = Math.max(0, allowanceMs - usedMs);
if (remainingMs <= 0) throw new Error('No allowance remaining');
const grantMs = remainingMs; // grant all remaining time in the window
const endsAt = now + grantMs;
pruned.push({ start: now, end: endsAt });
usageMap[blocksetId] = pruned;
const nextOverrides = { ...(overrides || {}) };
nextOverrides[blocksetId] = endsAt;
await idbSet(ALLOWANCE_USAGE_KEY, usageMap);
await idbSet(BLOCKSET_OVERRIDES_KEY, nextOverrides);
return { grantedMs: grantMs, endsAt };
}
// Try to match URL against a subset of blocksets (predicate filters which sets to consider)
async function matchFromBlocksets(url, blocksets, predicate) {
const host = hostname(url);
if (!host) return null;
for (let i = 1; i < (blocksets?.length || 0); i++) {
const bs = blocksets?.[i];
if (!bs) continue;
if (typeof predicate === 'function' && !predicate(bs)) continue;
const ok = await shouldBlockForBlockset(url, bs);
if (ok) {
const intrId = bs.intervention;
const map = await loadInterventionsMap();
const intr = map[intrId];
let type = intr?.type || (String(intrId).includes("soft") ? "soft_block" : String(intrId).includes("hard") ? "hard_block" : "soft_block");
try { const strict = await idbGet(STRICT_MODE_KEY); if (strict && type === 'soft_block') type = 'hard_block'; } catch { }
return { type, iid: intrId };
}
}
return null;
}
// Determine if a blockset should apply to a given URL right now (domain + schedule)
async function shouldBlockForBlockset(url, blockset) {
if (!blockset || !Array.isArray(blockset.website_list)) return false;
const host = hostname(url);
const listed = blockset.website_list.some((d) => domainMatches(host, String(d)));
if (!listed) return false;
// Respect schedule if present
const scheduled = withinSchedule(blockset.block_schedule);
if (!scheduled) return false;
// If a per-blockset override is active, allow
const overrides = (await idbGet(BLOCKSET_OVERRIDES_KEY)) || {};
const now = Date.now();
const endsAt = overrides?.[blockset.id];
if (endsAt && endsAt > now) return false;
// Do NOT auto-grant hourly allowance here. The intervention page
// presents an explicit "Use Allowance" option which, if chosen,
// will record usage and start a temporary override.
return true; // block
}
function getNowInTZ(tz) {
try {
const parts = new Intl.DateTimeFormat('en-US', { timeZone: tz || Intl.DateTimeFormat().resolvedOptions().timeZone, hour: '2-digit', minute: '2-digit', hour12: false, weekday: 'short' }).formatToParts(new Date());
const map = Object.fromEntries(parts.map(p => [p.type, p.value]));
const wd = String(map.weekday || '').toLowerCase().slice(0, 3);
const dayKey = wd === 'mon' || wd === 'tue' || wd === 'wed' || wd === 'thu' || wd === 'fri' || wd === 'sat' || wd === 'sun' ? wd : ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'][new Date().getDay()];
return { dayKey, hhmm: `${map.hour?.padStart(2, '0')}:${map.minute?.padStart(2, '0')}` };
} catch {
const d = new Date();
const dd = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'][d.getDay()];
const mm = String(d.getMinutes()).padStart(2, '0');
const hh = String(d.getHours()).padStart(2, '0');
return { dayKey: dd, hhmm: `${hh}:${mm}` };
}
}
function timeToMinutes(s) {
if (!s || typeof s !== 'string') return null;
const [h, m] = s.split(':').map(x => parseInt(x, 10));
if (Number.isNaN(h) || Number.isNaN(m)) return null;
return h * 60 + m;
}
// Support both shapes: { days, block_time_ranges, timezone } OR per-day { mon:[{start,end}], ... , timezone }
function withinSchedule(schedule) {
// If there is no schedule object at all, treat as always active (legacy default)
if (!schedule || typeof schedule !== 'object') return true;
const tz = schedule.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone;
const { dayKey, hhmm } = getNowInTZ(tz);
const nowMin = timeToMinutes(hhmm);
if (nowMin == null) return true;
// Helper to test ranges array
const inRanges = (ranges) => {
if (!Array.isArray(ranges)) return false;
if (ranges.length === 0) return false; // empty ranges => not scheduled for this day
return ranges.some((r) => {
const a = timeToMinutes(r?.start || r?.[0]);
const b = timeToMinutes(r?.end || r?.[1]);
if (a == null || b == null) return false;
return a <= nowMin && nowMin <= b;
});
};
// Shape A: per-day arrays present
const PER_DAY_KEYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
const hasPerDay = PER_DAY_KEYS.some((d) => Array.isArray(schedule[d]));
if (hasPerDay) {
// If any per-day arrays exist, consider this a configured schedule.
// For days with no ranges, treat as not scheduled (i.e., allow).
if (Array.isArray(schedule[dayKey])) return inRanges(schedule[dayKey]);
// Day key missing but schedule exists for other days => not scheduled today
return false;
}
// Shape B: days + block_time_ranges
if (Array.isArray(schedule.days) && Array.isArray(schedule.block_time_ranges)) {
const idx = schedule.days.findIndex(
(d) => String(d).slice(0, 3).toLowerCase() === dayKey
);
if (idx < 0) return false; // not in configured days => not scheduled today
const ranges = schedule.block_time_ranges[idx] || [];
return inRanges(ranges);
}
// Unknown/empty object -> treat as always active to keep legacy behavior
return true;
}
async function maybeRedirect(details) {
try {
if (details.frameId !== 0) return; // main frame only
if (processingTabs.has(details.tabId)) return;
if (isExtensionUrl(details.url)) return; // don't block our own pages
const match = await resolveMatch(details.url);
if (!match) return;
const q = new URLSearchParams();
q.set("type", toKebab(match.type));
q.set("iid", match.iid);
q.set("target", details.url);
q.set("auto", "1");
// Record analytics for the block event
try { await recordBlockEvent(Date.now()); } catch (e) { /* ignore */ }
const dest = getExtUrl(`interventions.html?${q.toString()}`);
processingTabs.add(details.tabId);
await chrome.tabs.update(details.tabId, { url: dest });
// clear guard after a short delay
setTimeout(() => processingTabs.delete(details.tabId), 1500);
} catch (e) {
console.warn("[background] maybeRedirect error", e);
}
}
// Register listeners
try {
chrome.webNavigation.onBeforeNavigate.addListener(maybeRedirect, { url: [{ urlMatches: ".*" }] });
chrome.webNavigation.onCommitted.addListener(maybeRedirect, { url: [{ urlMatches: ".*" }] });
} catch (e) {
console.warn("[background] Failed to add webNavigation listeners", e);
}
// Keep service worker alive a little when needed (optional no-op alarm)
chrome.runtime.onInstalled.addListener(() => {
try { chrome.alarms.create("nv_keepalive", { periodInMinutes: 4 }); } catch { }
});
chrome.alarms.onAlarm.addListener((a) => { if (a?.name === "nv_keepalive") {/* noop */ } });
import { loadActiveSessionState, startSessionById, cancelActiveSession, remainingMs, pauseActiveSession, resumeActiveSession } from './components/storage/active-session.js';
// Global state
let activeSessionTimer = null;
let notificationTimer = null;
let tabSessions = new Map(); // Track sessions per tab
const SESSION_RUNTIME_KEY = 'nv_session_runtime'; // { session_id, last_resume_at, accumulated_ms }
// ===== Overrides =====
async function startOverride(minutes = 5, reason = 'Quick override') {
const now = Date.now();
const ends_at = now + Math.max(1, minutes) * 60 * 1000;
await idbSet(OVERRIDE_KEY, { ends_at, reason });
await idbSet(OVERRIDE_RUNTIME_KEY, { started_at: now, ends_at });
try { await recordOverrideStart(now); } catch (_) { }
try { chrome.alarms.create('nv_override_end', { when: ends_at }); } catch { }
showNotification('Override Enabled', `Blocking paused for ${minutes} minute(s).`, 'info');
}
async function stopOverride() {
try {
const rt = await idbGet(OVERRIDE_RUNTIME_KEY);
if (rt && rt.started_at) {
const used = Math.max(0, Math.min(Date.now(), rt.ends_at || Date.now()) - rt.started_at);
if (used > 0) { try { await recordOverrideUsage(used, Date.now()); } catch (_) { } }
}
} catch (_) { }
await idbSet(OVERRIDE_RUNTIME_KEY, null);
await idbSet(OVERRIDE_KEY, null);
showNotification('Override Disabled', 'Blocking restored.', 'info');
}
// Initialize when extension starts
chrome.runtime.onStartup.addListener(initializeExtension);
chrome.runtime.onInstalled.addListener(initializeExtension);
async function initializeExtension() {
console.log('[Nirvanify] Extension initialized');
// Clear any existing alarms
await chrome.alarms.clearAll();
// Restore active session state if exists
await restoreActiveSession();
// Set up context menus
await setupContextMenus();
// Initialize tab session tracking
initializeTabTracking();
}
// ========================================
// Session Management
// ========================================
async function restoreActiveSession() {
try {
const state = await loadActiveSessionState();
if (state && state.status === 'running') {
const remaining = remainingMs(state);
if (remaining > 0) {
console.log(`[Nirvanify] Restoring active session: ${state.session_name}, ${Math.round(remaining / 1000 / 60)}m remaining`);
scheduleSessionEnd(remaining);
updateBadge(remaining);
} else {
// Session should have ended, trigger completion
await handleSessionPhaseComplete(state);
}
}
} catch (error) {
console.error('[Nirvanify] Failed to restore session:', error);
}
}
async function startSession(sessionId) {
try {
// Cancel any existing session
if (activeSessionTimer) {
clearTimeout(activeSessionTimer);
activeSessionTimer = null;
}
const state = await startSessionById(sessionId);
const duration = remainingMs(state);
console.log(`[Nirvanify] Starting session: ${state.session_name} for ${Math.round(duration / 1000 / 60)}m`);
// Schedule session end
scheduleSessionEnd(duration);
// Update badge
updateBadge(duration);
// Show notification
showNotification('Session Started', `${state.session_name} - Focus time!`, 'session-start');
// Broadcast to all tabs
broadcastToTabs('session-started', state);
// Track runtime for analytics accumulation
try { await idbSet(SESSION_RUNTIME_KEY, { session_id: state.session_id, last_resume_at: Date.now(), accumulated_ms: 0 }); } catch (_) { }
return state;
} catch (error) {
console.error('[Nirvanify] Failed to start session:', error);
throw error;
}
}
async function stopSession() {
try {
if (activeSessionTimer) {
clearTimeout(activeSessionTimer);
activeSessionTimer = null;
}
if (notificationTimer) {
clearTimeout(notificationTimer);
notificationTimer = null;
}
// Finalize analytics accumulation before cancelling
try {
const rt = await idbGet(SESSION_RUNTIME_KEY);
if (rt && (rt.last_resume_at || rt.accumulated_ms)) {
const now = Date.now();
const delta = rt.last_resume_at ? Math.max(0, now - rt.last_resume_at) : 0;
const total = (Number(rt.accumulated_ms) || 0) + delta;
if (total > 0) {
try { await recordFocusMs(total, now); } catch (_) { }
try { await recordSessionCompleted(now); } catch (_) { }
}
}
} catch (_) { }
try { await idbSet(SESSION_RUNTIME_KEY, null); } catch (_) { }
await cancelActiveSession();
// Clear badge
chrome.action.setBadgeText({ text: '' });
// Show notification
showNotification('Session Stopped', 'Your focus session has been stopped.', 'session-stop');
// Broadcast to all tabs
broadcastToTabs('session-stopped');
console.log('[Nirvanify] Session stopped');
} catch (error) {
console.error('[Nirvanify] Failed to stop session:', error);
}
}
function scheduleSessionEnd(durationMs) {
if (activeSessionTimer) {
clearTimeout(activeSessionTimer);
}
activeSessionTimer = setTimeout(async () => {
const state = await loadActiveSessionState();
await handleSessionPhaseComplete(state);
}, durationMs);
// Schedule reminder notifications
scheduleReminders(durationMs);
}
function scheduleReminders(durationMs) {
const minutes = Math.round(durationMs / 1000 / 60);
// 5-minute reminder for sessions longer than 10 minutes
if (minutes > 10) {
const reminderTime = durationMs - (5 * 60 * 1000);
notificationTimer = setTimeout(() => {
showNotification('5 Minutes Remaining', 'Your focus session will end in 5 minutes.', 'reminder');
}, reminderTime);
}
}
async function handleSessionPhaseComplete(state) {
try {
console.log('[Nirvanify] Session phase completed:', state.phase);
if (state.phase === 'focus') {
// Focus phase completed - show completion notification
showNotification('Focus Complete!', `Great job! You completed ${state.session_name}.`, 'session-complete');
// Finalize analytics accumulation
try {
const rt = await idbGet(SESSION_RUNTIME_KEY);
if (rt && (rt.last_resume_at || rt.accumulated_ms)) {
const now = Date.now();
const delta = rt.last_resume_at ? Math.max(0, now - rt.last_resume_at) : 0;
const total = (Number(rt.accumulated_ms) || 0) + delta;
if (total > 0) {
try { await recordFocusMs(total, now); } catch (_) { }
try { await recordSessionCompleted(now); } catch (_) { }
}
}
} catch (_) { }
try { await idbSet(SESSION_RUNTIME_KEY, null); } catch (_) { }
// For now, just end the session - future: implement break phases
await cancelActiveSession();
chrome.action.setBadgeText({ text: '' });
// Broadcast completion
broadcastToTabs('session-completed', state);
}
activeSessionTimer = null;
notificationTimer = null;
} catch (error) {
console.error('[Nirvanify] Failed to handle session completion:', error);
}
}
// ========================================
// Badge Management
// ========================================
function updateBadge(remainingMs) {
const minutes = Math.ceil(remainingMs / 1000 / 60);
const badgeText = minutes > 99 ? '99+' : minutes.toString();
chrome.action.setBadgeText({ text: badgeText });
chrome.action.setBadgeBackgroundColor({ color: '#3b82f6' });
// Update badge every minute
setTimeout(() => {
loadActiveSessionState().then(state => {
if (state.status === 'running') {
const remaining = remainingMs(state);
if (remaining > 0) {
updateBadge(remaining);
}
}
});
}, 60000);
}
// ========================================
// Notifications
// ========================================
function showNotification(title, message, type = 'default') {
const iconUrl = chrome.runtime.getURL('logo.png');
chrome.notifications.create({
type: 'basic',
iconUrl: iconUrl,
title: title,
message: message,
priority: type === 'session-complete' ? 2 : 1
});
}
// ========================================
// Context Menus
// ========================================
async function setupContextMenus() {
// Remove existing menus
chrome.contextMenus.removeAll();
// Add main menu
chrome.contextMenus.create({
id: 'nirvanify-main',
title: 'Nirvanify',
contexts: ['page', 'selection', 'action']
});
// Add session controls
chrome.contextMenus.create({
id: 'start-session',
parentId: 'nirvanify-main',
title: 'Start Focus Session',
contexts: ['page', 'action']
});
chrome.contextMenus.create({
id: 'stop-session',
parentId: 'nirvanify-main',
title: 'Stop Current Session',
contexts: ['page', 'action']
});
chrome.contextMenus.create({
id: 'session-separator',
parentId: 'nirvanify-main',
type: 'separator',
contexts: ['page']
});
// Add quick session options
try {
const sessions = await loadAllSessions();
const sessionList = Object.values(sessions).slice(0, 5); // Limit to 5 sessions
for (const session of sessionList) {
chrome.contextMenus.create({
id: `quick-session-${session.id}`,
parentId: 'nirvanify-main',
title: `Quick Start: ${session.name}`,
contexts: ['page', 'action']
});
}
} catch (error) {
console.error('[Nirvanify] Failed to load sessions for context menu:', error);
}
}
// ========================================
// Tab Management & Cross-Tab Communication
// ========================================
function initializeTabTracking() {
// Track when tabs are created/removed
chrome.tabs.onCreated.addListener(tab => {
tabSessions.set(tab.id, { sessionActive: false });
});
chrome.tabs.onRemoved.addListener(tabId => {
tabSessions.delete(tabId);
});
// Track tab updates for session-aware features
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete') {
const state = await loadActiveSessionState();
if (state.status === 'running') {
// Notify tab about active session
broadcastToTab(tabId, 'session-active', state);
}
}
});
}
function broadcastToTabs(event, data = null) {
chrome.tabs.query({}, (tabs) => {
tabs.forEach(tab => {
broadcastToTab(tab.id, event, data);
});
});
}
function broadcastToTab(tabId, event, data = null) {
// Use callback form to avoid unhandled promise rejections when no receiver exists
try {
chrome.tabs.sendMessage(
tabId,
{ type: 'nirvanify-session', event, data },
() => {
// Swallow missing receiver errors (no content script on page, etc.)
void chrome.runtime?.lastError; // access to suppress error logs
}
);
} catch (_) {
// ignore
}
}
async function pauseSession() {
try {
if (activeSessionTimer) { clearTimeout(activeSessionTimer); activeSessionTimer = null; }
if (notificationTimer) { clearTimeout(notificationTimer); notificationTimer = null; }
const st = await pauseActiveSession();
// indicate paused
chrome.action.setBadgeText({ text: '||' });
// accumulate elapsed into runtime
try {
const rt = await idbGet(SESSION_RUNTIME_KEY);
if (rt && rt.last_resume_at) {
const now = Date.now();
const delta = Math.max(0, now - rt.last_resume_at);
const acc = (Number(rt.accumulated_ms) || 0) + delta;
await idbSet(SESSION_RUNTIME_KEY, { ...rt, accumulated_ms: acc, last_resume_at: null });
}
} catch (_) { }
return st;
} catch (e) {
console.error('[Nirvanify] Failed to pause session:', e);
throw e;
}
}
async function resumeSession() {
try {
const st = await resumeActiveSession();
const duration = remainingMs(st);
if (duration > 0) {
scheduleSessionEnd(duration);
updateBadge(duration);
}
// mark last resume timestamp for runtime accumulation
try {
const rt = await idbGet(SESSION_RUNTIME_KEY);
await idbSet(SESSION_RUNTIME_KEY, { ...(rt || { session_id: st.session_id, accumulated_ms: 0 }), last_resume_at: Date.now() });
} catch (_) { }
return st;
} catch (e) {
console.error('[Nirvanify] Failed to resume session:', e);
throw e;
}
}
// ========================================
// Message Handling
// ========================================
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
const { type, action, data } = message;
if (type !== 'nirvanify-background') {
return false;
}
switch (action) {
case 'start-session':
startSession(data?.sessionId)
.then(state => sendResponse({ success: true, state }))
.catch(error => sendResponse({ success: false, error: error.message }));
return true;
case 'stop-session':
stopSession()
.then(() => sendResponse({ success: true }))
.catch(error => sendResponse({ success: false, error: error.message }));
return true;
case 'pause-session':
pauseSession()
.then(state => sendResponse({ success: true, state }))
.catch(error => sendResponse({ success: false, error: error.message }));
return true;
case 'resume-session':
resumeSession()
.then(state => sendResponse({ success: true, state }))
.catch(error => sendResponse({ success: false, error: error.message }));
return true;
case 'get-session-state':
loadActiveSessionState()
.then(state => sendResponse({ success: true, state }))
.catch(error => sendResponse({ success: false, error: error.message }));
return true;
case 'refresh-context-menu':
setupContextMenus()
.then(() => sendResponse({ success: true }))
.catch(error => sendResponse({ success: false, error: error.message }));
return true;
case 'start-override':
startOverride(Number(data?.minutes) || 5, data?.reason || 'override')
.then(() => sendResponse({ success: true }))
.catch(error => sendResponse({ success: false, error: error.message }));
return true;
case 'stop-override':
stopOverride()
.then(() => sendResponse({ success: true }))
.catch(error => sendResponse({ success: false, error: error.message }));
return true;
case 'get-timer-settings':
idbGet('nv_timer_settings')
.then(v => sendResponse({
success: true, settings: v || {
size: 'Medium',
location: 'Top Right',
options: { autoHide: true, showSeconds: false, persistent: false, soundAlerts: false }
}
}))
.catch(error => sendResponse({ success: false, error: error.message }));
return true;
case 'timer-settings-updated':
try {
broadcastToTabs('timer-settings', data);
sendResponse({ success: true });
} catch (error) {
sendResponse({ success: false, error: error.message });
}
return true;
case 'get-overlay-pos': {
(async () => {
try {
const v = await idbGet('nv_timer_overlay_pos');
sendResponse({ success: true, pos: v || null });
} catch (error) {
sendResponse({ success: false, error: error.message });
}
})();
return true;
}
case 'set-overlay-pos': {
const pos = data && typeof data === 'object' ? data : null;
(async () => {
try {
await idbSet('nv_timer_overlay_pos', pos);
sendResponse({ success: true });
} catch (error) {
sendResponse({ success: false, error: error.message });
}
})();
return true;
}
case 'open-extension-page': {
const raw = (data && data.path) || 'index.html#/dashboard';
try {
// Only allow extension-relative URLs
const safe = typeof raw === 'string' && raw.match(/^[\w\-.\/#!?=&%:+]*$/) ? raw : 'index.html#/dashboard';
const url = chrome.runtime.getURL(safe);
chrome.tabs.create({ url }, () => { void chrome.runtime?.lastError; });
sendResponse({ success: true });
} catch (error) {
sendResponse({ success: false, error: error.message });
}
return true;
}
case 'get-allowance-info': {
const url = data?.url || '';
(async () => {
try {
const found = await findAllowanceForUrl(url);
if (!found) return sendResponse({ success: true, info: null });
const { blockset, info } = found;
sendResponse({ success: true, info: { blocksetId: blockset.id, minutes: info.minutes, hours: info.hours, remainingMs: info.remainingMs, endsAt: info.endsAt } });
} catch (e) {
sendResponse({ success: false, error: e?.message || 'Failed to get allowance info' });
}
})();
return true;
}
case 'start-blockset-allowance': {
const blocksetId = Number(data?.blocksetId) || 0;
(async () => {
try {
const res = await startAllowanceForBlockset(blocksetId);
sendResponse({ success: true, result: res });
} catch (e) {
sendResponse({ success: false, error: e?.message || 'Failed to start allowance' });
}
})();
return true;
}
default:
sendResponse({ success: false, error: 'Unknown action' });
return false;
}
});
// ========================================
// Context Menu Clicks
// ========================================
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
const { menuItemId } = info;
try {
if (menuItemId === 'start-session') {
// Start default session (Pomodoro)
await startSession('pomodoro');
} else if (menuItemId === 'stop-session') {
await stopSession();
} else if (menuItemId === 'view-current') {
const url = chrome.runtime.getURL('index.html#/dashboard?open=current');
chrome.tabs.create({ url });
} else if (menuItemId === 'start-override-5') {
await startOverride(5);
} else if (menuItemId === 'stop-override') {
await stopOverride();
} else if (menuItemId.startsWith('quick-session-')) {
const sessionId = menuItemId.replace('quick-session-', '');
await startSession(sessionId);
}
} catch (error) {
console.error('[Nirvanify] Context menu action failed:', error);
showNotification('Error', 'Failed to perform action. Please try again.', 'error');
}
});
// ========================================
// Alarm Handling (for future use)
// ========================================
chrome.alarms.onAlarm.addListener(async (alarm) => {
const { name } = alarm;
if (name === 'session-end') {
const state = await loadActiveSessionState();
await handleSessionPhaseComplete(state);
} else if (name === 'session-reminder') {
showNotification('Session Reminder', 'Your focus session is still running!', 'reminder');
} else if (name === 'nv_override_end') {
try { await stopOverride(); } catch (_) { }
}
});
console.log('[Nirvanify] Background script loaded');