mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-25 02:15:08 +00:00
Merge pull request #116 from avi-dev-user/subtitle-nonfatal
fix(dl): make a failed subtitle non-fatal under --skip-subtitle-errors
This commit is contained in:
+121
-37
@@ -11,6 +11,7 @@ import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import Iterable
|
||||
from concurrent import futures
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from copy import deepcopy
|
||||
@@ -19,7 +20,7 @@ from http.cookiejar import CookieJar, MozillaCookieJar
|
||||
from itertools import product
|
||||
from pathlib import Path
|
||||
from threading import Lock
|
||||
from typing import Any, Callable, Optional
|
||||
from typing import Any, Callable, Optional, TypedDict
|
||||
from uuid import UUID
|
||||
|
||||
import click
|
||||
@@ -42,7 +43,7 @@ from unshackle.core.cdm import DecryptLabsRemoteCDM
|
||||
from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.console import console
|
||||
from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY, AnyTrack, context_settings
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, AnyTrack, context_settings
|
||||
from unshackle.core.credential import Credential
|
||||
from unshackle.core.drm import DRM_T, MonaLisa, PlayReady, Widevine
|
||||
from unshackle.core.events import events
|
||||
@@ -70,6 +71,59 @@ from unshackle.core.utils.subprocess import ffprobe
|
||||
from unshackle.core.vaults import Vaults
|
||||
|
||||
|
||||
class SkippedSubtitle(TypedDict):
|
||||
"""A subtitle skipped under ``--skip-subtitle-errors``. Accumulated as ``dl.skipped_subtitles``,
|
||||
one entry per track; ``id`` and ``title`` identify which subtitle of which title was unavailable."""
|
||||
|
||||
id: str
|
||||
language: str
|
||||
title: str
|
||||
|
||||
|
||||
def download_tracks_in_passes(
|
||||
tracks: Iterable[AnyTrack],
|
||||
max_concurrent: int,
|
||||
run_one: Callable[[AnyTrack, int], None],
|
||||
*,
|
||||
skip_subtitle_errors: bool,
|
||||
on_subtitle_skipped: Callable[[Subtitle], None],
|
||||
) -> None:
|
||||
"""Download a title's tracks so a skippable subtitle failure can't corrupt the rest.
|
||||
|
||||
A failed track sets the process-global ``DOWNLOAD_CANCELLED`` event, making other in-flight
|
||||
tracks early-return without raising. With ``skip_subtitle_errors`` set, video/audio download
|
||||
concurrently first; the subtitles then run one at a time (a concurrent pass would let one
|
||||
failure's cancel silently drop the others, unrecorded), with the event cleared before each.
|
||||
Video/audio failures stay fatal. The event is cleared on entry (stale cancel from a prior
|
||||
title) and in ``finally`` (never leave it set for later code).
|
||||
|
||||
``run_one(track, index)`` downloads a single track; ``on_subtitle_skipped(track)`` records a
|
||||
subtitle whose download raised (handled here).
|
||||
"""
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
indexed = list(enumerate(tracks))
|
||||
if skip_subtitle_errors:
|
||||
primary = [(i, t) for i, t in indexed if not isinstance(t, Subtitle)]
|
||||
skippable = [(i, t) for i, t in indexed if isinstance(t, Subtitle)]
|
||||
else:
|
||||
primary, skippable = indexed, []
|
||||
|
||||
try:
|
||||
with ThreadPoolExecutor(max_concurrent) as pool:
|
||||
future_to_track = {pool.submit(run_one, track, i): track for i, track in primary}
|
||||
for download in futures.as_completed(future_to_track):
|
||||
download.result() # a video/audio failure is fatal
|
||||
|
||||
for i, track in skippable:
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
try:
|
||||
run_one(track, i)
|
||||
except Exception:
|
||||
on_subtitle_skipped(track)
|
||||
finally:
|
||||
DOWNLOAD_CANCELLED.clear() # never leave a failed track's cancel set for later code
|
||||
|
||||
|
||||
class dl:
|
||||
@staticmethod
|
||||
def truncate_pssh_for_display(pssh_string: str, drm_type: str) -> str:
|
||||
@@ -474,6 +528,9 @@ class dl:
|
||||
@click.option("-S", "--subs-only", is_flag=True, default=False, help="Only download subtitle tracks.")
|
||||
@click.option("-C", "--chapters-only", is_flag=True, default=False, help="Only download chapter markers.")
|
||||
@click.option("-ns", "--no-subs", is_flag=True, default=False, help="Do not download subtitle tracks.")
|
||||
@click.option("--skip-subtitle-errors", is_flag=True, default=False,
|
||||
help="If a subtitle track fails to download, skip it and continue instead of "
|
||||
"aborting the whole title (video/audio failures stay fatal).")
|
||||
@click.option("-na", "--no-audio", is_flag=True, default=False, help="Do not download audio tracks.")
|
||||
@click.option("-nc", "--no-chapters", is_flag=True, default=False, help="Do not download chapter markers.")
|
||||
@click.option("-nv", "--no-video", is_flag=True, default=False, help="Do not download video tracks.")
|
||||
@@ -609,6 +666,9 @@ class dl:
|
||||
|
||||
self.log = logging.getLogger("download")
|
||||
self.completed_files: list[Path] = []
|
||||
# Subtitles skipped under --skip-subtitle-errors, recorded so an embedding caller can
|
||||
# report which weren't available without parsing the console output. See SkippedSubtitle.
|
||||
self.skipped_subtitles: list[SkippedSubtitle] = []
|
||||
|
||||
if not config.output_template:
|
||||
raise click.ClickException(
|
||||
@@ -1051,6 +1111,7 @@ class dl:
|
||||
subs_only: bool,
|
||||
chapters_only: bool,
|
||||
no_subs: bool,
|
||||
skip_subtitle_errors: bool,
|
||||
no_audio: bool,
|
||||
no_chapters: bool,
|
||||
no_video: bool,
|
||||
@@ -2181,41 +2242,64 @@ class dl:
|
||||
|
||||
try:
|
||||
with Live(Padding(download_table, (1, 5)), console=console, refresh_per_second=5):
|
||||
with ThreadPoolExecutor(downloads) as pool:
|
||||
for download in futures.as_completed(
|
||||
(
|
||||
pool.submit(
|
||||
track.download,
|
||||
session=track.session or service.session,
|
||||
no_proxy_download=no_proxy_download,
|
||||
prepare_drm=partial(
|
||||
partial(self.prepare_drm, table=download_table),
|
||||
track=track,
|
||||
title=title,
|
||||
certificate=partial(
|
||||
service.get_widevine_service_certificate,
|
||||
title=title,
|
||||
track=track,
|
||||
),
|
||||
licence=partial(
|
||||
service.get_playready_license
|
||||
if is_playready_cdm(self.cdm)
|
||||
else service.get_widevine_license,
|
||||
title=title,
|
||||
track=track,
|
||||
),
|
||||
cdm_only=cdm_only,
|
||||
vaults_only=vaults_only,
|
||||
export=export_path,
|
||||
),
|
||||
cdm=self.cdm,
|
||||
max_workers=workers,
|
||||
progress=tracks_progress_callables[i],
|
||||
)
|
||||
for i, track in enumerate(title.tracks)
|
||||
)
|
||||
):
|
||||
download.result()
|
||||
|
||||
def download_track(track: AnyTrack, i: int) -> None:
|
||||
track.download(
|
||||
session=track.session or service.session,
|
||||
no_proxy_download=no_proxy_download,
|
||||
prepare_drm=partial(
|
||||
partial(self.prepare_drm, table=download_table),
|
||||
track=track,
|
||||
title=title,
|
||||
certificate=partial(
|
||||
service.get_widevine_service_certificate,
|
||||
title=title,
|
||||
track=track,
|
||||
),
|
||||
licence=partial(
|
||||
service.get_playready_license
|
||||
if is_playready_cdm(self.cdm)
|
||||
else service.get_widevine_license,
|
||||
title=title,
|
||||
track=track,
|
||||
),
|
||||
cdm_only=cdm_only,
|
||||
vaults_only=vaults_only,
|
||||
export=export_path,
|
||||
),
|
||||
cdm=self.cdm,
|
||||
max_workers=workers,
|
||||
progress=tracks_progress_callables[i],
|
||||
)
|
||||
|
||||
def on_subtitle_skipped(track: Subtitle) -> None:
|
||||
lang = str(track.language)
|
||||
self.log.warning(f"Subtitle {lang} failed to download, skipping it.")
|
||||
self.skipped_subtitles.append(SkippedSubtitle(id=track.id, language=lang, title=str(title)))
|
||||
try:
|
||||
title.tracks.subtitles.remove(track)
|
||||
except ValueError:
|
||||
self.log.debug(f"Skipped subtitle {track.id} was already absent from the track list.")
|
||||
|
||||
skipped_before = len(self.skipped_subtitles)
|
||||
download_tracks_in_passes(
|
||||
title.tracks,
|
||||
downloads,
|
||||
download_track,
|
||||
skip_subtitle_errors=skip_subtitle_errors,
|
||||
on_subtitle_skipped=on_subtitle_skipped,
|
||||
)
|
||||
|
||||
if (
|
||||
len(self.skipped_subtitles) > skipped_before
|
||||
and not title.tracks.videos
|
||||
and not title.tracks.audio
|
||||
and not title.tracks.subtitles
|
||||
):
|
||||
self.log.warning(
|
||||
f"{title}: all subtitles were skipped and no video or audio was "
|
||||
"downloaded - nothing was produced for this title."
|
||||
)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
console.print(Padding(":x: Download Cancelled...", (0, 5, 1, 5)))
|
||||
|
||||
Reference in New Issue
Block a user