-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
563 lines (479 loc) · 17 KB
/
background.js
File metadata and controls
563 lines (479 loc) · 17 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
// ========== TRACES FEATURE - Detect curations on current URL ==========
// API base URL
function getApiBaseUrl() {
return 'https://api-prod.copus.network';
}
// Cache for traces API results: url -> { traces, timestamp }
const tracesCache = new Map();
const TRACES_CACHE_DURATION = 2 * 60 * 1000; // 2 minutes
let tracesInProgress = new Set(); // URLs currently being fetched
let tracesDebounceTimer = null;
let pendingTracesCheck = null; // { tabId, url } — latest pending check
// Check for traces on a URL and notify content script
async function checkAndShowTraces(tabId, url) {
if (!url || url.startsWith('chrome://') || url.startsWith('chrome-extension://')) {
return;
}
// Skip Copus pages
if (url.includes('copus.network') || url.includes('copus.io') || url.includes('copus.ai')) {
return;
}
// Check cache first
const cached = tracesCache.get(url);
if (cached && (Date.now() - cached.timestamp) < TRACES_CACHE_DURATION) {
if (cached.traces.length > 0) {
sendTracesToContentScript(tabId, cached.traces);
}
return;
}
// Skip if already fetching this URL
if (tracesInProgress.has(url)) {
return;
}
tracesInProgress.add(url);
try {
const apiBaseUrl = getApiBaseUrl();
const apiUrl = `${apiBaseUrl}/plugin/plugin/author/article/articlesByTargetUrl?pageIndex=0&pageSize=50&targetUrl=${encodeURIComponent(url)}`;
// Get auth token
let token = null;
try {
const result = await chrome.storage.local.get(['copus_token']);
token = result.copus_token;
} catch (e) {
// Storage might not be available
}
const headers = {
'Content-Type': 'application/json'
};
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
const response = await fetch(apiUrl, {
method: 'GET',
headers: headers
});
if (!response.ok) {
return;
}
const result = await response.json();
// API returns { status: 1, data: { data: [...], pageCount, pageIndex, pageSize, totalCount } }
let traces = [];
if (result.status === 1 && result.data) {
traces = Array.isArray(result.data.data) ? result.data.data : [];
}
// Store in cache
tracesCache.set(url, { traces, timestamp: Date.now() });
// Evict old cache entries (keep max 50)
if (tracesCache.size > 50) {
const oldest = tracesCache.keys().next().value;
tracesCache.delete(oldest);
}
if (traces.length > 0) {
sendTracesToContentScript(tabId, traces);
}
} catch (e) {
// Error checking traces - silently fail
} finally {
tracesInProgress.delete(url);
}
}
// Send traces to content script with retry
function sendTracesToContentScript(tabId, traces) {
const sendWithRetry = async (attempts = 0) => {
if (attempts > 5) return;
try {
await chrome.tabs.sendMessage(tabId, {
type: 'showTracesIndicator',
count: traces.length,
traces: traces
});
} catch (e) {
setTimeout(() => sendWithRetry(attempts + 1), 500);
}
};
sendWithRetry();
}
// Debounced wrapper — collapses rapid calls into one
function debouncedCheckTraces(tabId, url) {
pendingTracesCheck = { tabId, url };
if (tracesDebounceTimer) clearTimeout(tracesDebounceTimer);
tracesDebounceTimer = setTimeout(() => {
const check = pendingTracesCheck;
pendingTracesCheck = null;
if (check) checkAndShowTraces(check.tabId, check.url);
}, 300);
}
// Listen for page navigation completion
chrome.webNavigation.onCompleted.addListener((details) => {
// Only check main frame (not iframes)
if (details.frameId === 0) {
// Small delay to ensure content script is ready
setTimeout(() => {
debouncedCheckTraces(details.tabId, details.url);
}, 1500);
}
});
// Also check when tab becomes active (user switches tabs)
chrome.tabs.onActivated.addListener(async (activeInfo) => {
try {
const tab = await chrome.tabs.get(activeInfo.tabId);
if (tab.url) {
debouncedCheckTraces(activeInfo.tabId, tab.url);
}
} catch (e) {
// Tab might not exist
}
});
// Toggle the side panel
async function toggleSidePanel(tab) {
if (!tab || !tab.id) {
console.error('[Copus Extension BG] No valid tab to toggle side panel');
return;
}
try {
// Open the side panel for this tab
await chrome.sidePanel.open({ tabId: tab.id });
} catch (error) {
console.error('[Copus Extension BG] Failed to open side panel:', error);
}
}
// Handle extension icon click - open side panel
chrome.action.onClicked.addListener((tab) => {
toggleSidePanel(tab);
});
// Handle keyboard shortcuts
chrome.commands.onCommand.addListener((command, tab) => {
if (command === 'toggle-sidebar') {
toggleSidePanel(tab);
}
if (command === 'quick-save') {
handleQuickSave(tab);
}
});
// ========== QUICK SAVE ==========
// Saves current page privately with auto-captured title and cover image
async function handleQuickSave(tab) {
if (!tab || !tab.id || !tab.url) return;
// Skip chrome:// and extension pages
if (tab.url.startsWith('chrome://') || tab.url.startsWith('chrome-extension://')) {
sendQuickSaveToast(tab.id, 'Cannot save this page', 'error');
return;
}
// Check auth — if not logged in, open popup with login screen (don't save)
const { copus_token: token } = await chrome.storage.local.get(['copus_token']);
if (!token) {
openQuickSavePopup({ uuid: '', title: '', coverUrl: '', targetUrl: tab.url, notLoggedIn: true, sourceTabId: tab.id, sourceWindowId: tab.windowId });
return;
}
// Show saving indicator
sendQuickSaveToast(tab.id, 'Saving...', 'saving');
try {
// Collect page data from content script
const pageData = await chrome.tabs.sendMessage(tab.id, { type: 'collectPageData' });
const title = pageData.title || tab.title || '';
const coverUrl = pageData.ogImageContent || '';
const targetUrl = pageData.url || tab.url;
const payload = {
title,
content: '',
coverUrl,
targetUrl,
categoryId: 0,
visibility: 1 // 1 = private
};
// Call publish API
const apiBaseUrl = getApiBaseUrl();
const response = await fetch(`${apiBaseUrl}/client/author/article/edit`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(payload)
});
const result = await response.json();
if (!response.ok || (result.status && result.status !== 1 && result.status !== 1000)) {
const msg = result.msg || result.message || 'Save failed';
sendQuickSaveToast(tab.id, msg, 'error');
return;
}
// Dismiss the saving toast
sendQuickSaveToast(tab.id, '', 'dismiss');
// Open quick-save popup window with article details
const uuid = result.data || '';
openQuickSavePopup({ uuid, title, coverUrl, targetUrl, sourceTabId: tab.id, sourceWindowId: tab.windowId });
} catch (err) {
sendQuickSaveToast(tab.id, 'Save failed: ' + (err.message || 'Network error'), 'error');
}
}
// Open the quick-save enrichment popup window
async function openQuickSavePopup({ uuid, title, coverUrl, targetUrl, notLoggedIn, sourceTabId, sourceWindowId }) {
try {
const popupWidth = 400;
const popupHeight = 640;
// Center popup in current browser window
const currentWindow = await chrome.windows.getCurrent();
const left = Math.round(currentWindow.left + (currentWindow.width - popupWidth) / 2);
const top = Math.round(currentWindow.top + (currentWindow.height - popupHeight) / 2);
const params = new URLSearchParams({
uuid: uuid || '',
title: title || '',
cover: coverUrl || '',
url: targetUrl || '',
...(notLoggedIn ? { login: '1' } : {}),
...(sourceTabId ? { tabId: String(sourceTabId) } : {}),
...(sourceWindowId ? { windowId: String(sourceWindowId) } : {})
});
await chrome.windows.create({
url: chrome.runtime.getURL(`quicksave.html?${params.toString()}`),
type: 'popup',
width: popupWidth,
height: popupHeight,
left: Math.max(0, left),
top: Math.max(0, top)
});
} catch (e) {
// If popup fails to open, that's okay — the article is already saved
}
}
function sendQuickSaveToast(tabId, message, type) {
chrome.tabs.sendMessage(tabId, {
type: 'quickSaveToast',
message,
toastType: type
}).catch(() => {});
}
// Create context menu when extension is installed
chrome.runtime.onInstalled.addListener(() => {
// Set side panel to open on action click
chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
chrome.contextMenus.create({
id: 'copus-publish',
title: 'Publish to Copus',
contexts: ['page', 'selection', 'link', 'image']
});
});
// Handle context menu clicks
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
if (info.menuItemId === 'copus-publish') {
// Open side panel
toggleSidePanel(tab);
}
});
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'captureScreenshot') {
const targetWindowId = message.windowId;
chrome.tabs.captureVisibleTab(targetWindowId, { format: 'png' }, (dataUrl) => {
if (chrome.runtime.lastError) {
sendResponse({ success: false, error: chrome.runtime.lastError.message });
return;
}
sendResponse({ success: true, dataUrl });
});
return true;
}
if (message.type === 'storeAuthData') {
// Store both token and user data in extension storage
chrome.storage.local.set({
'copus_token': message.token,
'copus_user': message.user
}, () => {
});
return true;
}
if (message.type === 'clearAuthToken') {
// Clear the authentication token and user data from extension storage
chrome.storage.local.remove(['copus_token', 'copus_user'], () => {
});
return true;
}
// Open URL and inject token after page loads (handles session persistence)
if (message.type === 'openUrlAndInjectToken') {
const { url, token, user } = message;
(async () => {
try {
// Create the new tab
const tab = await chrome.tabs.create({ url });
if (token) {
// Wait for the tab to finish loading before injecting
const injectToken = async (tabId, attempts = 0) => {
if (attempts > 10) {
return;
}
try {
// Check if content script is ready
await chrome.tabs.sendMessage(tabId, {
type: 'injectToken',
token: token,
user: user
});
} catch (error) {
// Content script might not be ready yet, retry after delay
setTimeout(() => injectToken(tabId, attempts + 1), 500);
}
};
// Start injection attempts after a short delay for page to load
setTimeout(() => injectToken(tab.id), 1000);
}
} catch (error) {
console.error('[Copus Extension BG] Error opening URL:', error);
}
})();
return true;
}
// Fetch image via background script (bypasses CORS)
if (message.type === 'fetchImageAsDataUrl') {
(async () => {
try {
const response = await fetch(message.url);
if (!response.ok) {
sendResponse({ success: false, error: `HTTP ${response.status}` });
return;
}
const blob = await response.blob();
const reader = new FileReader();
reader.onload = () => {
const dataUrl = reader.result;
sendResponse({ success: true, dataUrl, mimeType: blob.type, size: blob.size });
};
reader.onerror = () => {
sendResponse({ success: false, error: 'Failed to read image blob' });
};
reader.readAsDataURL(blob);
} catch (error) {
console.error('[Copus Extension BG] Image fetch failed:', error);
sendResponse({ success: false, error: error.message });
}
})();
return true; // Keep message channel open for async response
}
// Set flag to show traces view when user opens sidepanel
if (message.type === 'setShowTracesFlag') {
chrome.storage.local.set({ 'copus_show_traces': true }, () => {
sendResponse({ success: true });
});
return true;
}
// Open traces panel directly - creates popup window with sidepanel content
if (message.type === 'openTracesPanel') {
// Store traces data and flag
chrome.storage.local.set({
'copus_show_traces': true,
'copus_traces_data': message.traces || []
}, async () => {
try {
// Try to open sidepanel first (works if called from valid context)
if (sender.tab && sender.tab.id) {
try {
await chrome.sidePanel.open({ tabId: sender.tab.id });
sendResponse({ success: true, method: 'sidepanel' });
return;
} catch (e) {
// Sidepanel failed, falling back to popup window
}
}
// Fallback: Open as popup window
const popupWidth = 380;
const popupHeight = 600;
// Get current window to position popup
const currentWindow = await chrome.windows.getCurrent();
const left = currentWindow.left + currentWindow.width - popupWidth - 20;
const top = currentWindow.top + 60;
await chrome.windows.create({
url: chrome.runtime.getURL('sidepanel.html?view=traces'),
type: 'popup',
width: popupWidth,
height: popupHeight,
left: Math.max(0, left),
top: Math.max(0, top)
});
sendResponse({ success: true, method: 'popup' });
} catch (error) {
console.error('[Copus BG] Failed to open traces panel:', error);
sendResponse({ success: false, error: error.message });
}
});
return true;
}
// Bind article to treasuries — mirrors sidepanel trace collect exactly
if (message.type === 'bindToTreasuries') {
(async () => {
try {
const { articleUuid, spaceIds } = message;
const result = await chrome.storage.local.get(['copus_token']);
const token = result.copus_token;
if (!token) {
sendResponse({ success: false, error: 'Not logged in' });
return;
}
const apiBaseUrl = getApiBaseUrl();
// Step 1: Get numeric article ID by looking up via targetUrl
// (same API as traces feature, confirmed working)
const { articleUuid: uuid, targetUrl } = message;
let numericId = null;
if (targetUrl) {
const lookupUrl = `${apiBaseUrl}/plugin/plugin/author/article/articlesByTargetUrl?pageIndex=0&pageSize=50&targetUrl=${encodeURIComponent(targetUrl)}`;
const lookupResp = await fetch(lookupUrl, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (lookupResp.ok) {
const lookupData = await lookupResp.json();
if (lookupData.status === 1 && Array.isArray(lookupData.data?.data)) {
const match = lookupData.data.data.find(a => a.uuid === articleUuid);
if (match) numericId = match.id;
}
}
}
if (!numericId) {
sendResponse({ success: false, error: 'Could not find article numeric ID' });
return;
}
// Step 2: Bind (same as sidepanel line 1715)
const bindResponse = await fetch(`${apiBaseUrl}/client/article/bind/bindArticles`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
articleId: numericId,
spaceIds: spaceIds
})
});
if (!bindResponse.ok) {
sendResponse({ success: false, error: `Bind API: ${bindResponse.status}` });
return;
}
const bindData = await bindResponse.json();
sendResponse({ success: bindData.status === 1, data: bindData, error: bindData.status !== 1 ? ('bind status=' + bindData.status + ' msg=' + (bindData.msg || '')) : undefined });
} catch (error) {
console.error('[Copus Extension BG] bindToTreasuries failed:', error);
sendResponse({ success: false, error: error.message });
}
})();
return true;
}
// Proxy API requests through background script to avoid popup network issues
if (message.type === 'apiRequest') {
(async () => {
try {
const response = await fetch(message.url, {
method: message.method || 'GET',
headers: message.headers || {},
body: message.body ? JSON.stringify(message.body) : undefined
});
const data = await response.json();
sendResponse({ success: true, data, status: response.status });
} catch (error) {
console.error('[Copus Extension BG] API request failed:', error);
sendResponse({ success: false, error: error.message });
}
})();
return true; // Keep message channel open for async response
}
return undefined;
});