dsh-zju-lecture-note 2.2.3 → 2.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +8 -7
  3. package/docs/technical.md +26 -4
  4. package/mcp_server.py +1 -1
  5. package/package.json +1 -1
  6. package/skills/scholia-notes/SKILL.md +8 -1
  7. package/skills/scholia-notes/references/format-spec.md +57 -6
  8. package/skills/scholia-notes/references/prelude.typ +42 -0
  9. package/skills/scholia-notes/references/typography-spec.md +4 -4
  10. package/skills/scholia-notes.manifest.json +9 -9
  11. package/skills/zju-lecture-summarizer/SKILL.md +13 -1
  12. package/skills/zju-lecture-summarizer.manifest.json +4 -4
  13. package/zju_lecture/client.py +741 -741
  14. package/zju_lecture/handout.py +353 -57
  15. package/zju_lecture/handout_prelude.typ +35 -2
  16. package/zju_lecture/prelude.typ +42 -0
  17. package/zju_lecture/study_notes.py +296 -1
  18. package/zju_lecture/typst-packages/VENDORED.md +1 -1
  19. package/zju_lecture/typst-packages/preview/noteworthy/0.4.0/LICENSE +20 -20
  20. package/zju_lecture/typst-packages/preview/noteworthy/0.4.0/lib.typ +128 -128
  21. package/zju_lecture/typst-packages/preview/noteworthy/0.4.0/typst.toml +15 -15
  22. package/zju_lecture/typst-packages/preview/scholia/0.1.0/src/lib.typ +2 -2
  23. package/zju_lecture/typst-packages/preview/showybox/2.0.4/LICENSE +21 -21
  24. package/zju_lecture/typst-packages/preview/showybox/2.0.4/lib/func.typ +142 -142
  25. package/zju_lecture/typst-packages/preview/showybox/2.0.4/lib/id.typ +11 -11
  26. package/zju_lecture/typst-packages/preview/showybox/2.0.4/lib/pre-rendering.typ +50 -50
  27. package/zju_lecture/typst-packages/preview/showybox/2.0.4/lib/sections.typ +141 -141
  28. package/zju_lecture/typst-packages/preview/showybox/2.0.4/lib/shadows.typ +118 -118
  29. package/zju_lecture/typst-packages/preview/showybox/2.0.4/showy.typ +267 -267
  30. package/zju_lecture/typst-packages/preview/showybox/2.0.4/typst.toml +11 -11
@@ -1,741 +1,741 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- Client for Zhejiang University 智云课堂 (classroom.zju.edu.cn) APIs.
4
- Pure Python standard library implementation with zero external dependencies.
5
- """
6
-
7
- import http.client
8
- import json
9
- import os
10
- import random
11
- import re
12
- import socket
13
- import ssl
14
- import time
15
- import urllib.error
16
- import urllib.parse
17
- import urllib.request
18
- from typing import Any, Dict, List, Optional
19
-
20
- from .security import sanitize_cookie_header
21
-
22
- BASE_URL = "https://classroom.zju.edu.cn"
23
- BASE_HOST = (urllib.parse.urlparse(BASE_URL).hostname or "classroom.zju.edu.cn").lower()
24
- USER_AGENT = (
25
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
26
- "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
27
- )
28
-
29
-
30
- _CA_SOURCE = "system"
31
- _CA_PATH: Optional[str] = None
32
-
33
-
34
- def _certifi_ca_path() -> Optional[str]:
35
- """Location of certifi's bundle, when certifi is installed and readable."""
36
- try:
37
- import certifi # type: ignore
38
-
39
- path = certifi.where()
40
- except Exception: # noqa: BLE001 - a broken certifi must not crash the tool
41
- return None
42
- return path if path and os.path.isfile(path) else None
43
-
44
-
45
- def _bundled_ca_path() -> Optional[str]:
46
- """The CA bundle shipped inside this package (``zju_lecture/cacert.pem``).
47
-
48
- dsh ships its own Python interpreter **without** certifi, and a plain
49
- ``ssl.create_default_context()`` on an incomplete OS root store raises
50
- ``CERTIFICATE_VERIFY_FAILED``. Carrying our own bundle means the common case
51
- (dsh on a fresh machine) stops depending on what the user happened to pip
52
- install.
53
- """
54
- path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cacert.pem")
55
- return path if os.path.isfile(path) else None
56
-
57
-
58
- def _context_from_cafile(path: str) -> Optional[ssl.SSLContext]:
59
- """Build a verifying context from ``path``; ``None`` when it is unusable."""
60
- try:
61
- return ssl.create_default_context(cafile=path)
62
- except (OSError, ssl.SSLError):
63
- return None
64
-
65
-
66
- def create_ssl_context() -> ssl.SSLContext:
67
- """Create the TLS context used for every request.
68
-
69
- Certificate verification is **never** disabled. The login cookie is sent
70
- over this connection, so silently downgrading to an unverified context
71
- (as an earlier version did when the local root store was incomplete) would
72
- turn a missing CA bundle into a cookie-exfiltration path.
73
-
74
- Trust store order: ``certifi``(跟得上 CA 轮换)→ 随包 ``cacert.pem``
75
- (dsh 自带 Python 没有 certifi 时的兜底)→ 系统根证书。三档都失败才会
76
- 在握手上报错,且错误信息里会写清用的是哪一档。
77
- """
78
- global _CA_SOURCE, _CA_PATH
79
-
80
- for source, resolver in (("certifi", _certifi_ca_path), ("bundled", _bundled_ca_path)):
81
- path = resolver()
82
- if not path:
83
- continue
84
- context = _context_from_cafile(path)
85
- if context is not None:
86
- _CA_SOURCE, _CA_PATH = source, path
87
- return context
88
- _CA_SOURCE, _CA_PATH = "system", None
89
- return ssl.create_default_context()
90
-
91
-
92
- _SSL_CONTEXT: Optional[ssl.SSLContext] = None
93
-
94
-
95
- def get_ssl_context() -> ssl.SSLContext:
96
- """Return the shared SSL context, building it on first use."""
97
- global _SSL_CONTEXT
98
- if _SSL_CONTEXT is None:
99
- _SSL_CONTEXT = create_ssl_context()
100
- return _SSL_CONTEXT
101
-
102
-
103
- def ssl_context_health() -> Dict[str, Any]:
104
- """Report the trust store actually in use (for actionable error messages)."""
105
- try:
106
- ca_count = len(get_ssl_context().get_ca_certs())
107
- except Exception: # noqa: BLE001 - diagnostics must never mask the real error
108
- ca_count = -1
109
- return {"source": _CA_SOURCE, "path": _CA_PATH, "ca_certs": ca_count}
110
-
111
-
112
- def _proxy_env() -> str:
113
- """Describe the proxy environment, naming the variables to inspect.
114
-
115
- "未设置" on its own does not tell the user which variable to look at, so the
116
- unset case spells the names out. Returns a phrase without brackets: the
117
- callers already wrap it in ().
118
- """
119
- found = []
120
- for key in ("HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy"):
121
- value = os.environ.get(key)
122
- if value:
123
- found.append(f"{key}={value}")
124
- if found:
125
- return ",".join(found)
126
- return "HTTPS_PROXY / HTTP_PROXY 均未设置"
127
-
128
-
129
- def describe_network_error(error: BaseException) -> str:
130
- """Turn a transport exception into ``原因 + 下一步``.
131
-
132
- The tool used to surface the raw ``<urlopen error ...>`` text, which made an
133
- incomplete CA store look like "the plugin's request is broken". 证书校验失败、
134
- 代理拦截、超时、连接被拒这四类占了网络失败的大头,各自给出可执行的下一步。
135
- """
136
- text = str(error)
137
- # urllib 把真实原因包一层 URLError(URLError(reason=SSLCertVerificationError(...))),
138
- # 不拆包的话「证书校验失败」这条分支永远命中不了。
139
- inner = getattr(error, "reason", None)
140
- if isinstance(error, urllib.error.URLError) and isinstance(inner, BaseException):
141
- text = f"{error} {inner}"
142
- error = inner
143
- context = ssl_context_health()
144
- store = {
145
- "certifi": "certifi",
146
- "bundled": "插件内置 cacert.pem",
147
- "system": "系统根证书",
148
- }.get(context["source"], "系统根证书")
149
- if context["path"]:
150
- store = f"{store} ({context['path']})"
151
-
152
- if isinstance(error, ssl.SSLCertVerificationError) or "CERTIFICATE_VERIFY_FAILED" in text:
153
- lines = [
154
- "原因:TLS 证书校验不通过(接口本身没挂,不要用关闭校验的方式绕过——登录 Cookie 走这条连接)。",
155
- f"信任库:{store},已加载 {context['ca_certs']} 张 CA 证书;代理环境:{_proxy_env()}。",
156
- ]
157
- if context["ca_certs"] == 0:
158
- lines.append(
159
- "1. 已加载 0 张证书 → 连随包 CA 都没读到,安装包可能不完整:"
160
- "重装插件;或 `pip install certifi` 后重试。"
161
- )
162
- else:
163
- lines.append(
164
- "1. 信任库里没有能验证该站点的根证书:`pip install --upgrade certifi`,"
165
- "或重装插件取回最新内置 cacert.pem。"
166
- )
167
- lines += [
168
- "2. 代理若做 HTTPS 解密(Clash / Surge / 企业网关),把 classroom.zju.edu.cn 设为直连,"
169
- "或设置 `NO_PROXY=classroom.zju.edu.cn`。",
170
- "3. 系统时间偏差过大会直接导致握手失败,核对一下系统时间。",
171
- ]
172
- return "\n".join(lines)
173
-
174
- if isinstance(error, (socket.timeout, TimeoutError)):
175
- return f"原因:请求超时({_proxy_env()})。可稍后重试;若代理不可用,先关掉代理或设置 NO_PROXY。"
176
- if isinstance(error, ConnectionRefusedError) or "Connection refused" in text or "10061" in text:
177
- return f"原因:连接被拒绝,代理很可能没启动({_proxy_env()})。"
178
- if isinstance(error, ssl.SSLEOFError) or "EOF occurred in violation of protocol" in text:
179
- return f"原因:TLS 握手被中断({_proxy_env()}),通常是代理/网关拦截,建议重试或改直连。"
180
- return f"原因:{text}(代理环境:{_proxy_env()})。"
181
-
182
-
183
- _RETRY_ATTEMPTS = 3
184
- _RETRY_BASE_DELAY = 0.5
185
-
186
-
187
- def _is_transient(error: BaseException) -> bool:
188
- """Classify a transport failure as worth retrying."""
189
- if isinstance(error, ssl.SSLCertVerificationError):
190
- return False # 证书问题重试多少次都一样,立刻把诊断交出去
191
- if isinstance(error, urllib.error.HTTPError):
192
- return error.code >= 500 or error.code == 429
193
- if isinstance(error, urllib.error.URLError):
194
- return _is_transient(error.reason)
195
- return isinstance(
196
- error,
197
- (socket.timeout, TimeoutError, ConnectionError, ssl.SSLError, http.client.HTTPException),
198
- )
199
-
200
-
201
- def _fetch_bytes(
202
- url: str,
203
- headers: Dict[str, str],
204
- timeout: int,
205
- attempts: int = _RETRY_ATTEMPTS,
206
- max_bytes: Optional[int] = None,
207
- allow_cross_host_redirect: bool = False,
208
- ) -> bytes:
209
- """GET ``url`` and read the **whole** body, retrying transient failures.
210
-
211
- The retry has to cover ``read()``, not just the handshake. ``urllib`` builds the
212
- TLS connection lazily on first use and the body arrives afterwards, so a flaky
213
- proxy can走完 TCP 握手之后才在读取阶段丢包,表现为
214
- ``IncompleteRead(201704 bytes read)`` / ``EOF occurred in violation of protocol``。
215
- 只重试建连的话,这类失败仍然一次就穿透到用户面前。
216
-
217
- Certification failures are *not* retried: they need a fix, not a rerun.
218
- ``max_bytes`` refuses oversized bodies (slide screenshots) before they are
219
- materialised in memory.
220
- """
221
- total = max(1, attempts)
222
- last: Optional[BaseException] = None
223
- for index in range(total):
224
- try:
225
- if allow_cross_host_redirect:
226
- context = _open_request(
227
- url, headers, timeout, allow_cross_host_redirect=True
228
- )
229
- else:
230
- context = _open_request(url, headers, timeout)
231
- with context as response:
232
- if max_bytes is None:
233
- return response.read()
234
- data = response.read(max_bytes + 1)
235
- if len(data) > max_bytes:
236
- raise ZJUAPIError(
237
- f"响应超过 {max_bytes // (1024 * 1024)} MiB 上限,已停止读取"
238
- )
239
- return data
240
- except Exception as error: # noqa: BLE001 - re-raised below unless transient
241
- if not _is_transient(error):
242
- raise
243
- last = error
244
- if index + 1 < total:
245
- time.sleep(_RETRY_BASE_DELAY * (2**index) + random.uniform(0, 0.25))
246
- assert last is not None
247
- raise last
248
-
249
-
250
- class _SameHostRedirectHandler(urllib.request.HTTPRedirectHandler):
251
- """Follow redirects only on the classroom host.
252
-
253
- ``urllib`` re-sends request headers on a redirect, so a compromised or
254
- misconfigured endpoint that answers ``302`` to another origin would leak
255
- the ``Cookie`` header. Cross-origin redirects are refused instead.
256
- """
257
-
258
- def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: D401
259
- target = (urllib.parse.urlparse(newurl).hostname or "").lower()
260
- if target != BASE_HOST:
261
- raise urllib.error.HTTPError(
262
- req.full_url,
263
- code,
264
- f"拒绝跨域重定向到 {target or '(未知主机)'}(保护登录 Cookie)",
265
- headers,
266
- fp,
267
- )
268
- return super().redirect_request(req, fp, code, msg, headers, newurl)
269
-
270
-
271
- class _StripAuthOnCrossHostRedirectHandler(urllib.request.HTTPRedirectHandler):
272
- """Allow slide-CDN redirects, but never carry credentials across origins.
273
-
274
- Slide screenshots are static files and may redirect to a media host. The
275
- classroom API keeps the stricter same-host rule; this handler is only used
276
- for image downloads, and it drops ``Cookie`` / ``Authorization`` whenever
277
- the redirect changes the host.
278
- """
279
-
280
- def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: D401
281
- new_request = super().redirect_request(req, fp, code, msg, headers, newurl)
282
- if new_request is None:
283
- return None
284
- old_host = (urllib.parse.urlparse(req.full_url).hostname or "").lower()
285
- new_host = (urllib.parse.urlparse(newurl).hostname or "").lower()
286
- if old_host != new_host:
287
- new_request.remove_header("Cookie")
288
- new_request.remove_header("Authorization")
289
- return new_request
290
-
291
-
292
- def _open_request(
293
- url: str,
294
- headers: Dict[str, str],
295
- timeout: int,
296
- allow_cross_host_redirect: bool = False,
297
- ):
298
- """Open ``url`` with certificate verification and a redirect policy."""
299
- redirect_handler = (
300
- _StripAuthOnCrossHostRedirectHandler()
301
- if allow_cross_host_redirect
302
- else _SameHostRedirectHandler()
303
- )
304
- opener = urllib.request.build_opener(
305
- urllib.request.HTTPSHandler(context=get_ssl_context()),
306
- redirect_handler,
307
- )
308
- request = urllib.request.Request(url, headers=headers)
309
- return opener.open(request, timeout=timeout)
310
-
311
-
312
- class ZJUAPIError(Exception):
313
- """Raised when an API call to ZJU Classroom fails."""
314
- pass
315
-
316
-
317
- def parse_lecture_url(url_or_sub_id: str) -> Dict[str, str]:
318
- """Extract course_id, sub_id, and tenant_code from a classroom URL or sub_id.
319
-
320
- Accepts:
321
- - Full livingroom URL: https://classroom.zju.edu.cn/livingroom?course_id=123&sub_id=456&tenant_code=112
322
- - Short query string: ?sub_id=456
323
- - Pure sub_id integer string: "456"
324
- """
325
- url_or_sub_id = url_or_sub_id.strip()
326
- if not url_or_sub_id:
327
- raise ZJUAPIError("URL 或 sub_id 不能为空")
328
-
329
- # If it's a numeric string, treat directly as sub_id
330
- if url_or_sub_id.isdigit():
331
- return {
332
- "course_id": "",
333
- "sub_id": url_or_sub_id,
334
- "tenant_code": "112",
335
- }
336
-
337
- try:
338
- parsed = urllib.parse.urlparse(url_or_sub_id)
339
- query = urllib.parse.parse_qs(parsed.query)
340
- except Exception as e:
341
- raise ZJUAPIError(f"URL 格式解析失败: {e}")
342
-
343
- sub_id = query.get("sub_id", [None])[0]
344
- if not sub_id:
345
- # Check path segments just in case
346
- parts = [p for p in parsed.path.split("/") if p]
347
- for idx, part in enumerate(parts):
348
- if part in ("sub_id", "record", "livingroom") and idx + 1 < len(parts) and parts[idx + 1].isdigit():
349
- sub_id = parts[idx + 1]
350
- break
351
-
352
- if not sub_id:
353
- raise ZJUAPIError("无法从 URL 中识别 sub_id 参数,请确认输入包含有效 sub_id")
354
-
355
- return {
356
- "course_id": query.get("course_id", [""])[0],
357
- "sub_id": str(sub_id),
358
- "tenant_code": query.get("tenant_code", ["112"])[0],
359
- }
360
-
361
-
362
- def fetch_transcript(
363
- sub_id: str,
364
- tenant_code: str = "112",
365
- timeout: int = 60
366
- ) -> List[Dict[str, Any]]:
367
- """Fetch speech-to-text transcript segments from public ZJU classroom API.
368
-
369
- NOTE: This endpoint is completely PUBLIC and requires no login or cookies.
370
- Returns:
371
- List of dicts: [{"begin_sec": int, "text": str}]
372
- """
373
- url = (
374
- f"{BASE_URL}/courseapi/v3/web-socket/search-trans-result"
375
- f"?sub_id={sub_id}&tenant_code={tenant_code}"
376
- )
377
- req_headers = {"User-Agent": USER_AGENT}
378
- try:
379
- data = json.loads(_fetch_bytes(url, req_headers, timeout).decode("utf-8"))
380
- except urllib.error.HTTPError as e:
381
- raise ZJUAPIError(f"字幕接口返回 HTTP {e.code}(已重试 {_RETRY_ATTEMPTS} 次)") from e
382
- except Exception as e:
383
- raise ZJUAPIError(
384
- f"请求字幕接口失败(已重试 {_RETRY_ATTEMPTS} 次)。\n" + describe_network_error(e)
385
- ) from e
386
-
387
- code = data.get("code")
388
- if code != 0:
389
- msg = data.get("msg") or f"未知错误 (code={code})"
390
- raise ZJUAPIError(f"字幕接口返回非零状态码: {msg}")
391
-
392
- items = data.get("list") or []
393
- if not items:
394
- raise ZJUAPIError("字幕数据列表为空,可能课程刚结束尚未生成字幕或该课程未开启录制转写")
395
-
396
- raw_segments = items[0].get("all_content") or []
397
- segments: List[Dict[str, Any]] = []
398
- for item in raw_segments:
399
- text = (item.get("Text") or "").strip()
400
- if text:
401
- sec = int(item.get("BeginSec", 0))
402
- segments.append({"begin_sec": sec, "text": text})
403
-
404
- segments.sort(key=lambda x: x["begin_sec"])
405
- if not segments:
406
- raise ZJUAPIError("字幕内容经清洗后为空")
407
-
408
- return segments
409
-
410
-
411
- def _record(diagnostics: Optional[List[str]], message: str) -> None:
412
- """Collect a degradation reason for the caller to surface (never raises)."""
413
- if diagnostics is not None:
414
- diagnostics.append(message)
415
-
416
-
417
- _CLASSROOM_TOKEN_RE = re.compile(
418
- r'\{i:\d+;s:\d+:"_token";i:\d+;s:\d+:"([^"]+)";\}'
419
- )
420
-
421
-
422
- def is_zju_host(host: Optional[str]) -> bool:
423
- """True for ``zju.edu.cn`` and its subdomains (never lookalikes)."""
424
- value = (host or "").strip().lower().strip(".")
425
- return value == "zju.edu.cn" or value.endswith(".zju.edu.cn")
426
-
427
-
428
- def secure_zju_url(url: str) -> str:
429
- """Upgrade ZJU ``http://`` URLs to HTTPS; leave other URLs untouched.
430
-
431
- The classroom SSO cookie has no ``Secure`` flag, so downloading a
432
- screenshot over plain HTTP would send the login credential unencrypted.
433
- """
434
- value = (url or "").strip()
435
- if value.startswith("//"):
436
- value = "https:" + value
437
- parsed = urllib.parse.urlparse(value)
438
- if parsed.scheme.lower() == "http" and is_zju_host(parsed.hostname):
439
- return "https" + value[4:]
440
- return value
441
-
442
-
443
- def extract_classroom_token(cookie_header: str) -> Optional[str]:
444
- """Extract the classroom Bearer token from a Cookie header.
445
-
446
- The token is not a cookie of its own: the classroom session cookie stores
447
- a percent-encoded PHP-serialized payload and ``_token`` is a field inside
448
- it. Plain ``_token=...`` is accepted as a fallback for hand-written
449
- cookie files. Returns ``None`` when no usable token is present.
450
- """
451
- if not cookie_header:
452
- return None
453
- decoded = urllib.parse.unquote(cookie_header)
454
- match = _CLASSROOM_TOKEN_RE.search(decoded)
455
- token = match.group(1) if match else ""
456
- if not token:
457
- for part in decoded.split(";"):
458
- name, separator, value = part.partition("=")
459
- if separator and name.strip() == "_token":
460
- token = value.strip()
461
- break
462
- token = token.strip()
463
- if not token or len(token) > 4096:
464
- return None
465
- if any(ord(char) < 0x21 or ord(char) > 0x7E for char in token):
466
- return None
467
- return token
468
-
469
-
470
- def _classroom_headers(
471
- cookie: str,
472
- token: Optional[str],
473
- sub_id: str,
474
- ) -> Dict[str, str]:
475
- """Headers shared by the authenticated classroom endpoints."""
476
- headers = {
477
- "User-Agent": USER_AGENT,
478
- "Cookie": cookie,
479
- "Referer": f"{BASE_URL}/livingroom?sub_id={sub_id}",
480
- }
481
- if token:
482
- headers["Authorization"] = f"Bearer {token}"
483
- return headers
484
-
485
-
486
- def _clean_text(value: Any) -> str:
487
- return value.strip() if isinstance(value, str) else ""
488
-
489
-
490
- def _first_not_none(*values: Any) -> Any:
491
- for value in values:
492
- if value is not None:
493
- return value
494
- return None
495
-
496
-
497
- def normalize_slide(item: Any, index: int) -> Dict[str, Any]:
498
- """Flatten one ``search-ppt`` row into a stable slide record.
499
-
500
- ``content`` is a JSON *string* in the real response
501
- (``{"pptimgurl": "http://..."}``), not note text. The old formatter
502
- rendered that string verbatim, so the model saw JSON instead of slides.
503
- """
504
- row = item if isinstance(item, dict) else {}
505
- content_raw = row.get("content")
506
- parsed: Dict[str, Any] = {}
507
- text = ""
508
-
509
- if isinstance(content_raw, dict):
510
- parsed = content_raw
511
- elif isinstance(content_raw, str):
512
- stripped = content_raw.strip()
513
- if stripped.startswith("{"):
514
- try:
515
- decoded = json.loads(stripped)
516
- except ValueError:
517
- decoded = None
518
- if isinstance(decoded, dict):
519
- parsed = decoded
520
- else:
521
- text = stripped
522
- else:
523
- text = stripped
524
-
525
- def pick(*keys: str) -> str:
526
- for source in (parsed, row):
527
- for key in keys:
528
- value = _clean_text(source.get(key))
529
- if value:
530
- return value
531
- return ""
532
-
533
- image_url = secure_zju_url(
534
- pick("pptimgurl", "ppt_img_url", "image_url", "imgurl")
535
- )
536
- text = text or pick("ocr_content", "ocr_text", "text", "ppttext", "ppt_text")
537
- slide: Dict[str, Any] = {
538
- "page": index,
539
- "image_url": image_url,
540
- "text": text,
541
- }
542
- time_point = _first_not_none(
543
- row.get("time"),
544
- row.get("time_point"),
545
- row.get("sec"),
546
- parsed.get("time"),
547
- parsed.get("time_point"),
548
- )
549
- if time_point is not None:
550
- slide["time"] = time_point
551
- if not image_url and not text:
552
- slide["raw"] = json.dumps(item, ensure_ascii=False)[:500]
553
- return slide
554
-
555
-
556
- def fetch_slides(
557
- sub_id: str,
558
- tenant_code: str = "112",
559
- cookie: Optional[str] = None,
560
- timeout: int = 30,
561
- diagnostics: Optional[List[str]] = None,
562
- course_id: str = "",
563
- ) -> Optional[List[Dict[str, Any]]]:
564
- """Fetch projected-slide screenshots from the classroom API.
565
-
566
- The endpoint returns **screenshots** (``content.pptimgurl``), not a text
567
- layer. Pagination is required because the API returns at most ~100 rows
568
- per page; it also sometimes ignores ``per_page`` and repeats the first
569
- page, so URLs are de-duplicated in order.
570
-
571
- Requires a login cookie that contains the classroom ``_token`` (found in
572
- the parent-domain ``.zju.edu.cn`` session cookie). ``diagnostics`` records
573
- one human-readable degradation reason on failure.
574
- """
575
- if not cookie:
576
- _record(diagnostics, "未提供登录 Cookie")
577
- return None
578
-
579
- try:
580
- cookie = sanitize_cookie_header(cookie)
581
- except ValueError as error:
582
- _record(diagnostics, f"Cookie 头未通过校验:{error}")
583
- return None
584
-
585
- token = extract_classroom_token(cookie)
586
- headers = _classroom_headers(cookie, token, sub_id)
587
- endpoint = f"{BASE_URL}/pptnote/v1/schedule/search-ppt"
588
-
589
- slides: List[Dict[str, Any]] = []
590
- seen: set = set()
591
- total = 0
592
- page = 1
593
- max_pages = 50
594
- while page <= max_pages:
595
- params = {
596
- "sub_id": sub_id,
597
- "tenant_code": tenant_code,
598
- "page": page,
599
- "per_page": 100,
600
- }
601
- if course_id:
602
- params["course_id"] = course_id
603
- url = f"{endpoint}?{urllib.parse.urlencode(params)}"
604
- try:
605
- data = json.loads(_fetch_bytes(url, headers, timeout).decode("utf-8"))
606
- except urllib.error.HTTPError as error:
607
- hint = ""
608
- if error.code in (401, 403):
609
- hint = ";登录态无效或 Cookie 缺少 _token,请重新登录智云课堂后重试"
610
- _record(diagnostics, f"PPT 接口返回 HTTP {error.code}{hint}")
611
- return slides or None
612
- except Exception as error: # noqa: BLE001 - degradation path, reason is recorded
613
- _record(diagnostics, "PPT 接口请求失败。" + describe_network_error(error))
614
- return slides or None
615
-
616
- if not isinstance(data, dict):
617
- _record(diagnostics, "PPT 接口返回了非对象 JSON,可能改版了")
618
- return slides or None
619
-
620
- code = data.get("code")
621
- if code != 0:
622
- message = data.get("msg") or f"未知错误 (code={code})"
623
- hint = (
624
- ""
625
- if token
626
- else ";Cookie 中未解析到 _token,请确认包含父域 .zju.edu.cn 的会话 Cookie"
627
- )
628
- _record(diagnostics, f"PPT 接口返回 code={code}: {message}{hint}")
629
- return slides or None
630
-
631
- items = data.get("list") or []
632
- try:
633
- page_total = int(data.get("total") or 0)
634
- except (TypeError, ValueError):
635
- page_total = 0
636
- if page_total:
637
- total = page_total
638
-
639
- added = 0
640
- for item in items:
641
- slide = normalize_slide(item, len(slides) + 1)
642
- key = (
643
- slide.get("image_url")
644
- or slide.get("text")
645
- or json.dumps(item, sort_keys=True, ensure_ascii=False)
646
- )
647
- if key in seen:
648
- continue
649
- seen.add(key)
650
- slides.append(slide)
651
- added += 1
652
-
653
- # The API may return the whole deck on page 1 and repeat it on page 2.
654
- if not items or added == 0:
655
- break
656
- if total and len(slides) >= total:
657
- break
658
- page += 1
659
-
660
- if not slides:
661
- if not course_id:
662
- _record(
663
- diagnostics,
664
- "PPT 列表为空;如果输入的是纯 sub_id,请补上 course_id"
665
- "(完整回放 URL 通常带有 course_id=...)后重试",
666
- )
667
- else:
668
- _record(diagnostics, "PPT 列表为空:老师可能没有使用智云投屏,或截图尚未生成")
669
- return None
670
-
671
- if total and len(slides) < total:
672
- _record(
673
- diagnostics,
674
- f"PPT 接口标记共 {total} 张,去重后取到 {len(slides)} 张(后续分页无新数据)",
675
- )
676
- if page > max_pages and (not total or len(slides) < total):
677
- _record(diagnostics, f"PPT 分页达到上限 {max_pages} 页,已停止")
678
- return slides
679
-
680
-
681
- def _find_mp4_in_json(obj: Any) -> Optional[str]:
682
- """Recursively search for first mp4 URL inside nested JSON response."""
683
- if isinstance(obj, str):
684
- if obj.startswith("http") and ".mp4" in obj.split("?")[0]:
685
- return obj
686
- return None
687
- if isinstance(obj, dict):
688
- for v in obj.values():
689
- found = _find_mp4_in_json(v)
690
- if found:
691
- return found
692
- elif isinstance(obj, list):
693
- for item in obj:
694
- found = _find_mp4_in_json(item)
695
- if found:
696
- return found
697
- return None
698
-
699
-
700
- def fetch_video_url(
701
- course_id: str,
702
- sub_id: str,
703
- tenant_code: str = "112",
704
- cookie: Optional[str] = None,
705
- timeout: int = 30,
706
- diagnostics: Optional[List[str]] = None,
707
- ) -> Optional[str]:
708
- """Fetch direct MP4 replay video URL from play template config.
709
-
710
- Requires user authentication cookie. Returns ``None`` on any failure, but
711
- appends the reason to ``diagnostics`` so the caller can tell "没登录" apart
712
- from "网络坏了".
713
- """
714
- if not cookie:
715
- _record(diagnostics, "未提供登录 Cookie")
716
- return None
717
-
718
- try:
719
- cookie = sanitize_cookie_header(cookie)
720
- except ValueError as error:
721
- _record(diagnostics, f"Cookie 头未通过校验:{error}")
722
- return None
723
-
724
- url = (
725
- f"{BASE_URL}/courseapi/v2/play-template/get-config"
726
- f"?course_id={course_id}&sub_id={sub_id}&tenant_code={tenant_code}"
727
- )
728
- headers = _classroom_headers(
729
- cookie,
730
- extract_classroom_token(cookie),
731
- sub_id,
732
- )
733
- try:
734
- data = json.loads(_fetch_bytes(url, headers, timeout).decode("utf-8"))
735
- found = _find_mp4_in_json(data)
736
- if not found:
737
- _record(diagnostics, "play-template 响应里没有找到 mp4 直链")
738
- return found
739
- except Exception as error: # noqa: BLE001 - degradation path, reason is recorded
740
- _record(diagnostics, "视频直链接口请求失败。" + describe_network_error(error))
741
- return None
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Client for Zhejiang University 智云课堂 (classroom.zju.edu.cn) APIs.
4
+ Pure Python standard library implementation with zero external dependencies.
5
+ """
6
+
7
+ import http.client
8
+ import json
9
+ import os
10
+ import random
11
+ import re
12
+ import socket
13
+ import ssl
14
+ import time
15
+ import urllib.error
16
+ import urllib.parse
17
+ import urllib.request
18
+ from typing import Any, Dict, List, Optional
19
+
20
+ from .security import sanitize_cookie_header
21
+
22
+ BASE_URL = "https://classroom.zju.edu.cn"
23
+ BASE_HOST = (urllib.parse.urlparse(BASE_URL).hostname or "classroom.zju.edu.cn").lower()
24
+ USER_AGENT = (
25
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
26
+ "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
27
+ )
28
+
29
+
30
+ _CA_SOURCE = "system"
31
+ _CA_PATH: Optional[str] = None
32
+
33
+
34
+ def _certifi_ca_path() -> Optional[str]:
35
+ """Location of certifi's bundle, when certifi is installed and readable."""
36
+ try:
37
+ import certifi # type: ignore
38
+
39
+ path = certifi.where()
40
+ except Exception: # noqa: BLE001 - a broken certifi must not crash the tool
41
+ return None
42
+ return path if path and os.path.isfile(path) else None
43
+
44
+
45
+ def _bundled_ca_path() -> Optional[str]:
46
+ """The CA bundle shipped inside this package (``zju_lecture/cacert.pem``).
47
+
48
+ dsh ships its own Python interpreter **without** certifi, and a plain
49
+ ``ssl.create_default_context()`` on an incomplete OS root store raises
50
+ ``CERTIFICATE_VERIFY_FAILED``. Carrying our own bundle means the common case
51
+ (dsh on a fresh machine) stops depending on what the user happened to pip
52
+ install.
53
+ """
54
+ path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cacert.pem")
55
+ return path if os.path.isfile(path) else None
56
+
57
+
58
+ def _context_from_cafile(path: str) -> Optional[ssl.SSLContext]:
59
+ """Build a verifying context from ``path``; ``None`` when it is unusable."""
60
+ try:
61
+ return ssl.create_default_context(cafile=path)
62
+ except (OSError, ssl.SSLError):
63
+ return None
64
+
65
+
66
+ def create_ssl_context() -> ssl.SSLContext:
67
+ """Create the TLS context used for every request.
68
+
69
+ Certificate verification is **never** disabled. The login cookie is sent
70
+ over this connection, so silently downgrading to an unverified context
71
+ (as an earlier version did when the local root store was incomplete) would
72
+ turn a missing CA bundle into a cookie-exfiltration path.
73
+
74
+ Trust store order: ``certifi``(跟得上 CA 轮换)→ 随包 ``cacert.pem``
75
+ (dsh 自带 Python 没有 certifi 时的兜底)→ 系统根证书。三档都失败才会
76
+ 在握手上报错,且错误信息里会写清用的是哪一档。
77
+ """
78
+ global _CA_SOURCE, _CA_PATH
79
+
80
+ for source, resolver in (("certifi", _certifi_ca_path), ("bundled", _bundled_ca_path)):
81
+ path = resolver()
82
+ if not path:
83
+ continue
84
+ context = _context_from_cafile(path)
85
+ if context is not None:
86
+ _CA_SOURCE, _CA_PATH = source, path
87
+ return context
88
+ _CA_SOURCE, _CA_PATH = "system", None
89
+ return ssl.create_default_context()
90
+
91
+
92
+ _SSL_CONTEXT: Optional[ssl.SSLContext] = None
93
+
94
+
95
+ def get_ssl_context() -> ssl.SSLContext:
96
+ """Return the shared SSL context, building it on first use."""
97
+ global _SSL_CONTEXT
98
+ if _SSL_CONTEXT is None:
99
+ _SSL_CONTEXT = create_ssl_context()
100
+ return _SSL_CONTEXT
101
+
102
+
103
+ def ssl_context_health() -> Dict[str, Any]:
104
+ """Report the trust store actually in use (for actionable error messages)."""
105
+ try:
106
+ ca_count = len(get_ssl_context().get_ca_certs())
107
+ except Exception: # noqa: BLE001 - diagnostics must never mask the real error
108
+ ca_count = -1
109
+ return {"source": _CA_SOURCE, "path": _CA_PATH, "ca_certs": ca_count}
110
+
111
+
112
+ def _proxy_env() -> str:
113
+ """Describe the proxy environment, naming the variables to inspect.
114
+
115
+ "未设置" on its own does not tell the user which variable to look at, so the
116
+ unset case spells the names out. Returns a phrase without brackets: the
117
+ callers already wrap it in ().
118
+ """
119
+ found = []
120
+ for key in ("HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy"):
121
+ value = os.environ.get(key)
122
+ if value:
123
+ found.append(f"{key}={value}")
124
+ if found:
125
+ return ",".join(found)
126
+ return "HTTPS_PROXY / HTTP_PROXY 均未设置"
127
+
128
+
129
+ def describe_network_error(error: BaseException) -> str:
130
+ """Turn a transport exception into ``原因 + 下一步``.
131
+
132
+ The tool used to surface the raw ``<urlopen error ...>`` text, which made an
133
+ incomplete CA store look like "the plugin's request is broken". 证书校验失败、
134
+ 代理拦截、超时、连接被拒这四类占了网络失败的大头,各自给出可执行的下一步。
135
+ """
136
+ text = str(error)
137
+ # urllib 把真实原因包一层 URLError(URLError(reason=SSLCertVerificationError(...))),
138
+ # 不拆包的话「证书校验失败」这条分支永远命中不了。
139
+ inner = getattr(error, "reason", None)
140
+ if isinstance(error, urllib.error.URLError) and isinstance(inner, BaseException):
141
+ text = f"{error} {inner}"
142
+ error = inner
143
+ context = ssl_context_health()
144
+ store = {
145
+ "certifi": "certifi",
146
+ "bundled": "插件内置 cacert.pem",
147
+ "system": "系统根证书",
148
+ }.get(context["source"], "系统根证书")
149
+ if context["path"]:
150
+ store = f"{store} ({context['path']})"
151
+
152
+ if isinstance(error, ssl.SSLCertVerificationError) or "CERTIFICATE_VERIFY_FAILED" in text:
153
+ lines = [
154
+ "原因:TLS 证书校验不通过(接口本身没挂,不要用关闭校验的方式绕过——登录 Cookie 走这条连接)。",
155
+ f"信任库:{store},已加载 {context['ca_certs']} 张 CA 证书;代理环境:{_proxy_env()}。",
156
+ ]
157
+ if context["ca_certs"] == 0:
158
+ lines.append(
159
+ "1. 已加载 0 张证书 → 连随包 CA 都没读到,安装包可能不完整:"
160
+ "重装插件;或 `pip install certifi` 后重试。"
161
+ )
162
+ else:
163
+ lines.append(
164
+ "1. 信任库里没有能验证该站点的根证书:`pip install --upgrade certifi`,"
165
+ "或重装插件取回最新内置 cacert.pem。"
166
+ )
167
+ lines += [
168
+ "2. 代理若做 HTTPS 解密(Clash / Surge / 企业网关),把 classroom.zju.edu.cn 设为直连,"
169
+ "或设置 `NO_PROXY=classroom.zju.edu.cn`。",
170
+ "3. 系统时间偏差过大会直接导致握手失败,核对一下系统时间。",
171
+ ]
172
+ return "\n".join(lines)
173
+
174
+ if isinstance(error, (socket.timeout, TimeoutError)):
175
+ return f"原因:请求超时({_proxy_env()})。可稍后重试;若代理不可用,先关掉代理或设置 NO_PROXY。"
176
+ if isinstance(error, ConnectionRefusedError) or "Connection refused" in text or "10061" in text:
177
+ return f"原因:连接被拒绝,代理很可能没启动({_proxy_env()})。"
178
+ if isinstance(error, ssl.SSLEOFError) or "EOF occurred in violation of protocol" in text:
179
+ return f"原因:TLS 握手被中断({_proxy_env()}),通常是代理/网关拦截,建议重试或改直连。"
180
+ return f"原因:{text}(代理环境:{_proxy_env()})。"
181
+
182
+
183
+ _RETRY_ATTEMPTS = 3
184
+ _RETRY_BASE_DELAY = 0.5
185
+
186
+
187
+ def _is_transient(error: BaseException) -> bool:
188
+ """Classify a transport failure as worth retrying."""
189
+ if isinstance(error, ssl.SSLCertVerificationError):
190
+ return False # 证书问题重试多少次都一样,立刻把诊断交出去
191
+ if isinstance(error, urllib.error.HTTPError):
192
+ return error.code >= 500 or error.code == 429
193
+ if isinstance(error, urllib.error.URLError):
194
+ return _is_transient(error.reason)
195
+ return isinstance(
196
+ error,
197
+ (socket.timeout, TimeoutError, ConnectionError, ssl.SSLError, http.client.HTTPException),
198
+ )
199
+
200
+
201
+ def _fetch_bytes(
202
+ url: str,
203
+ headers: Dict[str, str],
204
+ timeout: int,
205
+ attempts: int = _RETRY_ATTEMPTS,
206
+ max_bytes: Optional[int] = None,
207
+ allow_cross_host_redirect: bool = False,
208
+ ) -> bytes:
209
+ """GET ``url`` and read the **whole** body, retrying transient failures.
210
+
211
+ The retry has to cover ``read()``, not just the handshake. ``urllib`` builds the
212
+ TLS connection lazily on first use and the body arrives afterwards, so a flaky
213
+ proxy can走完 TCP 握手之后才在读取阶段丢包,表现为
214
+ ``IncompleteRead(201704 bytes read)`` / ``EOF occurred in violation of protocol``。
215
+ 只重试建连的话,这类失败仍然一次就穿透到用户面前。
216
+
217
+ Certification failures are *not* retried: they need a fix, not a rerun.
218
+ ``max_bytes`` refuses oversized bodies (slide screenshots) before they are
219
+ materialised in memory.
220
+ """
221
+ total = max(1, attempts)
222
+ last: Optional[BaseException] = None
223
+ for index in range(total):
224
+ try:
225
+ if allow_cross_host_redirect:
226
+ context = _open_request(
227
+ url, headers, timeout, allow_cross_host_redirect=True
228
+ )
229
+ else:
230
+ context = _open_request(url, headers, timeout)
231
+ with context as response:
232
+ if max_bytes is None:
233
+ return response.read()
234
+ data = response.read(max_bytes + 1)
235
+ if len(data) > max_bytes:
236
+ raise ZJUAPIError(
237
+ f"响应超过 {max_bytes // (1024 * 1024)} MiB 上限,已停止读取"
238
+ )
239
+ return data
240
+ except Exception as error: # noqa: BLE001 - re-raised below unless transient
241
+ if not _is_transient(error):
242
+ raise
243
+ last = error
244
+ if index + 1 < total:
245
+ time.sleep(_RETRY_BASE_DELAY * (2**index) + random.uniform(0, 0.25))
246
+ assert last is not None
247
+ raise last
248
+
249
+
250
+ class _SameHostRedirectHandler(urllib.request.HTTPRedirectHandler):
251
+ """Follow redirects only on the classroom host.
252
+
253
+ ``urllib`` re-sends request headers on a redirect, so a compromised or
254
+ misconfigured endpoint that answers ``302`` to another origin would leak
255
+ the ``Cookie`` header. Cross-origin redirects are refused instead.
256
+ """
257
+
258
+ def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: D401
259
+ target = (urllib.parse.urlparse(newurl).hostname or "").lower()
260
+ if target != BASE_HOST:
261
+ raise urllib.error.HTTPError(
262
+ req.full_url,
263
+ code,
264
+ f"拒绝跨域重定向到 {target or '(未知主机)'}(保护登录 Cookie)",
265
+ headers,
266
+ fp,
267
+ )
268
+ return super().redirect_request(req, fp, code, msg, headers, newurl)
269
+
270
+
271
+ class _StripAuthOnCrossHostRedirectHandler(urllib.request.HTTPRedirectHandler):
272
+ """Allow slide-CDN redirects, but never carry credentials across origins.
273
+
274
+ Slide screenshots are static files and may redirect to a media host. The
275
+ classroom API keeps the stricter same-host rule; this handler is only used
276
+ for image downloads, and it drops ``Cookie`` / ``Authorization`` whenever
277
+ the redirect changes the host.
278
+ """
279
+
280
+ def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: D401
281
+ new_request = super().redirect_request(req, fp, code, msg, headers, newurl)
282
+ if new_request is None:
283
+ return None
284
+ old_host = (urllib.parse.urlparse(req.full_url).hostname or "").lower()
285
+ new_host = (urllib.parse.urlparse(newurl).hostname or "").lower()
286
+ if old_host != new_host:
287
+ new_request.remove_header("Cookie")
288
+ new_request.remove_header("Authorization")
289
+ return new_request
290
+
291
+
292
+ def _open_request(
293
+ url: str,
294
+ headers: Dict[str, str],
295
+ timeout: int,
296
+ allow_cross_host_redirect: bool = False,
297
+ ):
298
+ """Open ``url`` with certificate verification and a redirect policy."""
299
+ redirect_handler = (
300
+ _StripAuthOnCrossHostRedirectHandler()
301
+ if allow_cross_host_redirect
302
+ else _SameHostRedirectHandler()
303
+ )
304
+ opener = urllib.request.build_opener(
305
+ urllib.request.HTTPSHandler(context=get_ssl_context()),
306
+ redirect_handler,
307
+ )
308
+ request = urllib.request.Request(url, headers=headers)
309
+ return opener.open(request, timeout=timeout)
310
+
311
+
312
+ class ZJUAPIError(Exception):
313
+ """Raised when an API call to ZJU Classroom fails."""
314
+ pass
315
+
316
+
317
+ def parse_lecture_url(url_or_sub_id: str) -> Dict[str, str]:
318
+ """Extract course_id, sub_id, and tenant_code from a classroom URL or sub_id.
319
+
320
+ Accepts:
321
+ - Full livingroom URL: https://classroom.zju.edu.cn/livingroom?course_id=123&sub_id=456&tenant_code=112
322
+ - Short query string: ?sub_id=456
323
+ - Pure sub_id integer string: "456"
324
+ """
325
+ url_or_sub_id = url_or_sub_id.strip()
326
+ if not url_or_sub_id:
327
+ raise ZJUAPIError("URL 或 sub_id 不能为空")
328
+
329
+ # If it's a numeric string, treat directly as sub_id
330
+ if url_or_sub_id.isdigit():
331
+ return {
332
+ "course_id": "",
333
+ "sub_id": url_or_sub_id,
334
+ "tenant_code": "112",
335
+ }
336
+
337
+ try:
338
+ parsed = urllib.parse.urlparse(url_or_sub_id)
339
+ query = urllib.parse.parse_qs(parsed.query)
340
+ except Exception as e:
341
+ raise ZJUAPIError(f"URL 格式解析失败: {e}")
342
+
343
+ sub_id = query.get("sub_id", [None])[0]
344
+ if not sub_id:
345
+ # Check path segments just in case
346
+ parts = [p for p in parsed.path.split("/") if p]
347
+ for idx, part in enumerate(parts):
348
+ if part in ("sub_id", "record", "livingroom") and idx + 1 < len(parts) and parts[idx + 1].isdigit():
349
+ sub_id = parts[idx + 1]
350
+ break
351
+
352
+ if not sub_id:
353
+ raise ZJUAPIError("无法从 URL 中识别 sub_id 参数,请确认输入包含有效 sub_id")
354
+
355
+ return {
356
+ "course_id": query.get("course_id", [""])[0],
357
+ "sub_id": str(sub_id),
358
+ "tenant_code": query.get("tenant_code", ["112"])[0],
359
+ }
360
+
361
+
362
+ def fetch_transcript(
363
+ sub_id: str,
364
+ tenant_code: str = "112",
365
+ timeout: int = 60
366
+ ) -> List[Dict[str, Any]]:
367
+ """Fetch speech-to-text transcript segments from public ZJU classroom API.
368
+
369
+ NOTE: This endpoint is completely PUBLIC and requires no login or cookies.
370
+ Returns:
371
+ List of dicts: [{"begin_sec": int, "text": str}]
372
+ """
373
+ url = (
374
+ f"{BASE_URL}/courseapi/v3/web-socket/search-trans-result"
375
+ f"?sub_id={sub_id}&tenant_code={tenant_code}"
376
+ )
377
+ req_headers = {"User-Agent": USER_AGENT}
378
+ try:
379
+ data = json.loads(_fetch_bytes(url, req_headers, timeout).decode("utf-8"))
380
+ except urllib.error.HTTPError as e:
381
+ raise ZJUAPIError(f"字幕接口返回 HTTP {e.code}(已重试 {_RETRY_ATTEMPTS} 次)") from e
382
+ except Exception as e:
383
+ raise ZJUAPIError(
384
+ f"请求字幕接口失败(已重试 {_RETRY_ATTEMPTS} 次)。\n" + describe_network_error(e)
385
+ ) from e
386
+
387
+ code = data.get("code")
388
+ if code != 0:
389
+ msg = data.get("msg") or f"未知错误 (code={code})"
390
+ raise ZJUAPIError(f"字幕接口返回非零状态码: {msg}")
391
+
392
+ items = data.get("list") or []
393
+ if not items:
394
+ raise ZJUAPIError("字幕数据列表为空,可能课程刚结束尚未生成字幕或该课程未开启录制转写")
395
+
396
+ raw_segments = items[0].get("all_content") or []
397
+ segments: List[Dict[str, Any]] = []
398
+ for item in raw_segments:
399
+ text = (item.get("Text") or "").strip()
400
+ if text:
401
+ sec = int(item.get("BeginSec", 0))
402
+ segments.append({"begin_sec": sec, "text": text})
403
+
404
+ segments.sort(key=lambda x: x["begin_sec"])
405
+ if not segments:
406
+ raise ZJUAPIError("字幕内容经清洗后为空")
407
+
408
+ return segments
409
+
410
+
411
+ def _record(diagnostics: Optional[List[str]], message: str) -> None:
412
+ """Collect a degradation reason for the caller to surface (never raises)."""
413
+ if diagnostics is not None:
414
+ diagnostics.append(message)
415
+
416
+
417
+ _CLASSROOM_TOKEN_RE = re.compile(
418
+ r'\{i:\d+;s:\d+:"_token";i:\d+;s:\d+:"([^"]+)";\}'
419
+ )
420
+
421
+
422
+ def is_zju_host(host: Optional[str]) -> bool:
423
+ """True for ``zju.edu.cn`` and its subdomains (never lookalikes)."""
424
+ value = (host or "").strip().lower().strip(".")
425
+ return value == "zju.edu.cn" or value.endswith(".zju.edu.cn")
426
+
427
+
428
+ def secure_zju_url(url: str) -> str:
429
+ """Upgrade ZJU ``http://`` URLs to HTTPS; leave other URLs untouched.
430
+
431
+ The classroom SSO cookie has no ``Secure`` flag, so downloading a
432
+ screenshot over plain HTTP would send the login credential unencrypted.
433
+ """
434
+ value = (url or "").strip()
435
+ if value.startswith("//"):
436
+ value = "https:" + value
437
+ parsed = urllib.parse.urlparse(value)
438
+ if parsed.scheme.lower() == "http" and is_zju_host(parsed.hostname):
439
+ return "https" + value[4:]
440
+ return value
441
+
442
+
443
+ def extract_classroom_token(cookie_header: str) -> Optional[str]:
444
+ """Extract the classroom Bearer token from a Cookie header.
445
+
446
+ The token is not a cookie of its own: the classroom session cookie stores
447
+ a percent-encoded PHP-serialized payload and ``_token`` is a field inside
448
+ it. Plain ``_token=...`` is accepted as a fallback for hand-written
449
+ cookie files. Returns ``None`` when no usable token is present.
450
+ """
451
+ if not cookie_header:
452
+ return None
453
+ decoded = urllib.parse.unquote(cookie_header)
454
+ match = _CLASSROOM_TOKEN_RE.search(decoded)
455
+ token = match.group(1) if match else ""
456
+ if not token:
457
+ for part in decoded.split(";"):
458
+ name, separator, value = part.partition("=")
459
+ if separator and name.strip() == "_token":
460
+ token = value.strip()
461
+ break
462
+ token = token.strip()
463
+ if not token or len(token) > 4096:
464
+ return None
465
+ if any(ord(char) < 0x21 or ord(char) > 0x7E for char in token):
466
+ return None
467
+ return token
468
+
469
+
470
+ def _classroom_headers(
471
+ cookie: str,
472
+ token: Optional[str],
473
+ sub_id: str,
474
+ ) -> Dict[str, str]:
475
+ """Headers shared by the authenticated classroom endpoints."""
476
+ headers = {
477
+ "User-Agent": USER_AGENT,
478
+ "Cookie": cookie,
479
+ "Referer": f"{BASE_URL}/livingroom?sub_id={sub_id}",
480
+ }
481
+ if token:
482
+ headers["Authorization"] = f"Bearer {token}"
483
+ return headers
484
+
485
+
486
+ def _clean_text(value: Any) -> str:
487
+ return value.strip() if isinstance(value, str) else ""
488
+
489
+
490
+ def _first_not_none(*values: Any) -> Any:
491
+ for value in values:
492
+ if value is not None:
493
+ return value
494
+ return None
495
+
496
+
497
+ def normalize_slide(item: Any, index: int) -> Dict[str, Any]:
498
+ """Flatten one ``search-ppt`` row into a stable slide record.
499
+
500
+ ``content`` is a JSON *string* in the real response
501
+ (``{"pptimgurl": "http://..."}``), not note text. The old formatter
502
+ rendered that string verbatim, so the model saw JSON instead of slides.
503
+ """
504
+ row = item if isinstance(item, dict) else {}
505
+ content_raw = row.get("content")
506
+ parsed: Dict[str, Any] = {}
507
+ text = ""
508
+
509
+ if isinstance(content_raw, dict):
510
+ parsed = content_raw
511
+ elif isinstance(content_raw, str):
512
+ stripped = content_raw.strip()
513
+ if stripped.startswith("{"):
514
+ try:
515
+ decoded = json.loads(stripped)
516
+ except ValueError:
517
+ decoded = None
518
+ if isinstance(decoded, dict):
519
+ parsed = decoded
520
+ else:
521
+ text = stripped
522
+ else:
523
+ text = stripped
524
+
525
+ def pick(*keys: str) -> str:
526
+ for source in (parsed, row):
527
+ for key in keys:
528
+ value = _clean_text(source.get(key))
529
+ if value:
530
+ return value
531
+ return ""
532
+
533
+ image_url = secure_zju_url(
534
+ pick("pptimgurl", "ppt_img_url", "image_url", "imgurl")
535
+ )
536
+ text = text or pick("ocr_content", "ocr_text", "text", "ppttext", "ppt_text")
537
+ slide: Dict[str, Any] = {
538
+ "page": index,
539
+ "image_url": image_url,
540
+ "text": text,
541
+ }
542
+ time_point = _first_not_none(
543
+ row.get("time"),
544
+ row.get("time_point"),
545
+ row.get("sec"),
546
+ parsed.get("time"),
547
+ parsed.get("time_point"),
548
+ )
549
+ if time_point is not None:
550
+ slide["time"] = time_point
551
+ if not image_url and not text:
552
+ slide["raw"] = json.dumps(item, ensure_ascii=False)[:500]
553
+ return slide
554
+
555
+
556
+ def fetch_slides(
557
+ sub_id: str,
558
+ tenant_code: str = "112",
559
+ cookie: Optional[str] = None,
560
+ timeout: int = 30,
561
+ diagnostics: Optional[List[str]] = None,
562
+ course_id: str = "",
563
+ ) -> Optional[List[Dict[str, Any]]]:
564
+ """Fetch projected-slide screenshots from the classroom API.
565
+
566
+ The endpoint returns **screenshots** (``content.pptimgurl``), not a text
567
+ layer. Pagination is required because the API returns at most ~100 rows
568
+ per page; it also sometimes ignores ``per_page`` and repeats the first
569
+ page, so URLs are de-duplicated in order.
570
+
571
+ Requires a login cookie that contains the classroom ``_token`` (found in
572
+ the parent-domain ``.zju.edu.cn`` session cookie). ``diagnostics`` records
573
+ one human-readable degradation reason on failure.
574
+ """
575
+ if not cookie:
576
+ _record(diagnostics, "未提供登录 Cookie")
577
+ return None
578
+
579
+ try:
580
+ cookie = sanitize_cookie_header(cookie)
581
+ except ValueError as error:
582
+ _record(diagnostics, f"Cookie 头未通过校验:{error}")
583
+ return None
584
+
585
+ token = extract_classroom_token(cookie)
586
+ headers = _classroom_headers(cookie, token, sub_id)
587
+ endpoint = f"{BASE_URL}/pptnote/v1/schedule/search-ppt"
588
+
589
+ slides: List[Dict[str, Any]] = []
590
+ seen: set = set()
591
+ total = 0
592
+ page = 1
593
+ max_pages = 50
594
+ while page <= max_pages:
595
+ params = {
596
+ "sub_id": sub_id,
597
+ "tenant_code": tenant_code,
598
+ "page": page,
599
+ "per_page": 100,
600
+ }
601
+ if course_id:
602
+ params["course_id"] = course_id
603
+ url = f"{endpoint}?{urllib.parse.urlencode(params)}"
604
+ try:
605
+ data = json.loads(_fetch_bytes(url, headers, timeout).decode("utf-8"))
606
+ except urllib.error.HTTPError as error:
607
+ hint = ""
608
+ if error.code in (401, 403):
609
+ hint = ";登录态无效或 Cookie 缺少 _token,请重新登录智云课堂后重试"
610
+ _record(diagnostics, f"PPT 接口返回 HTTP {error.code}{hint}")
611
+ return slides or None
612
+ except Exception as error: # noqa: BLE001 - degradation path, reason is recorded
613
+ _record(diagnostics, "PPT 接口请求失败。" + describe_network_error(error))
614
+ return slides or None
615
+
616
+ if not isinstance(data, dict):
617
+ _record(diagnostics, "PPT 接口返回了非对象 JSON,可能改版了")
618
+ return slides or None
619
+
620
+ code = data.get("code")
621
+ if code != 0:
622
+ message = data.get("msg") or f"未知错误 (code={code})"
623
+ hint = (
624
+ ""
625
+ if token
626
+ else ";Cookie 中未解析到 _token,请确认包含父域 .zju.edu.cn 的会话 Cookie"
627
+ )
628
+ _record(diagnostics, f"PPT 接口返回 code={code}: {message}{hint}")
629
+ return slides or None
630
+
631
+ items = data.get("list") or []
632
+ try:
633
+ page_total = int(data.get("total") or 0)
634
+ except (TypeError, ValueError):
635
+ page_total = 0
636
+ if page_total:
637
+ total = page_total
638
+
639
+ added = 0
640
+ for item in items:
641
+ slide = normalize_slide(item, len(slides) + 1)
642
+ key = (
643
+ slide.get("image_url")
644
+ or slide.get("text")
645
+ or json.dumps(item, sort_keys=True, ensure_ascii=False)
646
+ )
647
+ if key in seen:
648
+ continue
649
+ seen.add(key)
650
+ slides.append(slide)
651
+ added += 1
652
+
653
+ # The API may return the whole deck on page 1 and repeat it on page 2.
654
+ if not items or added == 0:
655
+ break
656
+ if total and len(slides) >= total:
657
+ break
658
+ page += 1
659
+
660
+ if not slides:
661
+ if not course_id:
662
+ _record(
663
+ diagnostics,
664
+ "PPT 列表为空;如果输入的是纯 sub_id,请补上 course_id"
665
+ "(完整回放 URL 通常带有 course_id=...)后重试",
666
+ )
667
+ else:
668
+ _record(diagnostics, "PPT 列表为空:老师可能没有使用智云投屏,或截图尚未生成")
669
+ return None
670
+
671
+ if total and len(slides) < total:
672
+ _record(
673
+ diagnostics,
674
+ f"PPT 接口标记共 {total} 张,去重后取到 {len(slides)} 张(后续分页无新数据)",
675
+ )
676
+ if page > max_pages and (not total or len(slides) < total):
677
+ _record(diagnostics, f"PPT 分页达到上限 {max_pages} 页,已停止")
678
+ return slides
679
+
680
+
681
+ def _find_mp4_in_json(obj: Any) -> Optional[str]:
682
+ """Recursively search for first mp4 URL inside nested JSON response."""
683
+ if isinstance(obj, str):
684
+ if obj.startswith("http") and ".mp4" in obj.split("?")[0]:
685
+ return obj
686
+ return None
687
+ if isinstance(obj, dict):
688
+ for v in obj.values():
689
+ found = _find_mp4_in_json(v)
690
+ if found:
691
+ return found
692
+ elif isinstance(obj, list):
693
+ for item in obj:
694
+ found = _find_mp4_in_json(item)
695
+ if found:
696
+ return found
697
+ return None
698
+
699
+
700
+ def fetch_video_url(
701
+ course_id: str,
702
+ sub_id: str,
703
+ tenant_code: str = "112",
704
+ cookie: Optional[str] = None,
705
+ timeout: int = 30,
706
+ diagnostics: Optional[List[str]] = None,
707
+ ) -> Optional[str]:
708
+ """Fetch direct MP4 replay video URL from play template config.
709
+
710
+ Requires user authentication cookie. Returns ``None`` on any failure, but
711
+ appends the reason to ``diagnostics`` so the caller can tell "没登录" apart
712
+ from "网络坏了".
713
+ """
714
+ if not cookie:
715
+ _record(diagnostics, "未提供登录 Cookie")
716
+ return None
717
+
718
+ try:
719
+ cookie = sanitize_cookie_header(cookie)
720
+ except ValueError as error:
721
+ _record(diagnostics, f"Cookie 头未通过校验:{error}")
722
+ return None
723
+
724
+ url = (
725
+ f"{BASE_URL}/courseapi/v2/play-template/get-config"
726
+ f"?course_id={course_id}&sub_id={sub_id}&tenant_code={tenant_code}"
727
+ )
728
+ headers = _classroom_headers(
729
+ cookie,
730
+ extract_classroom_token(cookie),
731
+ sub_id,
732
+ )
733
+ try:
734
+ data = json.loads(_fetch_bytes(url, headers, timeout).decode("utf-8"))
735
+ found = _find_mp4_in_json(data)
736
+ if not found:
737
+ _record(diagnostics, "play-template 响应里没有找到 mp4 直链")
738
+ return found
739
+ except Exception as error: # noqa: BLE001 - degradation path, reason is recorded
740
+ _record(diagnostics, "视频直链接口请求失败。" + describe_network_error(error))
741
+ return None