Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
549 lines (496 loc) · 19.3 KB
/
Copy pathbackground.js
File metadata and controls
549 lines (496 loc) · 19.3 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
// =============================================================================
// background.js — OpenTube SEO Service Worker
// =============================================================================
// This service worker handles:
// - Extension lifecycle management
// - Side panel configuration
// - Keyboard shortcuts (commands)
// - Context menu items for quick SEO actions
// - Alarms for scheduled keyword rank tracking
// - Message routing between content scripts and popup/sidebar
// - Data export/import for preferences and tracking data
// =============================================================================
import {
isWebGPUAvailable,
MODELS,
DEFAULT_MODEL,
loadModel,
generateSuggestions,
} from "./lib/engine.js";
// =============================================================================
// constants — app-wide configuration keys
// =============================================================================
const STORAGE_KEYS = {
SETTINGS: "opentube_settings",
KEYWORDS: "opentube_keywords",
HISTORY: "opentube_analysis_history",
CHANNELS: "opentube_watched_channels",
CACHED_SCORES: "opentube_cached_scores",
TRACKING: "opentube_tracking_data",
};
const DEFAULT_SETTINGS = {
// AI model configuration
model: DEFAULT_MODEL,
useAI: true,
// Analysis preferences
autoAnalyze: true,
showScoreBadge: true,
enableSidebar: true,
// Notifications
notifyOnComplete: false,
// Privacy
anonymousUsage: true,
// Export
autoBackup: false,
backupIntervalDays: 7,
// Theme
lightTheme: false,
};
// =============================================================================
// onInstalled — runs once after install or update
// =============================================================================
chrome.runtime.onInstalled.addListener((details) => {
log("[lifecycle] Install event:", details.reason);
if (details.reason === "install") {
// First-time install: set default settings and show onboarding
chrome.storage.local.set({
[STORAGE_KEYS.SETTINGS]: DEFAULT_SETTINGS,
});
// Open the onboarding/options page
chrome.tabs.create({ url: "options.html#onboarding" });
} else if (details.reason === "update") {
// Merge any new defaults into existing settings
migrateSettings();
}
// Create context menu items for quick access
createContextMenus();
// Set up alarms for scheduled tasks
setupAlarms();
// Log WebGPU availability info
log("[hardware] WebGPU available:", isWebGPUAvailable() ? "yes" : "no");
});
// =============================================================================
// createContextMenus — right-click menu items on YouTube pages
// =============================================================================
function createContextMenus() {
// Only create once
chrome.contextMenus.removeAll(() => {
// Parent menu
chrome.contextMenus.create({
id: "opentube-root",
title: "OpenTube SEO",
contexts: ["page", "selection", "link"],
documentUrlPatterns: ["https://*.youtube.com/*"],
});
// Analyze current video
chrome.contextMenus.create({
id: "analyze-video",
parentId: "opentube-root",
title: "Analyze this video",
contexts: ["page"],
});
// Generate AI suggestions
chrome.contextMenus.create({
id: "generate-ai",
parentId: "opentube-root",
title: "Generate AI title/tags/description",
contexts: ["page"],
});
// Analyze selected text as a keyword
chrome.contextMenus.create({
id: "analyze-keyword",
parentId: "opentube-root",
title: 'Research "%s" as a keyword',
contexts: ["selection"],
});
// Open sidebar
chrome.contextMenus.create({
id: "open-sidebar",
parentId: "opentube-root",
title: "Open SEO Sidebar",
contexts: ["page"],
});
log("[menus] Context menus created");
});
}
// =============================================================================
// contextMenus.onClicked — handle menu item clicks
// =============================================================================
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "analyze-video") {
chrome.tabs.sendMessage(tab.id, { type: "OPENTUBE_ANALYZE" });
} else if (info.menuItemId === "generate-ai") {
chrome.tabs.sendMessage(tab.id, { type: "OPENTUBE_GENERATE_AI" });
} else if (info.menuItemId === "analyze-keyword") {
// Store selected text for popup to pick up
chrome.storage.local.set({
opentube_pending_keyword: info.selectionText,
});
chrome.action.openPopup();
} else if (info.menuItemId === "open-sidebar") {
chrome.sidePanel.open({ windowId: tab.windowId });
}
});
// =============================================================================
// commands (keyboard shortcuts)
// =============================================================================
chrome.commands.onCommand.addListener((command, tab) => {
log("[commands] Received:", command);
if (command === "open-sidebar") {
// Toggle the side panel
chrome.sidePanel.open({ windowId: tab.windowId });
} else if (command === "analyze-video") {
chrome.tabs.sendMessage(tab.id, { type: "OPENTUBE_ANALYZE" }).catch(() => {
// Content script might not be loaded; inject it
chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ["content/watch.js"],
});
});
} else if (command === "generate-tags") {
chrome.tabs.sendMessage(tab.id, { type: "OPENTUBE_GENERATE_AI" }).catch(() => {
chrome.scripting.executeScript({
target: { tabId: tab.id },
files: ["content/watch.js"],
});
});
}
});
// =============================================================================
// setupAlarms — configure periodic background tasks
// =============================================================================
function setupAlarms() {
// Clean up old cached analysis data every day
chrome.alarms.create("cleanup-cache", { periodInMinutes: 1440 });
// Check for keyword tracking updates every 6 hours
chrome.alarms.create("keyword-track", { periodInMinutes: 360 });
}
// =============================================================================
// alarms.onAlarm — handle alarm events
// =============================================================================
chrome.alarms.onAlarm.addListener(async (alarm) => {
if (alarm.name === "cleanup-cache") {
await cleanupOldCache();
} else if (alarm.name === "keyword-track") {
await checkKeywordTracking();
}
});
// =============================================================================
// cleanupOldCache — remove stale cached data (>7 days)
// =============================================================================
async function cleanupOldCache() {
log("[maintenance] Cleaning old cache …");
const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000;
const { [STORAGE_KEYS.HISTORY]: history = [] } =
await chrome.storage.local.get(STORAGE_KEYS.HISTORY);
if (history.length === 0) return;
const fresh = history.filter((entry) => entry.timestamp > sevenDaysAgo);
await chrome.storage.local.set({ [STORAGE_KEYS.HISTORY]: fresh });
log(`[maintenance] Cache cleaned: ${history.length} → ${fresh.length} entries`);
}
// =============================================================================
// checkKeywordTracking — placeholder for scheduled keyword rank checks
// =============================================================================
async function checkKeywordTracking() {
log("[tracking] Keyword tracking check triggered (stub)");
// This would normally fetch ranking data for tracked keywords.
// For now it's a placeholder; full implementation requires a backend API.
}
// =============================================================================
// migrateSettings — merge missing defaults after an update
// =============================================================================
async function migrateSettings() {
const { [STORAGE_KEYS.SETTINGS]: current = {} } =
await chrome.storage.local.get(STORAGE_KEYS.SETTINGS);
let changed = false;
for (const [key, value] of Object.entries(DEFAULT_SETTINGS)) {
if (!(key in current)) {
current[key] = value;
changed = true;
}
}
if (changed) {
await chrome.storage.local.set({ [STORAGE_KEYS.SETTINGS]: current });
log("[migration] Settings updated with new defaults");
}
}
// =============================================================================
// sidePanel — configure side panel behavior
// =============================================================================
// Enable side panel for YouTube and Studio
chrome.sidePanel
.setPanelBehavior({ openPanelOnActionClick: false })
.catch(() => {});
// Open side panel automatically when navigating to Studio
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (
changeInfo.status === "complete" &&
tab.url &&
tab.url.includes("studio.youtube.com")
) {
const settings = chrome.storage.local.get(STORAGE_KEYS.SETTINGS);
// Side panel is available via the action button or shortcut
}
});
// =============================================================================
// message handling — central message router
// =============================================================================
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
log("[message] Received:", msg?.type, "from:", sender?.tab?.id);
switch (msg?.type) {
// ====================================================================
// Data request: popup/sidebar asks for current page data
// ====================================================================
case "GET_PAGE_DATA": {
getPageData(sender.tab?.id)
.then(sendResponse)
.catch((err) => sendResponse({ ok: false, error: String(err) }));
return true; // keep channel open for async response
}
// ====================================================================
// AI generation request
// ====================================================================
case "AI_GENERATE": {
handleAIGenerate(msg.data, sendResponse);
return true;
}
// ====================================================================
// Scrape request: forward to content script
// ====================================================================
case "SCRAPE_PAGE": {
forwardToContent(sender.tab?.id, { type: "SCRAPE_PAGE" }, sendResponse);
return true;
}
// ====================================================================
// Settings read/write
// ====================================================================
case "GET_SETTINGS": {
chrome.storage.local
.get(STORAGE_KEYS.SETTINGS)
.then((s) => sendResponse(s[STORAGE_KEYS.SETTINGS] || DEFAULT_SETTINGS));
return true;
}
case "SAVE_SETTINGS": {
chrome.storage.local
.set({ [STORAGE_KEYS.SETTINGS]: msg.settings })
.then(() => sendResponse({ ok: true }));
return true;
}
// ====================================================================
// Export/import data
// ====================================================================
case "EXPORT_DATA": {
handleExport(sendResponse);
return true;
}
case "IMPORT_DATA": {
handleImport(msg.data, sendResponse);
return true;
}
// ====================================================================
// Keyword tracking management
// ====================================================================
case "ADD_TRACKED_KEYWORD": {
addTrackedKeyword(msg.keyword, msg.videoId, sendResponse);
return true;
}
case "REMOVE_TRACKED_KEYWORD": {
removeTrackedKeyword(msg.keyword, sendResponse);
return true;
}
case "GET_TRACKED_KEYWORDS": {
getTrackedKeywords(sendResponse);
return true;
}
default:
log("[message] Unhandled type:", msg?.type);
sendResponse({ ok: false, error: "Unknown message type" });
}
});
// =============================================================================
// getPageData — aggregate page data from content script
// =============================================================================
async function getPageData(tabId) {
if (!tabId) throw new Error("No tab ID provided");
const injectForUrl = async () => {
const tab = await chrome.tabs.get(tabId);
const url = tab?.url || "";
let file = "content/watch.js";
if (url.includes("studio.youtube.com")) file = "content/studio.js";
else if (url.includes("/results")) file = "content/search.js";
else if (url.includes("/feed/")) file = "content/feed.js";
else if (url.includes("/channel") || url.includes("/c/") || url.includes("/@"))
file = "content/channel.js";
return chrome.scripting.executeScript({ target: { tabId }, files: [file] });
};
return new Promise((resolve, reject) => {
chrome.tabs.sendMessage(
tabId,
{ type: "OPENTUBE_GET_FULL_DATA" },
(response) => {
if (chrome.runtime.lastError) {
injectForUrl()
.then(() => {
setTimeout(() => {
chrome.tabs.sendMessage(
tabId,
{ type: "OPENTUBE_GET_FULL_DATA" },
(retryResponse) => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
} else {
resolve(retryResponse);
}
}
);
}, 500);
})
.catch(reject);
} else {
resolve(response);
}
}
);
});
}
// =============================================================================
// forwardToContent — generic message forwarder to content script
// =============================================================================
function forwardToContent(tabId, msg, sendResponse) {
if (!tabId) {
sendResponse({ ok: false, error: "No tab" });
return;
}
chrome.tabs.sendMessage(tabId, msg, (response) => {
if (chrome.runtime.lastError) {
sendResponse({ ok: false, error: chrome.runtime.lastError.message });
} else {
sendResponse(response);
}
});
}
// =============================================================================
// handleAIGenerate — run AI generation in the background worker
// =============================================================================
async function handleAIGenerate(data, sendResponse) {
try {
if (!isWebGPUAvailable()) {
sendResponse({
ok: false,
error: "WebGPU is not available in this browser",
});
return;
}
// Load model and generate
const { [STORAGE_KEYS.SETTINGS]: settings = DEFAULT_SETTINGS } =
await chrome.storage.local.get(STORAGE_KEYS.SETTINGS);
const modelId = settings.model || DEFAULT_MODEL;
await loadModel(modelId, () => {});
const result = await generateSuggestions(data);
sendResponse({ ok: true, data: result });
} catch (err) {
sendResponse({ ok: false, error: String(err) });
}
}
// =============================================================================
// handleExport — export all user data as JSON
// =============================================================================
async function handleExport(sendResponse) {
try {
const allData = await chrome.storage.local.get(null);
const exportObj = {
exportedAt: new Date().toISOString(),
version: chrome.runtime.getManifest().version,
data: {
settings: allData[STORAGE_KEYS.SETTINGS] || {},
keywords: allData[STORAGE_KEYS.KEYWORDS] || [],
history: (allData[STORAGE_KEYS.HISTORY] || []).slice(-100),
channels: allData[STORAGE_KEYS.CHANNELS] || [],
tracking: allData[STORAGE_KEYS.TRACKING] || [],
},
};
sendResponse({ ok: true, data: exportObj });
} catch (err) {
sendResponse({ ok: false, error: String(err) });
}
}
// =============================================================================
// handleImport — import previously exported data
// =============================================================================
async function handleImport(importData, sendResponse) {
try {
if (!importData?.data) {
sendResponse({ ok: false, error: "Invalid import data" });
return;
}
const { data } = importData;
const toSet = {};
if (data.settings) toSet[STORAGE_KEYS.SETTINGS] = data.settings;
if (data.keywords) toSet[STORAGE_KEYS.KEYWORDS] = data.keywords;
if (data.history) toSet[STORAGE_KEYS.HISTORY] = data.history;
if (data.channels) toSet[STORAGE_KEYS.CHANNELS] = data.channels;
if (data.tracking) toSet[STORAGE_KEYS.TRACKING] = data.tracking;
if (Object.keys(toSet).length > 0) {
await chrome.storage.local.set(toSet);
}
sendResponse({ ok: true, imported: Object.keys(toSet).length });
} catch (err) {
sendResponse({ ok: false, error: String(err) });
}
}
// =============================================================================
// addTrackedKeyword — add a keyword to the tracking list
// =============================================================================
async function addTrackedKeyword(keyword, videoId, sendResponse) {
try {
const { [STORAGE_KEYS.TRACKING]: tracking = [] } =
await chrome.storage.local.get(STORAGE_KEYS.TRACKING);
const entry = {
keyword,
videoId,
addedAt: Date.now(),
lastChecked: null,
rank: null,
};
tracking.push(entry);
await chrome.storage.local.set({ [STORAGE_KEYS.TRACKING]: tracking });
sendResponse({ ok: true });
} catch (err) {
sendResponse({ ok: false, error: String(err) });
}
}
// =============================================================================
// removeTrackedKeyword — remove keyword from tracking
// =============================================================================
async function removeTrackedKeyword(keyword, sendResponse) {
try {
const { [STORAGE_KEYS.TRACKING]: tracking = [] } =
await chrome.storage.local.get(STORAGE_KEYS.TRACKING);
const filtered = tracking.filter((t) => t.keyword !== keyword);
await chrome.storage.local.set({ [STORAGE_KEYS.TRACKING]: filtered });
sendResponse({ ok: true });
} catch (err) {
sendResponse({ ok: false, error: String(err) });
}
}
// =============================================================================
// getTrackedKeywords — list all tracked keywords
// =============================================================================
async function getTrackedKeywords(sendResponse) {
try {
const { [STORAGE_KEYS.TRACKING]: tracking = [] } =
await chrome.storage.local.get(STORAGE_KEYS.TRACKING);
sendResponse({ ok: true, data: tracking });
} catch (err) {
sendResponse({ ok: false, error: String(err) });
}
}
// =============================================================================
// logging — dev-only logging that's easy to find
// =============================================================================
function log(...args) {
console.log("[open-tube-seo]", ...args);
}
function logError(...args) {
console.error("[open-tube-seo:error]", ...args);
}