refactor(tracks): fold segment resume into one segment store module

This commit is contained in:
imSp4rky
2026-11-28 19:21:05 -07:00
parent 5a2680d63d
commit 37357673fe
15 changed files with 633 additions and 368 deletions
+21 -22
View File
@@ -43,7 +43,8 @@ from unshackle.core.manifests.segment_pipeline import (
)
from unshackle.core.manifests.trim import trim_overlaps
from unshackle.core.session import RnetSession, unrecorded
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video, resume
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video
from unshackle.core.tracks.segment_store import DownloadMode, SegmentStore
from unshackle.core.tracks.track import DRM_PREFERENCE_TYPES, Track, parse_sidx
from unshackle.core.utilities import is_close_match, log_event, try_ensure_utf8
from unshackle.core.utils import run_proxy
@@ -684,18 +685,23 @@ class DASH:
# subtitle segments are tiny, the post-download merge costs nothing there
use_rolling_merge = not collapse_single_url and config.merge_segments and not isinstance(track, Subtitle)
is_text_subtitle = (
not drm and isinstance(track, Subtitle) and track.codec not in (Subtitle.Codec.fVTT, Subtitle.Codec.fTTML)
)
known = timed and len(period_starts) > 1
rebase_vtt = known and is_text_subtitle and track.codec == Subtitle.Codec.WebVTT
store = SegmentStore(track, save_dir)
if not collapse_single_url:
# per-segment decryption rewrites each segment in place, so a segment kept from an
# earlier run would either be decrypted twice or never at all; a rolling merge
# unlinks each segment as it is appended, so there is nothing left to reuse
can_resume = config.continue_downloads and not use_segment_decrypt and not use_rolling_merge
# reuse a prior run's segments only when the fingerprint proves the segmentation unchanged
digest = resume.fingerprint(track.url, segments)
if not (can_resume and resume.reusable(save_dir, digest)):
shutil.rmtree(save_dir, ignore_errors=True)
save_dir.mkdir(parents=True, exist_ok=True)
if can_resume:
resume.write_sidecar(save_dir, digest)
store.open(
track.url,
segments,
mode=DownloadMode(
segment_decrypt=use_segment_decrypt,
rolling_merge=use_rolling_merge,
merge_rewrites=rebase_vtt,
),
)
urls: list[dict[str, Any]]
if collapse_single_url:
@@ -723,16 +729,11 @@ class DASH:
},
)
is_text_subtitle = (
not drm and isinstance(track, Subtitle) and track.codec not in (Subtitle.Codec.fVTT, Subtitle.Codec.fTTML)
)
decrypter: SegmentDecrypter | None = None
if use_segment_decrypt and init_data:
decrypter = SegmentDecrypter(cast(SEGMENT_DRM_T, drm), init_data, save_dir.parent, ctx.max_workers)
rebase: PeriodRebase | None = None
known = timed and len(period_starts) > 1
timescale = mdhd_timescale(init_data) if known and init_data and not is_text_subtitle else None
if timescale:
rebase = PeriodRebase(period_starts, timescale)
@@ -756,8 +757,7 @@ class DASH:
with open(save_path, "r+b") as collapsed:
collapsed.truncate(collapse_span[1] + 1)
elif merger:
for control_file in save_dir.glob("*.!dev"):
control_file.unlink(missing_ok=True)
store.merging()
check_merged(merger, len(segments), track, ctx, "DASH")
else:
if not save_dir.exists():
@@ -776,8 +776,7 @@ class DASH:
)
raise FileNotFoundError(error_msg)
for control_file in save_dir.glob("*.!dev"):
control_file.unlink(missing_ok=True)
store.merging()
segments_to_merge = [x for x in sorted(save_dir.iterdir()) if x.is_file()]
@@ -813,7 +812,7 @@ class DASH:
)
raise FileNotFoundError(error_msg)
if known and is_text_subtitle and track.codec == Subtitle.Codec.WebVTT:
if rebase_vtt:
firsts = sorted(period_starts)
groups: list[list[Path]] = [[] for _ in firsts]
for segment_file in segments_to_merge:
+23 -31
View File
@@ -44,10 +44,10 @@ from unshackle.core.manifests.segment_pipeline import (
fetch_segments,
license_drm,
licensing,
remove_segment_dir,
)
from unshackle.core.session import RnetResponse, RnetSession, unrecorded, utf8_text
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video, resume
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video
from unshackle.core.tracks.segment_store import DownloadMode, SegmentStore
from unshackle.core.tracks.track import DRM_PREFERENCE_TYPES, Track, assert_fragments_decrypted
from unshackle.core.utilities import get_extension, is_close_match, log_event, try_ensure_utf8
from unshackle.core.utils import run_proxy
@@ -798,26 +798,28 @@ class HLS:
segment_save_dir = save_dir / "segments"
# no resume for AES-128/ClearKey: in-place decryption at merge time makes numbered files ambiguous
# per-segment decryption rewrites each segment in place, so a segment kept from an
# earlier run would either be decrypted twice or never at all
resumable_drm = (
not use_segment_decrypt
and not use_rolling_merge
and (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(
map_data: tuple[m3u8.model.InitializationSection, bytes] | None = None
if use_segment_decrypt or use_rolling_merge:
init_section = wanted_segments[0].init_section
init_content, _ = HLS.fetch_init_section(session, init_section, 0)
map_data = (init_section, init_content)
use_segment_decrypt = use_segment_decrypt and can_use(session_drm, config.decryption, init_content)
store = SegmentStore(track, save_dir)
store.open(
track.url,
[(url["url"], url["headers"].get("Range")) for url in urls],
# media_sequence feeds AES IVs; total_segments pins the OnSegmentFilter verdict (shifts every index)
extra=[str(getattr(master, "media_sequence", None) or 0), str(total_segments)],
mode=DownloadMode(
segment_decrypt=use_segment_decrypt,
rolling_merge=use_rolling_merge,
drm=session_drm,
aes128=any(key and key.method == "AES-128" for key in (master.keys or [])),
merge_rewrites=True,
),
)
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)
segment_save_dir.mkdir(exist_ok=True)
log_event(
"manifest_hls_download_start",
@@ -833,13 +835,7 @@ class HLS:
},
)
map_data: tuple[m3u8.model.InitializationSection, bytes] | None = None
segment_decrypter: SegmentDecrypter | None = None
if use_segment_decrypt or use_rolling_merge:
init_section = wanted_segments[0].init_section
init_content, _ = HLS.fetch_init_section(session, init_section, 0)
map_data = (init_section, init_content)
use_segment_decrypt = use_segment_decrypt and can_use(session_drm, config.decryption, init_content)
if use_segment_decrypt:
assert isinstance(session_drm, (Widevine, PlayReady, ClearKeyCENC))
segment_decrypter = SegmentDecrypter(session_drm, init_content, save_dir.parent, ctx.max_workers)
@@ -857,15 +853,11 @@ class HLS:
decrypter=segment_decrypter,
)
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)
store.merging()
if merger:
check_merged(merger, total_segments, track, ctx, "HLS")
remove_segment_dir(save_dir)
store.complete()
log_event(
"manifest_hls_download_complete",
level="DEBUG",
@@ -1164,7 +1156,7 @@ class HLS:
with suppress(OSError):
discontinuity_file.unlink()
remove_segment_dir(save_dir)
store.complete()
progress(downloaded="Downloaded", completed=100, total=100)
+5 -10
View File
@@ -37,7 +37,8 @@ from unshackle.core.manifests.segment_pipeline import (
license_drm,
)
from unshackle.core.session import RnetSession
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Track, Tracks, Video, resume
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Track, Tracks, Video
from unshackle.core.tracks.segment_store import DownloadMode, SegmentStore
from unshackle.core.utilities import log_event, try_ensure_utf8
from unshackle.core.utils import run_proxy
from unshackle.core.utils.redact import safe_display_url
@@ -426,15 +427,10 @@ class ISM:
progress(total=len(segments))
use_rolling_merge = config.merge_segments and not isinstance(track, Subtitle)
can_resume = config.continue_downloads and not use_rolling_merge
assert isinstance(track.url, str)
digest = resume.fingerprint(track.url, [(url, None) for url in segments])
if not (can_resume and resume.reusable(save_dir, digest)):
shutil.rmtree(save_dir, ignore_errors=True)
save_dir.mkdir(parents=True, exist_ok=True)
if can_resume:
resume.write_sidecar(save_dir, digest)
store = SegmentStore(track, save_dir)
store.open(track.url, [(url, None) for url in segments], mode=DownloadMode(rolling_merge=use_rolling_merge))
log_event(
"manifest_ism_download_start",
@@ -496,8 +492,7 @@ class ISM:
)
raise FileNotFoundError(error_msg)
for control_file in save_dir.glob("*.!dev"):
control_file.unlink(missing_ok=True)
store.merging()
if merger:
check_merged(merger, len(segments), track, ctx, "ISM")
+3 -13
View File
@@ -22,7 +22,8 @@ from unshackle.core.drm.verify import decrypt_track
from unshackle.core.events import events
from unshackle.core.remote_protocol import APIErrorCode, coded
from unshackle.core.session import AnySession
from unshackle.core.tracks import DownloadContext, Track, resume
from unshackle.core.tracks import DownloadContext, Track
from unshackle.core.tracks.segment_store import SegmentStore
from unshackle.core.tracks.track import assert_fragments_decrypted
from unshackle.core.utilities import log_event, try_ensure_utf8
@@ -243,15 +244,6 @@ def decrypt_output(track: AnyTrack, ctx: DownloadContext, drm: DRM_T, decrypt: b
events.emit(events.Types.TRACK_DECRYPTED, track=track, drm=drm, segment=None)
def remove_segment_dir(save_dir: Path) -> None:
"""Remove the segment directory, also when a superseded hedge download still dropped a .!dev file in it."""
if save_dir.exists() and save_dir.name.endswith("_segments"):
try:
save_dir.rmdir()
except OSError:
shutil.rmtree(save_dir, ignore_errors=True)
def complete_track(track: AnyTrack, ctx: DownloadContext, drm: DRM_T | None, decrypt: bool = True) -> None:
"""Hand the merged file to the track, decrypt it, and remove the segment directory."""
track.path = ctx.save_path
@@ -260,8 +252,7 @@ def complete_track(track: AnyTrack, ctx: DownloadContext, drm: DRM_T | None, dec
decrypt_output(track, ctx, drm, decrypt)
ctx.progress(downloaded="Decrypted", completed=100, total=100)
remove_segment_dir(ctx.save_dir)
resume.clear_sidecar(ctx.save_dir)
SegmentStore(track, ctx.save_dir).complete()
ctx.progress(downloaded="Downloaded")
@@ -274,5 +265,4 @@ __all__ = (
"fetch_segments",
"license_drm",
"licensing",
"remove_segment_dir",
)
-53
View File
@@ -1,9 +1,7 @@
from __future__ import annotations
import contextlib
import functools
import logging
import os
import shutil
import time
import uuid
@@ -85,57 +83,6 @@ def resume_stash() -> Path | None:
return None if root == config.directories.temp else root / RESUME_STASH
def _move_with_sidecar(source: Path, target: Path) -> bool:
"""Rename a segment dir, then its resume sidecar. False if the dir rename fails; a sidecar failure only logs."""
from unshackle.core.tracks import resume
try:
source.rename(target)
except OSError as e:
log.debug("Could not move %s: %s", source, e)
return False
sidecar = resume.sidecar_path(source)
try:
if sidecar.exists():
sidecar.replace(resume.sidecar_path(target))
except OSError as e:
log.debug("Could not move %s: %s", sidecar, e)
return True
def stash_segments(save_dir: Path) -> None:
"""Move save_dir and its resume sidecar into the stash. Leave them in place on any OS error."""
from unshackle.core.tracks import resume
stash = resume_stash()
if stash is None or not save_dir.is_dir():
return
target = stash / save_dir.name
try:
stash.mkdir(parents=True, exist_ok=True)
if target.exists():
return
except OSError as e:
log.debug("Could not stash %s: %s", save_dir, e)
return
if _move_with_sidecar(save_dir, target):
# rename keeps the old mtime, and the sweep ages entries by it
for path in (target, resume.sidecar_path(target)):
with contextlib.suppress(OSError):
os.utime(path)
def restore_segments(save_dir: Path) -> None:
"""Move a stashed save_dir and its sidecar back to save_dir, if the stash has them and save_dir is free."""
stash = resume_stash()
if stash is None:
return
source = stash / save_dir.name
if source.is_symlink() or not source.is_dir() or save_dir.exists():
return
_move_with_sidecar(source, save_dir)
@contextmanager
def task_temp_dir(task_id: str | None = None) -> Iterator[Path]:
"""Point config.directories.temp at a private dir for this task. Remove it on any exit."""
-84
View File
@@ -1,84 +0,0 @@
"""Cross-run segment-resume sidecars.
A later download can reuse a track's completed segment files, but only after
the manifest proves that the segmentation did not change. 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 they would concatenate any file left in there into the
final output.
"""
from __future__ import annotations
import hashlib
import json
from collections.abc import Sequence
from pathlib import Path
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: 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 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 download can prove that 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)
+253
View File
@@ -0,0 +1,253 @@
"""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.
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 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
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
log = logging.getLogger("track")
@dataclass(frozen=True)
class DownloadMode:
"""The final download mode of a track: what the resume verdict reads."""
segment_decrypt: bool = False
rolling_merge: bool = False
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 _sidecar(save_dir: Path) -> Path:
return save_dir.with_name(save_dir.name + ".resume.json")
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()
@property
def sidecar(self) -> Path:
return _sidecar(self.save_dir)
@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.
Segment decryption decrypts each segment in place, so a kept one would be decrypted twice or never.
A rolling merge unlinks each segment once it appends it, so nothing is left to reuse. 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.
"""
if not self.keeps or mode.segment_decrypt or mode.rolling_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)))
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.
"""
self.mode = mode
resumable = self.resumable(mode)
digest = fingerprint(manifest_url, segments, extra)
reused = resumable and self._recorded_digest() == digest
if not reused:
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
if resumable and (reused or not any(self.save_dir.iterdir())):
self.sidecar.write_text(json.dumps({"version": _VERSION, "digest": digest}), encoding="utf-8")
else:
self.sidecar.unlink(missing_ok=True)
return reused
def merging(self) -> None:
"""End the download phase: remove the .!dev files that superseded downloads left, so no merge reads one.
When the merge rewrites segments in place (every HLS merge, the WebVTT rebase of a multi-period DASH
subtitle), the sidecar goes now. 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.merge_rewrites:
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()
def abandon(self) -> None:
"""Clean up a failed or cancelled download and stash the directory when it keeps its segments.
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.
"""
with contextlib.suppress(OSError):
self._sweep()
if self.keeps:
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 _recorded_digest(self) -> str | None:
"""The digest in the sidecar; None when it is missing, unreadable or malformed."""
try:
data = json.loads(self.sidecar.read_text(encoding="utf-8"))
return data.get("digest") or None
except (OSError, ValueError, AttributeError):
return None
def _sweep(self) -> None:
"""Keep only completed segments and the sidecar when the directory is kept, else remove both."""
if not self._owned:
return
if self.keeps:
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 _move(self, target: Path) -> bool:
"""Rename the directory, then its sidecar. False if the directory rename fails; a sidecar failure only logs."""
try:
self.save_dir.rename(target)
except OSError as e:
log.debug("Could not move %s: %s", self.save_dir, e)
return False
try:
if self.sidecar.exists():
self.sidecar.replace(_sidecar(target))
except OSError as e:
log.debug("Could not move %s: %s", self.sidecar, e)
return True
def _stash(self) -> None:
"""Move the directory and its sidecar into the stash. Leave them in place on any OS error."""
stash = resume_stash()
if stash is None or not self.save_dir.is_dir():
return
target = stash / self.save_dir.name
try:
stash.mkdir(parents=True, exist_ok=True)
if target.exists():
return
except OSError as e:
log.debug("Could not stash %s: %s", self.save_dir, e)
return
if self._move(target):
# rename keeps the old mtime, and the stash sweep ages entries by it
for path in (target, _sidecar(target)):
with contextlib.suppress(OSError):
os.utime(path)
def _unstash(self) -> None:
"""Move a stashed directory and its sidecar back, if the stash has them and the directory is free."""
stash = resume_stash()
if stash is None:
return
stashed = SegmentStore(self.track, stash / self.save_dir.name)
if stashed.save_dir.is_symlink() or not stashed.save_dir.is_dir() or self.save_dir.exists():
return
stashed._move(self.save_dir)
+7 -29
View File
@@ -40,8 +40,7 @@ from unshackle.core.drm.verify import (
)
from unshackle.core.events import events
from unshackle.core.session import MAX_BACKOFF, AnySession, RnetSession, unrecorded, utf8_text
from unshackle.core.temp import restore_segments, stash_segments
from unshackle.core.tracks import resume
from unshackle.core.tracks.segment_store import SegmentStore
from unshackle.core.utilities import language_name, log_event, try_ensure_utf8
from unshackle.core.utils import run_proxy
from unshackle.core.utils.subprocess import run_tool
@@ -774,31 +773,13 @@ class Track:
else:
save_dir = save_path.parent
keep_segments = config.continue_downloads and self.descriptor != self.Descriptor.URL
def cleanup() -> None:
save_path.unlink(missing_ok=True)
if save_dir.name.endswith("_segments"):
if keep_segments:
if save_dir.exists():
for partial in save_dir.rglob("*.!dev"):
partial.with_name(partial.name.removesuffix(".!dev")).unlink(missing_ok=True)
partial.unlink(missing_ok=True)
else:
if save_dir.exists():
shutil.rmtree(save_dir)
resume.clear_sidecar(save_dir)
store = SegmentStore(self, save_dir)
def abandon() -> None:
"""Clean up a failed or cancelled download and stash its segments when resume is on.
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 download's own error.
"""
"""Remove the output of a failed or cancelled download; a cleanup error must not replace its error."""
with contextlib.suppress(OSError):
cleanup()
if keep_segments:
stash_segments(save_dir)
save_path.unlink(missing_ok=True)
store.abandon()
if not DOWNLOAD_LICENCE_ONLY.is_set():
if config.directories.temp.is_file():
@@ -806,11 +787,8 @@ class Track:
config.directories.temp.mkdir(parents=True, exist_ok=True)
# completed segments are reusable once the parser proves the segmentation
# unchanged (resume sidecar); partial .!dev files never survive a run boundary
if keep_segments:
restore_segments(save_dir)
cleanup()
save_path.unlink(missing_ok=True)
store.restore()
try:
manifest_parsers: dict[Track.Descriptor, type[DASH] | type[HLS] | type[ISM]] = {