-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
2711 lines (2349 loc) · 101 KB
/
background.js
File metadata and controls
2711 lines (2349 loc) · 101 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
// background.js — service worker for Focus Mode
// Environment Detection - FORCE PRODUCTION MODE
function isDevelopment() {
// Always return false to use production API
// To enable development mode, set this to true manually
return false;
}
// API Configuration - Environment aware
const API_URL = isDevelopment()
? 'http://localhost:3000/api'
: 'https://focus-backend-g1zg.onrender.com/api';
const API_BASE_URL = isDevelopment()
? 'http://localhost:3000'
: 'https://focus-backend-g1zg.onrender.com';
console.log('[Background Environment] Mode:', isDevelopment() ? 'DEVELOPMENT' : 'PRODUCTION');
console.log('[Background Environment] API URL:', API_URL);
// Version control
let extensionBlocked = false;
let blockReason = '';
// Import update checker
importScripts('update-checker.js');
// Show What's New page on December 25th, 2025
chrome.runtime.onInstalled.addListener((details) => {
const now = new Date();
const launchDate = new Date('2025-12-25T00:00:00');
// Only show on or after December 25th, 2025
if (now >= launchDate) {
if (details.reason === 'install') {
// First-time install - show what's new page
chrome.tabs.create({ url: chrome.runtime.getURL('pages/whats-new.html') });
} else if (details.reason === 'update') {
const manifest = chrome.runtime.getManifest();
const currentVersion = manifest.version;
// Check if user has already seen this version's update page
chrome.storage.local.get(['lastSeenUpdateVersion'], (result) => {
if (result.lastSeenUpdateVersion !== currentVersion && currentVersion === '2.6.0') {
chrome.tabs.create({ url: chrome.runtime.getURL('pages/whats-new.html') });
// Mark this version as seen
chrome.storage.local.set({ lastSeenUpdateVersion: currentVersion });
}
});
}
}
});
// Core social media sites that are ALWAYS blocked during focus mode (cannot be removed)
const PERMANENT_BLOCKED_SITES = [
"instagram.com",
"facebook.com",
"x.com",
"twitter.com",
"reddit.com",
"tiktok.com",
"snapchat.com"
];
const DEFAULTS = {
allowed: ["https://www.youtube.com/","https://youtube.com/","https://www.google.com/"],
blockedKeywords: [
"whatsapp.com", "github.com", "quora.com", "pinterest.com",
"edxtratech.com", "edxtra.tech", "linkedin.com",
"netflix.com", "discord.com", "twitch.tv", "9gag.com", "imgur.com"
],
stats: {blockedCount: 0, attempts: 0, totalFocusTime: 0, sessionsCompleted: 0},
emergencyUsed: false,
streak: {current: 0, longest: 0, lastSessionDate: null},
points: 0,
level: 1,
badges: [],
dailyGoal: 120,
idleTimeAccumulated: 0, // minutes
todayFocusTime: 0,
todayDate: (() => {
// IST is UTC+5:30
const d = new Date();
const istOffset = 5.5 * 60 * 60 * 1000; // 5 hours 30 minutes in milliseconds
const istTime = new Date(d.getTime() + istOffset);
return istTime.toISOString().substring(0, 10);
})(),
presets: {
deepWork: {name: "Deep Work", duration: 90, allowedSites: ["https://www.google.com/"]},
study: {name: "Study", duration: 45, allowedSites: ["https://www.youtube.com/", "https://www.google.com/"]},
quickFocus: {name: "Quick Focus", duration: 15, allowedSites: []}
},
pomodoroEnabled: false,
pomodoroBreakDuration: 5,
theme: 'dark',
// Social features
user: null, // {userId, username, displayName, avatar, createdAt}
friends: [], // Array of friend userIds
friendsData: {}, // {userId: {username, displayName, avatar, stats, activity}}
activity: {status: 'offline', currentUrl: null, focusActive: false, lastUpdated: null},
allUsers: {} // Simple user registry (username -> userData)
};
// Check if extension version is blocked due to critical bugs
async function checkVersionStatus() {
try {
const manifest = chrome.runtime.getManifest();
const currentVersion = manifest.version;
const response = await fetch(`${API_BASE_URL}/api/version/check?version=${currentVersion}`, {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
});
if (response.ok) {
const data = await response.json();
if (!data.allowed) {
extensionBlocked = true;
blockReason = data.message;
console.error('[Version] 🚨 EXTENSION BLOCKED:', data.message);
console.error('[Version] Current:', currentVersion, 'Minimum Required:', data.minimumVersion);
// Show critical notification
chrome.notifications.create('critical-update-notification', {
type: 'basic',
iconUrl: 'icons/icon48.png',
title: '🚨 Critical Update Required',
message: data.message + ' Extension features are disabled.',
priority: 2,
requireInteraction: true,
buttons: [
{ title: 'Update Now' }
]
});
// Handle notification click to open critical update page
chrome.notifications.onButtonClicked.addListener((notifId, btnIdx) => {
if (notifId === 'critical-update-notification' && btnIdx === 0) {
chrome.tabs.create({ url: chrome.runtime.getURL('pages/critical-update.html') });
}
});
chrome.notifications.onClicked.addListener((notifId) => {
if (notifId === 'critical-update-notification') {
chrome.tabs.create({ url: chrome.runtime.getURL('pages/critical-update.html') });
}
});
// Store blocked status
await chrome.storage.local.set({
extensionBlocked: true,
blockReason: data.message,
minimumVersion: data.minimumVersion
});
return false;
} else {
extensionBlocked = false;
await chrome.storage.local.set({ extensionBlocked: false });
console.log('[Version] ✅ Version check passed:', currentVersion);
return true;
}
}
} catch (error) {
console.error('[Version] Failed to check version:', error);
// Don't block on network error
return true;
}
}
async function getState() {
const s = await chrome.storage.local.get();
return Object.assign({}, DEFAULTS, s);
}
function nowMs(){return Date.now();}
async function enforceTab(tab) {
if (!tab || !tab.url || tab.url.startsWith('chrome://') || tab.url.startsWith('about:')) return;
const state = await getState();
const {focusActive, sessionEnd, onBreak} = state;
const tNow = nowMs();
const url = tab.url.toLowerCase();
const hostname = (new URL(tab.url)).hostname.toLowerCase();
console.log('[EnforceTab] Checking tab:', hostname);
// ALWAYS check permanently blocked sites first (24/7 blocking)
const permanentBlocked = state.permanentBlocked || [];
console.log('[EnforceTab] Permanent blocked list:', permanentBlocked);
for (const site of permanentBlocked) {
const siteLower = site.toLowerCase();
console.log('[EnforceTab] Checking if', hostname, 'matches', siteLower);
if (url.includes(siteLower) || hostname.includes(siteLower)) {
console.log('[PermanentBlock] ⛔ BLOCKING permanently blocked site:', hostname);
await chrome.tabs.update(tab.id, {url: chrome.runtime.getURL('pages/blocked.html')});
await incrementStat('blockedCount');
return;
}
}
console.log('[EnforceTab] Not in permanent block list, continuing...');
// Only enforce focus mode restrictions when focus mode is active AND not on break
if (!focusActive || !sessionEnd || tNow > sessionEnd || onBreak) {
console.log('[EnforceTab] Focus mode not active, allowing site');
return;
}
// Allowed check (simple substring match for now)
for (const a of state.allowed || []) {
if (!a) continue;
const allowedHost = a.replace(/^https?:\/\//, '').replace(/\/$/, ''); // Remove protocol and trailing slash
if (url.includes(allowedHost) || hostname.includes(allowedHost)) return; // allowed — keep
}
// YouTube is allowed - removed single-tab restriction to allow multiple YouTube tabs
if (hostname.includes('youtube.com')) {
return; // Allow all YouTube tabs
}
// Check permanent blocked sites first (always blocked during focus)
for (const site of PERMANENT_BLOCKED_SITES) {
if (url.includes(site) || hostname.includes(site)) {
await chrome.tabs.update(tab.id, {url: chrome.runtime.getURL('pages/blocked.html')});
await incrementStat('blockedCount');
return;
}
}
// Blocked keywords check (custom user-added sites)
for (const kw of state.blockedKeywords || []) {
if (!kw) continue;
if (url.includes(kw) || hostname.includes(kw)) {
// redirect to local blocked page
await chrome.tabs.update(tab.id, {url: chrome.runtime.getURL('pages/blocked.html')});
await incrementStat('blockedCount');
return;
}
}
}
async function incrementStat(key) {
const s = await chrome.storage.local.get({stats: DEFAULTS.stats, sessionBlockedCount: 0});
s.stats = s.stats || {blockedCount:0, attempts:0};
s.stats[key] = (s.stats[key]||0)+1;
// Track session-specific blocked attempts for focus score calculation
if (key === 'blockedCount') {
s.sessionBlockedCount = (s.sessionBlockedCount || 0) + 1;
}
await chrome.storage.local.set({stats: s.stats, sessionBlockedCount: s.sessionBlockedCount});
// Sync blocked count to MongoDB
if (key === 'blockedCount') {
try {
const token = (await chrome.storage.local.get('authToken'))?.authToken;
const state = await getState();
if (token) {
await fetch(`${API_URL}/users/stats`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({
stats: {
sitesBlocked: s.stats.blockedCount,
totalFocusTime: state.stats?.totalFocusTime || 0,
sessionsCompleted: state.stats?.sessionsCompleted || 0
}
})
});
}
} catch (error) {
console.error('Failed to sync blocked count:', error);
}
}
}
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
// Enforce focus mode restrictions
if (changeInfo.status === 'complete' || changeInfo.url) {
enforceTab(tab).catch(console.error);
}
});
chrome.tabs.onCreated.addListener((tab) => {
enforceTab(tab).catch(console.error);
});
chrome.tabs.onActivated.addListener(async (activeInfo) => {
try {
const tab = await chrome.tabs.get(activeInfo.tabId);
enforceTab(tab).catch(console.error);
// Track browsing activity during focus session
await trackBrowsingActivity(tab);
// Update activity immediately
await updateUserActivity(tab);
// Also send to backend immediately
await sendActivityHeartbeat();
} catch (e) { /* ignore */ }
});
// Whitelist of educational/study domains that should not count as distractions
const STUDY_DOMAINS = [
'web.getmarks.app',
'getmarks.app',
'docs.google.com',
'drive.google.com',
'classroom.google.com',
'scholar.google.com',
'notion.so',
'notion.com',
'github.com',
'stackoverflow.com',
'stackexchange.com',
'coursera.org',
'udemy.com',
'khanacademy.org',
'edx.org',
'brilliant.org',
'leetcode.com',
'hackerrank.com',
'codecademy.com',
'freecodecamp.org',
'w3schools.com',
'mdn.mozilla.org',
'wikipedia.org',
'wolframalpha.com',
'desmos.com',
'geogebra.org',
'quizlet.com',
'anki.com',
'brainly.com',
'chegg.com',
'studyblue.com',
'grammarly.com',
'overleaf.com',
'latex.org',
'arxiv.org',
'researchgate.net',
'medium.com',
'dev.to'
];
// Check if a domain is a study/educational resource
function isStudyResource(domain) {
return STUDY_DOMAINS.some(studyDomain => domain.includes(studyDomain));
}
// Track browsing activity during focus session
async function trackBrowsingActivity(tab) {
if (!tab || !tab.url) return;
const state = await getState();
if (!state.focusActive) return; // Only track during focus session
// Get current session activities
const result = await chrome.storage.local.get(['sessionActivities']);
const activities = result.sessionActivities || [];
// Extract domain and title
let domain = 'Unknown';
let icon = '🌐';
try {
const url = new URL(tab.url);
domain = url.hostname.replace('www.', '');
// Skip study resources - they shouldn't count as distractions
if (isStudyResource(domain)) {
console.log('[Activity] Skipping study resource:', domain, '(not counted as distraction)');
return;
}
// Set icon based on domain
if (domain.includes('youtube')) icon = '📺';
else if (domain.includes('github')) icon = '💻';
else if (domain.includes('stackoverflow')) icon = '📚';
else if (domain.includes('google')) icon = '🔍';
else if (tab.url.endsWith('.pdf')) icon = '📄';
else if (domain.includes('docs.google') || domain.includes('notion')) icon = '📝';
} catch (e) {
// Invalid URL, skip
return;
}
// Add activity (only non-study sites reach here)
activities.push({
domain: domain,
title: tab.title || domain,
icon: icon,
timestamp: Date.now()
});
// Keep only last 50 activities to avoid memory issues
const recentActivities = activities.slice(-50);
console.log('[Activity] Tracked activity:', domain, '- Total activities:', recentActivities.length);
await chrome.storage.local.set({ sessionActivities: recentActivities });
}
// Track user activity
async function updateUserActivity(tab) {
if (!tab || !tab.url) return;
const state = await getState();
if (!state.user) return; // Not registered
let currentActivity = 'browsing';
let currentUrl = tab.url;
let videoTitle = null;
let status = 'online';
// Check what user is doing
if (state.focusActive) {
status = 'focusing';
currentActivity = 'focusing';
} else if (tab.url.includes('youtube.com/watch')) {
status = 'youtube';
currentActivity = 'youtube';
// Save the actual video URL (not the oEmbed fetch URL)
const videoUrl = tab.url;
// Extract video ID and fetch video details from YouTube oEmbed
try {
const urlParams = new URL(videoUrl);
const videoId = urlParams.searchParams.get('v');
if (videoId) {
console.log('[Activity] Fetching YouTube video info for:', videoId);
const oembedUrl = `https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=${videoId}&format=json`;
const response = await fetch(oembedUrl);
if (response.ok) {
const videoData = await response.json();
videoTitle = videoData.title || null;
// Store additional video info (use actual video URL, not oEmbed URL)
await chrome.storage.local.set({
youtubeVideo: {
title: videoData.title,
thumbnail: videoData.thumbnail_url,
channel: videoData.author_name,
videoId: videoId,
url: videoUrl // Use the actual video URL
}
});
console.log('[Activity] ✅ YouTube video info:', videoData.title);
} else {
console.log('[Activity] ⚠️ oEmbed API failed, using fallback');
// Fallback: try to extract from page
const result = await chrome.scripting.executeScript({
target: { tabId: tab.id },
func: () => document.title.replace(/ - YouTube$/, '').trim()
});
if (result && result[0]?.result) {
videoTitle = result[0].result;
}
}
}
} catch (e) {
console.error('[Activity] Error fetching video info:', e);
}
}
await chrome.storage.local.set({
activity: {
status: status,
currentActivity,
currentUrl: currentUrl.substring(0, 100), // Limit length
tabTitle: tab.title || null, // Include tab title
videoTitle: videoTitle,
focusActive: state.focusActive || false,
lastUpdated: Date.now()
}
});
// Also get the stored YouTube video info if available
const storedVideo = await chrome.storage.local.get('youtubeVideo');
if (storedVideo.youtubeVideo && status === 'youtube') {
await chrome.storage.local.set({
activity: {
status: status,
currentActivity,
currentUrl: currentUrl.substring(0, 100),
tabTitle: tab.title || null, // Include tab title
videoTitle: storedVideo.youtubeVideo.title,
videoThumbnail: storedVideo.youtubeVideo.thumbnail,
videoChannel: storedVideo.youtubeVideo.channel,
focusActive: state.focusActive || false,
lastUpdated: Date.now()
}
});
}
}
// Idle state detection DISABLED - Don't pause timer when user works in other browsers
// If user switches to another browser to work, Chrome detects it as "idle" and extends the timer
// This causes a 30min session to take 40+ minutes in real time
/*
chrome.idle.onStateChanged.addListener(async (newState) => {
const state = await getState();
if (!state.focusActive) return; // Only care about idle during focus sessions
console.log('[Idle] State changed to:', newState);
if (newState === 'idle' || newState === 'locked') {
// User went idle or locked screen - pause the timer
console.log('[Idle] ⚠️ User went idle during focus session, pausing timer');
await chrome.storage.local.set({
idlePausedAt: Date.now(),
wasIdleDuringSession: true
});
// Show notification
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon48.png',
title: '⏸️ Timer Paused',
message: 'Focus timer paused because you went idle. Resume when you return!',
priority: 1
});
} else if (newState === 'active') {
// User came back - resume timer
const idlePausedAt = state.idlePausedAt;
if (idlePausedAt) {
const idleDuration = Date.now() - idlePausedAt;
const idleMinutes = Math.floor(idleDuration / 60000);
console.log('[Idle] ✅ User returned, was idle for', idleMinutes, 'minutes');
// Extend session end time by idle duration (don't count idle time)
const newSessionEnd = state.sessionEnd + idleDuration;
const newSessionDuration = (state.sessionDuration || 0) + idleDuration;
const totalIdleTime = (state.idleTimeAccumulated || 0) + idleDuration;
// IMPORTANT: Do NOT extend plannedDurationSeconds - it should remain the original value
// Only sessionEnd is extended to pause the timer, but final stats use original planned duration
await chrome.storage.local.set({
sessionEnd: newSessionEnd,
sessionDuration: newSessionDuration,
idlePausedAt: 0,
idleTimeAccumulated: totalIdleTime
// plannedDurationSeconds is NOT updated - keeps original value
});
// Update alarm
chrome.alarms.create('focus-end', { when: newSessionEnd });
console.log('[Idle] Extended session end time by', idleMinutes, 'minutes');
// Show notification
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon48.png',
title: '▶️ Timer Resumed',
message: `Welcome back! Timer extended by ${idleMinutes} minutes (idle time doesn't count).`,
priority: 1
});
}
}
});
*/
// Alarms to end session when time's up
chrome.alarms.onAlarm.addListener(async (alarm) => {
if (alarm.name === 'activity-heartbeat') {
// Handle activity heartbeat
await sendActivityHeartbeat();
} else if (alarm.name === 'presence-check') {
// Handle presence check notification
const state = await getState();
if (state.focusActive) {
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon48.png',
title: '👋 Are you still there?',
message: 'Tap to confirm you\'re still focusing',
requireInteraction: true,
buttons: [{ title: 'Yes, I\'m here!' }]
}, (notificationId) => {
// Store notification ID for handling response
chrome.storage.local.set({ lastPresenceCheckId: notificationId });
});
// Schedule next check
schedulePresenceChecks();
}
} else if (alarm.name === 'break-end') {
// End the emergency break, resume blocking
await chrome.storage.local.set({onBreak: false});
console.log('[EmergencyBreak] Break ended, resuming blocking');
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon48.png',
title: 'Break Over ⏰',
message: 'Emergency break ended. Back to focus mode!'
});
} else if (alarm.name === 'focus-end') {
const state = await getState();
// CRITICAL: Check if session is still active to prevent double-processing
if (!state.focusActive) {
console.log('[SessionEnd] ⚠️ Session already ended, skipping duplicate alarm');
return;
}
// ALWAYS use the exact planned duration that was stored at session start
// Fallback: If plannedDurationSeconds is missing/invalid, calculate from session times
let durationSeconds = state.plannedDurationSeconds;
if (!durationSeconds || durationSeconds <= 0) {
console.warn('[SessionEnd] ⚠️ plannedDurationSeconds missing or invalid:', durationSeconds);
console.warn('[SessionEnd] Calculating from sessionStart and sessionEnd...');
// Calculate from actual session times (fallback)
const sessionStart = state.sessionStart || 0;
const sessionEnd = state.sessionEnd || Date.now();
const elapsedMs = sessionEnd - sessionStart;
const elapsedSeconds = Math.floor(elapsedMs / 1000);
// Round to nearest 5-minute interval (300 seconds) since all timers are multiples of 5
const fiveMinutes = 5 * 60; // 300 seconds
durationSeconds = Math.round(elapsedSeconds / fiveMinutes) * fiveMinutes;
console.warn('[SessionEnd] Calculated duration:', elapsedSeconds, 'seconds (raw) →', durationSeconds, 'seconds (rounded to 5-min interval)');
}
console.log('[SessionEnd] ================================');
console.log('[SessionEnd] State plannedDurationSeconds:', state.plannedDurationSeconds);
console.log('[SessionEnd] State sessionStart:', new Date(state.sessionStart).toISOString());
console.log('[SessionEnd] State sessionEnd:', new Date(state.sessionEnd).toISOString());
console.log('[SessionEnd] State sessionDuration:', state.sessionDuration, 'ms');
console.log('[SessionEnd] State idleTimeAccumulated:', state.idleTimeAccumulated, 'ms');
console.log('[SessionEnd] Using duration:', durationSeconds, 'seconds (', Math.floor(durationSeconds / 60), 'minutes', durationSeconds % 60, 'seconds)');
console.log('[SessionEnd] ================================');
// Get session activities
const result = await chrome.storage.local.get(['sessionActivities']);
const activities = result.sessionActivities || [];
// Save session summary with EXACT planned duration
await chrome.storage.local.set({
sessionSummary: {
duration: durationSeconds,
activities: activities,
completedAt: Date.now()
}
});
// Clear session activities
await chrome.storage.local.remove('sessionActivities');
// Use milliseconds for stats calculation
const actualDuration = durationSeconds * 1000;
// Check minimum session duration (15 minutes = 900000 ms)
const minimumDuration = 15 * 60 * 1000; // 15 minutes minimum
const earnedPoints = actualDuration >= minimumDuration;
if (!earnedPoints) {
console.log('[SessionEnd] Session too short for points:', Math.floor(actualDuration / 60000), 'minutes (minimum: 15 minutes)');
} else {
console.log('[SessionEnd] Updating stats for', Math.floor(actualDuration / 60000), 'minute session');
// Update stats using ACTUAL elapsed time
await updateSessionStats(actualDuration);
}
// IMPORTANT: Set focusActive to false FIRST to prevent duplicate processing
await chrome.storage.local.set({focusActive:false, sessionEnd: 0, emergencyUsed: false, sessionBlockedCount: 0});
// Clear alarms
chrome.alarms.clear('focus-end');
// Notify popup to update UI
chrome.runtime.sendMessage({ action: 'sessionEnded' }).catch(() => {
// Popup might not be open, that's okay
});
// Update activity back to online
try {
const token = (await chrome.storage.local.get('authToken'))?.authToken;
if (token) {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
const currentTab = tabs[0];
const activity = getDetailedActivity(currentTab?.url, currentTab?.title, false);
await chrome.storage.local.set({ activity: activity });
const activityToSend = {
status: activity.status || 'online',
focusActive: false,
currentUrl: activity.currentUrl || null,
videoTitle: activity.videoTitle || null,
videoThumbnail: activity.videoThumbnail || null,
videoChannel: activity.videoChannel || null,
activityType: activity.activityType || null,
activityDetails: activity.activityDetails || null,
actionButton: activity.actionButton || null
};
await fetch(`${API_BASE_URL}/api/users/activity`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
body: JSON.stringify({ activity: activityToSend })
});
}
} catch (error) {
console.error('[SessionEnd] Error updating activity:', error);
}
// Update session summary with points earned status
await chrome.storage.local.set({
sessionSummary: {
duration: durationSeconds,
activities: activities,
completedAt: Date.now(),
earnedPoints: earnedPoints,
minimumDuration: minimumDuration / 60000 // Store in minutes
}
});
// Open session summary popup AFTER stats are updated
console.log('[SessionEnd] Opening session summary popup with', activities.length, 'activities');
chrome.windows.create({
url: chrome.runtime.getURL('pages/session-summary.html'),
type: 'popup',
width: 650,
height: 700
}, (window) => {
console.log('[SessionEnd] Session summary window created:', window.id);
});
// Start break time
const breakDuration = 5; // 5 minutes break
const breakEnd = Date.now() + (breakDuration * 60 * 1000);
await chrome.storage.local.set({
onBreak: true,
breakEnd: breakEnd,
breakDuration: breakDuration * 60 * 1000
});
// Set alarm to end break
chrome.alarms.create('auto-break-end', { when: breakEnd });
// Show break notification
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon48.png',
title: '🎉 Focus Session Complete!',
message: `You focused for ${Math.floor(durationSeconds / 60)} minutes! Take a ${breakDuration} minute break.`,
requireInteraction: true
});
} else if (alarm.name === 'auto-break-end') {
// End the auto break
await chrome.storage.local.set({onBreak: false, breakEnd: 0});
console.log('[AutoBreak] Break ended');
chrome.notifications.create({
type: 'basic',
iconUrl: 'icons/icon48.png',
title: '⏰ Break Over!',
message: 'Break time ended. Ready for another focus session?'
});
} else if (alarm.name === 'sync-from-mongodb') {
console.log('[AutoSync] Pulling fresh data from MongoDB (source of truth)...');
await syncFromMongoDB();
} else if (alarm.name === 'version-check') {
console.log('[VersionCheck] Performing periodic version check...');
await checkVersionStatus();
} else if (alarm.name === 'check-storage') {
await checkStorageQuota();
} else if (alarm.name === 'retry-sync') {
// Retry syncing if we have pending offline data
const state = await chrome.storage.local.get(['pendingSync', 'authToken']);
if (state.pendingSync && state.authToken) {
console.log('[RetrySync] Attempting to sync offline data...');
const success = await syncCurrentStateToMongoDB();
if (success) {
await chrome.storage.local.set({ pendingSync: false });
console.log('[RetrySync] ✅ Successfully synced offline data!');
await syncFromMongoDB(); // Pull back to verify
} else {
console.warn('[RetrySync] ⚠️ Still offline, will retry later');
// Retry again in 5 minutes
chrome.alarms.create('retry-sync', { delayInMinutes: 5 });
}
}
}
});
// Helper function to sync current state to MongoDB (Global scope)
// CRITICAL: Only call this after completing a session or earning achievements
// MongoDB uses incremental updates only (never decreases values)
async function syncCurrentStateToMongoDB() {
try {
const token = (await chrome.storage.local.get('authToken'))?.authToken;
if (!token) {
console.log('[Sync] No auth token, skipping sync');
return false;
}
const currentState = await chrome.storage.local.get(['stats', 'points', 'level', 'badges', 'streak', 'focusHistory']);
console.log('[Sync] Sending incremental update to MongoDB:', {
totalFocusTime: currentState.stats?.totalFocusTime,
sessions: currentState.stats?.sessionsCompleted,
points: currentState.points,
level: currentState.level
});
// Add timeout for offline detection
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000); // 10 second timeout
const response = await fetch(`${API_URL}/users/stats`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({
stats: currentState.stats,
streak: currentState.streak,
badges: currentState.badges || [], // Send full badge objects
points: currentState.points,
level: currentState.level,
focusHistory: currentState.focusHistory || {}
}),
signal: controller.signal
});
clearTimeout(timeoutId);
if (response.ok) {
const result = await response.json();
console.log('[Sync] ✅ Incremental update sent to MongoDB (server validates no decreases)');
// Check if server rejected any values
if (result.rejected) {
if (result.rejected.totalFocusTime || result.rejected.sessionsCompleted) {
console.warn('[Sync] ⚠️ Server rejected some values - local data is WRONG');
console.warn('[Sync] Local had:', currentState.stats);
console.warn('[Sync] MongoDB has:', result.user.stats);
// Update local storage with correct MongoDB values
await chrome.storage.local.set({
stats: result.user.stats,
points: result.user.points,
level: result.user.level,
badges: result.user.badges,
streak: result.user.streak
});
console.log('[Sync] ✅ Corrected local data from MongoDB response');
}
}
return true;
} else {
const errorText = await response.text();
console.error('[Sync] MongoDB sync failed:', response.status, errorText);
return false;
}
} catch (error) {
if (error.name === 'AbortError') {
console.warn('[Sync] ⚠️ Request timeout - likely offline or poor connection');
} else {
console.error('[Sync] Failed to sync current state:', error.message);
}
// Don't throw - allow offline usage, data will sync when back online
return false;
}
}
// Update session stats and gamification
async function updateSessionStats(durationMs) {
const state = await getState();
const durationMin = Math.floor(durationMs / 60000);
// Calculate focus score based on blocked attempts
const sessionBlockedCount = state.sessionBlockedCount || 0;
// Focus Score: 100% - (blocked attempts / (minutes * 0.5))
// Allows ~0.5 blocks per minute before score drops significantly
// Examples:
// - 0 blocks in 30min = 100% score
// - 5 blocks in 30min = 67% score
// - 15 blocks in 30min = 0% score
const maxExpectedBlocks = durationMin * 0.5;
let focusScore = Math.max(0, 100 - (sessionBlockedCount / maxExpectedBlocks * 100));
focusScore = Math.min(100, focusScore); // Cap at 100%
// Focus multiplier (0.3x to 1.0x based on score)
// Even low focus gives some XP, but focused sessions get full rewards
const focusMultiplier = 0.3 + (focusScore / 100 * 0.7);
console.log(`[FocusScore] Blocked: ${sessionBlockedCount}, Duration: ${durationMin}min, Score: ${focusScore.toFixed(1)}%, Multiplier: ${focusMultiplier.toFixed(2)}x`);
// Update stats
const newTotalTime = (state.stats.totalFocusTime || 0) + durationMin;
const newSessions = (state.stats.sessionsCompleted || 0) + 1;
// CRITICAL: Use session START time for date tracking (not end time)
// This ensures cross-midnight sessions (e.g., 11:40 PM to 1 AM) are credited to the correct day
let sessionStartTime = state.sessionStart || Date.now();
// Validate session start time (detect clock issues)
const now = Date.now();
if (sessionStartTime > now) {
console.warn('[SessionTracking] ⚠️ Session start time is in the future! Clock drift detected.');
console.warn('[SessionTracking] Using current time instead');
sessionStartTime = now - durationMs; // Estimate start time
}
if (now - sessionStartTime > 24 * 60 * 60 * 1000) {
console.warn('[SessionTracking] ⚠️ Session started more than 24 hours ago!');
console.warn('[SessionTracking] This might be a stuck session or clock issue');
}
const sessionStartDate = new Date(sessionStartTime);
// Update daily focus time with IST date comparison (IST = UTC+5:30)
const istOffset = 5.5 * 60 * 60 * 1000; // 5 hours 30 minutes in milliseconds
const sessionStartIST = new Date(sessionStartDate.getTime() + istOffset);
const sessionDateString = sessionStartIST.toISOString().substring(0, 10); // YYYY-MM-DD in IST
console.log('[SessionTracking] Session started at:', sessionStartDate.toISOString());
console.log('[SessionTracking] Session date (IST):', sessionDateString);
console.log('[SessionTracking] Duration:', durationMin, 'minutes');
let todayTime = state.todayFocusTime || 0;
const storedDate = state.todayDate || '';
// Check if we need to update today's time or if this session belongs to a previous day
const currentTime = new Date();
const currentDateIST = new Date(currentTime.getTime() + istOffset);
const currentDateString = currentDateIST.toISOString().substring(0, 10);
if (sessionDateString === currentDateString) {
// Session belongs to today - add to today's time
if (storedDate !== currentDateString) {
todayTime = 0; // Reset if it's a new day
}
todayTime += durationMin;
console.log('[SessionTracking] ✅ Session credited to today:', currentDateString, '- Total today:', todayTime, 'min');
} else {
// Session started on a previous day (cross-midnight or delayed sync)
console.log('[SessionTracking] ⚠️ Session belongs to', sessionDateString, '(not today:', currentDateString, ')');
// Don't add to todayTime, but still update streak and history for that date
}
// Update streak with IST-based date comparison (Duolingo-style)
// CRITICAL: Use session START date for streak tracking
let lastDate = state.streak?.lastSessionDate;
// Migrate old date format to new format
lastDate = normalizeDateToISO(lastDate);
// Get yesterday based on session start date
const yesterdaySessionIST = new Date(sessionStartIST.getTime() - (24 * 60 * 60 * 1000));
const yesterdayDateString = yesterdaySessionIST.toISOString().substring(0, 10);
let currentStreak = state.streak?.current || 0;
let longestStreak = state.streak?.longest || 0;
console.log('[Streak] Last session date (normalized):', lastDate);
console.log('[Streak] This session date (IST):', sessionDateString);
console.log('[Streak] Yesterday from session (IST):', yesterdayDateString);
console.log('[Streak] Current streak before update:', currentStreak);
// Duolingo-style streak logic:
// - Only increment on FIRST session of each day
// - If last session was yesterday, continue streak (+1)
// - If last session was today, keep current streak (no increment)
// - If last session was before yesterday, streak was already broken by checkStreakOnLogin()
if (!lastDate) {
// First session ever
currentStreak = 1;