forked from kenzuya/unshackle
fix(import): carry the HLS segment filter in an export
An import kept the segments a service drops and failed on their key. A licence-only run now also licenses a key that starts part-way.
This commit is contained in:
@@ -4064,7 +4064,12 @@ class dl:
|
||||
doc.add(entry)
|
||||
|
||||
tracks_map = entry.ext("unshackle").setdefault("tracks", {})
|
||||
tracks_map.setdefault(str(track.id), track.to_dict())
|
||||
track_dict = tracks_map.setdefault(str(track.id), track.to_dict())
|
||||
unwanted = (track.data.get("hls") or {}).get("unwanted_segments")
|
||||
if unwanted:
|
||||
track_dict["unwanted_segments"] = unwanted
|
||||
elif unwanted is not None:
|
||||
track_dict.pop("unwanted_segments", None)
|
||||
# the row names the track's KIDs, so an import gives the track only their keys
|
||||
track_kids = [kid.hex for kid in own_kids(drm)] if drm is not None else []
|
||||
for row in entry.tracks:
|
||||
|
||||
@@ -18,7 +18,13 @@ from unshackle.core.constants import AnyTrack
|
||||
from unshackle.core.credential import Credential
|
||||
from unshackle.core.drm import drm_from_dict, real_kids
|
||||
from unshackle.core.manifests import DASH, HLS, ISM
|
||||
from unshackle.core.remote_service import RemoteService, build_title, match_track, resolve_proxy_arg
|
||||
from unshackle.core.remote_service import (
|
||||
RemoteService,
|
||||
build_title,
|
||||
match_track,
|
||||
resolve_proxy_arg,
|
||||
segment_uri_filter,
|
||||
)
|
||||
from unshackle.core.titles import Episode, Movies, Series, Title_T, Titles_T, remap_titles
|
||||
from unshackle.core.tracks import Audio, Chapter, Chapters, Subtitle, Tracks, Video
|
||||
from unshackle.core.tracks.attachment import Attachment
|
||||
@@ -409,6 +415,10 @@ class ImportService:
|
||||
drm = self.rebuild_drm(track_dict, title_id)
|
||||
if drm:
|
||||
track.drm = drm
|
||||
if track_dict.get("unwanted_segments"):
|
||||
track.OnSegmentFilter = segment_uri_filter(track_dict["unwanted_segments"])
|
||||
# HLS.download_track warns when none of these is in the playlist
|
||||
track.data["hls"]["unwanted_segments"] = list(track_dict["unwanted_segments"])
|
||||
tracks.add(track, warn_only=True)
|
||||
|
||||
if manifest_url and parser is None and not [*tracks.videos, *tracks.audio, *tracks.subtitles]:
|
||||
|
||||
@@ -674,6 +674,17 @@ class HLS:
|
||||
log.error("Track's HLS playlist has no segments, expecting an invariant M3U8 playlist.")
|
||||
sys.exit(1)
|
||||
|
||||
unwanted_segments = [
|
||||
segment for segment in master.segments if callable(track.OnSegmentFilter) and track.OnSegmentFilter(segment)
|
||||
]
|
||||
hls_data = track.data.setdefault("hls", {})
|
||||
if hls_data.get("unwanted_segments") and not unwanted_segments:
|
||||
log.warning(
|
||||
f"None of the {len(hls_data['unwanted_segments'])} segments that the export drops is in the "
|
||||
f"playlist of {track.id}. The download keeps every segment."
|
||||
)
|
||||
hls_data["unwanted_segments"] = [s.absolute_uri for s in unwanted_segments]
|
||||
|
||||
# Get session DRM as fallback but prefer media playlist keys for accurate KID matching
|
||||
if track.drm:
|
||||
session_drm = track.get_drm_for_cdm(cdm)
|
||||
@@ -745,13 +756,21 @@ class HLS:
|
||||
raise
|
||||
|
||||
if DOWNLOAD_LICENCE_ONLY.is_set():
|
||||
# a playlist can change its key part-way, and only the download loop licenses the later keys
|
||||
licensed_keys = [initial_drm_key]
|
||||
for segment in master.segments:
|
||||
if not segment.keys or segment in unwanted_segments:
|
||||
continue
|
||||
key = HLS.resolve_segment_key(segment.keys, cdm, track.drm_preference)
|
||||
if key is None or key.method == "AES-128" or key in licensed_keys:
|
||||
continue
|
||||
licensed_keys.append(key)
|
||||
later_drm = HLS.get_drm(key, session)
|
||||
if isinstance(later_drm, (Widevine, PlayReady)) and license_widevine:
|
||||
license_widevine(later_drm, track_kid=later_drm.kid)
|
||||
progress(downloaded="[yellow]SKIPPED")
|
||||
return
|
||||
|
||||
unwanted_segments = [
|
||||
segment for segment in master.segments if callable(track.OnSegmentFilter) and track.OnSegmentFilter(segment)
|
||||
]
|
||||
|
||||
# Downloaded segment files are named by post-filter index; map that back to the wanted
|
||||
# segment so the IV uses the absolute media sequence number, not the download index.
|
||||
wanted_segments = [seg for seg in master.segments if seg not in unwanted_segments]
|
||||
@@ -1152,9 +1171,6 @@ class HLS:
|
||||
drm.content_keys.setdefault(prev_kid, prev_key)
|
||||
encryption_data = (key, drm)
|
||||
|
||||
if DOWNLOAD_LICENCE_ONLY.is_set():
|
||||
continue
|
||||
|
||||
if is_last_segment:
|
||||
# required as it won't end with EXT-X-DISCONTINUITY nor a new key
|
||||
if encryption_data:
|
||||
@@ -1165,9 +1181,6 @@ class HLS:
|
||||
|
||||
progress(advance=1)
|
||||
|
||||
if DOWNLOAD_LICENCE_ONLY.is_set():
|
||||
return
|
||||
|
||||
def find_segments_recursively(directory: Path) -> list[Path]:
|
||||
"""Find all segment files recursively in any directory structure created by downloaders."""
|
||||
segments = []
|
||||
|
||||
@@ -22,7 +22,7 @@ from enum import Enum
|
||||
from http.cookiejar import CookieJar
|
||||
from pathlib import Path
|
||||
from threading import Event, Lock, Thread
|
||||
from typing import Any, Callable, Dict, Iterator, Optional, Union
|
||||
from typing import Any, Callable, Dict, Iterable, Iterator, Optional, Union
|
||||
from uuid import UUID
|
||||
|
||||
import click
|
||||
@@ -465,6 +465,22 @@ def resolve_manifest_data(tracks: Tracks, manifests: list) -> None:
|
||||
remote_track.drm = matched.drm
|
||||
|
||||
|
||||
def segment_uri_filter(uris: Iterable[Any]) -> Callable[[Any], bool]:
|
||||
"""Return an HLS ``OnSegmentFilter`` that drops the segments with these URIs.
|
||||
|
||||
A URI also matches without its query string, because a later fetch of the playlist can
|
||||
sign the same segment with a new one.
|
||||
"""
|
||||
exact = {str(u) for u in uris}
|
||||
paths = {u.split("?")[0] for u in exact}
|
||||
|
||||
def segment_filter(segment: Any) -> bool:
|
||||
uri = str(getattr(segment, "absolute_uri", "") or "")
|
||||
return bool(exact) and (uri in exact or uri.split("?")[0] in paths)
|
||||
|
||||
return segment_filter
|
||||
|
||||
|
||||
def same_bitrate(local: Optional[int], remote: Optional[int]) -> bool:
|
||||
"""Equal to the nearest kb/s. A server that predates ``bitrate_bps`` rounds to kb/s in transit."""
|
||||
if not local or not remote:
|
||||
@@ -895,7 +911,7 @@ class RemoteService:
|
||||
self.client_licensed: set[str] = set() # track ids this machine's device licenses by challenge relay
|
||||
self.server_vault_keys: Dict[UUID, str] = {}
|
||||
self.server_vault = ServerVault(self)
|
||||
self._segment_filters: Dict[str, tuple[set[str], set[str]]] = {}
|
||||
self._segment_filters: Dict[str, Callable[[Any], bool]] = {}
|
||||
self._log_seq = 0
|
||||
self._log_drain_lock = Lock()
|
||||
self._keepalive_stop = Event()
|
||||
@@ -1407,14 +1423,9 @@ class RemoteService:
|
||||
result = self.client.post_optional(
|
||||
f"/api/session/{self._session_id}/segment_filter", {"track_id": track_id}
|
||||
)
|
||||
uris = [str(u) for u in (result.get("unwanted") or [])]
|
||||
unwanted = (set(uris), {u.split("?")[0] for u in uris})
|
||||
unwanted = segment_uri_filter(result.get("unwanted") or [])
|
||||
self._segment_filters[track_id] = unwanted
|
||||
exact, paths = unwanted
|
||||
if not exact:
|
||||
return False
|
||||
uri = str(getattr(segment, "absolute_uri", "") or "")
|
||||
return uri in exact or uri.split("?")[0] in paths
|
||||
return unwanted(segment)
|
||||
|
||||
return segment_filter
|
||||
|
||||
|
||||
Reference in New Issue
Block a user