mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-24 09:55:12 +00:00
feat(dl): keep failed track segments across runs in a resume stash
Stash a failed or cancelled track's segments outside the task temp dir and restore them on the next download. Also drop a pre-sized data file with its .!dev control file.
This commit is contained in:
+84
-1
@@ -1,6 +1,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import functools
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
import uuid
|
||||
@@ -15,6 +18,10 @@ from unshackle.core.config import config
|
||||
TASK_PREFIX = "task_"
|
||||
LOCK_NAME = ".lock"
|
||||
STALE_GRACE = 60.0
|
||||
RESUME_STASH = "resume"
|
||||
STASH_MAX_AGE = 7 * 24 * 3600
|
||||
|
||||
log = logging.getLogger("temp")
|
||||
|
||||
P = ParamSpec("P")
|
||||
R = TypeVar("R")
|
||||
@@ -40,13 +47,89 @@ def is_stale(task_dir: Path) -> bool:
|
||||
|
||||
|
||||
def sweep_task_dirs(root: Path) -> None:
|
||||
"""Remove task dirs left by processes that died without cleaning up."""
|
||||
"""Remove task dirs left by processes that died without cleaning up, and resume stash entries past their age."""
|
||||
if not root.is_dir():
|
||||
return
|
||||
for entry in root.iterdir():
|
||||
if entry.is_dir() and not entry.is_symlink() and entry.name.startswith(TASK_PREFIX) and is_stale(entry):
|
||||
shutil.rmtree(entry, ignore_errors=True)
|
||||
|
||||
stash = root / RESUME_STASH
|
||||
if stash.is_dir():
|
||||
cutoff = time.time() - STASH_MAX_AGE
|
||||
for entry in stash.iterdir():
|
||||
try:
|
||||
if entry.stat().st_mtime > cutoff:
|
||||
continue
|
||||
except OSError:
|
||||
continue
|
||||
if entry.is_dir() and not entry.is_symlink():
|
||||
shutil.rmtree(entry, ignore_errors=True)
|
||||
else:
|
||||
entry.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def resume_stash() -> Optional[Path]:
|
||||
"""The dir beside the task dirs that keeps a failed track's segments for the next run.
|
||||
|
||||
None outside a task dir: there config.directories.temp itself outlives the run.
|
||||
"""
|
||||
temp = config.directories.temp
|
||||
if not temp.name.startswith(TASK_PREFIX):
|
||||
return None
|
||||
return temp.parent / 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: Optional[str] = None) -> Iterator[Path]:
|
||||
|
||||
@@ -32,6 +32,7 @@ from unshackle.core.drm import DRM_T, ClearKeyCENC, PlayReady, Widevine
|
||||
from unshackle.core.drm.verify import decrypt_track
|
||||
from unshackle.core.events import events
|
||||
from unshackle.core.session import MAX_BACKOFF, RnetSession, utf8_text
|
||||
from unshackle.core.temp import restore_segments, stash_segments
|
||||
from unshackle.core.tracks import resume
|
||||
from unshackle.core.utilities import get_boxes, log_event, try_ensure_utf8
|
||||
from unshackle.core.utils import run_proxy
|
||||
@@ -760,6 +761,7 @@ class Track:
|
||||
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():
|
||||
@@ -774,6 +776,8 @@ class Track:
|
||||
|
||||
# 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()
|
||||
|
||||
try:
|
||||
@@ -925,6 +929,8 @@ class Track:
|
||||
except DownloadCancelled:
|
||||
try:
|
||||
cleanup()
|
||||
if keep_segments:
|
||||
stash_segments(save_dir)
|
||||
except OSError:
|
||||
pass
|
||||
progress(downloaded="[yellow]SKIPPED")
|
||||
@@ -932,6 +938,8 @@ class Track:
|
||||
except (Exception, KeyboardInterrupt):
|
||||
if not DOWNLOAD_LICENCE_ONLY.is_set():
|
||||
cleanup()
|
||||
if keep_segments:
|
||||
stash_segments(save_dir)
|
||||
raise
|
||||
|
||||
if DOWNLOAD_CANCELLED.is_set():
|
||||
|
||||
Reference in New Issue
Block a user