mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-27 11:25:08 +00:00
feat(downloader): resume failed downloads from completed segments across runs
Fingerprint-gated reuse of atomically-published segment files (DASH/ISM/HLS) behind a continue_downloads config option and one-off dl --continue-downloads flag.
This commit is contained in:
@@ -588,6 +588,7 @@ def perform_download(
|
||||
workers=params.get("workers"),
|
||||
adaptive_workers=params.get("adaptive_workers", False),
|
||||
download_processes=params.get("download_processes", 1),
|
||||
continue_downloads=params.get("continue_downloads", False),
|
||||
downloads=params.get("downloads", 1),
|
||||
worst=params.get("worst", False),
|
||||
best_available=params.get("best_available", False),
|
||||
|
||||
@@ -72,6 +72,7 @@ DEFAULT_DOWNLOAD_PARAMS = {
|
||||
"workers": None,
|
||||
"adaptive_workers": False,
|
||||
"download_processes": 1,
|
||||
"continue_downloads": False,
|
||||
"downloads": 1,
|
||||
"worst": False,
|
||||
"best_available": False,
|
||||
|
||||
@@ -787,6 +787,9 @@ async def download(request: web.Request) -> web.Response:
|
||||
download_processes:
|
||||
type: integer
|
||||
description: Split a track's segments across this many processes; only engages for large batches (default - 1)
|
||||
continue_downloads:
|
||||
type: boolean
|
||||
description: Keep completed segment files across runs and resume a previously failed download (default - false)
|
||||
downloads:
|
||||
type: integer
|
||||
description: Amount of tracks to download concurrently (default - 1)
|
||||
|
||||
@@ -130,6 +130,7 @@ class Config:
|
||||
self.update_check_interval: int = kwargs.get("update_check_interval", 24)
|
||||
# mask local base dirs (install root/venv/home) in logged paths; False shows full paths
|
||||
self.redact_paths: bool = kwargs.get("redact_paths", True)
|
||||
self.continue_downloads: bool = kwargs.get("continue_downloads", False)
|
||||
|
||||
self.language_tags: dict = kwargs.get("language_tags") or {}
|
||||
self.tag_rules: list = kwargs.get("tag_rules") or []
|
||||
|
||||
@@ -23,11 +23,12 @@ from pywidevine.pssh import PSSH
|
||||
from requests import Session
|
||||
|
||||
from unshackle.core.cdm.detect import is_playready_cdm
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, AnyTrack
|
||||
from unshackle.core.drm import DRM_T, ClearKeyCENC, PlayReady, Widevine
|
||||
from unshackle.core.events import events
|
||||
from unshackle.core.session import RnetSession
|
||||
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video
|
||||
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video, resume
|
||||
from unshackle.core.tracks.track import assert_fragments_decrypted
|
||||
from unshackle.core.utilities import is_close_match, log_event, try_ensure_utf8
|
||||
from unshackle.core.utils.redact import safe_display_url
|
||||
@@ -456,6 +457,15 @@ class DASH:
|
||||
len(init_data) if init_data is not None else None,
|
||||
)
|
||||
|
||||
if not collapse_single_url:
|
||||
# reuse a prior run's segments only when the fingerprint proves the segmentation unchanged
|
||||
digest = resume.fingerprint(track.url, segments)
|
||||
if not (config.continue_downloads and resume.reusable(save_dir, digest)):
|
||||
shutil.rmtree(save_dir, ignore_errors=True)
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
if config.continue_downloads:
|
||||
resume.write_sidecar(save_dir, digest)
|
||||
|
||||
if collapse_single_url:
|
||||
# must carry no Range header, or the downloader would skip its ranged-parallel path
|
||||
downloader_args = dict(
|
||||
@@ -615,6 +625,7 @@ class DASH:
|
||||
except OSError:
|
||||
# Directory might not be empty, try removing recursively
|
||||
shutil.rmtree(save_dir, ignore_errors=True)
|
||||
resume.clear_sidecar(save_dir)
|
||||
|
||||
progress(downloaded="Downloaded")
|
||||
|
||||
|
||||
@@ -28,11 +28,12 @@ from requests import Session
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, AnyTrack
|
||||
from unshackle.core.drm import DRM_T, ClearKey, MonaLisa, PlayReady, Widevine
|
||||
from unshackle.core.events import events
|
||||
from unshackle.core.session import RnetResponse, RnetSession
|
||||
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video
|
||||
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video, resume
|
||||
from unshackle.core.tracks.track import assert_fragments_decrypted
|
||||
from unshackle.core.utilities import get_extension, is_close_match, log_event, try_ensure_utf8
|
||||
from unshackle.core.utils.redact import safe_display_url
|
||||
@@ -667,6 +668,22 @@ class HLS:
|
||||
|
||||
segment_save_dir = save_dir / "segments"
|
||||
|
||||
# no resume for AES-128/ClearKey: in-place decryption at merge time makes numbered files ambiguous
|
||||
resumable_drm = (session_drm is None or isinstance(session_drm, (Widevine, PlayReady))) and not any(
|
||||
key and key.method == "AES-128" for key in (master.keys or [])
|
||||
)
|
||||
# media_sequence feeds AES IVs; total_segments pins the OnSegmentFilter verdict (shifts every index)
|
||||
digest = resume.fingerprint(
|
||||
track.url,
|
||||
[(url["url"], url["headers"].get("Range")) for url in urls],
|
||||
extra=[str(getattr(master, "media_sequence", None) or 0), str(total_segments)],
|
||||
)
|
||||
if not (config.continue_downloads and resumable_drm and resume.reusable(save_dir, digest)):
|
||||
shutil.rmtree(save_dir, ignore_errors=True)
|
||||
segment_save_dir.mkdir(parents=True, exist_ok=True)
|
||||
if config.continue_downloads and resumable_drm:
|
||||
resume.write_sidecar(save_dir, digest)
|
||||
|
||||
downloader_args = dict(
|
||||
urls=urls,
|
||||
output_dir=segment_save_dir,
|
||||
@@ -707,6 +724,9 @@ class HLS:
|
||||
for control_file in segment_save_dir.glob("*.!dev"):
|
||||
control_file.unlink(missing_ok=True)
|
||||
|
||||
# merge mutates segment files in place from here on; withdraw the reuse proof
|
||||
resume.clear_sidecar(save_dir)
|
||||
|
||||
progress(total=total_segments, completed=0, downloaded="Merging")
|
||||
|
||||
name_len = len(str(total_segments))
|
||||
|
||||
@@ -17,6 +17,7 @@ from pyplayready.system.pssh import PSSH as PR_PSSH
|
||||
from pywidevine.pssh import PSSH
|
||||
from requests import Session
|
||||
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, AnyTrack
|
||||
from unshackle.core.drm import DRM_T, PlayReady, Widevine
|
||||
from unshackle.core.events import events
|
||||
@@ -28,7 +29,7 @@ from unshackle.core.manifests.ism_init import (
|
||||
read_track_id,
|
||||
)
|
||||
from unshackle.core.session import RnetSession
|
||||
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Track, Tracks, Video
|
||||
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Track, Tracks, Video, resume
|
||||
from unshackle.core.tracks.track import assert_fragments_decrypted
|
||||
from unshackle.core.utilities import log_event, try_ensure_utf8
|
||||
from unshackle.core.utils.redact import safe_display_url
|
||||
@@ -430,6 +431,14 @@ class ISM:
|
||||
progress(total=len(segments))
|
||||
|
||||
downloader = track.downloader
|
||||
|
||||
digest = resume.fingerprint(track.url, [(url, None) for url in segments])
|
||||
if not (config.continue_downloads and resume.reusable(save_dir, digest)):
|
||||
shutil.rmtree(save_dir, ignore_errors=True)
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
if config.continue_downloads:
|
||||
resume.write_sidecar(save_dir, digest)
|
||||
|
||||
downloader_args = dict(
|
||||
urls=[{"url": url} for url in segments],
|
||||
output_dir=save_dir,
|
||||
@@ -573,6 +582,7 @@ class ISM:
|
||||
except OSError:
|
||||
# a superseded hedge download may still drop a .!dev file here
|
||||
shutil.rmtree(save_dir, ignore_errors=True)
|
||||
resume.clear_sidecar(save_dir)
|
||||
progress(downloaded="Downloaded")
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
"""Cross-run segment-resume sidecars.
|
||||
|
||||
A track's completed segment files may be reused by a later run, but only once
|
||||
the manifest proves the segmentation is unchanged. The proof is a fingerprint
|
||||
of the segmentation stored in a JSON sidecar next to the segment directory.
|
||||
|
||||
The sidecar is deliberately a sibling of the segment directory, never a file
|
||||
inside it: the manifest parsers merge by globbing the directory with no
|
||||
extension filter, so any file left in there would be concatenated into the
|
||||
final output.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Optional, Sequence
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
|
||||
_VERSION = 1
|
||||
|
||||
|
||||
def sidecar_path(save_dir: Path) -> Path:
|
||||
"""Path of the resume sidecar for save_dir (always a sibling, see module docstring)."""
|
||||
return save_dir.with_name(save_dir.name + ".resume.json")
|
||||
|
||||
|
||||
def _strip_url(url: Optional[str]) -> 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: Optional[str],
|
||||
segments: Sequence[tuple[str, Optional[str]]],
|
||||
extra: Sequence[str] = (),
|
||||
) -> str:
|
||||
"""Stable digest of a track's segmentation.
|
||||
|
||||
Hashes the manifest URL (sans query), the segment count, and each
|
||||
segment's URL (sans query) with its byte-range string verbatim; byte
|
||||
ranges are the strongest identity signal available and never carry
|
||||
tokens. extra carries protocol-specific identity inputs (HLS: the
|
||||
media_sequence start and post-filter segment count).
|
||||
"""
|
||||
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 reusable(save_dir: Path, digest: str) -> bool:
|
||||
"""True when save_dir's sidecar records this exact digest.
|
||||
|
||||
Never raises: a missing, unreadable, or malformed sidecar means "cannot
|
||||
prove reuse is safe", which means restart clean.
|
||||
"""
|
||||
try:
|
||||
data = json.loads(sidecar_path(save_dir).read_text(encoding="utf-8"))
|
||||
return bool(data.get("digest")) and data["digest"] == digest
|
||||
except (OSError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def write_sidecar(save_dir: Path, digest: str) -> None:
|
||||
"""Record digest so a later run can prove save_dir's segments are reusable."""
|
||||
sidecar_path(save_dir).write_text(json.dumps({"version": _VERSION, "digest": digest}), encoding="utf-8")
|
||||
|
||||
|
||||
def clear_sidecar(save_dir: Path) -> None:
|
||||
"""Withdraw the reuse proof (merge is about to mutate files, or the track completed)."""
|
||||
sidecar_path(save_dir).unlink(missing_ok=True)
|
||||
@@ -26,6 +26,7 @@ from unshackle.core.downloaders import requests
|
||||
from unshackle.core.drm import DRM_T, ClearKeyCENC, PlayReady, Widevine
|
||||
from unshackle.core.events import events
|
||||
from unshackle.core.session import RnetSession
|
||||
from unshackle.core.tracks import resume
|
||||
from unshackle.core.utilities import get_boxes, log_event, try_ensure_utf8
|
||||
from unshackle.core.utils.subprocess import ffprobe
|
||||
|
||||
@@ -437,10 +438,19 @@ class Track:
|
||||
else:
|
||||
save_dir = save_path.parent
|
||||
|
||||
def cleanup():
|
||||
keep_segments = config.continue_downloads and self.descriptor != self.Descriptor.URL
|
||||
|
||||
def cleanup() -> None:
|
||||
save_path.unlink(missing_ok=True)
|
||||
if save_dir.exists() and save_dir.name.endswith("_segments"):
|
||||
shutil.rmtree(save_dir)
|
||||
if save_dir.name.endswith("_segments"):
|
||||
if keep_segments:
|
||||
if save_dir.exists():
|
||||
for partial in save_dir.rglob("*.!dev"):
|
||||
partial.unlink(missing_ok=True)
|
||||
else:
|
||||
if save_dir.exists():
|
||||
shutil.rmtree(save_dir)
|
||||
resume.clear_sidecar(save_dir)
|
||||
|
||||
if not DOWNLOAD_LICENCE_ONLY.is_set():
|
||||
if config.directories.temp.is_file():
|
||||
@@ -448,10 +458,8 @@ class Track:
|
||||
|
||||
config.directories.temp.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Delete any pre-existing temp files matching this track.
|
||||
# We can't re-use or continue downloading these tracks as they do not use a
|
||||
# lock file. Or at least the majority don't. Even if they did I've encountered
|
||||
# corruptions caused by sudden interruptions to the lock file.
|
||||
# completed segments are reusable once the parser proves the segmentation
|
||||
# unchanged (resume sidecar); partial .!dev files never survive a run boundary
|
||||
cleanup()
|
||||
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user