-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
475 lines (401 loc) · 13.9 KB
/
background.js
File metadata and controls
475 lines (401 loc) · 13.9 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
importScripts('utils/tenor.js');
importScripts('utils/giphy.js');
importScripts('utils/vimeo.js');
class CodeClimaxBackground {
constructor() {
this.tenorHandler = new TenorHandler();
this.giphyHandler = new GiphyHandler();
this.vimeoHandler = new VimeoHandler();
this.init();
}
init() {
console.log('CodeClimax background service worker initialized');
// Set up default settings on installation
chrome.runtime.onInstalled.addListener((details) => {
if (details.reason === 'install') {
this.setupDefaults();
}
});
// Handle messages from popup and content scripts
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
this.handleMessage(request, sender, sendResponse);
return true; // Keep the message channel open for async responses
});
// Handle storage changes
chrome.storage.onChanged.addListener((changes, namespace) => {
this.handleStorageChange(changes, namespace);
});
// Clean up old data periodically
this.scheduleCleanup();
}
async setupDefaults() {
const defaultSettings = {
enabled: true
};
const defaultCelebrations = [];
try {
await chrome.storage.local.set({
settings: defaultSettings,
celebrations: defaultCelebrations
});
console.log('Default settings and celebrations initialized');
} catch (error) {
console.error('Error setting up defaults:', error);
}
}
async handleMessage(request, sender, sendResponse) {
try {
switch (request.action) {
case 'getSettings':
const settings = await this.getSettings();
sendResponse({ success: true, data: settings });
break;
case 'updateSettings':
await this.updateSettings(request.settings);
sendResponse({ success: true });
break;
case 'getCelebrations':
const celebrations = await this.getCelebrations();
sendResponse({ success: true, data: celebrations });
break;
case 'addCelebration':
const addedCelebration = await this.addCelebration(request.celebration);
sendResponse({ success: true, data: addedCelebration });
break;
case 'updateCelebration':
await this.updateCelebration(request.id, request.updates);
sendResponse({ success: true });
break;
case 'deleteCelebration':
await this.deleteCelebration(request.id);
sendResponse({ success: true });
break;
case 'validateYouTube':
const validation = await this.validateYouTubeVideo(request.url);
sendResponse(validation);
break;
case 'validateTenor':
const tenorValidation = await this.validateTenorGif(request.url);
sendResponse(tenorValidation);
break;
case 'validateGiphy':
const giphyValidation = await this.validateGiphyGif(request.url);
sendResponse(giphyValidation);
break;
case 'validateVimeo':
const vimeoValidation = await this.validateVimeoVideo(request.url);
sendResponse(vimeoValidation);
break;
case 'getStorageUsage':
const usage = await this.getStorageUsage();
sendResponse({ success: true, data: usage });
break;
case 'exportData':
const exportData = await this.exportUserData();
sendResponse({ success: true, data: exportData });
break;
case 'importData':
await this.importUserData(request.data);
sendResponse({ success: true });
break;
default:
sendResponse({ success: false, error: 'Unknown action' });
}
} catch (error) {
console.error('Error handling message:', error);
sendResponse({ success: false, error: error.message });
}
}
async getSettings() {
const result = await chrome.storage.local.get(['settings']);
return result.settings || {
enabled: true
};
}
async updateSettings(newSettings) {
const currentSettings = await this.getSettings();
const updatedSettings = { ...currentSettings, ...newSettings };
await chrome.storage.local.set({ settings: updatedSettings });
return updatedSettings;
}
async getCelebrations() {
const result = await chrome.storage.local.get(['celebrations']);
return result.celebrations || [];
}
async addCelebration(celebration) {
const celebrations = await this.getCelebrations();
// Validate celebration data
if (!celebration.type || !celebration.data) {
throw new Error('Invalid celebration data');
}
// Check storage limits
const storageUsage = await this.getStorageUsage();
if (storageUsage.percentage > 90) {
throw new Error('Storage limit approaching. Please delete some media first.');
}
// Add unique ID and timestamp
const newCelebration = {
id: celebration.id || this.generateId(),
...celebration,
uploadedAt: celebration.uploadedAt || Date.now()
};
celebrations.push(newCelebration);
await chrome.storage.local.set({ celebrations });
return newCelebration;
}
async updateCelebration(id, updates) {
const celebrations = await this.getCelebrations();
const index = celebrations.findIndex(c => c.id === id);
if (index === -1) {
throw new Error('Celebration not found');
}
celebrations[index] = { ...celebrations[index], ...updates };
await chrome.storage.local.set({ celebrations });
}
async deleteCelebration(id) {
const celebrations = await this.getCelebrations();
const filteredCelebrations = celebrations.filter(c => c.id !== id);
if (celebrations.length === filteredCelebrations.length) {
throw new Error('Celebration not found');
}
await chrome.storage.local.set({ celebrations: filteredCelebrations });
}
async validateYouTubeVideo(url) {
try {
const videoId = this.extractYouTubeID(url);
if (!videoId) {
return { valid: false, error: 'Invalid YouTube URL' };
}
// Fetch video metadata
const response = await fetch(
`https://noembed.com/embed?url=https://www.youtube.com/watch?v=${videoId}`
);
if (!response.ok) {
return { valid: false, error: 'Could not fetch video information' };
}
const data = await response.json();
return {
valid: true,
videoId,
title: data.title,
thumbnail: `https://img.youtube.com/vi/${videoId}/mqdefault.jpg`
};
} catch (error) {
return { valid: false, error: 'Network error' };
}
}
extractYouTubeID(url) {
const patterns = [
/youtube\.com\/watch\?v=([^&]+)/,
/youtu\.be\/([^?]+)/,
/youtube\.com\/embed\/([^?]+)/,
/youtube\.com\/v\/([^?]+)/,
/youtube\.com\/shorts\/([a-zA-Z0-9_-]+)/, // YouTube Shorts support
/music\.youtube\.com\/watch\?v=([^&]+)/
];
console.log('Background: Processing YouTube URL:', url);
for (const pattern of patterns) {
const match = url.match(pattern);
if (match && match[1]) {
console.log('Background: Pattern matched:', pattern.toString(), 'Video ID:', match[1]);
return match[1];
}
}
console.log('Background: No patterns matched for URL:', url);
return null;
}
async validateTenorGif(url) {
try {
console.log('Background: Processing Tenor URL:', url);
// Use the TenorHandler utility to validate and extract GIF data
const validation = await this.tenorHandler.validateTenorGif(url);
if (validation.valid) {
console.log('Background: Tenor GIF validation successful:', validation);
return {
valid: true,
gifId: validation.gifId,
title: validation.title,
gifUrl: validation.gifUrl,
thumbnailUrl: validation.thumbnailUrl,
originalUrl: validation.originalUrl
};
} else {
console.log('Background: Tenor GIF validation failed:', validation.error);
return {
valid: false,
error: validation.error
};
}
} catch (error) {
console.error('Background: Error validating Tenor GIF:', error);
return { valid: false, error: error.message };
}
}
async validateGiphyGif(url) {
try {
console.log('Background: Processing Giphy URL:', url);
// Use the GiphyHandler utility to validate and extract GIF data
const validation = await this.giphyHandler.validateGiphyGif(url);
if (validation.valid) {
console.log('Background: Giphy GIF validation successful:', validation);
return {
valid: true,
gifId: validation.giphyId,
title: validation.title,
gifUrl: validation.gifUrl,
thumbnailUrl: validation.thumbnail,
originalUrl: validation.url
};
} else {
console.log('Background: Giphy GIF validation failed:', validation.error);
return {
valid: false,
error: validation.error
};
}
} catch (error) {
console.error('Background: Error validating Giphy GIF:', error);
return { valid: false, error: error.message };
}
}
async validateVimeoVideo(url) {
try {
console.log('Background: Processing Vimeo URL:', url);
// Use the VimeoHandler utility to validate and extract video data
const validation = await this.vimeoHandler.validateVimeoVideo(url);
if (validation.valid) {
console.log('Background: Vimeo video validation successful:', validation);
return {
valid: true,
videoId: validation.videoId,
title: validation.title,
thumbnail: validation.thumbnail,
duration: validation.duration,
author: validation.author,
hash: validation.hash,
embedUrl: this.vimeoHandler.generateEmbedURL(validation.videoId, { hash: validation.hash })
};
} else {
console.log('Background: Vimeo video validation failed:', validation.error);
return {
valid: false,
error: validation.error
};
}
} catch (error) {
console.error('Background: Error validating Vimeo video:', error);
return { valid: false, error: error.message };
}
}
async getStorageUsage() {
try {
const result = await chrome.storage.local.getBytesInUse();
const maxSize = 10 * 1024 * 1024; // 10MB default limit
const percentage = (result / maxSize) * 100;
return {
bytesUsed: result,
bytesTotal: maxSize,
percentage: Math.round(percentage),
formattedUsed: this.formatBytes(result),
formattedTotal: this.formatBytes(maxSize)
};
} catch (error) {
console.error('Error getting storage usage:', error);
return {
bytesUsed: 0,
bytesTotal: 10485760,
percentage: 0,
formattedUsed: '0 B',
formattedTotal: '10 MB'
};
}
}
formatBytes(bytes) {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
async exportUserData() {
try {
const data = await chrome.storage.local.get(['settings', 'celebrations']);
return {
version: '1.0',
exportDate: new Date().toISOString(),
data
};
} catch (error) {
throw new Error('Failed to export data');
}
}
async importUserData(importData) {
try {
if (!importData.data) {
throw new Error('Invalid import data format');
}
// Validate and merge data
const currentData = await chrome.storage.local.get(['settings', 'celebrations']);
const mergedSettings = {
...currentData.settings,
...importData.data.settings
};
const mergedCelebrations = [
...(currentData.celebrations || []),
...(importData.data.celebrations || [])
].filter((celebration, index, array) =>
// Remove duplicates by ID
array.findIndex(c => c.id === celebration.id) === index
);
await chrome.storage.local.set({
settings: mergedSettings,
celebrations: mergedCelebrations
});
} catch (error) {
throw new Error('Failed to import data');
}
}
handleStorageChange(changes, namespace) {
if (namespace === 'local') {
// Notify content scripts about setting changes
if (changes.settings) {
chrome.tabs.query({ url: 'https://leetcode.com/problems/*' }, (tabs) => {
tabs.forEach(tab => {
chrome.tabs.sendMessage(tab.id, {
action: 'settingsChanged',
settings: changes.settings.newValue
}).catch(() => {
// Ignore errors for tabs that don't have content script
});
});
});
}
}
}
scheduleCleanup() {
// Clean up old data daily
const cleanup = async () => {
try {
const celebrations = await this.getCelebrations();
const thirtyDaysAgo = Date.now() - (30 * 24 * 60 * 60 * 1000);
// Remove old non-favorite celebrations to free up space
const filteredCelebrations = celebrations.filter(celebration => {
return celebration.isFavorite || celebration.uploadedAt > thirtyDaysAgo;
});
if (filteredCelebrations.length < celebrations.length) {
await chrome.storage.local.set({ celebrations: filteredCelebrations });
console.log(`Cleaned up ${celebrations.length - filteredCelebrations.length} old celebrations`);
}
} catch (error) {
console.error('Error during cleanup:', error);
}
};
// Run cleanup daily
setInterval(cleanup, 24 * 60 * 60 * 1000);
}
generateId() {
return 'codecclimax_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
}
}
// Initialize the background service
new CodeClimaxBackground();