-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground-enhanced.js
More file actions
661 lines (556 loc) · 21.7 KB
/
Copy pathbackground-enhanced.js
File metadata and controls
661 lines (556 loc) · 21.7 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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
// Enhanced ToolThreads V2 - Background Script with Firebase Real-time Listeners
// made by @m4scarade
// Cost-optimized version using onSnapshot() listeners instead of polling
// IMPORTANT: This file requires Firebase SDK files to be present:
// - firebase-app-compat.js
// - firebase-firestore-compat.js
// See FIREBASE_SETUP.md for installation instructions
// Load Firebase SDK and dependencies
importScripts(
'config.js',
'xhr-polyfill.js', // XMLHttpRequest polyfill for service worker
'firebase-app-compat.js',
'firebase-firestore-compat.js',
'firebase-init.js',
'firebase-listener-manager.js'
);
// Prevent duplicate initialization
const globalContext = typeof self !== 'undefined' ? self : (typeof window !== 'undefined' ? window : globalThis);
if (globalContext.__BACKGROUND_ENHANCED_LOADED__) {
console.error('[Background] 🚫 DUPLICATE LOAD DETECTED! Background script already loaded. Aborting.');
console.trace('[Background] Duplicate load trace:');
} else {
globalContext.__BACKGROUND_ENHANCED_LOADED__ = true;
console.log('[Background] ✅ Enhanced ToolThreads V2 background script loaded (first time)');
}
console.log('[Background] Script execution continuing...');
// Global state
let extensionId = null;
let customerId = null;
let licenseKey = null;
let listenerManager = null;
let useListeners = ENHANCED_CONFIG.firebaseListeners?.enabled ?? false;
// Debug: Log initial state
console.log('[Background] 🔧 Initial configuration:', {
configLoaded: typeof ENHANCED_CONFIG !== 'undefined',
listenersConfig: ENHANCED_CONFIG.firebaseListeners?.enabled,
useListeners: useListeners
});
// Track processed instant posts to prevent duplicates
const processedInstantPosts = new Set();
// Track polling timer
let pollingTimer = null;
// ==================== INITIALIZATION ====================
/**
* Initialize extension and set up listeners or polling
*/
async function initializeExtension() {
console.log('[Background] 🚀 Initializing extension...');
try {
// Stop any existing polling
stopLegacyPolling();
// Cleanup existing listeners
if (listenerManager) {
console.log('[Background] 🧹 Cleaning up existing listeners...');
await listenerManager.cleanup();
listenerManager = null;
}
// Get or create extension ID
extensionId = await getOrCreateExtensionId();
console.log('[Background] Extension ID:', extensionId);
// Try to get license data
const licenseData = await getLicenseData();
if (licenseData && licenseData.licenseKey) {
licenseKey = licenseData.licenseKey;
customerId = licenseData.customerData?.customerId;
console.log('[Background] License found for customer:', customerId ? customerId.substring(0, 8) + '***' : 'unknown');
// Debug: Check conditions for Firebase listeners
console.log('[Background] 🔍 Checking Firebase listener conditions:', {
useListeners: useListeners,
hasCustomerId: !!customerId,
shouldActivate: useListeners && customerId
});
// Initialize Firebase listeners if enabled
if (useListeners && customerId) {
await setupFirebaseListeners();
} else {
console.log('[Background] Using legacy polling (listeners disabled or no customer ID)');
startLegacyPolling();
}
} else {
console.log('[Background] No license found, using legacy polling');
startLegacyPolling();
}
} catch (error) {
console.error('[Background] ❌ Initialization error:', error);
console.log('[Background] Falling back to legacy polling');
startLegacyPolling();
}
}
/**
* Set up Firebase real-time listeners
*/
async function setupFirebaseListeners() {
try {
console.log('[Background] 🔥 Setting up Firebase real-time listeners...');
// Create listener manager
listenerManager = new FirebaseListenerManager();
// Initialize with customer and extension info
const initialized = await listenerManager.initialize(customerId, extensionId, licenseKey);
if (!initialized) {
throw new Error('Failed to initialize listener manager');
}
// ✅ HYBRID MODE: Instant posts listener runs in content script (better network stability)
// Content script forwards posts to background → background activates tab → posts with full CPU
// This prevents both Firestore connection issues AND browser throttling
console.log('[Background] ℹ️ Instant posts listener runs in content script (forwarded to background for tab activation)');
// Set up preset version listener (optional, for immediate preset updates)
if (ENHANCED_CONFIG.firebaseListeners.presetVersion?.enabled) {
const presetVersionSuccess = await listenerManager.setupPresetVersionListener(handlePresetVersionChange);
if (presetVersionSuccess) {
console.log('[Background] ✅ Preset version listener active');
}
}
console.log('[Background] 🎉 All Firebase listeners setup complete!');
console.log('[Background] 💰 Cost savings: ~99.7% reduction in Firestore reads');
} catch (error) {
console.error('[Background] ❌ Failed to setup Firebase listeners:', error);
console.log('[Background] ⚠️ Falling back to legacy polling');
startLegacyPolling();
}
}
/**
* Handle new instant post from Firebase listener
*/
async function handleInstantPost(instantPost) {
try {
console.log('[Background] ⚡ New instant post received via listener:', instantPost.id);
// Check if already processed (duplicate prevention)
if (processedInstantPosts.has(instantPost.id)) {
console.log('[Background] ⏭️ Skipping already processed instant post:', instantPost.id);
return;
}
// ✅ Check if this post is targeted to this extension
if (instantPost.targetExtensions && Array.isArray(instantPost.targetExtensions)) {
if (!instantPost.targetExtensions.includes(extensionId)) {
console.log('[Background] ⏭️ Skipping - post not targeted to this extension');
// Don't mark as processed since it wasn't meant for us
return;
}
}
// Mark as processed IMMEDIATELY
processedInstantPosts.add(instantPost.id);
console.log('[Background] 🎯 Processing NEW instant post:', instantPost.id);
// Clean up old processed posts (keep last 50)
if (processedInstantPosts.size > 50) {
const entries = Array.from(processedInstantPosts);
const toRemove = entries.slice(0, entries.length - 25);
toRemove.forEach(entry => processedInstantPosts.delete(entry));
console.log('[Background] 🧹 Cleaned up old processed posts, keeping last 25');
}
// Process the instant post
if (instantPost.action === 'triggerPresetPost') {
await triggerPresetPost(instantPost);
}
} catch (error) {
console.error('[Background] ❌ Error handling instant post:', error);
}
}
/**
* Trigger preset post from instant post
*/
async function triggerPresetPost(instantPost) {
try {
// Find threads tabs
const tabs = await chrome.tabs.query({});
const targetTabs = tabs.filter(tab =>
tab.url && (tab.url.includes('threads.net') || tab.url.includes('threads.com'))
);
console.log('[Background] 🔍 Found', targetTabs.length, 'Threads tabs');
if (targetTabs.length > 0) {
const targetTab = targetTabs[0]; // Only use the FIRST tab
console.log('[Background] 📨 Sending to FIRST threads tab only (tab ID:', targetTab.id, ')');
// ✅ CRITICAL FIX: Activate tab AND focus window BEFORE sending message
// chrome.tabs.update alone isn't enough - must also focus the window
try {
// First, focus the window containing the tab
await chrome.windows.update(targetTab.windowId, { focused: true });
// Then activate the tab within that window
await chrome.tabs.update(targetTab.id, { active: true });
console.log('[Background] ✅ Window focused and tab activated to prevent throttling');
// Wait 1500ms for tab to FULLY wake up (longer than before)
await new Promise(resolve => setTimeout(resolve, 1500));
} catch (activateError) {
console.warn('[Background] ⚠️ Could not activate tab:', activateError);
}
// Send message to content script
chrome.tabs.sendMessage(
targetTab.id,
{
action: 'triggerPresetPost',
presetId: instantPost.presetId,
instantPostId: instantPost.id
},
(response) => {
if (chrome.runtime.lastError) {
console.error('[Background] ❌ Message failed:', chrome.runtime.lastError.message);
reportInstantPostCompletion(instantPost.id, 'failed', chrome.runtime.lastError.message);
} else {
console.log('[Background] ✅ Message sent successfully to tab');
reportInstantPostCompletion(
instantPost.id,
response && response.success ? 'completed' : 'failed',
response && response.error ? response.error : null
);
}
}
);
} else {
console.log('[Background] ⚠️ No Threads tabs found');
reportInstantPostCompletion(instantPost.id, 'failed', 'No Threads tabs available');
}
} catch (error) {
console.error('[Background] ❌ Error triggering preset post:', error);
reportInstantPostCompletion(instantPost.id, 'failed', error.message);
}
}
/**
* Report instant post completion to server
*/
async function reportInstantPostCompletion(instantPostId, status, error = null) {
try {
await fetch('https://us-central1-threadingv2.cloudfunctions.net/api/markInstantPostCompleted', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
instantPostId: instantPostId,
extensionId: extensionId,
status: status,
error: error
})
});
console.log('[Background] ✅ Reported instant post completion:', status);
} catch (error) {
console.error('[Background] ❌ Failed to report instant post completion:', error);
}
}
/**
* Handle preset version change from Firebase listener
*/
function handlePresetVersionChange(versionInfo) {
console.log('[Background] 📦 Preset version changed:', versionInfo.version);
console.log('[Background] Updated by:', versionInfo.updatedBy);
// Trigger preset sync in content script via message
chrome.tabs.query({}, (tabs) => {
const threadsTabs = tabs.filter(tab =>
tab.url && (tab.url.includes('threads.net') || tab.url.includes('threads.com'))
);
threadsTabs.forEach(tab => {
chrome.tabs.sendMessage(tab.id, {
action: 'presetVersionChanged',
version: versionInfo.version
}).catch(() => {
// Ignore errors (tab might not have content script loaded)
});
});
});
}
// ==================== LEGACY POLLING (FALLBACK) ====================
/**
* Stop legacy polling
*/
function stopLegacyPolling() {
if (pollingTimer) {
console.log('[Background] 🛑 Stopping legacy polling...');
clearInterval(pollingTimer);
pollingTimer = null;
}
}
/**
* Start legacy polling (fallback if listeners fail or are disabled)
*/
function startLegacyPolling() {
// Don't start if already running
if (pollingTimer) {
console.log('[Background] ⚠️ Polling already active, skipping...');
return;
}
console.log('[Background] 📊 Starting legacy polling mode...');
// Use longer intervals as fallback (30 seconds instead of 5)
const pollInterval = ENHANCED_CONFIG.firebaseListeners.instantPosts?.fallbackPollingInterval || 30000;
pollingTimer = setInterval(async () => {
if (!extensionId) {
console.log('[Background] 🚫 No extensionId, skipping update check');
return;
}
try {
console.log('[Background] 🔍 Polling for updates...');
// Get license data for customer identification
const licenseResult = await chrome.storage.local.get(['toolthreads_license_data']);
let customerId = null;
let licenseKey = null;
if (licenseResult.toolthreads_license_data) {
try {
const licenseData = typeof licenseResult.toolthreads_license_data === 'string'
? JSON.parse(licenseResult.toolthreads_license_data)
: licenseResult.toolthreads_license_data;
customerId = licenseData?.customerData?.customerId;
licenseKey = licenseData?.licenseKey;
} catch (e) {
console.error('[Background] Failed to parse license data:', e);
}
}
const response = await fetch('https://us-central1-threadingv2.cloudfunctions.net/api/checkUpdates', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
extensionId: extensionId,
customerId: customerId,
licenseKey: licenseKey,
version: await getStoredVersion(),
extensionVersion: chrome.runtime.getManifest().version
})
});
const data = await response.json();
// Update presets if needed
if (data.hasUpdates && data.updates) {
console.log('[Background] 📥 Updating presets...');
await chrome.storage.local.set({
enhancedPresets: data.updates.presets,
lastUpdated: Date.now(),
version: data.updates.version
});
console.log('[Background] ✅ Presets updated successfully');
}
// Process instant posts
if (data.instantPosts && data.instantPosts.length > 0) {
console.log('[Background] ⚡ Found', data.instantPosts.length, 'instant posts');
for (const instantPost of data.instantPosts) {
if (instantPost.action === 'triggerPresetPost') {
if (!processedInstantPosts.has(instantPost.id)) {
processedInstantPosts.add(instantPost.id);
await triggerPresetPost(instantPost);
}
}
}
}
} catch (error) {
console.error('[Background] ❌ Error polling for updates:', error);
}
}, pollInterval);
console.log('[Background] Legacy polling started with', pollInterval / 1000, 'second interval');
}
// ==================== HELPER FUNCTIONS ====================
/**
* Get or create extension ID
*/
async function getOrCreateExtensionId() {
const result = await chrome.storage.local.get(['extensionId']);
if (result.extensionId) {
return result.extensionId;
}
// Generate consistent extension ID
const installTime = Date.now();
const newExtensionId = 'ext_' + btoa(chrome.runtime.id).replace(/[^a-zA-Z0-9]/g, '').substr(0, 12) + '_' + installTime.toString(36);
await chrome.storage.local.set({ extensionId: newExtensionId });
return newExtensionId;
}
/**
* Get license data from storage
*/
async function getLicenseData() {
try {
const result = await chrome.storage.local.get(['toolthreads_license_data']);
if (result.toolthreads_license_data) {
return JSON.parse(result.toolthreads_license_data);
}
} catch (error) {
console.error('[Background] Error getting license data:', error);
}
return null;
}
/**
* Get stored version
*/
async function getStoredVersion() {
const result = await chrome.storage.local.get(['version']);
return result.version || 0;
}
// ==================== MESSAGE HANDLING ====================
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log('[Background] Received message:', message.action);
const action = message.action;
// Handle instant post detection from content script
if (action === 'instantPostDetected') {
console.log('[Background] ⚡ Instant post detected by content script:', message.instantPost.id);
handleInstantPost(message.instantPost);
sendResponse({ success: true });
return true;
}
// Handle all message types (forward to content script)
const messageActions = [
'postPreset',
'startEnhancedPosting',
'stopEnhancedPosting',
'updateSettings',
'setMediaUploads',
'getStatus',
'applyMediaHandler',
'toggleSetupMode',
'triggerPresetPost'
];
if (messageActions.includes(action)) {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (tabs.length > 0) {
chrome.tabs.sendMessage(tabs[0].id, message, (response) => {
sendResponse(response || { success: false, error: 'No response from content script' });
});
} else {
sendResponse({ success: false, error: 'No active tab' });
}
});
return true; // Async response
}
// Fetch media from Cloud Storage
if (action === 'fetchMedia') {
console.log('[Background] Fetching media from URL:', message.url);
fetch(message.url)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return response.blob();
})
.then(blob => {
const reader = new FileReader();
reader.onload = function() {
sendResponse({
success: true,
data: reader.result,
contentType: blob.type,
size: blob.size
});
};
reader.onerror = function() {
sendResponse({
success: false,
error: 'Failed to convert media to base64'
});
};
reader.readAsDataURL(blob);
})
.catch(error => {
sendResponse({
success: false,
error: error.message || 'Failed to fetch media'
});
});
return true; // Async response
}
return false;
});
// ==================== CONTEXT MENU ====================
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === 'enhance-threads') {
chrome.tabs.sendMessage(tab.id, {
action: 'enhanceInterface'
}, (response) => {
console.log('[Background] Context menu response:', response);
});
}
});
chrome.runtime.onStartup.addListener(() => {
createContextMenu();
});
chrome.runtime.onInstalled.addListener(() => {
createContextMenu();
// Note: initialization handled by smartInitialize() at bottom of file
});
function createContextMenu() {
chrome.contextMenus.create({
id: 'enhance-threads',
title: 'Enhance Threads Interface',
contexts: ['page'],
documentUrlPatterns: ['https://www.threads.net/*', 'https://www.threads.com/*']
});
}
// ==================== SERVICE WORKER LIFECYCLE ====================
// Handle service worker activation
self.addEventListener('activate', (event) => {
console.log('[Background] Service worker activated');
event.waitUntil(smartInitialize());
});
// Periodic cleanup
setInterval(() => {
if (processedInstantPosts.size > 10) {
const entries = Array.from(processedInstantPosts);
const toRemove = entries.slice(0, Math.floor(entries.length / 2));
toRemove.forEach(entry => processedInstantPosts.delete(entry));
console.log(`[Background] 🗑️ Periodic cleanup: removed ${toRemove.length} old processed posts`);
}
}, 5 * 60 * 1000); // Every 5 minutes
// Listen for license storage changes to re-initialize listeners
chrome.storage.onChanged.addListener(async (changes, areaName) => {
if (areaName === 'local' && changes.toolthreads_license_data) {
const newData = changes.toolthreads_license_data.newValue;
const oldData = changes.toolthreads_license_data.oldValue;
// Only re-initialize if license actually changed (not just on first set)
if (newData && newData !== oldData) {
console.log('[Background] 📝 License data changed, re-initializing...');
// Wait a bit to ensure storage is fully written
await new Promise(resolve => setTimeout(resolve, 500));
// Re-initialize with new license data
await initializeExtension();
}
}
});
// ✅ Message listener for content script requests
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
// Handle tab activation request from content script
if (message.action === 'activateThisTab') {
(async () => {
try {
if (sender.tab && sender.tab.id) {
console.log('[Background] 🎯 Activating tab on request from content script:', sender.tab.id);
// Focus window first
await chrome.windows.update(sender.tab.windowId, { focused: true });
// Then activate the tab
await chrome.tabs.update(sender.tab.id, { active: true });
console.log('[Background] ✅ Tab activated successfully');
sendResponse({ success: true });
} else {
console.warn('[Background] ⚠️ No sender tab info in message');
sendResponse({ success: false, error: 'No sender tab' });
}
} catch (error) {
console.error('[Background] ❌ Failed to activate tab:', error);
sendResponse({ success: false, error: error.message });
}
})();
return true; // Keep channel open for async response
}
});
// Smart initialization: Check if license exists first
async function smartInitialize() {
try {
const result = await chrome.storage.local.get(['toolthreads_license_data']);
if (result.toolthreads_license_data) {
// License already exists, initialize immediately
console.log('[Background] 📋 License found in storage, initializing immediately...');
await initializeExtension();
} else {
// No license yet, start with polling and wait for storage change
console.log('[Background] ⏳ No license found yet, starting polling mode...');
console.log('[Background] 💡 Will auto-switch to real-time when license loads');
await initializeExtension(); // Will start polling
}
} catch (error) {
console.error('[Background] ❌ Error in smart initialization:', error);
await initializeExtension(); // Fallback
}
}
// Start smart initialization
smartInitialize();
console.log('[Background] Enhanced ToolThreads V2 initialized successfully (Real-time mode)');