mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-04 06:55:09 +00:00
442 lines
19 KiB
Python
442 lines
19 KiB
Python
"""The segment store: the segment directory of one segmented track, from restore to removal.
|
|
|
|
A later run can reuse the completed segment files of a track only after the manifest proves that the
|
|
segmentation did not change. The proof is a digest of the segmentation, kept in a JSON sidecar beside the
|
|
directory. The sidecar is never a file inside the directory: the parsers merge by globbing the directory with
|
|
no extension filter, so they would join any file in there into the output.
|
|
|
|
Each segment has its state in its name: NNNN.<ext> is a segment as the server sent it, and NNNN.clear is the
|
|
same segment after segment decryption. The sidecar records a digest of the content keys that made the .clear
|
|
files, and the checkpoint of a failed rolling merge: the first segment the output does not hold and the output
|
|
length at that segment. On resume the output is cut back to the checkpoint, and the download skips every
|
|
segment that the output or a .clear file already holds.
|
|
|
|
Track.download calls restore() before the parser and abandon() when the download fails. The parser calls
|
|
open() once its download mode is final, merging() when the last segment is on disk, rewriting() before its
|
|
merge first changes a segment file, and complete() after the merge. A DASH track collapsed to one ranged download
|
|
never opens the store: it makes no segment files.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import contextlib
|
|
import hashlib
|
|
import json
|
|
import logging
|
|
import os
|
|
import shutil
|
|
from collections.abc import Sequence
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
from typing import TYPE_CHECKING, Any
|
|
from urllib.parse import urlsplit, urlunsplit
|
|
|
|
from unshackle.core.config import config
|
|
from unshackle.core.drm import DRM_T, PlayReady, Widevine
|
|
from unshackle.core.temp import resume_stash
|
|
|
|
if TYPE_CHECKING:
|
|
from unshackle.core.tracks.track import Track
|
|
|
|
_VERSION = 1
|
|
SIDECAR = ".resume.json"
|
|
CLEAR = ".clear"
|
|
"""The suffix of a decrypted segment."""
|
|
|
|
log = logging.getLogger("track")
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class DownloadMode:
|
|
"""The final download mode of a track: what the resume verdict reads."""
|
|
|
|
segment_keys: Sequence[str] = ()
|
|
"""The KID:KEY pairs that decrypt each segment as it lands; empty when the segments stay encrypted."""
|
|
rolling_merge: bool = False
|
|
stateful_merge: bool = False
|
|
"""The rolling merge carries state from one segment to the next, so it cannot restart at a checkpoint."""
|
|
drm: DRM_T | None = None
|
|
aes128: bool = False
|
|
merge_rewrites: bool = False
|
|
"""The merge rewrites segment files in place before it reads them."""
|
|
|
|
|
|
def _strip_url(url: str | None) -> str:
|
|
"""Drop query and fragment: auth tokens rotate between runs and would make every digest unique."""
|
|
if not url:
|
|
return ""
|
|
scheme, netloc, path, _, _ = urlsplit(url)
|
|
return urlunsplit((scheme, netloc, path, "", ""))
|
|
|
|
|
|
def fingerprint(
|
|
manifest_url: str | None,
|
|
segments: Sequence[tuple[str, str | None]],
|
|
extra: Sequence[str] = (),
|
|
) -> str:
|
|
"""Stable digest of the segmentation of a track.
|
|
|
|
Hashes the manifest URL and each segment URL without their query, the segment count, and each byte
|
|
range as it is. When the stripped URLs are not unique, the query is the only identity and is kept.
|
|
extra carries identity inputs of one protocol.
|
|
"""
|
|
stripped = [[_strip_url(url), byte_range or ""] for url, byte_range in segments]
|
|
if len({tuple(pair) for pair in stripped}) != len(stripped):
|
|
stripped = [[url, byte_range or ""] for url, byte_range in segments]
|
|
payload = {
|
|
"version": _VERSION,
|
|
"manifest": _strip_url(manifest_url),
|
|
"count": len(segments),
|
|
"segments": stripped,
|
|
"extra": list(extra),
|
|
}
|
|
canonical = json.dumps(payload, separators=(",", ":"), sort_keys=True)
|
|
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
|
|
|
|
def decrypted(segment: Path) -> Path:
|
|
"""The name of a segment once segment decryption has decrypted it."""
|
|
return segment.with_suffix(CLEAR)
|
|
|
|
|
|
def _sidecar(save_dir: Path) -> Path:
|
|
return save_dir.with_name(save_dir.name + SIDECAR)
|
|
|
|
|
|
def _output(save_dir: Path) -> Path:
|
|
"""The merged file of a segmented track; Track.download names the segment directory after it."""
|
|
return save_dir.with_name(save_dir.name.removesuffix("_segments"))
|
|
|
|
|
|
def _sidecar_record(save_dir: Path) -> dict[str, Any]:
|
|
"""The sidecar record of a segment directory; empty when it is missing, unreadable, malformed or has no digest."""
|
|
try:
|
|
data = json.loads(_sidecar(save_dir).read_text(encoding="utf-8"))
|
|
except (OSError, ValueError):
|
|
return {}
|
|
return data if isinstance(data, dict) and data.get("digest") else {}
|
|
|
|
|
|
def _move(save_dir: Path, target: Path) -> None:
|
|
"""Rename a stashed segment directory back, then its sidecar, then the output of its merge checkpoint.
|
|
|
|
A failure only logs: a checkpoint without its output does not count on resume. A symlinked output stays
|
|
where it is.
|
|
"""
|
|
merged = "merge" in _sidecar_record(save_dir)
|
|
try:
|
|
save_dir.rename(target)
|
|
except OSError as e:
|
|
log.debug("Could not move %s: %s", save_dir, e)
|
|
return
|
|
moves = [(_sidecar(save_dir), _sidecar(target))]
|
|
if merged and not _output(save_dir).is_symlink():
|
|
moves.append((_output(save_dir), _output(target)))
|
|
for source, destination in moves:
|
|
try:
|
|
if source.exists():
|
|
source.replace(destination)
|
|
except OSError as e:
|
|
log.debug("Could not move %s: %s", source, e)
|
|
|
|
|
|
def _index(path: Path) -> int | None:
|
|
"""The segment index at the start of a segment file name; None for any other file."""
|
|
head = path.name.split(".", 1)[0]
|
|
return int(head) if head.isdigit() else None
|
|
|
|
|
|
def _key_digest(key_args: Sequence[str]) -> str | None:
|
|
return hashlib.sha256("\n".join(sorted(key_args)).encode("utf-8")).hexdigest() if key_args else None
|
|
|
|
|
|
class SegmentStore:
|
|
"""The segment directory of one track, its resume sidecar and its stash entry."""
|
|
|
|
def __init__(self, track: Track, save_dir: Path) -> None:
|
|
self.track = track
|
|
self.save_dir = save_dir
|
|
self.mode = DownloadMode()
|
|
self.resumes = False
|
|
"""True once open() started a sidecar: a failed download then keeps its segments and its merge."""
|
|
self.cursor = 0
|
|
"""The first segment the kept rolling-merge output does not hold."""
|
|
self.length = 0
|
|
"""The byte length of the kept rolling-merge output at the cursor."""
|
|
self.clear: dict[int, Path] = {}
|
|
"""The kept decrypted segments by index."""
|
|
self._record: dict[str, Any] = {}
|
|
|
|
@property
|
|
def sidecar(self) -> Path:
|
|
return _sidecar(self.save_dir)
|
|
|
|
@property
|
|
def skip(self) -> frozenset[int]:
|
|
"""The segment indices the download skips: the kept output or a kept .clear file holds them."""
|
|
return frozenset(range(self.cursor)) | frozenset(self.clear)
|
|
|
|
@property
|
|
def keeps(self) -> bool:
|
|
"""True when a failed download keeps its completed segments for the next run."""
|
|
return config.continue_downloads and self._owned
|
|
|
|
def resumable(self, mode: DownloadMode) -> bool:
|
|
"""True when the segments of a download in this mode can cross a run boundary.
|
|
|
|
A rolling merge whose append keeps state from one segment to the next cannot restart at a checkpoint.
|
|
The HLS merge decrypts AES-128 segments and every DRM other than Widevine and PlayReady in place,
|
|
segment by segment, so a kept file can be plain or encrypted; a segment decrypter writes .clear files instead.
|
|
"""
|
|
if not self.keeps or (mode.rolling_merge and mode.stateful_merge):
|
|
return False
|
|
if self.track.descriptor is self.track.Descriptor.HLS:
|
|
return not mode.aes128 and (
|
|
mode.drm is None or isinstance(mode.drm, (Widevine, PlayReady)) or bool(mode.segment_keys)
|
|
)
|
|
return True
|
|
|
|
def open(
|
|
self,
|
|
manifest_url: str | None,
|
|
segments: Sequence[tuple[str, str | None]],
|
|
extra: Sequence[str] = (),
|
|
*,
|
|
mode: DownloadMode,
|
|
) -> bool:
|
|
"""Make the directory ready for the download and return True when it keeps the segments of a prior run.
|
|
|
|
Call it once the download mode is final. The segments of a prior run stay only when the mode is
|
|
resumable and the sidecar records the same digest; otherwise the directory starts empty. Kept .clear
|
|
files stay only when this run decrypts segments with the same keys, and a kept rolling-merge output
|
|
only when this run also merges as it downloads.
|
|
"""
|
|
self.mode = mode
|
|
resumable = self.resumable(mode)
|
|
digest = fingerprint(manifest_url, segments, extra)
|
|
record = _sidecar_record(self.save_dir)
|
|
reused = resumable and record.get("digest") == digest
|
|
keys = _key_digest(mode.segment_keys)
|
|
if reused:
|
|
self._settle(record, keys)
|
|
else:
|
|
shutil.rmtree(self.save_dir, ignore_errors=True)
|
|
self.save_dir.mkdir(parents=True, exist_ok=True)
|
|
# a file the wipe could not remove (locked on Windows) belongs to another segmentation
|
|
self.resumes = resumable and (reused or not any(self.save_dir.iterdir()))
|
|
if self.resumes:
|
|
self._record = {"version": _VERSION, "digest": digest, "keys": keys}
|
|
if self.cursor:
|
|
self._record["merge"] = [self.cursor, self.length]
|
|
try:
|
|
self._write()
|
|
except OSError as e:
|
|
log.debug("Could not write the resume sidecar of %s: %s", self.save_dir, e)
|
|
self.resumes = False
|
|
if not self.resumes:
|
|
with contextlib.suppress(OSError):
|
|
self.sidecar.unlink(missing_ok=True)
|
|
return reused
|
|
|
|
def checkpoint(self, cursor: int, length: int) -> bool:
|
|
"""Record that the first length bytes of the rolling-merge output hold the init and the segments below cursor.
|
|
|
|
The output goes to disk first, because the record vouches for its bytes. False when the store keeps
|
|
nothing; the caller then removes the output.
|
|
"""
|
|
if not self.resumes:
|
|
return False
|
|
self._record["merge"] = [cursor, length]
|
|
try:
|
|
with open(_output(self.save_dir), "rb+") as output:
|
|
os.fsync(output.fileno())
|
|
self._write()
|
|
except OSError as e:
|
|
log.debug("Could not record the merge checkpoint of %s: %s", self.save_dir, e)
|
|
return False
|
|
return True
|
|
|
|
def merging(self) -> None:
|
|
"""End the download phase: remove the .!dev files that superseded downloads left and each segment a
|
|
.clear file replaces, so no merge reads one.
|
|
|
|
When the mode says the merge rewrites segments in place (the WebVTT rebase of a multi-period DASH
|
|
subtitle), the sidecar goes now. HLS calls rewriting() itself before its first rewrite. Any other merge
|
|
only reads and deletes segments, so a merge that fails leaves segments that are still good.
|
|
"""
|
|
if self.save_dir.is_dir():
|
|
for control_file in self.save_dir.rglob("*.!dev"):
|
|
control_file.unlink(missing_ok=True)
|
|
if self.mode.segment_keys:
|
|
self._drop_replaced()
|
|
if self.mode.merge_rewrites:
|
|
self.rewriting()
|
|
|
|
def rewriting(self) -> None:
|
|
"""Withdraw the sidecar before the merge rewrites a segment in place, so no later run reuses a rewritten one.
|
|
|
|
Call it before every in-place write. Until then the merge only reads segments, so a merge step that fails
|
|
(an init fetch, a licence) keeps them.
|
|
"""
|
|
self.sidecar.unlink(missing_ok=True)
|
|
|
|
def complete(self) -> None:
|
|
"""Remove the directory and its sidecar after the merge, also when a superseded download left a file."""
|
|
if self._owned:
|
|
shutil.rmtree(self.save_dir, ignore_errors=True)
|
|
self.sidecar.unlink(missing_ok=True)
|
|
|
|
def restore(self) -> None:
|
|
"""Start a download: take back a stashed directory and drop its partial files, or wipe it when nothing is kept.
|
|
|
|
A partial file never crosses a run boundary. A completed segment does, and open() decides if the
|
|
download uses it.
|
|
"""
|
|
if self.keeps:
|
|
self._unstash()
|
|
self._sweep(self.keeps)
|
|
|
|
def abandon(self) -> None:
|
|
"""Clean up a failed or cancelled download and stash the directory when a later run can use it.
|
|
|
|
A directory without a sidecar goes: the next run would wipe it. The downloader does not wait for its
|
|
workers on failure, so on Windows one can still hold a .!dev file open (WinError 32). A cleanup error
|
|
must not replace the error of the download.
|
|
"""
|
|
keep = self.keeps and self.sidecar.exists()
|
|
with contextlib.suppress(OSError):
|
|
self._sweep(keep)
|
|
if keep:
|
|
with contextlib.suppress(OSError):
|
|
self._stash()
|
|
|
|
@property
|
|
def _owned(self) -> bool:
|
|
"""False for a directory the store must never remove, such as the temp directory of a URL track."""
|
|
return self.save_dir.name.endswith("_segments")
|
|
|
|
def _write(self) -> None:
|
|
partial = self.sidecar.with_name(self.sidecar.name + ".tmp")
|
|
partial.write_text(json.dumps(self._record), encoding="utf-8")
|
|
os.replace(partial, self.sidecar)
|
|
|
|
def _segment_files(self) -> list[tuple[int, Path]]:
|
|
return [
|
|
(index, path)
|
|
for path in self.save_dir.rglob("*")
|
|
if path.is_file() and not path.name.endswith(".!dev") and (index := _index(path)) is not None
|
|
]
|
|
|
|
def _settle(self, record: dict[str, Any], keys: str | None) -> None:
|
|
"""Keep the state of a prior run that this run can continue from, and read it into the store.
|
|
|
|
A .clear file made with other keys, or kept for a run that does not decrypt segments, goes, and the decrypt
|
|
runs again on a segment file that its decrypt left behind. merging() removes a segment file beside a kept
|
|
.clear file. A checkpoint counts only when this run merges as it
|
|
downloads with the same keys, and the output is at least as long as the checkpoint records.
|
|
"""
|
|
same_keys = record.get("keys") == keys
|
|
try:
|
|
cursor, length = map(int, record["merge"])
|
|
except (KeyError, TypeError, ValueError):
|
|
cursor, length = 0, 0
|
|
output = _output(self.save_dir)
|
|
if (
|
|
self.mode.rolling_merge
|
|
and same_keys
|
|
and cursor > 0
|
|
and output.is_file()
|
|
and output.stat().st_size >= length
|
|
):
|
|
self.cursor, self.length = cursor, length
|
|
for index, path in self._segment_files():
|
|
if index < self.cursor or (path.suffix == CLEAR and not (same_keys and keys)):
|
|
path.unlink(missing_ok=True)
|
|
elif path.suffix == CLEAR:
|
|
self.clear[index] = path
|
|
|
|
def _drop_replaced(self) -> None:
|
|
"""Remove each segment that a .clear file of the same index replaces; a decrypt that stopped left it."""
|
|
files = self._segment_files()
|
|
clear = {index for index, path in files if path.suffix == CLEAR}
|
|
for index, path in files:
|
|
if index in clear and path.suffix != CLEAR:
|
|
path.unlink(missing_ok=True)
|
|
|
|
def _sweep(self, keep: bool) -> None:
|
|
"""Keep only completed segments and the sidecar when keep is set, else remove both."""
|
|
if not self._owned:
|
|
return
|
|
if keep:
|
|
if self.save_dir.exists():
|
|
for partial in self.save_dir.rglob("*.!dev"):
|
|
partial.with_name(partial.name.removesuffix(".!dev")).unlink(missing_ok=True)
|
|
partial.unlink(missing_ok=True)
|
|
else:
|
|
if self.save_dir.exists():
|
|
shutil.rmtree(self.save_dir)
|
|
self.sidecar.unlink(missing_ok=True)
|
|
|
|
def _stash(self) -> None:
|
|
"""Move what the directory keeps for resume into the stash; see _stash_into."""
|
|
stash = resume_stash()
|
|
if stash is not None and self.save_dir.is_dir():
|
|
_stash_into(self.save_dir, stash)
|
|
|
|
def _unstash(self) -> None:
|
|
"""Move a stashed directory, its sidecar and its output back.
|
|
|
|
Only when the stash has them and the directory is free. The stash keeps the directory of a failed run, and
|
|
the sweep moves there the directory of a killed run.
|
|
"""
|
|
stash = resume_stash()
|
|
if stash is None or self.save_dir.exists():
|
|
return
|
|
kept = stash / self.save_dir.name
|
|
if not kept.is_symlink() and kept.is_dir():
|
|
_move(kept, self.save_dir)
|
|
|
|
|
|
def _stash_into(save_dir: Path, stash: Path) -> None:
|
|
"""Move the completed segments of a directory, then its checkpointed output, then its sidecar into the stash.
|
|
|
|
File by file, skipping a segment on an OS error: on Windows a worker that still writes a partial file after the
|
|
failure blocks the rename of its directory (WinError 5), and the task directory removal then loses it all. A
|
|
partial file, the segment it would replace and a symlinked output stay where they are.
|
|
"""
|
|
target = stash / save_dir.name
|
|
if target.exists():
|
|
return
|
|
merged = "merge" in _sidecar_record(save_dir)
|
|
target.mkdir(parents=True)
|
|
for path in save_dir.rglob("*"):
|
|
if not path.is_file() or path.name.endswith(".!dev") or path.with_name(path.name + ".!dev").exists():
|
|
continue
|
|
moved = target / path.relative_to(save_dir)
|
|
try:
|
|
moved.parent.mkdir(parents=True, exist_ok=True)
|
|
path.replace(moved)
|
|
except OSError as e:
|
|
log.debug("Could not stash %s: %s", path, e)
|
|
output = _output(save_dir)
|
|
if merged and output.is_file() and not output.is_symlink():
|
|
try:
|
|
output.replace(_output(target))
|
|
except OSError as e:
|
|
log.debug("Could not stash %s: %s", output, e)
|
|
sidecar = _sidecar(target)
|
|
_sidecar(save_dir).replace(sidecar)
|
|
# replace keeps the old mtime, and the stash sweep ages entries by it
|
|
for path in (target, sidecar, _output(target)):
|
|
with contextlib.suppress(OSError):
|
|
os.utime(path)
|
|
|
|
|
|
def stash_kept(task_dir: Path, stash: Path) -> None:
|
|
"""Move each segment directory that a dead task dir keeps for resume into the stash."""
|
|
for sidecar in task_dir.glob(f"*{SIDECAR}"):
|
|
save_dir = sidecar.with_name(sidecar.name.removesuffix(SIDECAR))
|
|
if save_dir.is_dir() and not save_dir.is_symlink():
|
|
with contextlib.suppress(OSError):
|
|
_stash_into(save_dir, stash)
|