-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
597 lines (507 loc) · 19.2 KB
/
Copy pathbackground.js
File metadata and controls
597 lines (507 loc) · 19.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
/**
* Splatoon 3 Rotation Tracker - Background Service Worker
* Handles data fetching, storage and notifications
*/
importScripts('utils.js', 'salmonRun.js');
// Initialize extension
chrome.runtime.onInstalled.addListener((details) => {
initializeExtension(details).catch(error => {
console.error('Extension initialization failed:', error);
});
});
async function initializeExtension(details) {
console.log('Splatoon Tracker extension installed/updated:', details.reason);
try {
// Set defaults only on a fresh install.
if (details.reason === 'install') {
const existing = await chrome.storage.sync.get(['enableNotifications']);
if (existing.enableNotifications === undefined) {
console.log('Setting default notification settings (fresh install)');
await chrome.storage.sync.set({
'enableNotifications': false,
'notifyRegular': false,
'notifyAnarchy': false,
'notifyXbattle': false,
'notifySalmon': false
});
}
}
} catch (error) {
// A sync-storage failure should not prevent the rotation cache from loading.
console.error('Failed to initialize notification settings:', error);
}
// Fetch directly. Chrome can stop an MV3 service worker before a timer fires.
await fetchAllData();
}
chrome.runtime.onStartup.addListener(() => {
fetchAllData().catch(error => console.error('Startup data fetch failed:', error));
});
// Listen for alarm - handles both smart refresh and fallback periodic refresh
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === 'refreshRotations' || alarm.name === 'smartRefresh') {
console.log(`Alarm triggered: ${alarm.name}`);
fetchAllData().catch(error => console.error('Alarm data fetch failed:', error));
}
});
/**
* Schedule the next smart refresh based on rotation end times
* @param {Object} rotationData The current rotation data
*/
async function scheduleNextRefresh(rotationData) {
const now = Date.now();
let nextRefreshTime = null;
// Find the earliest end time among all current rotations
const modes = ['regular', 'anarchy', 'xbattle', 'challenge', 'salmon'];
for (const mode of modes) {
const current = rotationData?.[mode]?.current;
if (current?.endTime) {
const endTime = new Date(current.endTime).getTime();
// Schedule refresh 1 minute after rotation ends
const refreshTime = endTime + (1 * 60 * 1000);
if (refreshTime > now && (!nextRefreshTime || refreshTime < nextRefreshTime)) {
nextRefreshTime = refreshTime;
}
}
}
// Clear both one-shot alarms so an earlier fallback cannot cause an extra fetch.
await Promise.all([
chrome.alarms.clear('smartRefresh'),
chrome.alarms.clear('refreshRotations')
]);
if (nextRefreshTime) {
const delayMinutes = (nextRefreshTime - now) / (60 * 1000);
console.log(`Scheduling smart refresh in ${delayMinutes.toFixed(1)} minutes (at ${new Date(nextRefreshTime).toLocaleTimeString()})`);
await chrome.alarms.create('smartRefresh', { when: nextRefreshTime });
} else {
// Fallback: if we can't determine the next refresh time, use periodic refresh
console.log('No valid end time found, falling back to periodic refresh');
await chrome.alarms.create('refreshRotations', {
delayInMinutes: Utils.API.REFRESH_INTERVAL
});
}
}
// Message handler
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request?.action === 'fetchRotations') {
fetchAllData()
.then(async success => {
const { isOffline = false } = await chrome.storage.local.get(['isOffline']);
sendResponse({ success, isOffline });
})
.catch(error => sendResponse({ success: false, error: error.message }));
return true; // Indicates async response
}
});
// Dedupe overlapping callers (alarm + popup message + onInstalled) within a
// single service-worker lifetime. They all join the same in-flight promise.
let inFlightFetch = null;
function fetchAllData() {
if (!inFlightFetch) {
inFlightFetch = _fetchAllData().finally(() => { inFlightFetch = null; });
}
return inFlightFetch;
}
/**
* Fetch the shared API data once and process both battle and Salmon Run data
* @returns {Promise<boolean>} Success status
*/
async function _fetchAllData() {
console.log('--- Starting data fetch cycle ---');
let oldRotationData = null;
try {
// Read the old value once for notification diffing and cache fallback.
({ rotationData: oldRotationData = null } =
await chrome.storage.local.get(['rotationData']));
const response = await fetch(Utils.API.SCHEDULES, { cache: 'no-store' });
if (!response.ok) throw new Error(`API error: ${response.status}`);
const apiData = await response.json();
const battleData = processRotationData(apiData);
const salmonData = SalmonRun.processSalmonRunData(apiData);
// If processing fails for either, treat as a fetch failure so the
// catch path falls back to cached data instead of writing fake values.
if (!battleData || !salmonData) {
throw new Error('API response shape invalid (battle or salmon processor returned null)');
}
const newRotationData = {
...battleData, // regular, anarchy, xbattle, challenge, splatfest
salmon: salmonData // current, next
};
await chrome.storage.local.set({
'rotationData': newRotationData,
'lastUpdated': new Date().toISOString(),
'isOffline': false
});
console.log('All rotation data updated successfully in a single operation.');
try {
await scheduleNextRefresh(newRotationData);
} catch (error) {
console.error('Failed to schedule the next refresh:', error);
await chrome.alarms.create('refreshRotations', {
delayInMinutes: Utils.API.REFRESH_INTERVAL
});
}
try {
await sendRotationNotifications(newRotationData, oldRotationData);
} catch (error) {
// Notification failures cannot invalidate data that was already stored.
console.error('Failed to send rotation notifications:', error);
}
return true;
} catch (error) {
console.error("Error in fetchAllData cycle:", error);
try {
await chrome.storage.local.set({ 'isOffline': true });
} catch (storageError) {
console.error('Failed to mark cached data offline:', storageError);
}
// Retry after every failure, including a failed first run with no cache.
try {
await chrome.alarms.create('refreshRotations', { delayInMinutes: 5 });
} catch (alarmError) {
console.error('Failed to schedule a retry:', alarmError);
}
// Use cached data only while at least one stored rotation is still useful.
if (oldRotationData && isDataStillValid(oldRotationData)) {
console.log('Network failed, using cached data');
return true;
}
return false;
}
}
/**
* Check if cached data is still valid (hasn't fully expired)
* @param {Object} rotationData The cached rotation data
* @returns {boolean} Whether the data is still valid
*/
function isDataStillValid(rotationData) {
const now = Date.now();
const modes = ['regular', 'anarchy', 'xbattle', 'challenge', 'salmon'];
for (const mode of modes) {
for (const slot of ['current', 'next']) {
const endTime = new Date(rotationData?.[mode]?.[slot]?.endTime).getTime();
if (Number.isFinite(endTime) && endTime > now) {
return true;
}
}
}
return false;
}
/**
* Validate that the API response has the expected structure
* @param {Object} data Raw API data
* @returns {boolean} Whether the data structure is valid
*/
function validateApiResponse(data) {
if (!data?.data) {
console.error('API validation failed: missing data root');
return false;
}
const d = data.data;
const scheduleKeys = [
'regularSchedules',
'bankaraSchedules',
'xSchedules',
'eventSchedules',
'festSchedules'
];
for (const key of scheduleKeys) {
if (d[key] && !Array.isArray(d[key].nodes)) {
console.error(`API validation failed: ${key}.nodes is not an array`);
return false;
}
}
if (d.coopGroupingSchedule) {
const coopKeys = ['regularSchedules', 'bigRunSchedules'];
for (const key of coopKeys) {
if (d.coopGroupingSchedule[key] && !Array.isArray(d.coopGroupingSchedule[key].nodes)) {
console.error(`API validation failed: coopGroupingSchedule.${key}.nodes is not an array`);
return false;
}
}
}
return true;
}
/**
* Process raw API data into structured rotation information
* @param {Object} data Raw API data
* @returns {Object|null} Processed rotation data or null on error
*/
function processRotationData(data) {
if (!validateApiResponse(data)) return null;
const now = new Date();
const result = {
regular: { current: null, next: null },
anarchy: { current: null, next: null },
xbattle: { current: null, next: null },
challenge: { current: null, next: null },
splatfest: null
};
try {
if (data.data.regularSchedules?.nodes) {
result.regular = findCurrentAndNext(data.data.regularSchedules.nodes, now, 'regular');
}
if (data.data.bankaraSchedules?.nodes) {
result.anarchy = findCurrentAndNextAnarchy(data.data.bankaraSchedules.nodes, now);
}
if (data.data.xSchedules?.nodes) {
result.xbattle = findCurrentAndNext(data.data.xSchedules.nodes, now, 'xbattle');
}
// Process Challenge/Event schedules
if (data.data.eventSchedules?.nodes) {
result.challenge = processEventSchedules(data.data.eventSchedules.nodes, now);
}
// Process Splatfest data
result.splatfest = processSplatfestData(data.data);
return result;
} catch (error) {
console.error('Error processing rotation data:', error);
return null;
}
}
/**
* Find current and next rotation from a list of rotation nodes
* @param {Array} nodes List of rotation nodes from API
* @param {Date} now Current time
* @param {string} mode Game mode (regular, anarchy, xbattle)
* @returns {Object} Object with current and next rotation
*/
function findCurrentAndNext(nodes, now, mode) {
let current = null;
let next = null;
if (!nodes?.length) return { current, next };
// Sort by start time to simplify the logic
const sortedNodes = [...nodes].sort((a, b) => new Date(a.startTime) - new Date(b.startTime));
const nowMs = now.getTime();
for (const node of sortedNodes) {
try {
if (!node.startTime || !node.endTime) continue;
const startTime = new Date(node.startTime);
const endTime = new Date(node.endTime);
const startMs = startTime.getTime();
const endMs = endTime.getTime();
if (!Number.isFinite(startMs) || !Number.isFinite(endMs) || endMs <= startMs) {
continue;
}
// Extract rule and stages based on the mode
let rule = { name: 'Unknown Mode' };
let stages = [];
if (mode === 'regular' && node.regularMatchSetting) {
rule = node.regularMatchSetting.vsRule || rule;
stages = (node.regularMatchSetting.vsStages || []).map(stage => ({
name: stage.name,
image: stage.image?.url || null
}));
} else if (mode === 'xbattle' && node.xMatchSetting) {
rule = node.xMatchSetting.vsRule || rule;
stages = (node.xMatchSetting.vsStages || []).map(stage => ({
name: stage.name,
image: stage.image?.url || null
}));
}
const processedNode = {
startTime: node.startTime,
endTime: node.endTime,
rule: rule,
stages: stages
};
// Current rotation is the one that spans the current time
if (startMs <= nowMs && endMs > nowMs) {
current = processedNode;
}
// Next rotation is the earliest one that starts after now
else if (startMs > nowMs && (!next || startMs < new Date(next.startTime).getTime())) {
next = processedNode;
}
} catch (error) {
console.error(`Error processing ${mode} node:`, error);
}
}
return { current, next };
}
/**
* Extract stages from a bankara match setting
* @param {Object} setting Match setting object
* @returns {Object} Extracted rule and stages
*/
function extractAnarchyMode(setting) {
if (!setting) return null;
return {
rule: setting.vsRule || { name: 'Unknown Mode' },
stages: (setting.vsStages || []).map(stage => ({
name: stage.name,
image: stage.image?.url || null
}))
};
}
/**
* Find current and next Anarchy rotations with both Series and Open modes
* @param {Array} nodes List of rotation nodes from API
* @param {Date} now Current time
* @returns {Object} Object with current and next rotation (each containing series and open)
*/
function findCurrentAndNextAnarchy(nodes, now) {
let current = null;
let next = null;
if (!nodes?.length) return { current, next };
const sortedNodes = [...nodes].sort((a, b) => new Date(a.startTime) - new Date(b.startTime));
const nowMs = now.getTime();
for (const node of sortedNodes) {
try {
if (!node.startTime || !node.endTime) continue;
const startMs = new Date(node.startTime).getTime();
const endMs = new Date(node.endTime).getTime();
if (!Number.isFinite(startMs) || !Number.isFinite(endMs) || endMs <= startMs) {
continue;
}
const series = extractAnarchyMode(node.bankaraMatchSettings?.[0]);
const open = extractAnarchyMode(node.bankaraMatchSettings?.[1]);
const processedNode = {
startTime: node.startTime,
endTime: node.endTime,
// Primary display uses Series data
rule: series?.rule || open?.rule || { name: 'Unknown Mode' },
stages: series?.stages || open?.stages || [],
// Both sub-modes available
series: series,
open: open
};
if (startMs <= nowMs && endMs > nowMs) {
current = processedNode;
} else if (startMs > nowMs && (!next || startMs < new Date(next.startTime).getTime())) {
next = processedNode;
}
} catch (error) {
console.error('Error processing anarchy node:', error);
}
}
return { current, next };
}
/**
* Process event/challenge schedule data
* @param {Array} nodes Event schedule nodes from API
* @param {Date} now Current time
* @returns {Object} Current and next challenge events
*/
function processEventSchedules(nodes, now) {
let current = null;
let next = null;
const nowMs = now.getTime();
for (const event of nodes) {
const setting = event.leagueMatchSetting;
if (!setting?.leagueMatchEvent) continue;
const eventInfo = setting.leagueMatchEvent;
const timePeriods = event.timePeriods || [];
const rule = setting.vsRule || { name: 'Unknown Mode' };
const stages = (setting.vsStages || []).map(s => ({
name: s.name,
image: s.image?.url || null
}));
for (const period of timePeriods) {
if (!period.startTime || !period.endTime) continue;
const startMs = new Date(period.startTime).getTime();
const endMs = new Date(period.endTime).getTime();
if (!Number.isFinite(startMs) || !Number.isFinite(endMs) || endMs <= startMs) {
continue;
}
const processedEvent = {
startTime: period.startTime,
endTime: period.endTime,
eventName: eventInfo.name || 'Unknown Event',
eventDesc: eventInfo.desc || '',
regulation: eventInfo.regulation || '',
rule: rule,
stages: stages
};
if (startMs <= nowMs && endMs > nowMs && !current) {
current = processedEvent;
} else if (startMs > nowMs && (!next || startMs < new Date(next.startTime).getTime())) {
next = processedEvent;
}
}
}
return { current, next };
}
/**
* Process Splatfest data from API response
* @param {Object} apiDataRoot The data.data object from the API
* @returns {Object|null} Splatfest info or null if none active/upcoming
*/
function processSplatfestData(apiDataRoot) {
// Check for currently active Splatfest
const currentFest = apiDataRoot.currentFest;
if (currentFest) {
return {
title: currentFest.title || 'Splatfest',
state: currentFest.state || 'ACTIVE',
startTime: currentFest.startTime,
endTime: currentFest.endTime,
teams: (currentFest.teams || []).map(t => ({
teamName: t.teamName,
color: t.color ? `rgba(${Math.round(t.color.r * 255)}, ${Math.round(t.color.g * 255)}, ${Math.round(t.color.b * 255)}, ${t.color.a})` : null,
image: t.image?.url || null
}))
};
}
// Check festSchedules for upcoming Splatfest periods with active settings
const festNodes = apiDataRoot.festSchedules?.nodes || [];
for (const node of festNodes) {
if (node.festMatchSettings && new Date(node.startTime).getTime() > Date.now()) {
return {
title: 'Upcoming Splatfest',
state: 'SCHEDULED',
startTime: node.startTime,
endTime: node.endTime,
teams: []
};
}
}
return null;
}
/**
* Compares new and old rotation data and sends notifications for changes.
* @param {Object} newRotations The latest, complete rotation data.
* @param {Object|null} oldRotations The data from before the fetch cycle began.
*/
async function sendRotationNotifications(newRotations, oldRotations) {
const settings = await chrome.storage.sync.get([
'enableNotifications', 'notifyRegular', 'notifyAnarchy', 'notifyXbattle', 'notifySalmon'
]);
if (!settings.enableNotifications) {
console.log("Notifications are disabled globally.");
return;
}
const modes = [
{ key: 'regular', name: 'Regular', setting: 'notifyRegular' },
{ key: 'anarchy', name: 'Anarchy', setting: 'notifyAnarchy' },
{ key: 'xbattle', name: 'X Battle', setting: 'notifyXbattle' },
{ key: 'salmon', name: 'Salmon Run', setting: 'notifySalmon' }
];
const isNewRotation = (newCurrent, oldCurrent) => {
if (!newCurrent) return false;
if (!oldCurrent) return true;
return newCurrent.startTime !== oldCurrent.startTime;
};
for (const modeInfo of modes) {
const newCurrent = newRotations[modeInfo.key]?.current;
const oldCurrent = oldRotations?.[modeInfo.key]?.current;
if (settings[modeInfo.setting] && isNewRotation(newCurrent, oldCurrent)) {
let title = `New ${modeInfo.name} Rotation!`;
let message;
if (modeInfo.key === 'salmon') {
message = `Stage: ${newCurrent.stage?.name || 'N/A'}`;
if (newCurrent.isBigRun) title = `BIG RUN IS HERE!`;
} else {
message = `Mode: ${newCurrent.rule?.name || 'N/A'}\nStages: ${newCurrent.stages?.map(s => s.name).join(', ') || 'N/A'}`;
}
const notificationId = `rotation-${modeInfo.key}-${newCurrent.startTime}`;
await chrome.notifications.create(notificationId, {
type: 'basic',
iconUrl: 'images/icon128.png',
title: title,
message: message,
priority: 1
});
console.log(`Notification sent for ${modeInfo.name}`);
}
}
}