-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
279 lines (254 loc) · 8.36 KB
/
background.js
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
// Background.js
// Debug configuration
let DEBUG = false;
// Debug function
const debug = (...args) => {
if (DEBUG) {
console.log(...args);
}
};
// Core variables
let streamers = [];
let refreshInterval = 1;
let intervalId = null;
// Clear streamers on browser startup
browser.runtime.onStartup.addListener(() => {
debug("Browser started. Clearing streamers...");
browser.storage.local.get(null).then((items) => {
const keysToRemove = Object.keys(items).filter(
(key) => key !== "notificationsEnabled" && key !== "refreshInterval"
);
browser.storage.local.remove(keysToRemove).then(() => {
debug("Streamers have been cleared after browser restart.");
});
});
});
// Initialize streamers and setup
browser.storage.local.get(null).then((items) => {
streamers = Object.keys(items).filter(
(streamer) =>
streamer !== "notificationsEnabled" && streamer !== "refreshInterval"
);
setupRefreshInterval();
startFetchingStreamers();
debug("Loaded streamers:", streamers);
});
debug("background.js script started, streamers:", streamers);
// Message listener
browser.runtime.onMessage.addListener((message, sender) => {
debug("Received message:", message.type, "from", sender);
switch (message.type) {
case "addStreamer":
return handleAddStreamer(message.content);
case "removeStreamer":
return handleRemoveStreamer(message.content);
case "refreshStreamers":
return handleRefreshStreamers();
case "toggleStreamer":
return handleToggleStreamer(message.content);
default:
return Promise.resolve({
status: "error",
error: "Unknown message type",
});
}
});
function handleAddStreamer(streamerName) {
debug("addStreamer message received. Streamer:", streamerName);
streamerName = streamerName.toLowerCase();
if (streamers.includes(streamerName)) {
return Promise.resolve({
status: "error",
error: "Streamer already exists",
});
}
return fetchAndUpdateStreamer(streamerName)
.then(() => {
streamers.push(streamerName);
updateBadgeCount();
debug("After Adding - streamers:", streamers);
return { status: "success" };
})
.catch((error) => {
debug("Error fetching and updating streamer:", error);
return { status: "error", error: error.toString() };
});
}
function handleRemoveStreamer(streamerName) {
debug("removeStreamer message received. Streamer:", streamerName);
streamerName = streamerName.toLowerCase();
const index = streamers.indexOf(streamerName);
if (index > -1) {
streamers.splice(index, 1);
return browser.storage.local.remove(streamerName).then(() => {
updateBadgeCount();
debug("Removed streamer from local storage:", streamerName);
return { status: "success" };
});
} else {
return Promise.resolve({ status: "error", error: "Streamer not found" });
}
}
function handleRefreshStreamers() {
debug("refreshStreamers message received.");
clearInterval(intervalId);
startFetchingStreamers();
return Promise.resolve({ status: "success" });
}
function handleToggleStreamer(streamerName) {
streamerName = streamerName.toLowerCase();
const index = streamers.indexOf(streamerName);
if (index === -1) {
return fetchAndUpdateStreamer(streamerName)
.then(() => {
streamers.push(streamerName);
debug("Streamer added:", streamerName);
return { status: "success" };
})
.catch((error) => {
debug("Error adding streamer:", error);
return { status: "error", error: error.toString() };
});
} else {
streamers.splice(index, 1);
debug("Streamer removed:", streamerName);
return browser.storage.local.remove(streamerName).then(() => {
updateBadgeCount();
debug("Removed streamer from local storage:", streamerName);
return { status: "success" };
});
}
}
function fetchAndUpdateStreamer(streamer) {
debug("fetchAndUpdateStreamer called for:", streamer);
return fetch(`https://kick.com/api/v2/channels/${streamer}`)
.then(handleResponse)
.then((data) => processStreamerData(streamer, data))
.then(updateBadgeCount)
.catch((error) => {
debug("Error in fetchAndUpdateStreamer:", error);
throw error;
});
}
function handleResponse(response) {
debug("Fetch response:", response);
if (!response.ok) {
if (response.status === 404) {
throw new Error("Streamer not found");
} else {
throw new Error("Network response was not ok");
}
}
return response.json();
}
function processStreamerData(streamer, data) {
let streamerData = extractStreamerData(data);
return browser.storage.local.get(streamer).then((storedData) => {
let shouldNotify = checkNotification(storedData[streamer], streamerData);
if (shouldNotify) {
showNotification(streamerData);
}
return browser.storage.local.set({ [streamer]: streamerData });
});
}
function extractStreamerData(data) {
return {
exactUsername: data.user ? data.user.username : "",
slug: data.slug || "",
isLive: data.livestream && data.livestream.is_live,
profilePic: data.user?.profile_pic ?? "user-profile-pic.png",
category: data.livestream?.categories?.[0]?.name ?? "Unknown",
title: data.livestream ? data.livestream.session_title : "",
viewer_count:
data.livestream && data.livestream.viewer_count
? data.livestream.viewer_count
: 0,
liveTime: data.livestream ? data.livestream.created_at : null,
};
}
function checkNotification(storedData, newData) {
return (
(!storedData && newData.isLive) ||
(storedData && !storedData.isLive && newData.isLive)
);
}
function calculateLiveTime(createdAt) {
if (!createdAt) return "00:00:00";
const start = new Date(createdAt + "Z");
const now = new Date();
const diffMs = now - start;
const hours = Math.floor(diffMs / 3600000);
const minutes = Math.floor((diffMs % 3600000) / 60000);
const seconds = Math.floor((diffMs % 60000) / 1000);
return `${hours.toString().padStart(2, "0")}:${minutes
.toString()
.padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
}
function showNotification(streamerData) {
const notificationOptions = {
type: "basic",
iconUrl: streamerData.profilePic,
title: `${streamerData.exactUsername} is now live!`,
message: `${streamerData.category}\n${streamerData.title}`,
};
browser.notifications
.create(streamerData.slug, notificationOptions)
.catch((error) => {
debug("Error creating notification:", error);
});
}
browser.notifications.onClicked.addListener((notificationId) => {
browser.storage.local.get(notificationId.toLowerCase()).then((data) => {
if (data[notificationId.toLowerCase()]) {
const slug = data[notificationId.toLowerCase()].slug;
browser.tabs.create({ url: `https://kick.com/${slug}` });
}
});
});
browser.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === "refresh") {
startFetchingStreamers();
}
});
function startFetchingStreamers() {
debug("Starting to fetch streamers...");
streamers.forEach(fetchAndUpdateStreamer);
}
function setupRefreshInterval() {
browser.storage.local.get("refreshInterval").then((result) => {
refreshInterval = result.refreshInterval || 1;
setupRefreshAlarm();
});
}
function setupRefreshAlarm() {
const interval = Number(refreshInterval);
const validInterval = isNaN(interval) ? 1 : interval;
browser.alarms.create("refresh", { periodInMinutes: validInterval });
debug(`Refresh alarm set for every ${validInterval} minutes`);
}
browser.storage.onChanged.addListener((changes, area) => {
if (area === "local" && changes.refreshInterval) {
refreshInterval = changes.refreshInterval.newValue;
setupRefreshAlarm();
}
});
function updateBadgeCount() {
return Promise.all(
streamers.map((streamer) =>
browser.storage.local
.get(streamer)
.then((data) => data[streamer] && data[streamer].isLive)
)
).then((results) => {
const liveCount = results.filter(Boolean).length;
browser.browserAction.setBadgeText({ text: liveCount.toString() });
browser.browserAction.setBadgeBackgroundColor({ color: "#706565" });
browser.browserAction.setBadgeTextColor({ color: "#ffffff" });
debug(`Badge updated: ${liveCount} live streamers`);
});
}
// Function to toggle debug mode
const toggleDebug = () => {
DEBUG = !DEBUG;
debug(`Debug mode ${DEBUG ? "enabled" : "disabled"}`);
};