-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
100 lines (89 loc) · 2.51 KB
/
Copy pathbackground.js
File metadata and controls
100 lines (89 loc) · 2.51 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
// --------------------
// EXTENSION INSTALL
// --------------------
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.sync.set({
isFocusOn: false,
focusEndTime: 0,
sessionMinutes: 0,
blockedSites: ["youtube.com", "instagram.com", "facebook.com"],
totalPoints: 0,
level: "Bronze",
history: {}
});
});
// --------------------
// LEVEL LOGIC
// --------------------
function getLevel(points) {
if (points >= 1500) return "Platinum";
if (points >= 600) return "Gold";
if (points >= 200) return "Silver";
return "Bronze";
}
// --------------------
// SAVE FOCUS HISTORY
// --------------------
function saveFocusHistory(minutes, callback) {
const today = new Date().toLocaleDateString("en-CA");
chrome.storage.sync.get(["history"], (data) => {
const history = data.history || {};
history[today] = (history[today] || 0) + minutes;
chrome.storage.sync.set({ history }, () => {
if (callback) callback();
});
});
}
// --------------------
// MESSAGE LISTENER
// --------------------
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
// ⭐ SESSION COMPLETED
if (request.action === "SESSION_COMPLETED") {
const minutes = Number(request.minutes) || 0;
chrome.storage.sync.get(["totalPoints"], (data) => {
const currentPoints = data.totalPoints || 0;
const newPoints = currentPoints + minutes;
const newLevel = getLevel(newPoints);
saveFocusHistory(minutes, () => {
chrome.storage.sync.set(
{
totalPoints: newPoints,
level: newLevel,
isFocusOn: false,
focusEndTime: 0,
sessionMinutes: 0
},
() => {
sendResponse({
totalPoints: newPoints,
level: newLevel
});
}
);
});
});
return true; // keep sendResponse alive
}
// ❌ PENALTY FOR BLOCKED SITE VISIT
if (request.action === "BLOCKED_SITE_VISITED") {
chrome.storage.sync.get(["totalPoints"], (data) => {
const currentPoints = data.totalPoints || 0;
const newPoints = Math.max(0, currentPoints - 2);
const newLevel = getLevel(newPoints);
chrome.storage.sync.set(
{
totalPoints: newPoints,
level: newLevel
},
() => {
chrome.runtime.sendMessage({
action: "POINTS_UPDATED",
totalPoints: newPoints,
level: newLevel
}).catch(() => {});
}
);
});
}
});