-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathsession.py
More file actions
1064 lines (932 loc) · 41.8 KB
/
session.py
File metadata and controls
1064 lines (932 loc) · 41.8 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
"""Session and context management CLI commands.
Commands:
login Log in to NotebookLM via browser
use Set the current notebook context
status Show current context
clear Clear current notebook context
"""
import asyncio
import json
import logging
import os
import shutil
import subprocess
import sys
import time
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
from typing import Any
import click
import httpx
from rich.table import Table
from ..auth import (
ALLOWED_COOKIE_DOMAINS,
GOOGLE_REGIONAL_CCTLDS,
AuthTokens,
convert_rookiepy_cookies_to_storage_state,
extract_cookies_from_storage,
fetch_tokens,
)
from ..client import NotebookLMClient
from ..paths import (
get_browser_profile_dir,
get_context_path,
get_home_dir,
get_path_info,
get_storage_path,
)
from .helpers import (
clear_context,
console,
get_client,
get_current_notebook,
json_output_response,
resolve_notebook_id,
run_async,
set_current_notebook,
)
from .language import set_language
logger = logging.getLogger(__name__)
GOOGLE_ACCOUNTS_URL = "https://accounts.google.com/"
NOTEBOOKLM_URL = "https://notebooklm.google.com/"
NOTEBOOKLM_HOST = "notebooklm.google.com"
# Retryable Playwright connection errors
RETRYABLE_CONNECTION_ERRORS = ("ERR_CONNECTION_CLOSED", "ERR_CONNECTION_RESET")
LOGIN_MAX_RETRIES = 3
CONNECTION_ERROR_HELP = (
"[red]Failed to connect to NotebookLM after multiple retries.[/red]\n"
"This may be caused by:\n"
" • Network connectivity issues\n"
" • Firewall or VPN blocking notebooklm.google.com\n"
" • Corporate proxy interfering with the connection\n"
" • Google rate limiting (too many login attempts)\n\n"
"Try:\n"
" 1. Check your internet connection\n"
" 2. Disable VPN/proxy temporarily\n"
" 3. Wait a few minutes before retrying\n"
" 4. Check if notebooklm.google.com is accessible in your browser"
)
# Maps user-facing browser names to rookiepy function names.
_ROOKIEPY_BROWSER_ALIASES: dict[str, str] = {
"arc": "arc",
"brave": "brave",
"chrome": "chrome",
"chromium": "chromium",
"edge": "edge",
"firefox": "firefox",
"ie": "ie",
"librewolf": "librewolf",
"octo": "octo",
"opera": "opera",
"opera-gx": "opera_gx",
"opera_gx": "opera_gx",
"safari": "safari",
"vivaldi": "vivaldi",
"zen": "zen",
}
def _handle_rookiepy_error(e: Exception, browser_name: str) -> None:
"""Print a user-friendly error for rookiepy exceptions."""
msg = str(e).lower()
if "lock" in msg or "database" in msg:
console.print(
f"[red]Could not read {browser_name} cookies: browser database is locked.[/red]\n"
"Close your browser and try again."
)
elif "permission" in msg or "access" in msg:
console.print(
f"[red]Permission denied reading {browser_name} cookies.[/red]\n"
"You may need to grant Terminal/Python access to your browser profile directory."
)
elif "keychain" in msg or "decrypt" in msg:
console.print(
f"[red]Could not decrypt {browser_name} cookies.[/red]\n"
"On macOS, allow Keychain access when prompted, or try a different browser."
)
else:
console.print(f"[red]Failed to read cookies from {browser_name}:[/red] {e}")
def _login_with_browser_cookies(storage_path: Path, browser_name: str) -> None:
"""Extract Google cookies from an installed browser via rookiepy.
Args:
storage_path: Where to write storage_state.json.
browser_name: "auto" to use rookiepy.load(), or a specific browser name.
"""
try:
import rookiepy
except ImportError:
console.print(
"[red]rookiepy is not installed.[/red]\n"
"Install it with:\n"
" pip install 'notebooklm-py[cookies]'\n"
"or directly:\n"
" pip install rookiepy"
)
raise SystemExit(1) from None
# Build domains list including base and regional Google domains for rookiepy
domains = list(ALLOWED_COOKIE_DOMAINS)
# Add regional Google auth domains (e.g., .google.co.uk, .google.com.sg)
for cctld in GOOGLE_REGIONAL_CCTLDS:
domain = f".google.{cctld}"
if domain not in domains:
domains.append(domain)
if browser_name == "auto":
console.print("[yellow]Reading cookies from installed browser (auto-detect)...[/yellow]")
try:
raw_cookies = rookiepy.load(domains=domains)
except (OSError, RuntimeError) as e:
# OSError: file access issues (locked DB, permission denied)
# RuntimeError: decryption/keychain errors
_handle_rookiepy_error(e, "auto-detect")
raise SystemExit(1) from None
else:
canonical = _ROOKIEPY_BROWSER_ALIASES.get(browser_name.lower())
if canonical is None:
console.print(
f"[red]Unknown browser: '{browser_name}'[/red]\n"
f"Supported: {', '.join(sorted(_ROOKIEPY_BROWSER_ALIASES))}"
)
raise SystemExit(1)
console.print(f"[yellow]Reading cookies from {browser_name}...[/yellow]")
browser_fn = getattr(rookiepy, canonical, None)
if browser_fn is None or not callable(browser_fn):
console.print(
f"[red]rookiepy does not support '{canonical}' on this platform.[/red]\n"
"Check that rookiepy is properly installed: pip install rookiepy"
)
raise SystemExit(1)
try:
raw_cookies = browser_fn(domains=domains)
except (OSError, RuntimeError) as e:
# OSError: file access issues (locked DB, permission denied)
# RuntimeError: decryption/keychain errors
_handle_rookiepy_error(e, browser_name)
raise SystemExit(1) from None
storage_state = convert_rookiepy_cookies_to_storage_state(raw_cookies)
try:
cookies = extract_cookies_from_storage(storage_state) # validates SID is present
except ValueError as e:
console.print(
"[red]No valid Google authentication cookies found.[/red]\n"
f"{e}\n\n"
"Make sure you are logged into Google in your browser."
)
raise SystemExit(1) from None
# Create parent directory (avoid mode= on Windows to prevent ACL issues)
try:
storage_path.parent.mkdir(parents=True, exist_ok=True)
storage_path.write_text(
json.dumps(storage_state, indent=2, ensure_ascii=False), encoding="utf-8"
)
if sys.platform != "win32":
# On Unix: ensure both directory and file have restrictive permissions
storage_path.parent.chmod(0o700)
storage_path.chmod(0o600)
except OSError as e:
logger.error("Failed to save authentication to %s: %s", storage_path, e)
console.print(
f"[red]Failed to save authentication to {storage_path}.[/red]\n" f"Details: {e}"
)
raise SystemExit(1) from None
console.print(f"\n[green]Authentication saved to:[/green] {storage_path}")
# Verify that cookies work — reuse cookies extracted above (no redundant disk read)
try:
run_async(fetch_tokens(cookies))
logger.info("Cookies verified successfully")
console.print("[green]Cookies verified successfully.[/green]")
except ValueError as e:
# Cookie validation failed - the extracted cookies are invalid
logger.error("Extracted cookies are invalid: %s", e)
console.print(
"[red]Warning: Extracted cookies failed validation.[/red]\n"
"The cookies may be expired or malformed.\n"
f"Error: {e}\n\n"
"Saved anyway, but you may need to re-run login if these are invalid."
)
except httpx.RequestError as e:
# Network error - can't verify but cookies might be OK
logger.warning("Could not verify cookies due to network error: %s", e)
console.print(
"[yellow]Warning: Could not verify cookies (network issue).[/yellow]\n"
"Cookies saved but may not be working.\n"
"Try running 'notebooklm ask' to test authentication."
)
except Exception as e:
# Unexpected error - log it fully
logger.warning("Unexpected error verifying cookies: %s: %s", type(e).__name__, e)
console.print(
f"[yellow]Warning: Unexpected error during verification: {e}[/yellow]\n"
"Cookies saved but please verify with 'notebooklm auth check --test'"
)
_sync_server_language_to_config()
def _sync_server_language_to_config() -> None:
"""Fetch server language setting and persist to local config.
Called after login to ensure the local config reflects the server's
global language setting. This prevents generate commands from defaulting
to 'en' when the user has configured a different language on the server.
Non-critical: logs errors at debug level to avoid blocking login.
"""
async def _fetch():
async with await NotebookLMClient.from_storage() as client:
return await client.settings.get_output_language()
try:
server_lang = run_async(_fetch())
if server_lang:
set_language(server_lang)
except Exception as e:
logger.debug("Failed to sync server language to config: %s", e)
console.print(
"[dim]Warning: Could not sync language setting. "
"Run 'notebooklm language get' to sync manually.[/dim]"
)
@contextmanager
def _windows_playwright_event_loop() -> Iterator[None]:
"""Temporarily restore default event loop policy for Playwright on Windows.
Playwright's sync API uses subprocess to spawn the browser, which requires
ProactorEventLoop on Windows. However, we set WindowsSelectorEventLoopPolicy
globally to fix CLI hanging issues (#79). This context manager temporarily
restores the default policy for Playwright, then switches back.
On non-Windows platforms, this is a no-op.
Yields:
None
Example:
with _windows_playwright_event_loop():
with sync_playwright() as p:
# Browser operations work on Windows
...
"""
if sys.platform != "win32":
yield
return
# Save current policy and restore default (ProactorEventLoop) for Playwright
original_policy = asyncio.get_event_loop_policy()
asyncio.set_event_loop_policy(asyncio.DefaultEventLoopPolicy())
try:
yield
finally:
# Restore WindowsSelectorEventLoopPolicy for other async operations
asyncio.set_event_loop_policy(original_policy)
def _ensure_chromium_installed() -> None:
"""Check if Chromium is installed and install if needed.
This pre-flight check runs `playwright install --dry-run chromium` to detect
if the browser needs installation, then auto-installs if necessary.
Silently proceeds on any errors - Playwright will handle them during launch.
"""
try:
result = subprocess.run(
["playwright", "install", "--dry-run", "chromium"],
capture_output=True,
text=True,
)
# Check if dry-run indicates browser needs installing
stdout_lower = result.stdout.lower()
if "chromium" not in stdout_lower or "will download" not in stdout_lower:
return
console.print("[yellow]Chromium browser not installed. Installing now...[/yellow]")
install_result = subprocess.run(
["playwright", "install", "chromium"],
capture_output=True,
text=True,
)
if install_result.returncode != 0:
console.print(
"[red]Failed to install Chromium browser.[/red]\n"
"Run manually: playwright install chromium"
)
raise SystemExit(1)
console.print("[green]Chromium installed successfully.[/green]\n")
except SystemExit:
raise
except Exception as e:
# FileNotFoundError: playwright CLI not found but sync_playwright imported
# Other exceptions: dry-run check failed - let Playwright handle it during launch
console.print(
f"[dim]Warning: Chromium pre-flight check failed: {e}. Proceeding anyway.[/dim]"
)
def _clear_auth_files(storage_path: Path, browser_profile: Path) -> list[Path]:
"""Delete auth files/directories for the active profile.
Also checks legacy default-profile paths when the resolved paths are profile-based.
Returns the paths that were actually removed.
"""
paths_to_remove = [storage_path, browser_profile]
legacy_storage = get_home_dir() / "storage_state.json"
legacy_browser = get_home_dir() / "browser_profile"
for legacy_path in (legacy_storage, legacy_browser):
if legacy_path not in paths_to_remove:
paths_to_remove.append(legacy_path)
removed: list[Path] = []
for path in paths_to_remove:
if not path.exists():
continue
if path.is_symlink():
path.unlink()
elif path.is_dir():
shutil.rmtree(path)
else:
path.unlink(missing_ok=True)
removed.append(path)
return removed
def _get_recovered_page(context: Any, current_page: Any) -> Any:
"""Recover a live page when the original Playwright page was closed."""
pages = [page for page in context.pages if not page.is_closed()]
if pages:
return pages[0]
if current_page and not current_page.is_closed():
return current_page
return context.new_page()
def register_session_commands(cli):
"""Register session commands on the main CLI group."""
@cli.command("login")
@click.option(
"--storage",
type=click.Path(),
default=None,
help="Where to save storage_state.json (default: profile-specific location)",
)
@click.option(
"--browser",
type=click.Choice(["chromium", "msedge"], case_sensitive=False),
default="chromium",
help="Browser to use for login (default: chromium). Use 'msedge' for Microsoft Edge.",
)
@click.option(
"--browser-cookies",
"browser_cookies",
default=None,
is_flag=False,
flag_value="auto",
help=(
"Read cookies from an installed browser instead of launching Playwright. "
"Optionally specify browser: chrome, firefox, brave, edge, safari, arc, ... "
"Requires: pip install 'notebooklm[cookies]'"
),
)
@click.option(
"--fresh",
is_flag=True,
help="Delete saved browser session before login so you can choose a different account.",
)
def login(storage, browser, browser_cookies, fresh):
"""Log in to NotebookLM via browser.
Opens a browser window for Google login. After logging in,
press ENTER in the terminal to save authentication.
Use --browser msedge if your organization requires Microsoft Edge for SSO.
Note: Cannot be used when NOTEBOOKLM_AUTH_JSON is set (use file-based
auth or unset the env var first).
"""
# Check for conflicting env var
if os.environ.get("NOTEBOOKLM_AUTH_JSON"):
console.print(
"[red]Error: Cannot run 'login' when NOTEBOOKLM_AUTH_JSON is set.[/red]\n"
"The NOTEBOOKLM_AUTH_JSON environment variable provides inline authentication,\n"
"which conflicts with browser-based login that saves to a file.\n\n"
"Either:\n"
" 1. Unset NOTEBOOKLM_AUTH_JSON and run 'login' again\n"
" 2. Continue using NOTEBOOKLM_AUTH_JSON for authentication"
)
raise SystemExit(1)
# rookiepy fast-path: skip Playwright entirely
if browser_cookies is not None:
resolved_storage = Path(storage) if storage else get_storage_path()
_login_with_browser_cookies(resolved_storage, browser_cookies)
return
storage_path = Path(storage) if storage else get_storage_path()
browser_profile = get_browser_profile_dir()
if fresh:
try:
removed = _clear_auth_files(storage_path, browser_profile)
except OSError as e:
console.print(
"[red]Could not clear the saved browser session.[/red]\n"
"Close any running NotebookLM/Chromium windows and try again.\n"
f"Details: {e}"
)
raise SystemExit(1) from e
if removed:
console.print("[yellow]Cleared saved browser session for a fresh login.[/yellow]")
if sys.platform == "win32":
# On Windows < Python 3.13, mode= is ignored by mkdir(). On
# Python 3.13+, mode= applies Windows ACLs that can be overly
# restrictive (0o700 blocks other same-user processes). Skip mode
# and chmod entirely; Windows inherits ACLs from the parent.
storage_path.parent.mkdir(parents=True, exist_ok=True)
browser_profile.mkdir(parents=True, exist_ok=True)
else:
storage_path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
storage_path.parent.chmod(0o700)
browser_profile.mkdir(parents=True, exist_ok=True, mode=0o700)
browser_profile.chmod(0o700)
try:
from playwright.sync_api import Error as PlaywrightError
from playwright.sync_api import sync_playwright
except ImportError:
if browser == "msedge":
install_hint = " pip install notebooklm[browser]"
else:
install_hint = " pip install notebooklm[browser]\n playwright install chromium"
console.print(f"[red]Playwright not installed. Run:[/red]\n{install_hint}")
raise SystemExit(1) from None
# Pre-flight check: verify Chromium browser is installed (skip for Edge)
if browser == "chromium":
_ensure_chromium_installed()
from ..paths import resolve_profile
profile_name = resolve_profile()
browser_label = "Microsoft Edge" if browser == "msedge" else "Chromium"
console.print(f"[dim]Profile: {profile_name}[/dim]")
console.print(f"[yellow]Opening {browser_label} for Google login...[/yellow]")
console.print(f"[dim]Using persistent profile: {browser_profile}[/dim]")
# Use context manager to restore ProactorEventLoop for Playwright on Windows
# (fixes #89: NotImplementedError on Windows Python 3.12)
with _windows_playwright_event_loop(), sync_playwright() as p:
launch_kwargs: dict[str, Any] = {
"user_data_dir": str(browser_profile),
"headless": False,
"args": [
"--disable-blink-features=AutomationControlled",
"--password-store=basic", # Avoid macOS keychain encryption for headless compatibility
],
"ignore_default_args": ["--enable-automation"],
}
if browser == "msedge":
launch_kwargs["channel"] = "msedge"
context = None
try:
context = p.chromium.launch_persistent_context(**launch_kwargs)
page = context.pages[0] if context.pages else context.new_page()
# Retry navigation on transient connection errors with backoff
for attempt in range(1, LOGIN_MAX_RETRIES + 1):
try:
page.goto(NOTEBOOKLM_URL, timeout=30000)
break
except PlaywrightError as exc:
error_str = str(exc)
is_target_closed = (
"target page, context or browser has been closed" in error_str.lower()
)
is_retryable = any(
code in error_str for code in RETRYABLE_CONNECTION_ERRORS
)
# Check if we should retry
if is_target_closed and attempt < LOGIN_MAX_RETRIES:
page = _get_recovered_page(context, page)
backoff_seconds = attempt
console.print(
f"[yellow]Browser page was replaced during login "
f"(attempt {attempt}/{LOGIN_MAX_RETRIES}). "
f"Retrying in {backoff_seconds}s...[/yellow]"
)
time.sleep(backoff_seconds)
elif is_target_closed:
logger.error("Login page kept closing during account switch")
console.print(
"[red]The login page kept closing while switching accounts.[/red]\n"
"Retry with 'notebooklm login --fresh' to start from a clean browser session."
)
raise SystemExit(1) from None
elif is_retryable and attempt < LOGIN_MAX_RETRIES:
# Retryable error with attempts remaining: retry
backoff_seconds = attempt # Linear backoff: 1s, 2s
logger.debug(
f"Retryable connection error on attempt {attempt}/{LOGIN_MAX_RETRIES}: {error_str}"
)
console.print(
f"[yellow]Connection interrupted "
f"(attempt {attempt}/{LOGIN_MAX_RETRIES}). "
f"Retrying in {backoff_seconds}s...[/yellow]"
)
time.sleep(backoff_seconds)
elif is_retryable:
# Exhausted retries on a retryable error
logger.error(
f"Failed to connect to NotebookLM after {LOGIN_MAX_RETRIES} attempts. "
f"Last error: {error_str}"
)
console.print(CONNECTION_ERROR_HELP)
raise SystemExit(1) from exc
else:
# Non-retryable error - re-raise immediately
logger.debug(f"Non-retryable error: {error_str}")
raise
console.print("\n[bold green]Instructions:[/bold green]")
console.print("1. Complete the Google login in the browser window")
console.print("2. Wait until you see the NotebookLM homepage")
console.print("3. Press [bold]ENTER[/bold] here to save and close\n")
input("[Press ENTER when logged in] ")
page = _get_recovered_page(context, page)
# Force .google.com cookies for regional users (e.g. UK lands on
# .google.co.uk). Use "commit" to resolve once response headers
# (including Set-Cookie) are processed, before any client-side
# JS redirect can interrupt. See #214.
for url in [GOOGLE_ACCOUNTS_URL, NOTEBOOKLM_URL]:
try:
page.goto(url, wait_until="commit")
except PlaywrightError as exc:
error_str = str(exc).lower()
if "target page, context or browser has been closed" in error_str:
page = _get_recovered_page(context, page)
page.goto(url, wait_until="commit")
elif "navigation interrupted" not in error_str:
raise
current_url = page.url
if NOTEBOOKLM_HOST not in current_url:
console.print(f"[yellow]Warning: Current URL is {current_url}[/yellow]")
if not click.confirm("Save authentication anyway?"):
raise SystemExit(1)
context.storage_state(path=str(storage_path))
# Restrict permissions to owner only (contains sensitive cookies)
if sys.platform != "win32":
# chmod is a no-op on Windows (and can confuse ACLs)
storage_path.chmod(0o600)
except Exception as e:
# Handle browser launch errors specially (context will be None if launch failed)
if context is None:
if browser == "msedge" and (
"executable doesn't exist" in str(e).lower()
or "no such file" in str(e).lower()
or "failed to launch" in str(e).lower()
):
logger.error(f"Microsoft Edge not found: {e}")
console.print(
"[red]Microsoft Edge not found.[/red]\n"
"Install from: https://www.microsoft.com/edge\n"
"Or use the default Chromium browser: notebooklm login"
)
raise SystemExit(1) from e
logger.error(f"Login failed: {e}", exc_info=True)
raise
finally:
# Always close the browser context to prevent resource leaks
if context:
context.close()
console.print(f"\n[green]Authentication saved to:[/green] {storage_path}")
# Sync server language setting to local config so generate commands
# respect the user's global language preference (fixes #121)
_sync_server_language_to_config()
@cli.command("use")
@click.argument("notebook_id")
@click.pass_context
def use_notebook(ctx, notebook_id):
"""Set the current notebook context.
Once set, all commands will use this notebook by default.
You can still override by passing --notebook explicitly.
Supports partial IDs - 'notebooklm use abc' matches 'abc123...'
\b
Example:
notebooklm use nb123
notebooklm ask "what is this about?" # Uses nb123
notebooklm generate video "a fun explainer" # Uses nb123
"""
try:
cookies, csrf, session_id = get_client(ctx)
auth = AuthTokens(cookies=cookies, csrf_token=csrf, session_id=session_id)
async def _get():
async with NotebookLMClient(auth) as client:
# Resolve partial ID to full ID
resolved_id = await resolve_notebook_id(client, notebook_id)
nb = await client.notebooks.get(resolved_id)
return nb, resolved_id
nb, resolved_id = run_async(_get())
created_str = nb.created_at.strftime("%Y-%m-%d") if nb.created_at else None
set_current_notebook(resolved_id, nb.title, nb.is_owner, created_str)
table = Table()
table.add_column("ID", style="cyan")
table.add_column("Title", style="green")
table.add_column("Owner")
table.add_column("Created", style="dim")
created = created_str or "-"
owner_status = "Owner" if nb.is_owner else "Shared"
table.add_row(nb.id, nb.title, owner_status, created)
console.print(table)
except FileNotFoundError:
set_current_notebook(notebook_id)
table = Table()
table.add_column("ID", style="cyan")
table.add_column("Title", style="green")
table.add_column("Owner")
table.add_column("Created", style="dim")
table.add_row(notebook_id, "-", "-", "-")
console.print(table)
except click.ClickException:
# Re-raise click exceptions (from resolve_notebook_id)
raise
except Exception as e:
set_current_notebook(notebook_id)
table = Table()
table.add_column("ID", style="cyan")
table.add_column("Title", style="green")
table.add_column("Owner")
table.add_column("Created", style="dim")
table.add_row(notebook_id, f"Warning: {str(e)}", "-", "-")
console.print(table)
@cli.command("status")
@click.option("--json", "json_output", is_flag=True, help="Output as JSON")
@click.option("--paths", "show_paths", is_flag=True, help="Show resolved file paths")
def status(json_output, show_paths):
"""Show current context (active notebook and conversation).
Use --paths to see where configuration files are located
(useful for debugging NOTEBOOKLM_HOME).
"""
context_file = get_context_path()
notebook_id = get_current_notebook()
# Handle --paths flag
if show_paths:
path_info = get_path_info()
if json_output:
json_output_response({"paths": path_info})
return
table = Table(title="Configuration Paths")
table.add_column("File", style="dim")
table.add_column("Path", style="cyan")
table.add_column("Source", style="green")
table.add_row(
"Profile",
path_info.get("profile", "default"),
path_info.get("profile_source", ""),
)
table.add_row("Home Directory", path_info["home_dir"], path_info["home_source"])
table.add_row("Profile Directory", path_info.get("profile_dir", ""), "")
table.add_row("Storage State", path_info["storage_path"], "")
table.add_row("Context", path_info["context_path"], "")
table.add_row("Browser Profile", path_info["browser_profile_dir"], "")
# Show if NOTEBOOKLM_AUTH_JSON is set
if os.environ.get("NOTEBOOKLM_AUTH_JSON"):
console.print(
"[yellow]Note: NOTEBOOKLM_AUTH_JSON is set (inline auth active)[/yellow]\n"
)
console.print(table)
return
if notebook_id:
try:
data = json.loads(context_file.read_text(encoding="utf-8"))
title = data.get("title", "-")
is_owner = data.get("is_owner", True)
created_at = data.get("created_at", "-")
conversation_id = data.get("conversation_id")
if json_output:
json_data = {
"has_context": True,
"notebook": {
"id": notebook_id,
"title": title if title != "-" else None,
"is_owner": is_owner,
},
"conversation_id": conversation_id,
}
json_output_response(json_data)
return
table = Table(title="Current Context")
table.add_column("Property", style="dim")
table.add_column("Value", style="cyan")
table.add_row("Notebook ID", notebook_id)
table.add_row("Title", str(title))
owner_status = "Owner" if is_owner else "Shared"
table.add_row("Ownership", owner_status)
table.add_row("Created", created_at)
if conversation_id:
table.add_row("Conversation", conversation_id)
else:
table.add_row("Conversation", "[dim]None (will auto-select on next ask)[/dim]")
console.print(table)
except (OSError, json.JSONDecodeError):
if json_output:
json_data = {
"has_context": True,
"notebook": {
"id": notebook_id,
"title": None,
"is_owner": None,
},
"conversation_id": None,
}
json_output_response(json_data)
return
table = Table(title="Current Context")
table.add_column("Property", style="dim")
table.add_column("Value", style="cyan")
table.add_row("Notebook ID", notebook_id)
table.add_row("Title", "-")
table.add_row("Ownership", "-")
table.add_row("Created", "-")
table.add_row("Conversation", "[dim]None[/dim]")
console.print(table)
else:
if json_output:
json_data = {
"has_context": False,
"notebook": None,
"conversation_id": None,
}
json_output_response(json_data)
return
console.print(
"[yellow]No notebook selected. Use 'notebooklm use <id>' to set one.[/yellow]"
)
@cli.command("clear")
def clear_cmd():
"""Clear current notebook context."""
clear_context()
console.print("[green]Context cleared[/green]")
@cli.group("auth")
def auth_group():
"""Authentication management commands."""
pass
@auth_group.command("check")
@click.option(
"--test", "test_fetch", is_flag=True, help="Test token fetch (makes network request)"
)
@click.option("--json", "json_output", is_flag=True, help="Output as JSON")
def auth_check(test_fetch, json_output):
"""Check authentication status and diagnose issues.
Validates that authentication is properly configured by checking:
- Storage file exists and is readable
- JSON structure is valid
- Required cookies (SID) are present
- Cookie domains are correct
Use --test to also verify tokens can be fetched from NotebookLM
(requires network access).
\b
Examples:
notebooklm auth check # Quick local validation
notebooklm auth check --test # Full validation with network test
notebooklm auth check --json # Machine-readable output
"""
from ..auth import (
extract_cookies_from_storage,
fetch_tokens,
)
storage_path = get_storage_path()
has_env_var = bool(os.environ.get("NOTEBOOKLM_AUTH_JSON"))
has_home_env = bool(os.environ.get("NOTEBOOKLM_HOME"))
checks: dict[str, bool | None] = {
"storage_exists": False,
"json_valid": False,
"cookies_present": False,
"sid_cookie": False,
"token_fetch": None, # None = not tested, True/False = result
}
# Determine auth source for display
if has_env_var:
auth_source = "NOTEBOOKLM_AUTH_JSON"
elif has_home_env:
auth_source = f"$NOTEBOOKLM_HOME ({storage_path})"
else:
auth_source = f"file ({storage_path})"
details: dict[str, Any] = {
"storage_path": str(storage_path),
"auth_source": auth_source,
"cookies_found": [],
"cookie_domains": [],
"error": None,
}
# Check 1: Storage exists
if has_env_var:
checks["storage_exists"] = True
else:
checks["storage_exists"] = storage_path.exists()
if not checks["storage_exists"]:
details["error"] = f"Storage file not found: {storage_path}"
_output_auth_check(checks, details, json_output)
return
# Check 2: JSON valid
try:
if has_env_var:
storage_state = json.loads(os.environ["NOTEBOOKLM_AUTH_JSON"])
else:
storage_state = json.loads(storage_path.read_text(encoding="utf-8"))
checks["json_valid"] = True
except json.JSONDecodeError as e:
details["error"] = f"Invalid JSON: {e}"
_output_auth_check(checks, details, json_output)
return
# Check 3: Cookies present
try:
cookies = extract_cookies_from_storage(storage_state)
checks["cookies_present"] = True
checks["sid_cookie"] = "SID" in cookies
details["cookies_found"] = list(cookies.keys())
# Build detailed cookie-by-domain mapping for debugging
cookies_by_domain: dict[str, list[str]] = {}
for cookie in storage_state.get("cookies", []):
domain = cookie.get("domain", "")
name = cookie.get("name", "")
if domain and name and "google" in domain.lower():
cookies_by_domain.setdefault(domain, []).append(name)
details["cookies_by_domain"] = cookies_by_domain
details["cookie_domains"] = sorted(cookies_by_domain.keys())
except ValueError as e:
details["error"] = str(e)
_output_auth_check(checks, details, json_output)
return
# Check 4: Token fetch (optional)
if test_fetch:
try:
csrf, session_id = run_async(fetch_tokens(cookies))
checks["token_fetch"] = True
details["csrf_length"] = len(csrf)
details["session_id_length"] = len(session_id)
except Exception as e:
checks["token_fetch"] = False
details["error"] = f"Token fetch failed: {e}"
_output_auth_check(checks, details, json_output)
def _output_auth_check(checks: dict, details: dict, json_output: bool):
"""Output auth check results."""
all_passed = all(v is True for v in checks.values() if v is not None)
if json_output:
json_output_response(
{
"status": "ok" if all_passed else "error",
"checks": checks,
"details": details,
}
)
return
# Rich output
table = Table(title="Authentication Check")
table.add_column("Check", style="dim")
table.add_column("Status")
table.add_column("Details", style="cyan")
def status_icon(val):
if val is None:
return "[dim]⊘ skipped[/dim]"
return "[green]✓ pass[/green]" if val else "[red]✗ fail[/red]"
table.add_row(
"Storage exists",
status_icon(checks["storage_exists"]),
details["auth_source"],
)
table.add_row(
"JSON valid",
status_icon(checks["json_valid"]),
"",
)
table.add_row(
"Cookies present",
status_icon(checks["cookies_present"]),
f"{len(details.get('cookies_found', []))} cookies" if checks["cookies_present"] else "",
)
table.add_row(
"SID cookie",
status_icon(checks["sid_cookie"]),
", ".join(details.get("cookie_domains", [])[:3]) or "",
)
table.add_row(
"Token fetch",
status_icon(checks["token_fetch"]),
"use --test to check" if checks["token_fetch"] is None else "",
)
console.print(table)
# Show detailed cookie breakdown by domain
cookies_by_domain = details.get("cookies_by_domain", {})