forked from kenzuya/unshackle
refactor(tracks): make complete_track the one finish step for every track kind
This commit is contained in:
@@ -39,8 +39,9 @@ from unshackle.core.events import events
|
||||
from unshackle.core.manifests.dash import PeriodRebase, mdhd_timescale, missing_language, rebase_webvtt_files
|
||||
from unshackle.core.manifests.segment_pipeline import (
|
||||
append_segment,
|
||||
check_decrypted,
|
||||
check_merged,
|
||||
decrypt_output,
|
||||
complete_track,
|
||||
fetch_segments,
|
||||
license_drm,
|
||||
licensing,
|
||||
@@ -48,7 +49,7 @@ from unshackle.core.manifests.segment_pipeline import (
|
||||
from unshackle.core.session import RnetResponse, RnetSession, unrecorded, utf8_text
|
||||
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.tracks.track import DRM_PREFERENCE_TYPES, Track
|
||||
from unshackle.core.utilities import get_extension, is_close_match, log_event, try_ensure_utf8
|
||||
from unshackle.core.utils import run_proxy
|
||||
from unshackle.core.utils.redact import safe_display_url
|
||||
@@ -871,10 +872,7 @@ class HLS:
|
||||
"downloader": "requests",
|
||||
},
|
||||
)
|
||||
if session_drm:
|
||||
decrypt_output(track, ctx, session_drm, decrypt=not segment_decrypter)
|
||||
progress(downloaded="Downloaded", completed=100, total=100)
|
||||
track.path = save_path
|
||||
complete_track(track, ctx, session_drm, decrypt=not segment_decrypter)
|
||||
return
|
||||
|
||||
progress(total=total_segments, completed=0, downloaded="Merging")
|
||||
@@ -969,7 +967,7 @@ class HLS:
|
||||
map_data = (map_data[0], decrypted_init)
|
||||
merge(to=merged_path, via=files, delete=True, include_map_data=True)
|
||||
decrypt_track(drm, merged_path, license_widevine, decrypt=not segment_decrypter, track=track)
|
||||
assert_fragments_decrypted(merged_path)
|
||||
check_decrypted(track, merged_path, drm)
|
||||
merged_path.rename(decrypted_path)
|
||||
else:
|
||||
# AES segments must be decrypted individually before merging: each segment
|
||||
@@ -1161,12 +1159,9 @@ class HLS:
|
||||
|
||||
store.complete()
|
||||
|
||||
progress(downloaded="Downloaded", completed=100, total=100)
|
||||
|
||||
track.path = save_path
|
||||
|
||||
if session_drm:
|
||||
track.drm = None
|
||||
complete_track(track, ctx, None)
|
||||
|
||||
@staticmethod
|
||||
def discontinuity_starts(wanted_segments: list[Any]) -> list[float]:
|
||||
|
||||
@@ -16,9 +16,10 @@ from typing import Any, BinaryIO
|
||||
from uuid import UUID
|
||||
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED, AnyTrack
|
||||
from unshackle.core.drm import DRM_T, ClearKeyCENC, ClearKeyCTR, MonaLisa, PlayReady, Widevine
|
||||
from unshackle.core.drm import DRM_T, WHOLE_FILE_DRM, ClearKeyCENC, ClearKeyCTR, MonaLisa, PlayReady, Widevine, cbcs
|
||||
from unshackle.core.drm.cbcs import SampleDecrypter
|
||||
from unshackle.core.drm.segment_decrypt import SegmentDecrypter
|
||||
from unshackle.core.drm.verify import decrypt_track
|
||||
from unshackle.core.drm.verify import decrypt_track, has_encrypted_sample_entry
|
||||
from unshackle.core.events import events
|
||||
from unshackle.core.remote_protocol import APIErrorCode, coded
|
||||
from unshackle.core.session import AnySession
|
||||
@@ -28,17 +29,21 @@ from unshackle.core.tracks.track import assert_fragments_decrypted
|
||||
from unshackle.core.utilities import log_event, try_ensure_utf8
|
||||
|
||||
|
||||
def text_subtitle_bytes(data: bytes) -> bytes:
|
||||
"""`data` as UTF-8, with the ‎ and ‏ entities as their characters."""
|
||||
return (
|
||||
try_ensure_utf8(data)
|
||||
.decode("utf8")
|
||||
.replace("‎", html.unescape("‎"))
|
||||
.replace("‏", html.unescape("‏"))
|
||||
.encode("utf8")
|
||||
)
|
||||
|
||||
|
||||
def append_segment(dst: BinaryIO, segment_file: Path, is_text_subtitle: bool) -> None:
|
||||
"""Append one segment file to the output, with the text subtitle fixups when they apply."""
|
||||
if is_text_subtitle:
|
||||
segment_data = try_ensure_utf8(segment_file.read_bytes())
|
||||
segment_data = (
|
||||
segment_data.decode("utf8")
|
||||
.replace("‎", html.unescape("‎"))
|
||||
.replace("‏", html.unescape("‏"))
|
||||
.encode("utf8")
|
||||
)
|
||||
dst.write(segment_data)
|
||||
dst.write(text_subtitle_bytes(segment_file.read_bytes()))
|
||||
else:
|
||||
with open(segment_file, "rb") as src:
|
||||
shutil.copyfileobj(src, dst, 1024 * 1024)
|
||||
@@ -256,36 +261,70 @@ def check_merged(merger: RollingMerge, total: int, track: AnyTrack, ctx: Downloa
|
||||
raise FileNotFoundError(error_msg)
|
||||
|
||||
|
||||
def decrypt_output(track: AnyTrack, ctx: DownloadContext, drm: DRM_T, decrypt: bool = True) -> None:
|
||||
"""Decrypt ctx.save_path through decrypt_track, check every fragment, and emit TRACK_DECRYPTED.
|
||||
def check_decrypted(track: AnyTrack, path: Path, drm: DRM_T | None) -> None:
|
||||
"""Raise if a fragment of `path` still carries encryption, and mark the track for a repack when its moov does.
|
||||
|
||||
A whole-file cipher leaves no fragments to check. An encrypted sample entry that survives the decrypt
|
||||
would lock the muxer to a generic codec.
|
||||
"""
|
||||
if not isinstance(drm, WHOLE_FILE_DRM):
|
||||
assert_fragments_decrypted(path)
|
||||
if has_encrypted_sample_entry(path):
|
||||
track.needs_repack = True
|
||||
|
||||
|
||||
def decrypt_output(
|
||||
track: AnyTrack, ctx: DownloadContext, drm: DRM_T, decrypt: bool = True, kid: UUID | None = None
|
||||
) -> None:
|
||||
"""Decrypt ctx.save_path through decrypt_track, check it, and emit TRACK_DECRYPTED.
|
||||
|
||||
`decrypt=False` means a SegmentDecrypter already decrypted the segments, so only the check runs.
|
||||
"""
|
||||
ctx.progress(downloaded="Decrypting", completed=0, total=None)
|
||||
decrypt_track(drm, ctx.save_path, ctx.license_widevine, decrypt=decrypt, track=track)
|
||||
assert_fragments_decrypted(ctx.save_path)
|
||||
decrypt_track(drm, ctx.save_path, ctx.license_widevine, kid, decrypt=decrypt, track=track)
|
||||
check_decrypted(track, ctx.save_path, drm)
|
||||
track.drm = None
|
||||
events.emit(events.Types.TRACK_DECRYPTED, track=track, drm=drm, segment=None)
|
||||
|
||||
|
||||
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."""
|
||||
def decrypt_samples(track: AnyTrack, ctx: DownloadContext, decrypter: Callable[[int], bytes | SampleDecrypter]) -> None:
|
||||
"""Decrypt ctx.save_path with the service sample decrypter, check it, and emit TRACK_DECRYPTED with no DRM."""
|
||||
cbcs.decrypt_file(ctx.save_path, lambda _layout, entry: decrypter(entry.index))
|
||||
check_decrypted(track, ctx.save_path, None)
|
||||
events.emit(events.Types.TRACK_DECRYPTED, track=track, drm=None, segment=None)
|
||||
|
||||
|
||||
def complete_track(
|
||||
track: AnyTrack, ctx: DownloadContext, drm: DRM_T | None, decrypt: bool = True, kid: UUID | None = None
|
||||
) -> None:
|
||||
"""Hand the merged file to the track, decrypt it, and remove the segment directory.
|
||||
|
||||
The track decrypts with `drm` (key ID `kid`), with the service sample decrypter of ctx, or both.
|
||||
"""
|
||||
track.path = ctx.save_path
|
||||
|
||||
samples = None if DOWNLOAD_CANCELLED.is_set() else ctx.sample_decrypter
|
||||
if drm or samples:
|
||||
ctx.progress(downloaded="Decrypting", completed=0, total=None)
|
||||
if drm:
|
||||
decrypt_output(track, ctx, drm, decrypt)
|
||||
decrypt_output(track, ctx, drm, decrypt, kid)
|
||||
if samples:
|
||||
decrypt_samples(track, ctx, samples)
|
||||
if drm or samples:
|
||||
ctx.progress(downloaded="Decrypted", completed=100, total=100)
|
||||
|
||||
SegmentStore(track, ctx.save_dir).complete()
|
||||
ctx.progress(downloaded="Downloaded")
|
||||
ctx.progress(downloaded="Downloaded", completed=100, total=100)
|
||||
|
||||
|
||||
__all__ = (
|
||||
"RollingMerge",
|
||||
"append_segment",
|
||||
"check_decrypted",
|
||||
"check_merged",
|
||||
"text_subtitle_bytes",
|
||||
"complete_track",
|
||||
"decrypt_output",
|
||||
"decrypt_samples",
|
||||
"fetch_segments",
|
||||
"license_drm",
|
||||
"licensing",
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
"""The download step of a URL track: one file, fetched whole or cut to the sample window."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import logging
|
||||
import shutil
|
||||
|
||||
import click
|
||||
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import (
|
||||
DOWNLOAD_ALL_DRM,
|
||||
DOWNLOAD_CANCELLED,
|
||||
DOWNLOAD_LICENCE_ONLY,
|
||||
AnyTrack,
|
||||
DownloadCancelled,
|
||||
)
|
||||
from unshackle.core.drm import WHOLE_FILE_DRM, PlayReady, Widevine
|
||||
from unshackle.core.manifests.segment_pipeline import complete_track, license_drm, text_subtitle_bytes
|
||||
from unshackle.core.session import AnySession
|
||||
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Video
|
||||
|
||||
|
||||
def download_track(track: AnyTrack, ctx: DownloadContext, session: AnySession) -> None:
|
||||
"""Find the DRM of the track, license it, download the file and hand it to complete_track.
|
||||
|
||||
`session` reads the init and the KID, ctx.session downloads the file. A failure shows FAILED and cancels
|
||||
the pending track downloads.
|
||||
"""
|
||||
log = logging.getLogger("track")
|
||||
progress = ctx.progress
|
||||
save_path = ctx.save_path
|
||||
media = isinstance(track, (Video, Audio))
|
||||
try:
|
||||
track.ensure_url()
|
||||
if (
|
||||
DOWNLOAD_ALL_DRM.is_set()
|
||||
and media
|
||||
and not {Widevine, PlayReady} <= {type(d) for d in track.drm or []}
|
||||
and all(type(d) in (Widevine, PlayReady) for d in track.drm or [])
|
||||
):
|
||||
track.add_init_drm(track.get_init_segment(session=session), ctx.cdm)
|
||||
elif not track.drm and media:
|
||||
track.drm_from_pssh(ctx.cdm, lambda system: system.from_track(track, session), log)
|
||||
|
||||
drm = track.get_drm_for_cdm(ctx.cdm) if track.drm else None
|
||||
track_kid = track.get_key_id(session=session) if drm and not isinstance(drm, WHOLE_FILE_DRM) else None
|
||||
if drm:
|
||||
license_drm(track, drm, ctx, track_kid)
|
||||
|
||||
if DOWNLOAD_LICENCE_ONLY.is_set():
|
||||
progress(downloaded="[yellow]SKIPPED")
|
||||
return
|
||||
|
||||
dl_session = ctx.ensure_session()
|
||||
sample_range = None
|
||||
if config.sample and media:
|
||||
sample_range = track.sample_byte_range(dl_session)
|
||||
if not sample_range:
|
||||
raise click.ClickException("--sample cannot cut this track: it is one file with no segment index.")
|
||||
for status_update in track.downloader(
|
||||
urls=[{"url": track.url, "headers": {"Range": f"bytes={sample_range[1]}"}}] if sample_range else track.url,
|
||||
output_dir=save_path.parent,
|
||||
filename=save_path.name,
|
||||
headers=dl_session.headers,
|
||||
cookies=dl_session.cookies,
|
||||
proxy=ctx.proxy,
|
||||
max_workers=ctx.max_workers,
|
||||
session=dl_session,
|
||||
adaptive=ctx.adaptive_workers,
|
||||
processes=ctx.download_processes,
|
||||
):
|
||||
if not status_update.get("file_downloaded"):
|
||||
downloaded = status_update.get("downloaded")
|
||||
if downloaded and downloaded.endswith("/s"):
|
||||
status_update["downloaded"] = f"URL {downloaded}"
|
||||
progress(**status_update)
|
||||
|
||||
if sample_range:
|
||||
media_path = save_path.with_name(f"{save_path.name}.media")
|
||||
save_path.replace(media_path)
|
||||
with save_path.open("wb") as joined, media_path.open("rb") as body:
|
||||
joined.write(sample_range[0])
|
||||
shutil.copyfileobj(body, joined)
|
||||
with contextlib.suppress(OSError):
|
||||
media_path.unlink()
|
||||
|
||||
complete_track(track, ctx, drm, kid=track_kid)
|
||||
|
||||
if isinstance(track, Subtitle) and track.codec and track.codec.name not in ("fVTT", "fTTML"):
|
||||
save_path.write_bytes(text_subtitle_bytes(save_path.read_bytes()))
|
||||
except KeyboardInterrupt:
|
||||
DOWNLOAD_CANCELLED.set()
|
||||
progress(downloaded="[yellow]CANCELLED")
|
||||
raise
|
||||
except DownloadCancelled:
|
||||
raise
|
||||
except Exception:
|
||||
DOWNLOAD_CANCELLED.set()
|
||||
progress(downloaded="[red]FAILED")
|
||||
raise
|
||||
|
||||
|
||||
__all__ = ("download_track",)
|
||||
@@ -4,7 +4,9 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from abc import ABCMeta, abstractmethod
|
||||
from collections.abc import Callable
|
||||
from enum import Enum
|
||||
from functools import partial
|
||||
from http.cookiejar import CookieJar
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, NamedTuple, Protocol
|
||||
@@ -249,11 +251,15 @@ class TitleSource(metaclass=ABCMeta):
|
||||
def get_sample_decrypter(self, track: AnyTrack, entry: int) -> bytes | SampleDecrypter:
|
||||
"""The content key, or a `cbcs.SampleDecrypter`, for `stsd` entry `entry` (1-based) of `track`.
|
||||
|
||||
unshackle calls this only for a track `decrypts_samples` names. A remote session runs it on the
|
||||
server, so a decrypter that needs a local process works for remote clients too.
|
||||
unshackle calls this only for a track `decrypts_samples` names, before TRACK_DOWNLOADED. A remote session
|
||||
runs it on the server, so a decrypter that needs a local process works for remote clients too.
|
||||
"""
|
||||
raise NotImplementedError(f"{self.__class__.__name__} does not decrypt samples")
|
||||
|
||||
def sample_decrypter(self, track: AnyTrack) -> Callable[[int], bytes | SampleDecrypter] | None:
|
||||
"""`get_sample_decrypter` for `track`, when `decrypts_samples` names it."""
|
||||
return partial(self.get_sample_decrypter, track) if self.decrypts_samples(track) else None
|
||||
|
||||
# Optional Event methods
|
||||
|
||||
def on_segment_downloaded(self, track: AnyTrack, segment: Path) -> None:
|
||||
@@ -267,20 +273,20 @@ class TitleSource(metaclass=ABCMeta):
|
||||
|
||||
def on_track_downloaded(self, track: AnyTrack) -> None:
|
||||
"""
|
||||
Called once when a Track has finished downloading, after unshackle decrypted its `drm`.
|
||||
Called once when a Track has finished downloading, after unshackle decrypted it.
|
||||
In a licence-only run the track has no file.
|
||||
|
||||
Parameters:
|
||||
track: The downloaded Track object.
|
||||
"""
|
||||
|
||||
def on_track_decrypted(self, track: AnyTrack, drm: DRM_T, segment: m3u8.Segment | None = None) -> None:
|
||||
def on_track_decrypted(self, track: AnyTrack, drm: DRM_T | None, segment: m3u8.Segment | None = None) -> None:
|
||||
"""
|
||||
Called when a Track has finished decrypting.
|
||||
|
||||
Parameters:
|
||||
track: The decrypted Track object.
|
||||
drm: The DRM object it decrypted with.
|
||||
drm: The DRM object it decrypted with. None for a track `get_sample_decrypter` decrypted.
|
||||
segment: The decrypted HLS segment information. None for DASH and ISM tracks and
|
||||
for an HLS track that merged during the download (merge_segments).
|
||||
"""
|
||||
|
||||
@@ -22,6 +22,7 @@ from subtitle_filter import Subtitles
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.drm.cbcs import SampleDecrypter
|
||||
from unshackle.core.session import AnySession
|
||||
from unshackle.core.tracks.track import Track
|
||||
from unshackle.core.utilities import PYMP4_LOCK, try_ensure_utf8, with_script
|
||||
@@ -245,6 +246,7 @@ class Subtitle(Track):
|
||||
adaptive_workers: bool = False,
|
||||
download_processes: int = 1,
|
||||
on_segments: Callable[[Track, list[Any]], None] | None = None,
|
||||
sample_decrypter: Callable[[int], bytes | SampleDecrypter] | None = None,
|
||||
) -> None:
|
||||
super().download(
|
||||
session,
|
||||
@@ -257,6 +259,7 @@ class Subtitle(Track):
|
||||
adaptive_workers=adaptive_workers,
|
||||
download_processes=download_processes,
|
||||
on_segments=on_segments,
|
||||
sample_decrypter=sample_decrypter,
|
||||
)
|
||||
if not self.path:
|
||||
return
|
||||
|
||||
+13
-107
@@ -1,5 +1,4 @@
|
||||
import contextlib
|
||||
import html
|
||||
import logging
|
||||
import re
|
||||
import shutil
|
||||
@@ -25,15 +24,14 @@ from requests.adapters import HTTPAdapter, Retry
|
||||
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_ALL_DRM, DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, DownloadCancelled
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, DownloadCancelled
|
||||
from unshackle.core.downloaders.requests import requests
|
||||
from unshackle.core.drm import DRM_T, WHOLE_FILE_DRM, PlayReady, Widevine
|
||||
from unshackle.core.drm import DRM_T, PlayReady, Widevine
|
||||
from unshackle.core.drm.cbcs import SampleDecrypter
|
||||
from unshackle.core.drm.cenc import cenc_key, init_kid
|
||||
from unshackle.core.drm.verify import (
|
||||
children,
|
||||
decrypt_track,
|
||||
find_child_box,
|
||||
has_encrypted_sample_entry,
|
||||
read_top_level_box,
|
||||
senc_protects_samples,
|
||||
walk,
|
||||
@@ -41,7 +39,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.tracks.segment_store import SegmentStore
|
||||
from unshackle.core.utilities import language_name, log_event, try_ensure_utf8
|
||||
from unshackle.core.utilities import language_name, log_event
|
||||
from unshackle.core.utils import run_proxy
|
||||
from unshackle.core.utils.subprocess import run_tool
|
||||
|
||||
@@ -401,6 +399,8 @@ class DownloadContext:
|
||||
cdm: object | None = None
|
||||
on_segments: Callable[["Track", list[Any]], None] | None = None
|
||||
"""Called by the HLS step with a track and its wanted media segments, before they download."""
|
||||
sample_decrypter: Callable[[int], bytes | SampleDecrypter] | None = None
|
||||
"""The service's key or `cbcs.SampleDecrypter` for a 1-based `stsd` entry, for a track it decrypts itself."""
|
||||
|
||||
def ensure_session(self) -> AnySession:
|
||||
"""Return the HTTP session, or a new ``Session`` if none was set."""
|
||||
@@ -729,14 +729,16 @@ class Track:
|
||||
adaptive_workers: bool = False,
|
||||
download_processes: int = 1,
|
||||
on_segments: Callable[["Track", list[Any]], None] | None = None,
|
||||
sample_decrypter: Callable[[int], bytes | SampleDecrypter] | None = None,
|
||||
) -> None:
|
||||
"""Download and optionally Decrypt this Track.
|
||||
"""Download and optionally Decrypt this Track, then emit TRACK_DOWNLOADED.
|
||||
|
||||
For a URL-descriptor Video or Audio track with no `drm` set, unshackle probes the DRM from the
|
||||
track's init data and stores it on the track, so a service need not declare `drm` itself.
|
||||
`sample_decrypter` decrypts a track the service decrypts itself (see DownloadContext).
|
||||
"""
|
||||
from unshackle.core.manifests import DASH, HLS, ISM
|
||||
from unshackle.core.manifests.segment_pipeline import license_drm, licensing
|
||||
from unshackle.core.manifests import DASH, HLS, ISM, url
|
||||
from unshackle.core.manifests.segment_pipeline import licensing
|
||||
from unshackle.core.tracks.audio import Audio
|
||||
from unshackle.core.tracks.subtitle import Subtitle
|
||||
from unshackle.core.tracks.video import Video
|
||||
@@ -749,8 +751,6 @@ class Track:
|
||||
progress(downloaded="[yellow]SKIPPED")
|
||||
return
|
||||
|
||||
log = logging.getLogger("track")
|
||||
|
||||
proxy = next(iter(session.proxies.values()), None)
|
||||
|
||||
dl_session = session
|
||||
@@ -811,106 +811,12 @@ class Track:
|
||||
license_widevine=prepare_drm,
|
||||
cdm=cdm,
|
||||
on_segments=on_segments,
|
||||
sample_decrypter=sample_decrypter,
|
||||
)
|
||||
if self.descriptor in manifest_parsers:
|
||||
manifest_parsers[self.descriptor].download_track(track=self, ctx=ctx)
|
||||
elif self.descriptor == self.Descriptor.URL:
|
||||
try:
|
||||
self.ensure_url()
|
||||
if (
|
||||
DOWNLOAD_ALL_DRM.is_set()
|
||||
and track_type in ("Video", "Audio")
|
||||
and not {Widevine, PlayReady} <= {type(d) for d in self.drm or []}
|
||||
and all(type(d) in (Widevine, PlayReady) for d in self.drm or [])
|
||||
):
|
||||
self.add_init_drm(self.get_init_segment(session=session), cdm)
|
||||
elif not self.drm and track_type in ("Video", "Audio"):
|
||||
self.drm_from_pssh(cdm, lambda system: system.from_track(self, session), log)
|
||||
|
||||
if self.drm:
|
||||
drm = self.get_drm_for_cdm(cdm)
|
||||
track_kid = None if isinstance(drm, WHOLE_FILE_DRM) else self.get_key_id(session=session)
|
||||
license_drm(self, drm, ctx, track_kid)
|
||||
else:
|
||||
drm = None
|
||||
|
||||
if DOWNLOAD_LICENCE_ONLY.is_set():
|
||||
progress(downloaded="[yellow]SKIPPED")
|
||||
else:
|
||||
sample_range = None
|
||||
if config.sample and track_type in ("Video", "Audio"):
|
||||
sample_range = self.sample_byte_range(dl_session)
|
||||
if not sample_range:
|
||||
raise click.ClickException(
|
||||
"--sample cannot cut this track: it is one file with no segment index."
|
||||
)
|
||||
for status_update in self.downloader(
|
||||
urls=[{"url": self.url, "headers": {"Range": f"bytes={sample_range[1]}"}}]
|
||||
if sample_range
|
||||
else self.url,
|
||||
output_dir=save_path.parent,
|
||||
filename=save_path.name,
|
||||
headers=dl_session.headers,
|
||||
cookies=dl_session.cookies,
|
||||
proxy=proxy,
|
||||
max_workers=max_workers,
|
||||
session=dl_session,
|
||||
adaptive=adaptive_workers,
|
||||
processes=download_processes,
|
||||
):
|
||||
file_downloaded = status_update.get("file_downloaded")
|
||||
if not file_downloaded:
|
||||
downloaded = status_update.get("downloaded")
|
||||
if downloaded and downloaded.endswith("/s"):
|
||||
status_update["downloaded"] = f"URL {downloaded}"
|
||||
progress(**status_update)
|
||||
|
||||
if sample_range:
|
||||
media_path = save_path.with_name(f"{save_path.name}.media")
|
||||
save_path.replace(media_path)
|
||||
with save_path.open("wb") as joined, media_path.open("rb") as media:
|
||||
joined.write(sample_range[0])
|
||||
shutil.copyfileobj(media, joined)
|
||||
with contextlib.suppress(OSError):
|
||||
media_path.unlink()
|
||||
|
||||
self.path = save_path
|
||||
|
||||
if drm:
|
||||
progress(downloaded="Decrypting", completed=0, total=None)
|
||||
decrypt_track(drm, save_path, prepare_drm, track_kid, track=self)
|
||||
if not isinstance(drm, WHOLE_FILE_DRM):
|
||||
assert_fragments_decrypted(save_path)
|
||||
self.drm = None
|
||||
events.emit(events.Types.TRACK_DECRYPTED, track=self, drm=drm, segment=None)
|
||||
progress(downloaded="Decrypted", completed=100, total=100)
|
||||
# residual encv/enca => decrypt tool skipped/failed; force a repack so the
|
||||
# muxer isn't first-FourCC-locked to a generic (encrypted) codec. OR-in only.
|
||||
if has_encrypted_sample_entry(save_path):
|
||||
self.needs_repack = True
|
||||
|
||||
if isinstance(self, Subtitle) and self.codec and self.codec.name not in ("fVTT", "fTTML"):
|
||||
track_data = self.path.read_bytes()
|
||||
track_data = try_ensure_utf8(track_data)
|
||||
track_data = (
|
||||
track_data.decode("utf8")
|
||||
.replace("‎", html.unescape("‎"))
|
||||
.replace("‏", html.unescape("‏"))
|
||||
.encode("utf8")
|
||||
)
|
||||
self.path.write_bytes(track_data)
|
||||
|
||||
progress(downloaded="Downloaded")
|
||||
except KeyboardInterrupt:
|
||||
DOWNLOAD_CANCELLED.set()
|
||||
progress(downloaded="[yellow]CANCELLED")
|
||||
raise
|
||||
except DownloadCancelled:
|
||||
raise
|
||||
except Exception:
|
||||
DOWNLOAD_CANCELLED.set()
|
||||
progress(downloaded="[red]FAILED")
|
||||
raise
|
||||
url.download_track(self, ctx, session)
|
||||
|
||||
if DOWNLOAD_CANCELLED.is_set():
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user