import json import re from pathlib import Path from urllib.parse import quote, urljoin from server.services.device import DeviceProfile from server.services.http import http from server.services.rapt import API_BASE CACHE_DIR = Path(__file__).resolve().parents[2] / "cache" / "playlists" def safe_name(text: str, fallback: str) -> str: cleaned = re.sub(r'[<>:"/\\|?*\x00-\x1f]', " ", text or "") cleaned = re.sub(r"\s+", " ", cleaned).strip().rstrip(". ") return (cleaned[:80] or fallback) def _items(data): if isinstance(data, list): return data, len(data) items = (data or {}).get("list") or [] return items, (data or {}).get("count") def _normalize(item: dict) -> dict | None: cid = item.get("cid") or item.get("id") if cid is None: return None idx = item.get("idx") or item.get("number") or 0 title = str(item.get("msg") or item.get("title") or f"EP.{idx}").strip() return { "cid": int(cid), "idx": int(idx) if str(idx).isdigit() else 0, "title": title, "src": str(item.get("src") or "").strip(), } def _request_playlist(token: str, device: DeviceProfile, vid: int) -> list[dict]: try: data = http.request_data("POST", API_BASE + "/app/video/playlist", token, device, { "vid": vid, "page": 1, "before": 1, }) items, total = _items(data) episodes = [row for row in (_normalize(item) for item in items if isinstance(item, dict)) if row] if episodes and (total is None or len(episodes) >= int(total)): return episodes except RuntimeError: episodes = [] collected = [] total = None for page in range(1, 41): data = http.request_data("POST", API_BASE + "/app/video/playlistv2", token, device, { "vid": vid, "page": page, "before": 1 if page == 1 else 0, }) items, page_total = _items(data) if page_total is not None: total = page_total if not items: break for item in items: if isinstance(item, dict): row = _normalize(item) if row: collected.append(row) if total is not None and len(collected) >= int(total): break return collected or episodes def cached_episode_src(vid: int, cid: int) -> str: for ep in _read_cache(vid): if int(ep.get("cid") or 0) == cid: return str(ep.get("src") or "").strip() return "" def _cache_path(vid: int) -> Path: return CACHE_DIR / f"{vid}.json" def _read_cache(vid: int) -> list[dict]: path = _cache_path(vid) if not path.is_file(): return [] try: data = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): return [] rows = data.get("episodes") if isinstance(data, dict) else None return [row for row in rows if isinstance(row, dict)] if isinstance(rows, list) else [] def _write_cache(vid: int, episodes: list[dict]) -> None: CACHE_DIR.mkdir(parents=True, exist_ok=True) payload = { "episodes": [ {"cid": ep["cid"], "idx": ep["idx"], "title": ep["title"], "src": ep.get("src") or ""} for ep in episodes ] } path = _cache_path(vid) temporary = path.with_suffix(".json.tmp") temporary.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8") temporary.replace(path) def _filled(episodes: list[dict]) -> int: return sum(1 for ep in episodes if ep.get("src")) def merge_episodes(cached: list[dict], fresh: list[dict]) -> tuple[list[dict], bool]: by_cid: dict[int, dict] = {} for source in (cached, fresh): for ep in source: cid = int(ep["cid"]) current = by_cid.get(cid) if current is None: by_cid[cid] = { "cid": cid, "idx": int(ep.get("idx") or 0), "title": ep.get("title") or f"EP.{ep.get('idx') or cid}", "src": ep.get("src") or "", } continue if ep.get("title"): current["title"] = ep["title"] if ep.get("idx"): current["idx"] = int(ep["idx"]) if ep.get("src"): current["src"] = ep["src"] merged = sorted(by_cid.values(), key=lambda ep: (ep["idx"], ep["cid"])) return merged, _filled(fresh) >= _filled(cached) and _filled(fresh) > 0 def load_episodes(token: str, device: DeviceProfile | None, vid: int) -> list[dict]: cached = _read_cache(vid) fresh = [] if token and device is not None: try: fresh = _request_playlist(token, device, vid) except RuntimeError: fresh = [] merged, save = merge_episodes(cached, fresh) if save: _write_cache(vid, merged) elif not cached and merged: _write_cache(vid, merged) return merged def audio_rendition_uris(text: str) -> list[str]: found = [] for line in text.splitlines(): stripped = line.strip() if "TYPE=AUDIO" not in stripped.upper() or "URI=" not in stripped: continue match = re.search(r'URI="([^"]*)"', stripped) if match and match.group(1): found.append(match.group(1)) return found def is_direct_media(url: str) -> bool: path = url.split("?", 1)[0].lower() return path.endswith((".mp4", ".m4v", ".webm", ".mkv")) def looks_like_segment(url: str) -> bool: path = url.split("?", 1)[0].lower() return path.endswith((".ts", ".m4s", ".m4v", ".mp4", ".aac", ".vtt")) def is_media_playlist(text: str) -> bool: first = next( (line.strip() for line in text.splitlines() if line.strip() and not line.startswith("#")), "", ) return bool(first) and looks_like_segment(first) def expand_variant(master_url: str, headers: dict | None = None) -> tuple[str, str, list[dict], str, list[dict]]: if is_direct_media(master_url): raise RuntimeError("这是整段视频,不是播放列表") master_text = http.read_text(master_url, headers=headers) variant_rel = next( (line.strip() for line in master_text.splitlines() if line.strip() and not line.startswith("#")), "", ) if not variant_rel: raise RuntimeError("播放列表没有视频地址") if looks_like_segment(variant_rel): variant_url = master_url media_text = master_text else: variant_url = urljoin(master_url, variant_rel) media_text = http.read_text(variant_url, headers=headers) localized, items = localize_media(media_text, variant_url) if not items: raise RuntimeError("播放列表没有分片") audio_text = "" audio_items: list[dict] = [] for rel in audio_rendition_uris(master_text): audio_url = urljoin(master_url, rel) fetched = http.read_text(audio_url, headers=headers) audio_text, audio_items = localize_media(fetched, audio_url, name_prefix="audio-") if audio_items: break return master_text, localized, items, audio_text, audio_items def guess_audio_playlist_urls(segment_url: str) -> list[str]: """由视频分片地址推测同一视频目录下的音频列表。""" if not segment_url.startswith(("http://", "https://")): return [] path, sep, query = segment_url.partition("?") parts = path.rstrip("/").split("/") if len(parts) < 3: return [] suffix = f"?{query}" if sep and query else "" root = "/".join(parts[:-2]) parent = "/".join(parts[:-1]) return [ f"{root}/audio/audio.m3u8{suffix}", f"{parent}/audio.m3u8{suffix}", ] def localize_media(text: str, base: str, name_prefix: str = "") -> tuple[str, list[dict]]: urls = _resource_urls(text, base) names: list[str] = [] items: list[dict] = [] used: set[str] = set() known: dict[str, str] = {} for index, url in enumerate(urls, start=1): name = known.get(url) if name is None: name = name_prefix + _resource_name(url, index, used) known[url] = name items.append({"name": name, "url": url}) names.append(name) return _apply_local_names(text, names), items def _resource_urls(text: str, base: str) -> list[str]: urls = [] for line in text.splitlines(): stripped = line.strip() if not stripped: continue if stripped.startswith("#"): urls.extend(urljoin(base, match) for match in re.findall(r'URI="([^"]*)"', stripped)) continue urls.append(urljoin(base, stripped)) return urls def _resource_name(url: str, index: int, used: set[str]) -> str: raw = Path(url.split("?", 1)[0].rstrip("/")).name raw = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", raw).strip(" .") or f"part-{index}.ts" candidate = raw sequence = index while candidate in used: suffix = Path(raw).suffix stem = Path(raw).stem candidate = f"{stem}-{sequence}{suffix}" sequence += 1 used.add(candidate) return candidate def _apply_local_names(text: str, names: list[str]) -> str: index = 0 def take() -> str: nonlocal index name = names[index] if index < len(names) else "" index += 1 return name lines = [] for line in text.splitlines(): stripped = line.strip() if not stripped: lines.append(line) continue if stripped.startswith("#"): lines.append(re.sub(r'URI="([^"]*)"', lambda _match: f'URI="{take()}"', line)) continue lines.append(take() or stripped) return "\n".join(lines) + "\n" def _playlist_local_files(playlist: Path) -> list[Path]: text = playlist.read_text(encoding="utf-8") base = playlist.parent found: list[Path] = [] for line in text.splitlines(): stripped = line.strip() if not stripped: continue if stripped.startswith("#"): for match in re.findall(r'URI="([^"]*)"', stripped): if match and not match.startswith(("http://", "https://")): found.append(base / match) continue if not stripped.startswith(("http://", "https://")): found.append(base / stripped) return found def _playlist_complete(playlist: Path) -> bool: if not playlist.is_file(): return False files = _playlist_local_files(playlist) if not files: return False return all(path.is_file() and path.stat().st_size > 0 for path in files) def _segment_urls(source: Path) -> list[str]: manifest = source / "segments.json" if not manifest.is_file(): return [] try: items = json.loads(manifest.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): return [] urls = [] if isinstance(items, list): for item in items: if isinstance(item, dict): url = str(item.get("url") or "") if url.startswith(("http://", "https://")): urls.append(url) return urls def _cdn_master_base(segment_url: str) -> tuple[str, str]: path, sep, query = segment_url.partition("?") parts = path.rstrip("/").split("/") if len(parts) < 3: return "", "" return "/".join(parts[:-2]) + "/", query if sep else "" def _master_audio_urls(source: Path) -> list[str]: master_file = source / "master.url" if not master_file.is_file(): return [] try: master_url = master_file.read_text(encoding="utf-8").strip() except OSError: return [] if not master_url.startswith(("http://", "https://")): return [] try: master_text = http.read_text(master_url) except RuntimeError: return [] return [urljoin(master_url, rel) for rel in audio_rendition_uris(master_text)] def audio_download_candidates(source: Path) -> list[str]: """从已保存的播放列表和分片地址里找出还能尝试的音频列表。""" found: list[str] = [] playlist = source / "playlist.m3u8" relatives: list[str] = [] if playlist.is_file(): try: relatives = audio_rendition_uris(playlist.read_text(encoding="utf-8")) except OSError: relatives = [] segment_urls = _segment_urls(source) base = "" query = "" for url in segment_urls: base, query = _cdn_master_base(url) if base: break for rel in relatives: if rel.startswith(("http://", "https://")): found.append(rel) continue if rel in {"audio.m3u8", "video.m3u8"} or not base: continue joined = urljoin(base, rel) if query and "?" not in joined: joined = f"{joined}?{query}" found.append(joined) for url in segment_urls: found.extend(guess_audio_playlist_urls(url)) break unique: list[str] = [] seen: set[str] = set() for url in found: if url not in seen: seen.add(url) unique.append(url) return unique def store_audio_playlist(source: Path, playlist_url: str) -> None: text = http.read_text(playlist_url) localized, items = localize_media(text, playlist_url, name_prefix="audio-") if not items: raise RuntimeError("音频列表没有分片") source.mkdir(parents=True, exist_ok=True) created: list[Path] = [] try: for item in items: target = source / item["name"] if target.is_file() and target.stat().st_size > 0: continue http.download_file(item["url"], target) created.append(target) missing = [item["name"] for item in items if not (source / item["name"]).is_file() or (source / item["name"]).stat().st_size <= 0] if missing: raise RuntimeError("音频分片没有下全") (source / "audio.m3u8").write_text(localized, encoding="utf-8", newline="\n") except Exception: for path in created: path.unlink(missing_ok=True) partial = source / "audio.m3u8" if partial.is_file() and not _playlist_complete(partial): partial.unlink(missing_ok=True) raise def _complete_audio_from_manifest(source: Path) -> bool: audio = source / "audio.m3u8" if not audio.is_file(): return False needed = _playlist_local_files(audio) if not needed: return False manifest = dict(_manifest_items(source)) for path in needed: if path.is_file() and path.stat().st_size > 0: continue url = manifest.get(path.name) if not url: return False http.download_file(url, path) return _playlist_complete(audio) def _manifest_items(source: Path) -> list[tuple[str, str]]: manifest = source / "segments.json" if not manifest.is_file(): return [] try: items = json.loads(manifest.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): return [] pairs = [] if isinstance(items, list): for item in items: if isinstance(item, dict): name = str(item.get("name") or "") url = str(item.get("url") or "") if name and url.startswith(("http://", "https://")): pairs.append((name, url)) return pairs def ensure_saved_audio(source: Path) -> bool: """准备好 audio.m3u8。没有音频引用时返回 False;地址失效时抛出错误。""" audio = source / "audio.m3u8" if _playlist_complete(audio): return True try: if _complete_audio_from_manifest(source): return True except RuntimeError: pass if audio.is_file(): audio.unlink(missing_ok=True) candidates: list[str] = [] seen: set[str] = set() for url in _master_audio_urls(source) + audio_download_candidates(source): if url not in seen: seen.add(url) candidates.append(url) if not candidates: return False errors: list[str] = [] for url in candidates: try: store_audio_playlist(source, url) return True except RuntimeError as exc: errors.append(str(exc)) detail = errors[-1] if errors else "下载失败" raise RuntimeError(f"音频地址已失效,没法补上下载:{detail}") def episode_src(token: str, device: DeviceProfile | None, vid: int, cid: int) -> str: for ep in load_episodes(token, device, vid): if int(ep.get("cid") or 0) == cid and ep.get("src"): return str(ep["src"]) return "" def playback_playlist(master_url: str) -> str: master_text = http.read_text(master_url) variant_rel = next( (line.strip() for line in master_text.splitlines() if line.strip() and not line.startswith("#")), "", ) if not variant_rel: raise RuntimeError("播放列表没有视频地址") if looks_like_segment(variant_rel): return _rewrite_playlist(master_text, master_url) variant_url = urljoin(master_url, variant_rel) return _rewrite_playlist(http.read_text(variant_url), variant_url) def _proxy_url(url: str) -> str: return "/api/play/segment?url=" + quote(url, safe="") def _rewrite_playlist(text: str, base: str) -> str: lines = [] for line in text.splitlines(): stripped = line.strip() if not stripped: lines.append(line) continue if stripped.startswith("#"): lines.append(_rewrite_tag(line, base)) continue lines.append(_proxy_url(urljoin(base, stripped))) return "\n".join(lines) + "\n" def _rewrite_tag(line: str, base: str) -> str: def replace(match: re.Match) -> str: return 'URI="' + _proxy_url(urljoin(base, match.group(1))) + '"' return re.sub(r'URI="([^"]*)"', replace, line)