forked from kenzuya/unshackle
feat(export): write mediaexport files and read legacy exports through the package
--export writes the mediaexport format with DRM, content keys and manifests at title level, and unshackle's own track dicts under x-unshackle. unshackle import reads mediaexport, unidl v1 and unshackle v2 through the shared reader, applies the export's request headers to the import session, and rebuilds DRM from the title-level pool. mediaexport is a git dependency on unshackle-dl/mediaexport.
This commit is contained in:
+102
-47
@@ -1,7 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
@@ -27,6 +26,7 @@ from typing import Any, Callable, Collection, Optional, Sequence, TypedDict, Uni
|
||||
from uuid import UUID
|
||||
|
||||
import click
|
||||
import mediaexport
|
||||
import yaml
|
||||
from click.core import ParameterSource
|
||||
from langcodes import Language, tag_is_valid
|
||||
@@ -40,7 +40,7 @@ from rich.table import Table
|
||||
from rich.text import Text
|
||||
from rich.tree import Tree
|
||||
|
||||
from unshackle.core import binaries, providers
|
||||
from unshackle.core import __version__, binaries, providers
|
||||
from unshackle.core.cdm import DecryptLabsRemoteCDM
|
||||
from unshackle.core.cdm.detect import cdm_type_stub, is_playready_cdm, is_widevine_cdm
|
||||
from unshackle.core.config import config, resolve_cdm_name, resolve_decryption
|
||||
@@ -3914,63 +3914,118 @@ class dl:
|
||||
return meta
|
||||
|
||||
def write_export(self, export: Path, title: Title_T, track: AnyTrack, drm: Any = None) -> None:
|
||||
"""Write a shareable v2 export usable by ``unshackle import``.
|
||||
"""Write a shareable mediaexport file usable by ``unshackle import`` and unidl.
|
||||
|
||||
Carries no HTTP session, cookies, or dl-flags. The export records the region (country
|
||||
code) only when the export used ``--proxy``, as an import geofence. Each track records
|
||||
only the licensed DRM system. Content keys live once under the track's ``keys``. ``drm`` may be None
|
||||
(DRM-free track) or a DRM system without ``to_dict``/``content_keys`` (e.g. ClearKey) -
|
||||
the export still records the track, manifest, chapter and attachment info.
|
||||
Carries no HTTP session or cookies. The export records the region (country code)
|
||||
only when the export used ``--proxy``, as an import geofence. DRM init data and
|
||||
content keys live once per title. ``drm`` may be None (DRM-free track) or a DRM
|
||||
system without ``to_dict``/``content_keys`` (e.g. ClearKey) - the export still
|
||||
records the track, manifest, chapter and attachment info. unshackle's full track
|
||||
dicts and title meta go under ``x-unshackle`` for its own importer.
|
||||
"""
|
||||
with self.EXPORT_LOCK:
|
||||
doc: dict[str, Any] = {}
|
||||
if export.is_file():
|
||||
doc = json.loads(export.read_text(encoding="utf8")) or {}
|
||||
doc = mediaexport.read(export) if export.is_file() else mediaexport.Document(service_tag=self.service)
|
||||
doc.generator.setdefault("app", "unshackle")
|
||||
doc.generator.setdefault("version", __version__)
|
||||
if not doc.region and getattr(self, "proxy_requested", False):
|
||||
doc.region = getattr(getattr(self, "export_service", None), "current_region", None) or ""
|
||||
|
||||
doc.setdefault("version", 2)
|
||||
doc.setdefault("service", self.service)
|
||||
if "region" not in doc and getattr(self, "proxy_requested", False):
|
||||
region = getattr(getattr(self, "export_service", None), "current_region", None)
|
||||
if region:
|
||||
doc["region"] = region
|
||||
entry = doc.get(str(title.id))
|
||||
if entry is None:
|
||||
entry = self.export_entry(title)
|
||||
doc.add(entry)
|
||||
|
||||
titles = doc.setdefault("titles", {})
|
||||
tinfo = titles.setdefault(str(title.id), {})
|
||||
tinfo.setdefault("meta", self.title_to_meta(title))
|
||||
tracks_map = entry.ext("unshackle").setdefault("tracks", {})
|
||||
tracks_map.setdefault(str(track.id), track.to_dict())
|
||||
for row in entry.tracks:
|
||||
if row.get("id") == str(track.id):
|
||||
row["selected"] = True
|
||||
|
||||
if title.tracks.manifest_url:
|
||||
tinfo.setdefault("manifest_url", title.tracks.manifest_url)
|
||||
|
||||
all_tracks = [*title.tracks.videos, *title.tracks.audio, *title.tracks.subtitles]
|
||||
if "manifest_type" not in tinfo:
|
||||
tinfo["manifest_type"] = next(
|
||||
(t.descriptor.name for t in all_tracks if t.descriptor != Video.Descriptor.URL), None
|
||||
)
|
||||
|
||||
tracks_map = tinfo.setdefault("tracks", {})
|
||||
if not tracks_map:
|
||||
for t in all_tracks:
|
||||
tracks_map[str(t.id)] = t.to_dict()
|
||||
|
||||
track_data = tracks_map.setdefault(str(track.id), track.to_dict())
|
||||
if drm is not None:
|
||||
if hasattr(drm, "to_dict"):
|
||||
track_data["drm"] = [drm.to_dict()]
|
||||
d = drm.to_dict()
|
||||
own = entry.ext("unshackle").setdefault("drm", [])
|
||||
if d not in own:
|
||||
own.append(d)
|
||||
system = str(d.get("system", "")).lower().replace("cenc", "")
|
||||
pssh = str(d.get("pssh_b64") or "")
|
||||
if system and all(x.pssh != pssh or x.system != system for x in entry.drm):
|
||||
entry.drm.append(mediaexport.Drm(system, pssh))
|
||||
content_keys = getattr(drm, "content_keys", None) or {}
|
||||
if content_keys:
|
||||
keys = track_data.setdefault("keys", {})
|
||||
for kid, key in content_keys.items():
|
||||
keys[kid.hex] = key
|
||||
for kid, key in content_keys.items():
|
||||
entry.keys[kid.hex] = key
|
||||
|
||||
if "chapters" not in tinfo:
|
||||
tinfo["chapters"] = [
|
||||
{"timestamp": chapter.timestamp, "name": chapter.name} for chapter in (title.tracks.chapters or [])
|
||||
]
|
||||
mediaexport.write(export, doc)
|
||||
|
||||
if "attachments" not in tinfo:
|
||||
tinfo["attachments"] = [a.to_dict() for a in (title.tracks.attachments or []) if a.url]
|
||||
def export_entry(self, title: Title_T) -> mediaexport.Entry:
|
||||
"""A mediaexport entry for ``title``: manifests, chapters, a small track list, no keys yet."""
|
||||
meta = self.title_to_meta(title)
|
||||
all_tracks = [*title.tracks.videos, *title.tracks.audio, *title.tracks.subtitles]
|
||||
primary_url = title.tracks.manifest_url or next(
|
||||
(str(t.url) for t in all_tracks if t.descriptor != Video.Descriptor.URL), ""
|
||||
)
|
||||
manifest_type = next(
|
||||
(t.descriptor.name.lower() for t in all_tracks if t.descriptor != Video.Descriptor.URL), ""
|
||||
)
|
||||
session = getattr(getattr(self, "export_service", None), "session", None)
|
||||
headers = {
|
||||
k: v
|
||||
for k, v in (getattr(session, "headers", None) or {}).items()
|
||||
if k.lower() not in ("cookie", "authorization")
|
||||
}
|
||||
manifests = [mediaexport.Manifest(primary_url, manifest_type, headers, role="primary")] if primary_url else []
|
||||
seen = {primary_url.split("?")[0]}
|
||||
for t in all_tracks:
|
||||
url = str(t.url)
|
||||
if t.descriptor in (Video.Descriptor.DASH, Video.Descriptor.ISM) and url.split("?")[0] not in seen:
|
||||
seen.add(url.split("?")[0])
|
||||
manifests.append(mediaexport.Manifest(url, t.descriptor.name.lower(), role="extra"))
|
||||
|
||||
export.write_text(json.dumps(doc, indent=4, ensure_ascii=False), encoding="utf8")
|
||||
rows = []
|
||||
for t in all_tracks:
|
||||
row: dict[str, Any] = {
|
||||
"id": str(t.id),
|
||||
"type": t.__class__.__name__.lower(),
|
||||
"codec": codec.name.lower() if (codec := getattr(t, "codec", None)) else "",
|
||||
"language": str(t.language) if t.language else "",
|
||||
"bitrate": int(bitrate) if (bitrate := getattr(t, "bitrate", None)) else None,
|
||||
}
|
||||
if isinstance(t, Video):
|
||||
row.update(width=t.width, height=t.height, range=t.range.name.lower() if t.range else "")
|
||||
elif isinstance(t, Audio):
|
||||
row.update(channels=str(t.channels) if t.channels else "", atmos=bool(t.joc), descriptive=t.descriptive)
|
||||
elif isinstance(t, Subtitle):
|
||||
row.update(sdh=t.sdh, forced=t.forced, cc=t.cc)
|
||||
if t.descriptor == Video.Descriptor.URL:
|
||||
row["url"] = str(t.url)
|
||||
rows.append({k: v for k, v in row.items() if v not in (None, "")})
|
||||
|
||||
return mediaexport.Entry(
|
||||
id=str(title.id),
|
||||
kind=meta.get("type", "movie"),
|
||||
title=meta.get("name") or "",
|
||||
series=meta.get("series_title") or "",
|
||||
season=meta.get("season"),
|
||||
episode=meta.get("number"),
|
||||
year=meta.get("year"),
|
||||
language=meta.get("language") or "",
|
||||
artist=meta.get("artist") or "",
|
||||
album=meta.get("album") or "",
|
||||
track_number=meta.get("track"),
|
||||
manifests=manifests,
|
||||
chapters=[
|
||||
{"start_ms": mediaexport.ts_ms(c.timestamp), "title": c.name or ""}
|
||||
for c in (title.tracks.chapters or [])
|
||||
],
|
||||
tracks=rows,
|
||||
extensions={
|
||||
"x-unshackle": {
|
||||
"meta": meta,
|
||||
"tracks": {},
|
||||
"attachments": [a.to_dict() for a in (title.tracks.attachments or []) if a.url],
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
def decrypt_verified(
|
||||
self,
|
||||
|
||||
@@ -794,7 +794,7 @@ async def download(request: web.Request) -> web.Response:
|
||||
description: Skip downloading, only retrieve decryption keys (default - false)
|
||||
export:
|
||||
type: boolean
|
||||
description: Export manifest, track URLs, keys, and subtitles to JSON in the exports directory (default - false)
|
||||
description: Export manifest, DRM init data, keys, and track info to a JSON file in the exports directory (default - false)
|
||||
cdm_only:
|
||||
type: boolean
|
||||
description: Only use CDM for content key retrieval (true) or only vaults (false) (default - None)
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from http.cookiejar import CookieJar
|
||||
from pathlib import Path
|
||||
@@ -8,6 +7,7 @@ from typing import Any, Optional, Union
|
||||
from uuid import UUID
|
||||
|
||||
import click
|
||||
import mediaexport
|
||||
import requests
|
||||
from langcodes import tag_is_valid
|
||||
|
||||
@@ -124,33 +124,72 @@ class ImportService:
|
||||
if not export_path.is_file():
|
||||
raise click.ClickException(f"Export file not found: {export_path}")
|
||||
|
||||
self.data: dict[str, Any] = json.loads(export_path.read_text(encoding="utf8"))
|
||||
version = self.data.get("version")
|
||||
if version != 2:
|
||||
raise click.ClickException(
|
||||
f"Unsupported export version {version!r}. Re-create the export with a current build."
|
||||
)
|
||||
try:
|
||||
self.doc = mediaexport.read(export_path)
|
||||
except mediaexport.ExportError as e:
|
||||
raise click.ClickException(f"Cannot import {export_path.name}: {e}")
|
||||
|
||||
self.titles_data: dict[str, Any] = self.data.get("titles", {})
|
||||
self.region: Optional[str] = self.data.get("region")
|
||||
self.titles_data: dict[str, Any] = {e.id: self.legacy_entry(e) for e in self.doc.titles}
|
||||
self.region: Optional[str] = self.doc.region or None
|
||||
self.titles: Optional[Titles_T] = None
|
||||
self.tracks_by_title: dict[str, Tracks] = {}
|
||||
|
||||
self._server_cdm = True
|
||||
self._server_cdm_type = "widevine"
|
||||
|
||||
self.session = self.build_session(ctx, self.region)
|
||||
first = self.doc.titles[0].primary if self.doc.titles else None
|
||||
headers = first.headers if first else {}
|
||||
self.session = self.build_session(ctx, self.region, headers)
|
||||
|
||||
@staticmethod
|
||||
def build_session(ctx: click.Context, region: Optional[str] = None) -> requests.Session:
|
||||
def legacy_entry(entry: mediaexport.Entry) -> dict[str, Any]:
|
||||
"""The per-title dict the rest of this class reads, from a mediaexport entry.
|
||||
|
||||
unshackle's own exports carry the full title meta and track dicts under
|
||||
``x-unshackle``; a file from another tool has only the shared fields, so the meta is
|
||||
rebuilt from those and the track map stays empty (the manifest is parsed instead).
|
||||
"""
|
||||
x = entry.extensions.get("x-unshackle") or {}
|
||||
meta = x.get("meta") or {
|
||||
"type": entry.kind,
|
||||
"id": entry.id,
|
||||
"name": entry.title,
|
||||
"series_title": entry.series,
|
||||
"season": entry.season,
|
||||
"number": entry.episode,
|
||||
"year": entry.year,
|
||||
"language": entry.language or None,
|
||||
"artist": entry.artist,
|
||||
"album": entry.album,
|
||||
"track": entry.track_number,
|
||||
}
|
||||
primary = entry.primary
|
||||
manifest_type = x.get("manifest_type") or (
|
||||
(primary.type or mediaexport.guess_type(primary.url)).upper() if primary else ""
|
||||
)
|
||||
return {
|
||||
"meta": meta,
|
||||
"manifest_url": primary.url if primary else None,
|
||||
"manifest_type": manifest_type or None,
|
||||
"tracks": x.get("tracks") or {},
|
||||
"chapters": entry.chapters,
|
||||
"attachments": x.get("attachments") or [],
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def build_session(
|
||||
ctx: click.Context, region: Optional[str] = None, headers: Optional[dict[str, str]] = None
|
||||
) -> requests.Session:
|
||||
"""HTTP session for re-fetching the manifest.
|
||||
|
||||
Honours the importer's ``--proxy``. Without one, it falls back to the export region
|
||||
as a geofence. An explicit proxy that unshackle cannot find raises an error. A region
|
||||
fallback gives a warning.
|
||||
Exported request headers go over the config defaults, since a CDN can gate the
|
||||
manifest on the User-Agent the exporter used. Honours the importer's ``--proxy``.
|
||||
Without one, it falls back to the export region as a geofence. An explicit proxy
|
||||
that unshackle cannot find raises an error. A region fallback gives a warning.
|
||||
"""
|
||||
session = requests.Session()
|
||||
session.headers.update(config.headers)
|
||||
session.headers.update(headers or {})
|
||||
|
||||
params = ctx.parent.params if ctx.parent else {}
|
||||
if params.get("no_proxy"):
|
||||
@@ -224,7 +263,8 @@ class ImportService:
|
||||
tracks.manifest_url = manifest_url
|
||||
|
||||
parser = PARSERS.get(manifest_type or "")
|
||||
if manifest_url and parser is not None and manifest_type in ("DASH", "ISM"):
|
||||
# An export from another tool has no track dicts, so HLS is parsed from the manifest too
|
||||
if manifest_url and parser is not None and (manifest_type in ("DASH", "ISM") or not tracks_map):
|
||||
try:
|
||||
manifest = parser.from_url(url=manifest_url, session=self.session)
|
||||
except Exception as e:
|
||||
@@ -272,7 +312,7 @@ class ImportService:
|
||||
except Exception as e:
|
||||
self.log.warning(f"Skipping exported track {track_dict.get('id')!r}: {e}")
|
||||
continue
|
||||
drm = self.rebuild_drm(track_dict)
|
||||
drm = self.rebuild_drm(track_dict, title_id)
|
||||
if drm:
|
||||
track.drm = drm
|
||||
tracks.add(track, warn_only=True)
|
||||
@@ -307,18 +347,37 @@ class ImportService:
|
||||
|
||||
def key_pool(self, title_id: Optional[str] = None) -> dict[UUID, str]:
|
||||
"""Exported KID:KEY pairs as {UUID: key_hex}, for one title or across every title."""
|
||||
pool: dict[UUID, str] = {}
|
||||
entries = [self.titles_data.get(title_id, {})] if title_id else self.titles_data.values()
|
||||
for entry in entries:
|
||||
for track_dict in (entry.get("tracks") or {}).values():
|
||||
for kid_hex, key in (track_dict.get("keys") or {}).items():
|
||||
pool[UUID(hex=kid_hex)] = key
|
||||
return pool
|
||||
entry = self.doc.get(title_id) if title_id else None
|
||||
keys = entry.keys if entry else self.doc.key_pool()
|
||||
return {UUID(hex=kid): key for kid, key in keys.items()}
|
||||
|
||||
def rebuild_drm(self, track_dict: dict[str, Any]) -> Optional[list[Any]]:
|
||||
"""Rebuild a DRM object (from stored PSSH, falling back to a stub) with the exported keys."""
|
||||
keys = track_dict.get("keys") or {}
|
||||
drm_dicts = track_dict.get("drm") or []
|
||||
def title_drm_dicts(self, title_id: str) -> list[dict[str, Any]]:
|
||||
"""The title's DRM entries in ``drm_from_dict`` form.
|
||||
|
||||
unshackle's own export keeps the exact ``to_dict`` output under ``x-unshackle``, so a
|
||||
ClearKeyCENC licence URL or a PlayReady PSSH comes back byte for byte.
|
||||
"""
|
||||
entry = self.doc.get(title_id)
|
||||
if entry is None:
|
||||
return []
|
||||
own = (entry.extensions.get("x-unshackle") or {}).get("drm")
|
||||
if own:
|
||||
return list(own)
|
||||
out = []
|
||||
for d in entry.drm:
|
||||
system = {"widevine": "Widevine", "playready": "PlayReady", "clearkey": "ClearKeyCENC"}.get(d.system)
|
||||
if system:
|
||||
out.append({"system": system, "pssh_b64": d.pssh, "kids": list(entry.keys)})
|
||||
return out
|
||||
|
||||
def rebuild_drm(self, track_dict: dict[str, Any], title_id: str) -> Optional[list[Any]]:
|
||||
"""Rebuild a DRM object (from stored PSSH, falling back to a stub) with the exported keys.
|
||||
|
||||
Keys and DRM are title-level in the shared format; a legacy v2 track dict that still
|
||||
carries its own is honoured first.
|
||||
"""
|
||||
keys = track_dict.get("keys") or {kid.hex: key for kid, key in self.key_pool(title_id).items()}
|
||||
drm_dicts = track_dict.get("drm") or self.title_drm_dicts(title_id)
|
||||
if not drm_dicts and not keys:
|
||||
return None
|
||||
|
||||
@@ -395,17 +454,20 @@ class ImportService:
|
||||
|
||||
def exported_drm_system(self) -> str:
|
||||
"""The DRM system the exporter licensed (e.g. 'playready'), defaulting to widevine."""
|
||||
for entry in self.titles_data.values():
|
||||
for track_dict in (entry.get("tracks") or {}).values():
|
||||
for drm_dict in track_dict.get("drm") or []:
|
||||
if drm_dict.get("system"):
|
||||
return drm_dict["system"].lower()
|
||||
for entry in self.doc.titles:
|
||||
for d in entry.drm:
|
||||
if d.system:
|
||||
return d.system
|
||||
return "widevine"
|
||||
|
||||
def get_chapters(self, title: Title_T) -> Chapters:
|
||||
entry = self.titles_data.get(str(title.id), {})
|
||||
entry = self.doc.get(str(title.id))
|
||||
return Chapters(
|
||||
[Chapter(ch["timestamp"], ch.get("name")) for ch in (entry.get("chapters") or []) if ch.get("timestamp")]
|
||||
[
|
||||
Chapter(int(ch["start_ms"]), ch.get("title") or None)
|
||||
for ch in (entry.chapters if entry else [])
|
||||
if ch.get("start_ms") is not None
|
||||
]
|
||||
)
|
||||
|
||||
def get_widevine_service_certificate(self, **_: Any) -> Optional[str]:
|
||||
|
||||
Reference in New Issue
Block a user