-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
335 lines (289 loc) · 12.1 KB
/
background.js
File metadata and controls
335 lines (289 loc) · 12.1 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
const browserApi = typeof browser !== 'undefined' ? browser : chrome;
const actionApi = browserApi.action || browserApi.browserAction;
const urls = [
"https://mentalmars.com/game-news/tiny-tinas-wonderlands-shift-codes/",
"https://www.rockpapershotgun.com/tiny-tinas-wonderlands-shift-codes"
];
async function fetchCodesFromWebsites(urls, game = 'tinytina') {
let allCodes = new Set(); // Use a Set to automatically handle duplicates
for (const url of urls) {
try {
// Fetch the page content
const response = await fetch(url);
const text = await response.text();
// Use regex to extract SHIFT codes
const regex = /\b[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}\b/g;
const codes = text.match(regex) || []; // Match codes or fallback to an empty array
// Add codes to the set to ensure uniqueness
codes.forEach(code => allCodes.add(code));
} catch (error) {
console.error(`Failed to fetch codes from ${url}:`, error);
}
}
// Store codes in local storage with state tracking
try {
// Get already stored codes and states
const storedData = await browserApi.storage.local.get(["ShiftCodes", "gameNewCodes", "codeStates"]);
let storedCodes = storedData.ShiftCodes || [];
let gameNewCodes = storedData.gameNewCodes || {};
let codeStates = storedData.codeStates || {};
// Initialize game-specific storage if not exists
if (!gameNewCodes[game]) {
gameNewCodes[game] = [];
}
// Add only new codes
const newCodes = [...allCodes].filter(code => !storedCodes.includes(code));
storedCodes = [...storedCodes, ...newCodes];
// Add new codes to game-specific storage
const gameSpecificNewCodes = newCodes.filter(code => !gameNewCodes[game].includes(code));
gameNewCodes[game] = [...gameNewCodes[game], ...gameSpecificNewCodes];
// Initialize state for new codes
newCodes.forEach(code => {
// Initialize for all platforms using new key format
const platforms = ['steam', 'xbox', 'nintendo', 'epic', 'psn', 'stadia'];
platforms.forEach(platform => {
const key = `${platform}:${game}:${code}`;
if (!codeStates[key]) {
codeStates[key] = {
state: 'new',
timestamp: Date.now(),
game: game,
platform: platform,
retryCount: 0
};
}
});
});
// Store updated codes and states
await browserApi.storage.local.set({
ShiftCodes: storedCodes,
gameNewCodes: gameNewCodes,
codeStates: codeStates
});
console.info(`Stored ${gameSpecificNewCodes.length} new codes for ${game}.`);
return { success: true, newCodes: gameSpecificNewCodes };
} catch (error) {
console.error("Failed to store codes:", error);
return { success: false, error };
}
}
// Listen for messages from the popup
browserApi.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === "fetchCodes") {
const urls = message.urls || [
"https://mentalmars.com/game-news/tiny-tinas-wonderlands-shift-codes/",
"https://www.rockpapershotgun.com/tiny-tinas-wonderlands-shift-codes"
];
const game = message.game || 'tinytina';
fetchCodesFromWebsites(urls, game)
.then(result => sendResponse(result))
.catch(error => {
console.error("Fetch codes failed:", error);
sendResponse({ success: false, error: error?.message || String(error) });
});
return true;
}
if (message.action === "updateNotificationSettings") {
updateNotificationAlarm(message.settings)
.then(() => sendResponse({ success: true }))
.catch(error => {
console.error("Update notification settings failed:", error);
sendResponse({ success: false, error: error?.message || String(error) });
});
return true;
}
return false;
});
// Notification system implementation
async function updateNotificationAlarm(settings) {
// Clear existing alarm
browserApi.alarms.clear('dailyCodeCheck');
if (settings.enabled) {
// Use intervalMinutes from settings (defaults to 1440 for daily)
const intervalMinutes = settings.intervalMinutes || 1440;
const delayMinutes = Math.min(1, intervalMinutes); // Start quickly, but not longer than interval
browserApi.alarms.create('dailyCodeCheck', {
delayInMinutes: delayMinutes,
periodInMinutes: intervalMinutes
});
// Determine mode for logging
let mode;
if (intervalMinutes < 60) {
mode = `${intervalMinutes} minutes`;
} else if (intervalMinutes < 1440) {
mode = `${Math.round(intervalMinutes/60)} hours`;
} else {
mode = `${Math.round(intervalMinutes/1440)} days`;
}
console.info(`Code checking alarm enabled (${mode})`);
} else {
console.info('Code checking alarm disabled');
}
}
// Handle alarm triggers
browserApi.alarms.onAlarm.addListener(async (alarm) => {
if (alarm.name === 'dailyCodeCheck') {
console.info('Running daily code check...');
await performDailyCodeCheck();
}
});
// Default URLs for each game
const gameDefaultUrls = {
'borderlands4': [
"https://mentalmars.com/game-news/borderlands-4-shift-codes/",
"https://www.polygon.com/borderlands-4-active-shift-codes-redeem/"
],
'borderlands3': [
"https://mentalmars.com/game-news/borderlands-3-shift-codes/",
"https://www.polygon.com/borderlands-3-active-shift-codes-redeem/"
],
'borderlands2': [
"https://mentalmars.com/game-news/borderlands-2-shift-codes/",
"https://www.rockpapershotgun.com/borderlands-2-shift-codes"
],
'borderlandsps': [
"https://mentalmars.com/game-news/borderlands-pre-sequel-shift-codes/",
"https://www.rockpapershotgun.com/borderlands-pre-sequel-shift-codes"
],
'ttwonderlands': [
"https://mentalmars.com/game-news/tiny-tinas-wonderlands-shift-codes/",
"https://www.rockpapershotgun.com/tiny-tinas-wonderlands-shift-codes"
]
};
// Perform daily code check for enabled games
async function performDailyCodeCheck() {
try {
console.info('=== DAILY CODE CHECK STARTED ===');
// Get notification settings
const result = await browserApi.storage.local.get(['notificationSettings', 'customUrls']);
const notificationSettings = result.notificationSettings;
const customUrls = result.customUrls || {};
console.debug('Notification settings:', notificationSettings);
console.debug('Custom URLs:', customUrls);
if (!notificationSettings || !notificationSettings.enabled) {
console.info('Notifications disabled, skipping daily check');
return;
}
let totalNewCodes = 0;
const gameResults = {};
// Check each enabled game
for (const [game, enabled] of Object.entries(notificationSettings.games)) {
if (enabled) {
console.debug(`Checking for new codes in ${game}...`);
// Use custom URLs if available, otherwise use defaults
const urls = customUrls[game] || gameDefaultUrls[game] || [];
console.debug(`URLs for ${game}:`, urls);
if (urls.length > 0) {
const result = await fetchCodesFromWebsites(urls, game);
console.debug(`Fetch result for ${game}:`, result);
if (result.success && result.newCodes.length > 0) {
gameResults[game] = result.newCodes.length;
totalNewCodes += result.newCodes.length;
console.info(`Found ${result.newCodes.length} new codes for ${game}`);
}
} else {
console.warn(`No URLs configured for ${game}`);
}
}
}
console.info(`Total new codes found: ${totalNewCodes}`);
// Show notification if new codes found
if (totalNewCodes > 0) {
console.info('Showing notification...');
await showNewCodesNotification(gameResults, totalNewCodes);
await updateBadge(totalNewCodes);
} else {
console.info('No new codes found in daily check');
await updateBadge(0);
}
console.info('=== DAILY CODE CHECK COMPLETED ===');
} catch (error) {
console.error('Error in daily code check:', error);
}
}
// Show notification for new codes
async function showNewCodesNotification(gameResults, totalCount) {
const gameNames = {
'borderlands4': 'Borderlands 4',
'borderlands3': 'Borderlands 3',
'borderlands2': 'Borderlands 2',
'borderlandsps': 'Borderlands Pre-Sequel',
'ttwonderlands': 'Tiny Tina\'s Wonderlands'
};
let message = '';
const games = Object.keys(gameResults);
if (games.length === 1) {
const game = games[0];
message = `Found ${gameResults[game]} new codes for ${gameNames[game]}`;
} else {
message = `Found ${totalCount} new codes across ${games.length} games`;
}
// Create notification options
const notificationOptions = {
type: 'basic',
iconUrl: 'icon-48.png',
title: 'New SHIFT Codes Available!',
message: message
};
// Only add buttons for Chrome (Firefox doesn't support them)
const isFirefox = browserApi.runtime.getURL('').startsWith('moz-extension://');
if (!isFirefox) {
notificationOptions.buttons = [
{ title: 'View Codes' },
{ title: 'Dismiss' }
];
}
browserApi.notifications.create('newCodesFound', notificationOptions);
}
// Update extension badge
async function updateBadge(count) {
if (!actionApi) {
return;
}
if (count > 0) {
actionApi.setBadgeText({ text: count.toString() });
actionApi.setBadgeBackgroundColor({ color: '#007cba' });
} else {
actionApi.setBadgeText({ text: '' });
}
}
// Handle notification clicks
browserApi.notifications.onClicked.addListener((notificationId) => {
if (notificationId === 'newCodesFound') {
// Open extension popup
if (actionApi?.openPopup) {
actionApi.openPopup();
}
}
});
// Handle notification button clicks (Chrome only)
const isFirefox = browserApi.runtime.getURL('').startsWith('moz-extension://');
if (!isFirefox && browserApi.notifications.onButtonClicked) {
browserApi.notifications.onButtonClicked.addListener((notificationId, buttonIndex) => {
if (notificationId === 'newCodesFound') {
if (buttonIndex === 0) { // View Codes button
if (actionApi?.openPopup) {
actionApi.openPopup();
}
}
// Dismiss button (index 1) does nothing, notification will close
browserApi.notifications.clear(notificationId);
}
});
}
// Initialize notification system on extension startup
browserApi.runtime.onStartup.addListener(async () => {
const result = await browserApi.storage.local.get(['notificationSettings']);
const settings = result.notificationSettings;
if (settings) {
await updateNotificationAlarm(settings);
}
});
// Also initialize on extension install
browserApi.runtime.onInstalled.addListener(async () => {
const result = await browserApi.storage.local.get(['notificationSettings']);
const settings = result.notificationSettings;
if (settings) {
await updateNotificationAlarm(settings);
}
});