Repository navigation
Expand file tree
/
Copy pathdownloader.py
More file actions
1957 lines (1708 loc) · 78.8 KB
/
Copy pathdownloader.py
File metadata and controls
1957 lines (1708 loc) · 78.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
"""
downloader.py — Unified Canvas Downloader
Combines video_downloader.py and material_downloader.py into a single CLI.
Usage:
python downloader.py --course-list
python downloader.py --video-list
python downloader.py --video-list --course 85427
python downloader.py --download-video 1 3 5
python downloader.py --download-video 2 4 --course 85427
python downloader.py --download-video-all
python downloader.py --download-video-all --course 85427 --secretly
python downloader.py --material-list --course 85427
python downloader.py --download-material "L02-slides.pdf" --course 85427
python downloader.py --download-material-all --course 85427
python downloader.py --download-material-all --secretly --path /data/courses
"""
from __future__ import annotations
import argparse
import json
import os
import random
import re
import subprocess
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
try:
import requests
from canvasapi import Canvas
from tqdm import tqdm
except ImportError as _e:
print(f"[error] Missing dependency: {_e}")
print("[error] Please install the ML environment from Settings → ML Environment in the AutoNote app.")
sys.exit(1)
# ── Configuration ──────────────────────────────────────────────────────────────
PROJECT_DIR = Path(__file__).parent
MANIFEST_FILE = None # set after DATA_DIR is resolved below
# Persistent data dir: ~/.auto_note/ when installed (AppImage or scripts/ copy),
# else the project directory (dev mode).
_AUTO_NOTE_DIR = Path.home() / ".auto_note"
# AUTONOTE_DATA_DIR env var lets the Electron app (or any launcher) explicitly
# set the data directory so config/credentials are always found regardless of
# where the script file lives (dev mode vs installed).
if os.environ.get("AUTONOTE_DATA_DIR"):
DATA_DIR = Path(os.environ["AUTONOTE_DATA_DIR"])
elif getattr(sys, "frozen", False) or PROJECT_DIR == _AUTO_NOTE_DIR / "scripts":
DATA_DIR = _AUTO_NOTE_DIR
else:
DATA_DIR = PROJECT_DIR
MANIFEST_FILE = DATA_DIR / "manifest.json"
# ── User-configurable connection settings (set via GUI Settings page) ──────────
_config_file = DATA_DIR / "config.json"
_config: dict = json.load(open(_config_file, encoding="utf-8")) if _config_file.exists() else {}
CANVAS_URL = _config.get("CANVAS_URL", "").strip().rstrip("/")
if CANVAS_URL and not CANVAS_URL.startswith(("http://", "https://")):
CANVAS_URL = "https://" + CANVAS_URL
PANOPTO_HOST = _config.get("PANOPTO_HOST", "")
# Strip protocol prefix if user accidentally stored a full URL (e.g. "https://mediaweb.ap.panopto.com")
if PANOPTO_HOST.startswith(("https://", "http://")):
PANOPTO_HOST = re.sub(r'^https?://', '', PANOPTO_HOST).split('/')[0]
_canvas_token_file = DATA_DIR / "canvas_token.txt"
CANVAS_TOKEN = (
# strip() covers leading/trailing whitespace; split()[0] takes the first
# token only, guarding against files that accidentally contain two tokens
# separated by newlines (e.g. copy-paste from two accounts).
(_canvas_token_file.read_text().split()[0] if _canvas_token_file.exists() else None)
or os.environ.get("CANVAS_TOKEN", "")
)
SIZE_LIMIT = 1 * 1024 ** 3 # 1 GB
SKIP_COURSE_KEYWORDS = [
"training", "pdp", "rmcpdp", "osa", "soct", "travel", "essentials",
"respect", "consent",
]
# Slack-mode delay ranges (seconds)
_SECRETLY_VIDEO_MIN = 5 * 60 # 5 min
_SECRETLY_VIDEO_MAX = 15 * 60 # 15 min
_SECRETLY_DIR_MIN = 2 * 60 # 2 min
_SECRETLY_DIR_MAX = 5 * 60 # 5 min
# ── Shared helpers ─────────────────────────────────────────────────────────────
def _sanitize(name: str) -> str:
return re.sub(r'[\\/*?:"<>|]', "_", name).strip()
def _canvas_headers() -> dict:
return {"Authorization": f"Bearer {CANVAS_TOKEN}"}
_playwright_checked = False
def _ensure_playwright_browsers() -> None:
"""Auto-install Chromium browser for Playwright if not already present.
Called once per process — checks if the Chromium binary exists, and
if not, runs `playwright install chromium` automatically so the user
never has to do it themselves.
"""
global _playwright_checked
if _playwright_checked:
return
_playwright_checked = True
try:
from playwright._impl._driver import compute_driver_executable
driver_exec = compute_driver_executable()
import subprocess as _sp
result = _sp.run(
[str(driver_exec), "install", "--dry-run", "chromium"],
capture_output=True, text=True, timeout=10,
)
# If dry-run succeeds without mentioning "not installed", we're good
if result.returncode == 0:
return
except Exception:
pass
# Check by actually trying to find the executable path
try:
from playwright.sync_api import sync_playwright as _sp_check
with _sp_check() as p:
p.chromium.executable_path # noqa: B018
return # browser exists
except Exception:
pass
# Browser not found — install it
tqdm.write(" [playwright] Chromium not found — installing automatically…")
import subprocess as _sp
try:
proc = _sp.run(
[sys.executable, "-m", "playwright", "install", "chromium"],
capture_output=True, text=True, timeout=300,
)
if proc.returncode == 0:
tqdm.write(" [playwright] Chromium installed successfully.")
else:
tqdm.write(f" [playwright] Install exited with code {proc.returncode}")
if proc.stderr:
tqdm.write(f" [playwright] {proc.stderr.strip()[:200]}")
except Exception as e:
tqdm.write(f" [playwright] Auto-install failed: {e}")
tqdm.write(" [playwright] Run manually: python -m playwright install chromium")
def _is_academic(course) -> bool:
try:
name = course.name.lower()
except AttributeError:
return False
return not any(kw in name for kw in SKIP_COURSE_KEYWORDS)
def _load_json(path: Path) -> dict:
if path.exists():
with open(path, encoding="utf-8") as f:
return json.load(f)
return {}
def _save_json(path: Path, data: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
# ── Concurrent transcription helper ───────────────────────────────────────────
_transcribe_procs: list[subprocess.Popen] = []
def _spawn_transcribe(video_path: str) -> None:
"""Spawn transcription for a video in the background.
Runs extract_caption.py --video <path> as a subprocess.
The download loop continues immediately without waiting.
"""
script = PROJECT_DIR / "extract_caption.py"
# Also check installed scripts dir
installed = Path.home() / ".auto_note" / "scripts" / "extract_caption.py"
if installed.exists():
script = installed
cmd = [sys.executable, str(script), "--video", video_path]
tqdm.write(f" [transcribe] Starting background transcription: {Path(video_path).name}")
proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
env={**os.environ, "AUTONOTE_DATA_DIR": str(DATA_DIR)},
)
_transcribe_procs.append(proc)
def _wait_transcriptions() -> None:
"""Wait for all background transcription processes to finish."""
if not _transcribe_procs:
return
tqdm.write(f"\n Waiting for {len(_transcribe_procs)} background transcription(s) to finish...")
for proc in _transcribe_procs:
for line in proc.stdout:
tqdm.write(f" [transcribe] {line.rstrip()}")
proc.wait()
if proc.returncode == 0:
tqdm.write(f" [transcribe] Done (exit 0)")
else:
tqdm.write(f" [transcribe] Failed (exit {proc.returncode})")
_transcribe_procs.clear()
def _secretly_wait_video() -> None:
delay = random.uniform(_SECRETLY_VIDEO_MIN, _SECRETLY_VIDEO_MAX)
mins = delay / 60
for _ in tqdm(range(int(delay)), desc=f" [secretly] Next video in {mins:.1f} min",
unit="s", bar_format="{desc} |{bar}| {n}/{total}s", leave=False):
time.sleep(1)
def _secretly_wait_dir() -> None:
delay = random.uniform(_SECRETLY_DIR_MIN, _SECRETLY_DIR_MAX)
mins = delay / 60
for _ in tqdm(range(int(delay)), desc=f" [secretly] Next folder in {mins:.1f} min",
unit="s", bar_format="{desc} |{bar}| {n}/{total}s", leave=False):
time.sleep(1)
# ── Canvas course listing ──────────────────────────────────────────────────────
def get_academic_courses(canvas: Canvas) -> list:
"""Return all academic courses the user has any enrollment in.
Intentionally does NOT filter by enrollment_state="active" so that
courses with TA, auditor, design-experience, or cross-listed enrollments
are included — these often have an enrollment state other than "active".
"""
courses = []
for c in canvas.get_courses():
if _is_academic(c):
courses.append(c)
return courses
def get_course_by_id(canvas: Canvas, course_id: int):
"""Fetch a single course by ID (even if not in active list)."""
return canvas.get_course(course_id)
# ══════════════════════════════════════════════════════════════════════════════
# VIDEO SECTION
# ══════════════════════════════════════════════════════════════════════════════
# Canvas external-tool ID for the "Videos/Panopto" course navigation tab.
# Used as a fallback; the actual ID is discovered per-course via
# _resolve_panopto_tool_id() because Canvas assigns different tool IDs
# per-institution and sometimes per-course.
_PANOPTO_TAB_TOOL_ID_FALLBACK = 128
# Stream-tag preference order. Can be overridden at runtime via
# AUTONOTE_PREFER_STREAM or the --prefer-stream CLI flag. Default keeps the
# existing screen-share-first behaviour, which is right for most lectures.
_PREFER_STREAM_ORDER: tuple[str, ...] = tuple(
os.environ.get("AUTONOTE_PREFER_STREAM", "SS,OBJECT,DV").split(",")
)
# Per-course cache for resolved Panopto tool IDs.
_PANOPTO_TOOL_ID_CACHE: dict[int, int] = {}
def _resolve_panopto_tool_id(course_id: int) -> int | None:
"""Discover the Canvas external-tool ID of the Panopto/Videos tab for a
specific course.
Canvas assigns different external-tool IDs per-institution and sometimes
per-course, so the old hardcoded ID (128) only worked for the author's
default token. For a different token or course (e.g. EE4802), a different
tool ID or tool set may apply — and Strategy 2 silently returned zero.
Resolution order:
1. /api/v1/courses/<id>/tabs — works even when the LTI tool is account-
scoped (not "installed" at the course level). The tab id is of the
form "context_external_tool_<N>", so we parse N directly. This is
what the UI itself uses to render the left-hand navigation.
2. /api/v1/courses/<id>/external_tools — works for tools explicitly
installed in the course. Matches on name/domain/url.
Results are cached.
"""
if course_id in _PANOPTO_TOOL_ID_CACHE:
return _PANOPTO_TOOL_ID_CACHE[course_id]
_VIDEO_LABELS = ("videos/panopto", "videos", "video", "lecture videos", "panopto")
# ── Strategy A: course tabs (most reliable for account-scoped tools) ─────
try:
r = requests.get(
f"{CANVAS_URL}/api/v1/courses/{course_id}/tabs",
headers=_canvas_headers(),
timeout=30,
)
if r.status_code == 200:
for tab in r.json():
tid_str = (tab.get("id") or "")
label = (tab.get("label") or "").lower()
if not tid_str.startswith("context_external_tool_"):
continue
if "panopto" in label or label in _VIDEO_LABELS:
try:
tid = int(tid_str.rsplit("_", 1)[-1])
_PANOPTO_TOOL_ID_CACHE[course_id] = tid
return tid
except ValueError:
continue
except Exception as e:
tqdm.write(f" [warn] _resolve_panopto_tool_id tabs({course_id}): {e}")
# ── Strategy B: external_tools (explicit course-level installs) ──────────
try:
r = requests.get(
f"{CANVAS_URL}/api/v1/courses/{course_id}/external_tools",
headers=_canvas_headers(),
params={"per_page": 100},
timeout=30,
)
if r.status_code == 200:
for tool in r.json():
name = (tool.get("name") or "").lower()
domain = (tool.get("domain") or "").lower()
url = (tool.get("url") or "").lower()
if ("panopto" in name or "panopto" in domain or "panopto" in url
or name in _VIDEO_LABELS):
tid = int(tool["id"])
_PANOPTO_TOOL_ID_CACHE[course_id] = tid
return tid
except Exception as e:
tqdm.write(f" [warn] _resolve_panopto_tool_id tools({course_id}): {e}")
return None
def _find_panopto_items(canvas: Canvas, course) -> list[dict]:
"""
Discover all Panopto sessions for a course using three strategies:
1. Module ExternalTool items (e.g. CS3210 — each lecture linked in a module)
2. Panopto folder API (e.g. CS2105 — sessions stored in a Panopto folder)
3. Canvas Pages scan (e.g. CS2101 — Viewer.aspx links embedded in pages)
All three are merged and de-duplicated by session UUID.
"""
seen_ids: set[str] = set()
seen_titles: set[str] = set() # title-based dedup across strategies
videos: list[dict] = []
def _add(v: dict) -> None:
uid = str(v["item_id"])
if uid in seen_ids:
return
# Cross-strategy dedup: Panopto "delivery" IDs (LTI) differ from
# "session" IDs (folder API), so fall back to title matching.
title_key = v.get("title", "").strip().lower()
if title_key and title_key in seen_titles:
return
seen_ids.add(uid)
if title_key:
seen_titles.add(title_key)
videos.append(v)
# ── Strategy 1: module ExternalTool items ─────────────────────────────────
s1_count = 0
try:
for module in course.get_modules():
for item in module.get_module_items():
if item.type == "ExternalTool":
url = getattr(item, "external_url", "") or ""
if "panopto" in url.lower():
_add({
"course_id": course.id,
"course_name": course.name,
"module_name": module.name,
"title": item.title,
"lti_url": url,
"item_id": item.id,
"viewer_url": None,
})
s1_count += 1
except Exception as e:
tqdm.write(f" [warn] Strategy 1 (modules) {course.id}: {e}")
tqdm.write(f" [info] Strategy 1 (modules): {s1_count} video(s)")
# ── Strategy 2: Panopto folder API (Videos/Panopto tab) ───────────────────
s2_count = 0
try:
tqdm.write(f" [info] Strategy 2 (Panopto tab): launching browser…")
folder_id, panopto_cookies, bearer_token = _get_panopto_tab_folder(course.id)
if folder_id:
tqdm.write(f" [info] Strategy 2: folder_id={folder_id}, scanning…")
for s in _iter_panopto_folder(folder_id, panopto_cookies, bearer_token=bearer_token):
viewer_url = (f"https://{PANOPTO_HOST}/Panopto/Pages/Viewer.aspx"
f"?id={s['session_id']}")
_add({
"course_id": course.id,
"course_name": course.name,
"module_name": s.get("folder_name", "Videos/Panopto"),
"title": s["name"],
"lti_url": None,
"item_id": s["session_id"],
"viewer_url": viewer_url,
"_panopto_cookies": panopto_cookies,
"_bearer_token": bearer_token,
})
s2_count += 1
else:
tqdm.write(f" [warn] Strategy 2: could not find Panopto folder (browser may have failed)")
except Exception as e:
tqdm.write(f" [warn] Strategy 2 (Panopto folder) {course.id}: {e}")
tqdm.write(f" [info] Strategy 2 (Panopto tab): {s2_count} video(s)")
# ── Strategy 3: Canvas Pages scan (fallback only) ─────────────────────────
if not videos:
tqdm.write(f" [info] Strategy 3 (pages scan): trying…")
try:
s3_before = len(videos)
for v in _find_panopto_in_pages(course):
_add(v)
tqdm.write(f" [info] Strategy 3 (pages scan): {len(videos) - s3_before} video(s)")
except Exception as e:
tqdm.write(f" [warn] Strategy 3 (pages scan) {course.id}: {e}")
return videos
def _get_panopto_tab_folder(course_id: int) -> tuple[str | None, list[dict], str | None]:
"""
Launch the Videos/Panopto tab via Canvas sessionless LTI, navigate with
Playwright, capture the root Panopto folder ID, auth cookies, and OAuth
Bearer token.
Returns (folder_id, panopto_cookies, bearer_token).
"""
global PANOPTO_HOST # may be auto-detected from Playwright request URLs
_ensure_playwright_browsers()
from playwright.sync_api import sync_playwright
tool_id = _resolve_panopto_tool_id(course_id) or _PANOPTO_TAB_TOOL_ID_FALLBACK
r = requests.get(
f"{CANVAS_URL}/api/v1/courses/{course_id}/external_tools/sessionless_launch"
f"?id={tool_id}&launch_type=course_navigation",
headers=_canvas_headers(),
timeout=30,
)
if r.status_code != 200:
tqdm.write(f" [warn] Panopto tab launch failed (tool_id={tool_id}, status={r.status_code})")
return None, [], None
launch_url = r.json().get("url")
if not launch_url:
return None, [], None
folder_id: str | None = None
bearer_token: str | None = None
detected_host: str | None = None
cookies: list[dict] = []
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
ctx = browser.new_context()
page = ctx.new_page()
def _on_request(req: object) -> None:
nonlocal folder_id, bearer_token, detected_host
url = req.url
m = re.search(r"folderID=([0-9a-f-]{36})", url, re.IGNORECASE)
if m and folder_id is None:
folder_id = m.group(1)
# Auto-detect Panopto hostname from any Panopto request URL.
if detected_host is None and "panopto" in url.lower():
from urllib.parse import urlparse
netloc = urlparse(url).netloc
if netloc and "panopto" in netloc.lower():
detected_host = netloc
# Capture the OAuth Bearer token issued to the embedded page.
# The WCF GetSessions endpoint requires it to return Subfolders.
auth = req.headers.get("authorization", "")
if auth.startswith("Bearer ") and bearer_token is None:
bearer_token = auth[len("Bearer "):]
page.on("request", _on_request)
try:
page.goto(launch_url, wait_until="networkidle", timeout=60000)
time.sleep(3)
cookies = [c for c in ctx.cookies()
if "panopto" in c.get("domain", "").lower()]
# Also try cookies domain as a fallback host source
if detected_host is None and cookies:
domain = cookies[0].get("domain", "").lstrip(".")
if domain:
detected_host = domain
except Exception as e:
tqdm.write(f" [warn] Playwright (Panopto tab) course {course_id}: {e}")
finally:
browser.close()
# Persist the detected host so all subsequent API calls use it.
if detected_host:
if not PANOPTO_HOST:
PANOPTO_HOST = detected_host
tqdm.write(f" [info] Auto-detected PANOPTO_HOST: {PANOPTO_HOST}")
# Save to config so future sessions don't need to re-detect.
try:
cfg = json.load(open(_config_file, encoding="utf-8")) if _config_file.exists() else {}
cfg["PANOPTO_HOST"] = PANOPTO_HOST
with open(_config_file, "w", encoding="utf-8") as f:
json.dump(cfg, f, indent=2)
except Exception:
pass
return folder_id, cookies, bearer_token
def _iter_panopto_folder(
folder_id: str,
cookies: list[dict],
folder_name: str = "Videos/Panopto",
bearer_token: str | None = None,
_sess: "requests.Session | None" = None,
) -> list[dict]:
"""
Recursively list all sessions in a Panopto folder via the WCF GetSessions
endpoint.
Key requirements discovered by request inspection:
- The WCF endpoint requires an OAuth Bearer token (captured by Playwright)
to return the Subfolders list; cookie-only requests receive Subfolders=None.
- getFolderData=true must be set to receive the Subfolders field at all.
- Duration filter: entries with no Duration are navigation placeholders
(e.g. "Home") not actual recordings.
Returns list of {session_id, name, folder_name}.
"""
if _sess is None:
_sess = requests.Session()
for ck in cookies:
_sess.cookies.set(ck["name"], ck["value"], domain=ck.get("domain", ""))
headers = {"Content-Type": "application/json"}
if bearer_token:
headers["Authorization"] = f"Bearer {bearer_token}"
results: list[dict] = []
subfolders: list[dict] = [] # collected from first page (getFolderData)
PAGE_SIZE = 250
start_idx = 0
while True:
r = _sess.post(
f"https://{PANOPTO_HOST}/Panopto/Services/Data.svc/GetSessions",
json={"queryParameters": {
"folderID": folder_id,
"startIndex": start_idx,
"maxResults": PAGE_SIZE,
"sortColumn": 1,
"sortAscending": True,
"getFolderData": start_idx == 0, # only needed on first page
"includeArchived": True,
"includePlaylists": True,
"includePlaceholderSessions": False,
}},
headers=headers,
timeout=30,
)
if r.status_code != 200:
tqdm.write(f" [warn] GetSessions HTTP {r.status_code} for folder {folder_id}")
break
d = r.json().get("d") or {}
page_results = d.get("Results") or []
for s in page_results:
sid = s.get("DeliveryID") or s.get("SessionID")
name = s.get("SessionName", "")
duration = s.get("Duration")
# Skip placeholder/empty sessions that have no video content.
# These appear as folder-level navigation entries (Duration=None)
# and return ErrorCode=6 from DeliveryInfo.aspx.
if duration is None:
continue
if sid and name:
results.append({
"session_id": sid,
"name": name,
"folder_name": folder_name,
})
if start_idx == 0:
subfolders = d.get("Subfolders") or []
start_idx += len(page_results)
total = d.get("TotalNumberOfResults") or 0
if not page_results or start_idx >= total:
break
# Recurse into subfolders
for sf in subfolders:
sf_id = sf.get("ID") or sf.get("FolderID") or sf.get("Id")
sf_name = sf.get("Name") or folder_name
if sf_id:
tqdm.write(f" [info] Scanning subfolder: {sf_name}")
results.extend(
_iter_panopto_folder(sf_id, cookies, sf_name, bearer_token, _sess)
)
return results
def _find_panopto_in_pages(course) -> list[dict]:
"""
Scan Canvas Pages for embedded Panopto Viewer.aspx links.
Returns video dicts for each unique session UUID found.
"""
global PANOPTO_HOST # may be auto-detected from page bodies
videos: list[dict] = []
seen: set[str] = set()
try:
for page_stub in course.get_pages():
page = course.get_page(page_stub.url)
body = getattr(page, "body", "") or ""
if "panopto" not in body.lower():
continue
# Auto-detect PANOPTO_HOST from embedded URLs if not yet known.
if not PANOPTO_HOST:
m = re.search(
r"https?://([\w.-]*panopto[\w.-]*)/Panopto/",
body, re.IGNORECASE,
)
if m:
PANOPTO_HOST = m.group(1)
tqdm.write(f" [info] Auto-detected PANOPTO_HOST from page: {PANOPTO_HOST}")
try:
cfg = json.load(open(_config_file, encoding="utf-8")) if _config_file.exists() else {}
cfg["PANOPTO_HOST"] = PANOPTO_HOST
with open(_config_file, "w", encoding="utf-8") as f:
json.dump(cfg, f, indent=2)
except Exception:
pass
# Match ?id=UUID (Viewer.aspx or Embed.aspx links)
for uid in re.findall(
r"[?&]id=([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}"
r"-[0-9a-f]{4}-[0-9a-f]{12})",
body, re.IGNORECASE,
):
uid = uid.lower()
if uid in seen:
continue
seen.add(uid)
viewer_url = (f"https://{PANOPTO_HOST}/Panopto/Pages/Viewer.aspx"
f"?id={uid}")
videos.append({
"course_id": course.id,
"course_name": course.name,
"module_name": page_stub.title,
"title": page_stub.title,
"lti_url": None,
"item_id": uid, # UUID string
"viewer_url": viewer_url,
})
except Exception as e:
tqdm.write(f" [warn] pages scan {course.id}: {e}")
return videos
def discover_videos(canvas: Canvas, course_id: int | None = None) -> list[dict]:
"""
Discover all Panopto videos.
If course_id is given, only scan that course.
Each entry gets a 'global_num' (1-based across all courses) and
'course_num' (1-based within its course).
"""
if course_id:
courses = [get_course_by_id(canvas, course_id)]
else:
courses = get_academic_courses(canvas)
all_videos: list[dict] = []
course_counters: dict[int, int] = {}
with tqdm(courses, desc="Scanning courses", unit="course") as bar:
for course in bar:
bar.set_postfix_str(course.name[:40])
videos = _find_panopto_items(canvas, course)
cid = course.id
course_counters.setdefault(cid, 0)
for v in videos:
course_counters[cid] += 1
v["course_num"] = course_counters[cid]
all_videos.extend(videos)
# Assign global numbers
for i, v in enumerate(all_videos, start=1):
v["global_num"] = i
return all_videos
def print_video_list(videos: list[dict], manifest: dict, by_course: bool = False) -> None:
"""Print a numbered video listing."""
num_key = "course_num" if by_course else "global_num"
print()
print(f" {'#':>3} {'Status':<10} {'Course':<20} {'Module':<22} Title")
print(f" {'-'*3} {'-'*10} {'-'*20} {'-'*22} {'-'*40}")
for v in videos:
status = manifest.get(str(v["item_id"]), {}).get("status", "pending")
num = v[num_key]
course = v["course_name"][:20]
module = v["module_name"][:22]
title = v["title"][:50]
mark = "✓" if status == "done" else " "
print(f" {num:>3} [{mark}]{status:<8} {course:<20} {module:<22} {title}")
print()
print(f" Total: {len(videos)} video(s)")
print()
def _get_sessionless_launch_url(course_id: int, item_id: int) -> str | None:
r = requests.get(
f"{CANVAS_URL}/api/v1/courses/{course_id}/external_tools/sessionless_launch"
f"?launch_type=module_item&module_item_id={item_id}",
headers=_canvas_headers(),
timeout=30,
)
return r.json().get("url") if r.status_code == 200 else None
def _get_panopto_session(launch_url: str) -> tuple[str | None, list[dict]]:
_ensure_playwright_browsers()
from playwright.sync_api import sync_playwright
session_id, cookies = None, []
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
ctx = browser.new_context()
page = ctx.new_page()
try:
page.goto(launch_url, wait_until="networkidle", timeout=60000)
time.sleep(2)
m = re.search(r"[?&]id=([0-9a-f-]{36})", page.url, re.IGNORECASE)
if m:
session_id = m.group(1)
cookies = [c for c in ctx.cookies()
if "panopto" in c.get("domain", "").lower()]
except Exception as e:
tqdm.write(f" [warn] Playwright: {e}")
finally:
browser.close()
return session_id, cookies
def _download_authenticated(
url: str,
out_path: "Path",
headers: dict,
progress_cb: "callable",
) -> None:
"""Stream-download a URL that requires auth headers, with progress callback."""
r = requests.get(url, headers=headers, stream=True, timeout=300, allow_redirects=True)
r.raise_for_status()
total = int(r.headers.get("Content-Length", 0))
downloaded = 0
with open(out_path, "wb") as f:
for chunk in r.iter_content(chunk_size=65536):
if chunk:
f.write(chunk)
downloaded += len(chunk)
if total:
progress_cb(downloaded / total * 100)
if not total:
progress_cb(100)
def _get_stream_candidates(
session_id: str,
cookies: list[dict],
bearer_token: str | None = None,
course_id: int | None = None,
) -> list[tuple[str, dict, str]]:
"""Return all HLS stream candidates for a Panopto session in preference
order. Each item is (stream_url, auth_headers, stream_tag). Empty list on
failure. download_video() probes each candidate for audio and uses the
first one that has it."""
singles = _get_stream_url(
session_id, cookies,
bearer_token=bearer_token, course_id=course_id,
_return_all=True,
)
return singles or []
def _get_stream_url(
session_id: str,
cookies: list[dict],
bearer_token: str | None = None,
course_id: int | None = None,
_return_all: bool = False,
) -> tuple[str, dict] | list[tuple[str, dict, str]] | None:
"""Get the HLS stream URL for a Panopto session.
Returns (stream_url, auth_headers, stream_tag) on success, None on failure.
If _return_all=True, returns a list of all candidate tuples in preference
order so callers can fall back (audio-less stream → try next).
auth_headers is always {} (HLS streams are CDN-public once the URL is known).
stream_tag is the Panopto stream tag ("SS" for screen share, "DV" for camera, etc.).
Priority:
1. DeliveryInfo.aspx POST with Bearer token → HLS master.m3u8
2. Playwright LTI re-launch → navigate to Viewer.aspx → intercept DeliveryInfo
"""
def _extract_streams(body: dict) -> list[tuple[str, str]]:
"""Return a list of (stream_url, tag) candidates in preference order.
Caller can try each until one produces a video with an audio track —
some Panopto recordings store audio only in the DV stream while SS /
OBJECT are video-only for screen recordings.
Tag matching is case-insensitive: Panopto returns either upper-case
("OBJECT", "DV") or lower-case ("object", "dv") tags depending on
the session's recording setup. A case-sensitive match would fall
through to "any stream first" — which is DV (the camera), so the
downloaded video would be a lecture-hall camera shot instead of
the screen recording.
"""
streams = (body.get("Delivery") or {}).get("Streams") or []
# Preference: SS (screen-share) > OBJECT (screen recording) > DV (camera).
# We still yield *all* streams so the caller can fall back if the
# preferred one lacks audio.
order = tuple(t.upper() for t in _PREFER_STREAM_ORDER)
out: list[tuple[str, str]] = []
seen_urls: set[str] = set()
for tag in order + (None,):
for s in streams:
surl = s.get("StreamUrl", "")
if not surl or surl in seen_urls:
continue
stream_tag = (s.get("Tag", "") or "").upper()
if tag is None or stream_tag == tag:
seen_urls.add(surl)
out.append((surl, s.get("Tag", "unknown")))
return out
def _extract_stream(body: dict) -> tuple[str, str] | None:
streams = _extract_streams(body)
return streams[0] if streams else None
sess = requests.Session()
for ck in cookies:
sess.cookies.set(ck["name"], ck["value"], domain=ck.get("domain", ""))
auth_hdrs: dict = {}
if bearer_token:
auth_hdrs["Authorization"] = f"Bearer {bearer_token}"
# ── 1. DeliveryInfo.aspx POST ─────────────────────────────────────────────
# The bearer token in Authorization header allows the server to validate
# the LTI enrollment context and return the HLS stream URL.
delivery_url = f"https://{PANOPTO_HOST}/Panopto/Pages/Viewer/DeliveryInfo.aspx"
try:
r = sess.post(
delivery_url,
data={
"deliveryId": session_id, "isLiveNotes": "false",
"refreshAuthCookie": "true", "isActiveBroadcast": "false",
"isEditing": "false", "isKollectiveAgentInstalled": "false",
"isEmbed": "false", "responseType": "json",
},
headers=auth_hdrs,
timeout=30,
)
if r.status_code == 200:
body = r.json()
if not body.get("ErrorCode"):
if _return_all:
all_streams = _extract_streams(body)
if all_streams:
return [(u, {}, t) for (u, t) in all_streams]
result = _extract_stream(body)
if result:
surl, stag = result
return surl, {}, stag
except Exception:
pass
# ── 3. Playwright LTI re-launch → viewer intercept ───────────────────────
if course_id is None:
return None
tqdm.write(f" DeliveryInfo unavailable; re-launching via Canvas LTI…")
tool_id = _resolve_panopto_tool_id(course_id) or _PANOPTO_TAB_TOOL_ID_FALLBACK
r2 = requests.get(
f"{CANVAS_URL}/api/v1/courses/{course_id}/external_tools/sessionless_launch"
f"?id={tool_id}&launch_type=course_navigation",
headers=_canvas_headers(), timeout=30,
)
if r2.status_code != 200:
return None
launch_url = r2.json().get("url")
if not launch_url:
return None
_ensure_playwright_browsers()
from playwright.sync_api import sync_playwright
viewer_page_url = f"https://{PANOPTO_HOST}/Panopto/Pages/Viewer.aspx?id={session_id}"
captured: list[tuple[str, dict, str]] = []
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
ctx = browser.new_context()
page = ctx.new_page()
def _on_response(resp) -> None:
if "DeliveryInfo.aspx" in resp.url and not captured:
try:
body = resp.json()
if _return_all:
for surl, stag in _extract_streams(body):
captured.append((surl, {}, stag))
else:
result = _extract_stream(body)
if result:
surl, stag = result
captured.append((surl, {}, stag))
except Exception:
pass
page.on("response", _on_response)
try:
page.goto(launch_url, wait_until="networkidle", timeout=60000)
time.sleep(2)
page.goto(viewer_page_url, wait_until="networkidle", timeout=60000)
time.sleep(3)
except Exception as e:
tqdm.write(f" [warn] Playwright viewer: {e}")
finally:
browser.close()
if _return_all:
return list(captured) if captured else []
return captured[0] if captured else None
def _resolve_ffmpeg() -> str | None:
"""Locate an ffmpeg executable.
Order:
1. System ffmpeg in PATH (best — usually fastest, tracks user updates)
2. imageio-ffmpeg's bundled binary (cross-platform fallback for macOS
and any system without ffmpeg installed; pip-installable, no admin
rights needed). If imageio-ffmpeg isn't present (e.g. the user has
a venv from an older AutoNote release that pre-dates this fallback),
install it on demand — it's a single platform-specific wheel under
30 MB and the binary is cached for future runs.
"""
from shutil import which
sys_ff = which("ffmpeg")
if sys_ff:
return sys_ff
def _try_imageio() -> str | None:
try:
import imageio_ffmpeg
return imageio_ffmpeg.get_ffmpeg_exe()
except ImportError:
return None
except Exception as e:
tqdm.write(f" [warn] imageio-ffmpeg get_ffmpeg_exe failed: {e}")
return None
ff = _try_imageio()
if ff:
return ff
# Auto-install on first need. Quiet, fast, idempotent.
tqdm.write(" ffmpeg not found locally — installing imageio-ffmpeg fallback…")
try:
import subprocess as _sp
_sp.run(
[sys.executable, "-m", "pip", "install", "--quiet", "--disable-pip-version-check", "imageio-ffmpeg"],
check=True, timeout=180,
)
except Exception as e:
tqdm.write(f" [warn] auto-install imageio-ffmpeg failed: {e}")