Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
1085 lines (916 loc) · 32.5 KB
/
Copy pathbackground.js
File metadata and controls
1085 lines (916 loc) · 32.5 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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Background Service Worker for NotebookLM++
// Handles NotebookLM import flows and related helper actions.
importScripts('lib/youtube-comments-api.js', 'lib/comments-to-md.js');
// ============================================
// Utilities
// ============================================
async function fetchWithTimeout(url, options = {}, timeout = 30000) {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, { ...options, signal: controller.signal });
return response;
} finally {
clearTimeout(id);
}
}
// ============================================
// NotebookLM API Client (inline)
// ============================================
const NotebookLMAPI = {
BASE_URL: 'https://notebooklm.google.com',
tokens: null,
// Get authentication tokens from NotebookLM page
async getTokens(authuser = 0) {
try {
const url = authuser > 0
? `${this.BASE_URL}/?authuser=${authuser}&pageId=none`
: this.BASE_URL;
const response = await fetchWithTimeout(url, {
credentials: 'include',
redirect: 'manual'
});
if (!response.ok && response.type !== 'opaqueredirect') {
throw new Error('Failed to fetch NotebookLM page');
}
const html = await response.text();
// Extract tokens from HTML
const bl = this.extractToken('cfb2h', html);
const at = this.extractToken('SNlM0e', html);
if (!bl || !at) {
throw new Error('Not authorized. Please login to NotebookLM first.');
}
this.tokens = { bl, at, authuser };
return this.tokens;
} catch (error) {
console.error('getTokens error:', error);
throw new Error('Please login to NotebookLM first');
}
},
// Extract token from HTML using regex
extractToken(key, html) {
const regex = new RegExp(`"${key}":"([^"]+)"`);
const match = regex.exec(html);
return match ? match[1] : null;
},
// List all notebooks
async listNotebooks() {
const response = await this.rpc('wXbhsf', [null, 1, null, [2]]);
return this.parseNotebookList(response);
},
// Parse notebook list from RPC response
parseNotebookList(responseText) {
try {
// Response format: )]}'\n\nXX[[["wrb.fr","wXbhsf","[...]",...
const lines = responseText.split('\n');
const dataLine = lines.find(line => line.includes('wrb.fr'));
if (!dataLine) return [];
// Parse the nested JSON
const parsed = JSON.parse(dataLine);
const innerData = JSON.parse(parsed[0][2]);
if (!innerData || !innerData[0]) return [];
return innerData[0]
.filter(item => item && item.length >= 3)
.filter(item => {
// Filter out shared notebooks (type 3)
const metadata = item[5];
return !(Array.isArray(metadata) && metadata.length > 0 && metadata[0] === 3);
})
.map(item => ({
id: item[2],
name: item[0]?.trim() || 'Untitled notebook',
sources: item[1]?.length || 0,
emoji: item[3] || '📔'
}));
} catch (error) {
console.error('parseNotebookList error:', error);
return [];
}
},
// Create a new notebook
async createNotebook(title, emoji = '📔') {
const response = await this.rpc('CCqFvf', [title]);
// Extract notebook ID from response
const uuidMatch = response.match(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/);
if (!uuidMatch) {
throw new Error('Failed to create notebook');
}
return { id: uuidMatch[0], name: title, emoji };
},
// Add a single source to notebook
async addSource(notebookId, url) {
return this.addSources(notebookId, [url]);
},
// Add multiple sources to notebook
async addSources(notebookId, urls) {
const sources = urls.map(url => {
// YouTube URLs need special format
if (url.includes('youtube.com') || url.includes('youtu.be')) {
return [null, null, null, null, null, null, null, [url]];
}
// Regular URLs
return [null, null, [url]];
});
const response = await this.rpc('izAoDd', [sources, notebookId], `/notebook/${notebookId}`);
return response;
},
// Add text content as source
async addTextSource(notebookId, text, title = 'Imported content') {
const source = [[null, [title, text], null, null, null, null, null, null]];
const response = await this.rpc('izAoDd', [source, notebookId, [2], null, null], `/notebook/${notebookId}`);
return response;
},
// Register a PDF source in the notebook (step 1 of PDF upload)
async registerPdfSource(notebookId, filename) {
const response = await this.rpc('o4cbdc', [[[filename]], notebookId, [2], [1,null,null,null,null,null,null,null,null,null,[1]]], `/notebook/${notebookId}`);
const uuidMatch = response.match(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/);
if (!uuidMatch) {
throw new Error('Failed to register PDF source');
}
return uuidMatch[0];
},
// Get a resumable upload URL from SCOTTY (step 2 of PDF upload)
async getUploadUrl(notebookId, filename, sourceId, byteLength) {
const authuser = this.tokens.authuser || 0;
const url = `https://notebooklm.google.com/upload/_/?authuser=${authuser}`;
const body = JSON.stringify({
PROJECT_ID: notebookId,
SOURCE_NAME: filename,
SOURCE_ID: sourceId
});
const response = await fetchWithTimeout(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-upload-command': 'start',
'x-goog-upload-header-content-length': byteLength.toString(),
'x-goog-upload-protocol': 'resumable'
},
credentials: 'include',
body
});
if (!response.ok) {
throw new Error(`Failed to get upload URL: ${response.status}`);
}
const uploadUrl = response.headers.get('x-goog-upload-url');
if (!uploadUrl) {
throw new Error('No upload URL in response');
}
return uploadUrl;
},
// Upload PDF bytes to SCOTTY (step 3 of PDF upload)
async uploadPdfBytes(uploadUrl, pdfBytes) {
const response = await fetchWithTimeout(uploadUrl, {
method: 'POST',
headers: {
'x-goog-upload-command': 'upload, finalize',
'x-goog-upload-offset': '0',
'Content-Type': 'application/pdf'
},
credentials: 'include',
body: pdfBytes
}, 60000);
if (!response.ok) {
throw new Error(`PDF upload failed: ${response.status}`);
}
return response;
},
// Full PDF upload orchestrator: register → get URL → upload bytes
async addPdfSource(notebookId, pdfBase64, filename) {
const binaryStr = atob(pdfBase64);
const bytes = new Uint8Array(binaryStr.length);
for (let i = 0; i < binaryStr.length; i++) {
bytes[i] = binaryStr.charCodeAt(i);
}
const sourceId = await this.registerPdfSource(notebookId, filename);
const uploadUrl = await this.getUploadUrl(notebookId, filename, sourceId, bytes.byteLength);
await this.uploadPdfBytes(uploadUrl, bytes);
return { sourceId };
},
// Check notebook status (sources loading)
async getNotebookStatus(notebookId) {
const response = await this.rpc('rLM1Ne', [notebookId, null, [2]], `/notebook/${notebookId}`);
// Check if notebook ID appears in response (means sources are loaded)
return !response.includes(`null,\\"${notebookId}`);
},
// Wait for sources to be added
async waitForSources(notebookId, maxAttempts = 30) {
for (let i = 0; i < maxAttempts; i++) {
const ready = await this.getNotebookStatus(notebookId);
if (ready) return true;
await new Promise(resolve => setTimeout(resolve, 1000));
}
return false;
},
// Execute RPC call to NotebookLM
async rpc(rpcId, params, sourcePath = '/') {
if (!this.tokens) {
await this.getTokens();
}
const url = new URL(`${this.BASE_URL}/_/LabsTailwindUi/data/batchexecute`);
const reqId = Math.floor(Math.random() * 900000 + 100000).toString();
url.searchParams.set('rpcids', rpcId);
url.searchParams.set('source-path', sourcePath);
url.searchParams.set('bl', this.tokens.bl);
url.searchParams.set('_reqid', reqId);
url.searchParams.set('rt', 'c');
if (this.tokens.authuser > 0) {
url.searchParams.set('authuser', this.tokens.authuser);
}
const body = new URLSearchParams({
'f.req': JSON.stringify([[[rpcId, JSON.stringify(params), null, 'generic']]]),
'at': this.tokens.at
});
const response = await fetchWithTimeout(url.toString(), {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
credentials: 'include',
body: body.toString()
});
if (!response.ok) {
throw new Error(`RPC call failed: ${response.status}`);
}
return await response.text();
},
// Get list of Google accounts (filter out YouTube channels/profiles)
async listAccounts() {
try {
const response = await fetchWithTimeout(
'https://accounts.google.com/ListAccounts?json=standard&source=ogb&md=1&cc=1&mn=1&mo=1&gpsia=1&fwput=860&listPages=1&origin=https%3A%2F%2Fwww.google.com',
{ credentials: 'include' }
);
const text = await response.text();
// Extract JSON from postMessage call
const match = text.match(/postMessage\('([^']*)'\s*,\s*'https:/);
if (!match) return [];
// Decode escaped characters
const decoded = match[1]
.replace(/\\x5b/g, '[')
.replace(/\\x5d/g, ']')
.replace(/\\x22/g, '"');
const parsed = JSON.parse(decoded);
const accounts = parsed[1] || [];
// Filter: only keep entries with valid email addresses (real Google accounts)
// YouTube channels/profiles don't have email in acc[3]
return accounts
.filter(acc => acc[3] && acc[3].includes('@'))
.map((acc, idx) => ({
name: acc[2] || null,
email: acc[3] || null,
avatar: acc[4] || null,
isActive: acc[5] || false,
isDefault: acc[6] || false,
index: idx // Use filtered index for authuser param
}));
} catch (error) {
console.error('listAccounts error:', error);
return [];
}
},
// Get notebook URL
getNotebookUrl(notebookId, authuser = 0) {
const base = `${this.BASE_URL}/notebook/${notebookId}`;
return authuser > 0 ? `${base}?authuser=${authuser}` : base;
},
// Get notebook details with sources list
async getNotebook(notebookId) {
const response = await this.rpc('rLM1Ne', [notebookId, null, [2], null, 0], `/notebook/${notebookId}`);
return this.parseNotebookDetails(response);
},
// Parse notebook details from RPC response
parseNotebookDetails(responseText) {
try {
const lines = responseText.split('\n');
const dataLine = lines.find(line => line.includes('wrb.fr'));
if (!dataLine) return { sources: [] };
const parsed = JSON.parse(dataLine);
const innerData = JSON.parse(parsed[0][2]);
if (!innerData || !innerData[0]) return { sources: [] };
// Structure: innerData[0] = [title, [sources...], notebookId, ...]
const notebookData = innerData[0];
const sourcesArray = Array.isArray(notebookData[1]) ? notebookData[1] : [];
const typeNames = {
1: 'google_docs',
2: 'google_other',
3: 'pdf',
4: 'pasted_text',
5: 'web_page',
8: 'generated_text',
9: 'youtube',
11: 'uploaded_file',
13: 'image',
14: 'word_doc'
};
const sources = sourcesArray
.filter(source => source && Array.isArray(source[0]) && source[0][0])
.map(source => {
// Source structure: [[sourceId], title, [metadata...], [null, 2]]
const sourceId = source[0][0];
const title = source[1] || 'Untitled';
const metadata = Array.isArray(source[2]) ? source[2] : [];
const sourceType = metadata[4] || 0;
const driveDocId = Array.isArray(metadata[0]) ? metadata[0][0] : null;
const url = Array.isArray(metadata[7]) ? metadata[7][0] : null;
return {
id: sourceId,
title: title,
type: typeNames[sourceType] || 'unknown',
typeCode: sourceType,
url: url,
driveDocId: driveDocId,
canSync: driveDocId != null && (sourceType === 1 || sourceType === 2)
};
});
return {
id: notebookData[2] || null,
title: notebookData[0] || '',
sources
};
} catch (error) {
console.error('parseNotebookDetails error:', error);
return { sources: [] };
}
},
// Check if a Drive source is fresh (up-to-date with Google Drive)
// Returns: true = fresh, false = stale, null = not a Drive source
async checkSourceFreshness(sourceId, notebookId) {
try {
const response = await this.rpc('yR9Yof', [null, [sourceId], [2]], `/notebook/${notebookId}`);
const lines = response.split('\n');
const dataLine = lines.find(line => line.includes('wrb.fr'));
if (!dataLine) return null;
const parsed = JSON.parse(dataLine);
const innerData = JSON.parse(parsed[0][2]);
if (innerData && Array.isArray(innerData[0]) && innerData[0].length >= 2) {
return innerData[0][1]; // true = fresh, false = stale
}
return null;
} catch (e) {
return null;
}
},
// Sync a Drive source with latest content from Google Drive
async syncDriveSource(sourceId, notebookId) {
const response = await this.rpc('FLmJqe', [null, [sourceId], [2]], `/notebook/${notebookId}`);
return response;
},
// Delete a single source from notebook
async deleteSource(notebookId, sourceId) {
// Note: notebook_id is passed via source_path, NOT in params!
// Payload structure: [[[source_id]]] (triple-nested)
const response = await this.rpc('tGMBJ', [[[sourceId]]], `/notebook/${notebookId}`);
return response;
},
// Delete multiple sources from notebook (batch operation)
// API supports max ~20 sources per request, so we chunk into batches
async deleteSources(notebookId, sourceIds) {
if (sourceIds.length === 0) {
return { success: true, deletedCount: 0 };
}
const BATCH_SIZE = 20;
let deletedCount = 0;
// Split into chunks of BATCH_SIZE
for (let i = 0; i < sourceIds.length; i += BATCH_SIZE) {
const batch = sourceIds.slice(i, i + BATCH_SIZE);
// Batch delete: payload format is [[[id1], [id2], [id3]...]]
const batchPayload = [batch.map(id => [id])];
await this.rpc('tGMBJ', batchPayload, `/notebook/${notebookId}`);
deletedCount += batch.length;
}
return { success: true, deletedCount };
}
};
// Generate PDF from a tab using Chrome Debugger API
async function generatePdf(tabId) {
try {
await chrome.debugger.attach({ tabId }, '1.3');
const result = await chrome.debugger.sendCommand({ tabId }, 'Page.printToPDF', {
printBackground: true,
preferCSSPageSize: true
});
return result.data; // base64 encoded PDF
} finally {
await chrome.debugger.detach({ tabId }).catch(() => {});
}
}
// Add page as PDF to notebook
async function addAsPdf(notebookId, tabId, title) {
const filename = (title || 'page').replace(/[^a-zA-Z0-9а-яА-ЯёЁ _\-\.]/g, '').substring(0, 100) + '.pdf';
const pdfBase64 = await generatePdf(tabId);
await NotebookLMAPI.addPdfSource(notebookId, pdfBase64, filename);
return { success: true };
}
// ============================================
// Background Service Worker Logic
// ============================================
// Store for current state
let currentAuthuser = 0;
// YouTube comments parse state
let parseState = {
active: false,
videoId: null,
progress: { fetched: 0, total: null, phase: 'idle' },
cancelToken: null,
error: null,
result: null
};
const NOTE_EXPORT_SELECTION_STORAGE_KEY = 'nlmPendingNoteExportSelection';
const NOTE_EXPORT_RESULTS_STORAGE_KEY = 'nlmLastNoteExportBatch';
// Initialize on install
chrome.runtime.onInstalled.addListener((details) => {
if (details.reason === 'install') {
// Initialize storage
chrome.storage.sync.set({
selectedAccount: 0,
lastNotebook: null,
autoOpenNotebook: false
});
}
// Clean up old API key setting (no longer needed)
chrome.storage.local.remove('youtubeApiKey');
// Setup context menus
chrome.contextMenus.removeAll(() => {
chrome.contextMenus.create({
id: 'send-to-notebooklm',
title: '📔 Send to NotebookLM',
contexts: ['page', 'link']
});
});
});
// Handle messages from popup and content scripts
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
handleMessage(request, sender)
.then(sendResponse)
.catch(error => {
console.error('Message handler error:', error);
sendResponse({ error: error.message });
});
// Return true to indicate async response
return true;
});
// Main message handler
async function handleMessage(request, sender) {
const { cmd, ...params } = request;
// Get selected account from storage
// Support both storage key formats
const storage = await chrome.storage.sync.get(['selectedAccount', 'selected_account']);
currentAuthuser = storage.selectedAccount || storage.selected_account || 0;
// Commands that don't require tokens
const noTokenCommands = ['list-accounts', 'ping', 'get-current-tab', 'get-all-tabs', 'get-parse-status', 'cancel-parse', 'set-note-export-selection', 'get-note-export-selection', 'clear-note-export-selection', 'get-note-export-results', 'clear-note-export-results'];
// Ensure we have tokens for API calls
if (!noTokenCommands.includes(cmd)) {
try {
await NotebookLMAPI.getTokens(currentAuthuser);
} catch (error) {
return { error: 'Please login to NotebookLM first', err: 'Please authorize NotebookLM to continue' };
}
}
switch (cmd) {
case 'ping':
return { ok: true };
case 'list-accounts':
return await listAccounts();
case 'list-notebooks':
return await listNotebooks();
// Legacy command support
case 'list-notebooklm':
return await listNotebooksLegacy();
case 'create-notebook':
return await createNotebook(params.title, params.emoji);
case 'add-source':
return await addSource(params.notebookId, params.url);
case 'add-sources':
return await addSources(params.notebookId, params.urls);
case 'add-text-source':
return await addTextSource(params.notebookId, params.text, params.title);
case 'get-current-tab':
return await getCurrentTab();
case 'get-all-tabs':
return await getAllTabs();
case 'save-to-notebook':
return await saveToNotebook(params);
case 'save-to-notebooklm':
return await saveToNotebookLMOriginal(params.title, params.urls, params.currentURL, params.notebookID);
case 'get-notebook':
return await getNotebook(params.notebookId);
case 'get-sources':
return await getSources(params.notebookId);
case 'delete-source':
return await deleteSource(params.notebookId, params.sourceId);
case 'sync-drive-sources':
return await syncDriveSources(params.notebookId);
case 'delete-sources':
return await deleteSources(params.notebookId, params.sourceIds);
case 'get-parse-status':
return {
active: parseState.active,
videoId: parseState.videoId,
progress: parseState.progress,
error: parseState.error,
result: parseState.result
};
case 'cancel-parse':
if (parseState.cancelToken) {
parseState.cancelToken.cancelled = true;
parseState.progress.phase = 'cancelled';
parseState.active = false;
}
return { success: true };
case 'set-note-export-selection':
return await setNoteExportSelection(params);
case 'get-note-export-selection':
return await getNoteExportSelection();
case 'clear-note-export-selection':
return await clearNoteExportSelection();
case 'get-note-export-results':
return await getNoteExportResults();
case 'clear-note-export-results':
return await clearNoteExportResults();
case 'add-as-pdf':
try {
return await addAsPdf(params.notebookId, params.tabId, params.title);
} catch (error) {
return { error: error.message };
}
case 'parse-comments':
if (parseState.active) {
return { error: 'Parse already in progress' };
}
doParseComments(params.notebookId, params.videoId, params.tabId);
return { started: true };
default:
console.log('Unknown command:', cmd);
return { error: `Unknown command: ${cmd}` };
}
}
// List Google accounts
async function listAccounts() {
try {
const accounts = await NotebookLMAPI.listAccounts();
// Return both formats for compatibility
return { accounts, list: accounts };
} catch (error) {
return { error: error.message, accounts: [], list: [] };
}
}
// List notebooks
async function listNotebooks() {
try {
const notebooks = await NotebookLMAPI.listNotebooks();
return { notebooks };
} catch (error) {
return { error: error.message, notebooks: [] };
}
}
// List notebooks in legacy format
async function listNotebooksLegacy() {
try {
const notebooks = await NotebookLMAPI.listNotebooks();
return { list: notebooks };
} catch (error) {
return { err: error.message, list: [] };
}
}
// Create new notebook
async function createNotebook(title, emoji = '📔') {
try {
const notebook = await NotebookLMAPI.createNotebook(title, emoji);
return { notebook };
} catch (error) {
return { error: error.message };
}
}
// Add single source
async function addSource(notebookId, url) {
try {
await NotebookLMAPI.addSource(notebookId, url);
return { success: true };
} catch (error) {
return { error: error.message };
}
}
// Add multiple sources
async function addSources(notebookId, urls) {
try {
await NotebookLMAPI.addSources(notebookId, urls);
// Wait for sources to be processed
await NotebookLMAPI.waitForSources(notebookId);
return {
success: true,
notebookUrl: NotebookLMAPI.getNotebookUrl(notebookId, currentAuthuser)
};
} catch (error) {
return { error: error.message };
}
}
// Add text content as source
async function addTextSource(notebookId, text, title) {
try {
await NotebookLMAPI.addTextSource(notebookId, text, title);
return { success: true };
} catch (error) {
return { error: error.message };
}
}
// Get notebook details with sources
async function getNotebook(notebookId) {
try {
const notebook = await NotebookLMAPI.getNotebook(notebookId);
return { notebook };
} catch (error) {
return { error: error.message };
}
}
// Get sources list for a notebook
async function getSources(notebookId) {
try {
const notebook = await NotebookLMAPI.getNotebook(notebookId);
return { sources: notebook.sources || [] };
} catch (error) {
return { error: error.message, sources: [] };
}
}
// Delete single source
async function deleteSource(notebookId, sourceId) {
try {
await NotebookLMAPI.deleteSource(notebookId, sourceId);
return { success: true };
} catch (error) {
return { error: error.message };
}
}
// Delete multiple sources (batch)
async function deleteSources(notebookId, sourceIds) {
try {
const result = await NotebookLMAPI.deleteSources(notebookId, sourceIds);
return {
success: true,
successCount: result.deletedCount || sourceIds.length,
failCount: 0
};
} catch (error) {
return { error: error.message };
}
}
// Sync all Drive sources in a notebook
async function syncDriveSources(notebookId) {
try {
const notebook = await NotebookLMAPI.getNotebook(notebookId);
const sources = notebook.sources || [];
if (sources.length === 0) return { error: 'No sources found' };
const results = { synced: 0, fresh: 0, skipped: 0, errors: 0, total: sources.length };
for (const source of sources) {
try {
// Check freshness via RPC — returns null for non-Drive sources
const isFresh = await NotebookLMAPI.checkSourceFreshness(source.id, notebookId);
if (isFresh === null) {
results.skipped++;
} else if (isFresh === true) {
results.fresh++;
} else {
await NotebookLMAPI.syncDriveSource(source.id, notebookId);
results.synced++;
}
} catch (e) {
console.error('Sync error for source', source.id, e);
results.errors++;
}
}
return { success: true, results };
} catch (error) {
return { error: error.message };
}
}
// Get current active tab
async function getCurrentTab() {
try {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
return {
tab: {
id: tab.id,
url: tab.url,
title: tab.title,
favIconUrl: tab.favIconUrl
}
};
} catch (error) {
return { error: error.message };
}
}
// Get all open tabs
async function getAllTabs() {
try {
const tabs = await chrome.tabs.query({});
return {
tabs: tabs
.filter(tab => tab.url && tab.url.startsWith('http'))
.map(tab => ({
id: tab.id,
url: tab.url,
title: tab.title,
favIconUrl: tab.favIconUrl,
windowId: tab.windowId
}))
};
} catch (error) {
return { error: error.message, tabs: [] };
}
}
async function setNoteExportSelection({ notebookId, noteKeys, notes, source }) {
if (!notebookId || !Array.isArray(noteKeys) || noteKeys.length === 0) {
return { error: 'No note selection provided' };
}
const sanitizedNotes = Array.isArray(notes)
? notes
.filter((note) => note && typeof note.key === 'string')
.map((note) => ({
key: note.key,
title: typeof note.title === 'string' ? note.title : '',
index: typeof note.index === 'number' ? note.index : null
}))
: [];
const selection = {
notebookId,
noteKeys: noteKeys.filter((noteKey) => typeof noteKey === 'string' && noteKey),
notes: sanitizedNotes,
source: typeof source === 'string' ? source : 'unknown',
updatedAt: Date.now()
};
await chrome.storage.local.set({
[NOTE_EXPORT_SELECTION_STORAGE_KEY]: selection
});
return {
success: true,
selection
};
}
async function getNoteExportSelection() {
const result = await chrome.storage.local.get([NOTE_EXPORT_SELECTION_STORAGE_KEY]);
return {
selection: result[NOTE_EXPORT_SELECTION_STORAGE_KEY] || null
};
}
async function clearNoteExportSelection() {
await chrome.storage.local.remove([NOTE_EXPORT_SELECTION_STORAGE_KEY]);
return { success: true };
}
async function getNoteExportResults() {
const result = await chrome.storage.local.get([NOTE_EXPORT_RESULTS_STORAGE_KEY]);
return {
results: result[NOTE_EXPORT_RESULTS_STORAGE_KEY] || null
};
}
async function clearNoteExportResults() {
await chrome.storage.local.remove([NOTE_EXPORT_RESULTS_STORAGE_KEY]);
return { success: true };
}
// Save URL(s) to notebook (main workflow)
async function saveToNotebook({ title, urls, notebookId, createNew }) {
try {
let targetNotebookId = notebookId;
// Create new notebook if requested
if (createNew || !notebookId) {
const emoji = urls.some(url => url.includes('youtube.com')) ? '📺' : '📔';
const result = await NotebookLMAPI.createNotebook(title || 'Imported content', emoji);
targetNotebookId = result.id;
}
// Add sources
await NotebookLMAPI.addSources(targetNotebookId, urls);
// Wait for sources to be processed
await NotebookLMAPI.waitForSources(targetNotebookId);
// Get settings
const settings = await chrome.storage.sync.get(['autoOpenNotebook']);
// Open notebook if setting enabled
if (settings.autoOpenNotebook) {
const notebookUrl = NotebookLMAPI.getNotebookUrl(targetNotebookId, currentAuthuser);
chrome.tabs.create({ url: notebookUrl });
}
return {
success: true,
notebookId: targetNotebookId,
notebookUrl: NotebookLMAPI.getNotebookUrl(targetNotebookId, currentAuthuser)
};
} catch (error) {
return { error: error.message };
}
}
// Save to NotebookLM (legacy format)
async function saveToNotebookLMOriginal(title, urls, currentURL, notebookID) {
try {
// Set progress indicator in local storage
if (currentURL) {
await chrome.storage.local.set({ [currentURL]: { label: 'Creating Notebook...' } });
}
let targetNotebookId = notebookID;
// Create new notebook if no ID provided
if (!notebookID) {
const result = await NotebookLMAPI.createNotebook(title || 'YouTube Videos', '📺');
targetNotebookId = result.id;
}
// Update progress
if (currentURL) {
await chrome.storage.local.set({ [currentURL]: { label: 'Adding sources...' } });
}
// Add sources
await NotebookLMAPI.addSources(targetNotebookId, urls);
// Wait for sources to be processed
await NotebookLMAPI.waitForSources(targetNotebookId);
// Clear progress indicators
if (currentURL) {
await chrome.storage.local.remove([currentURL, 'ytLinks']);
}
// Build authuser param for URL
const authParam = currentAuthuser > 0 ? `?authuser=${currentAuthuser}` : '';
return {
url: `https://notebooklm.google.com/notebook/${targetNotebookId}${authParam}`
};
} catch (error) {
return { err: error.message };
}
}
// Fire-and-forget: fetch comments, format, send to NotebookLM
async function doParseComments(notebookId, videoId, tabId) {
const cancelToken = { cancelled: false };
parseState = {
active: true,
videoId,
progress: { fetched: 0, total: null, phase: 'fetching' },
cancelToken,
error: null,
result: null
};