feat: 合成 MP4 时带上独立音频并支持按剧重新下载
This commit is contained in:
+252
-4
@@ -73,6 +73,13 @@ def _request_playlist(token: str, device: DeviceProfile, vid: int) -> list[dict]
|
||||
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"
|
||||
|
||||
@@ -147,7 +154,19 @@ def load_episodes(token: str, device: DeviceProfile | None, vid: int) -> list[di
|
||||
return merged
|
||||
|
||||
|
||||
def expand_variant(master_url: str) -> tuple[str, str, list[dict]]:
|
||||
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 expand_variant(master_url: str) -> tuple[str, str, list[dict], str, list[dict]]:
|
||||
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("#")),
|
||||
@@ -164,10 +183,35 @@ def expand_variant(master_url: str) -> tuple[str, str, list[dict]]:
|
||||
localized, items = localize_media(media_text, variant_url)
|
||||
if not items:
|
||||
raise RuntimeError("播放列表没有分片")
|
||||
return master_text, localized, items
|
||||
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)
|
||||
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 localize_media(text: str, base: str) -> tuple[str, list[dict]]:
|
||||
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] = []
|
||||
@@ -176,7 +220,7 @@ def localize_media(text: str, base: str) -> tuple[str, list[dict]]:
|
||||
for index, url in enumerate(urls, start=1):
|
||||
name = known.get(url)
|
||||
if name is None:
|
||||
name = _resource_name(url, index, used)
|
||||
name = name_prefix + _resource_name(url, index, used)
|
||||
known[url] = name
|
||||
items.append({"name": name, "url": url})
|
||||
names.append(name)
|
||||
@@ -232,6 +276,210 @@ def _apply_local_names(text: str, names: list[str]) -> str:
|
||||
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"):
|
||||
|
||||
Reference in New Issue
Block a user