mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-27 11:25:08 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5bc92b5517 |
@@ -19,24 +19,6 @@ This changelog is automatically generated using [git-cliff](https://git-cliff.or
|
||||
- *dl*: Animate merge/decrypt/mux stages with gradient pulse bars
|
||||
- *tags*: Add imdb_api_enabled toggle, off by default
|
||||
- *tags*: Add OMDb metadata provider with omdb_api_key config
|
||||
- *cdm*: Stamp remote CDM DRM type at load for reliable detection
|
||||
- *ism*: Harden Smooth parsing and derive fps/codec from spec fields
|
||||
- Original-language aware DUAL/MULTi tagging and new DUBBED variable
|
||||
- *drm*: Add PlayReady HRESULT decoder
|
||||
- *drm*: Detect revoked PlayReady devices from license responses
|
||||
- *drm*: Auto-repack tracks with a residual encrypted sample entry
|
||||
- *dl*: Extend --select-titles to movie listings
|
||||
- Show git commit hash alongside the version
|
||||
- Identify the running code by source hash
|
||||
- *dl*: Add --speed-limit and serve global_speed_limit
|
||||
- *providers*: Add TheTVDB v4 as a metadata provider
|
||||
- *tracks*: Add subtitle.group_by to keep a language with its variants
|
||||
- *temp*: Give each download task its own temp directory
|
||||
- *dl*: Add -fsl/--forced-s-lang to filter forced subtitles by language
|
||||
- *tracks*: Add language_priority to sort preferred languages first
|
||||
- *vaults*: Support custom headers on API vault
|
||||
- *dl*: Add tag_rules to conditionally swap the group tag
|
||||
- *titles*: Add optional Episode.part, selected with -w s1e1.2
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
@@ -54,52 +36,23 @@ This changelog is automatically generated using [git-cliff](https://git-cliff.or
|
||||
- *gitignore*: Add memory directory to .gitignore
|
||||
- *dl*: Prevent missing tracks error when excluding track types
|
||||
- *subs*: Stop segmented WebVTT merge from stripping formatting
|
||||
- *proxies*: Show ExpressVPN country/location counts at startup
|
||||
- *tracks*: Keep regional language variants distinct in exact selection
|
||||
- *services*: Register modules in sys.modules so repo-cloned services can self-import and remove old benchmark that should have been deleted
|
||||
- Skip decrypt on mislabeled-clear segments
|
||||
- Harden ClearKey/CENC decryption correctness
|
||||
- *import*: Stop losing side-loaded subtitles and blaming the manifest URL
|
||||
- *ism*: Emit two stsd entries so sample_description_index 2 resolves
|
||||
- *ism*: Repair synthesized init and verify fragments decrypted
|
||||
- *core*: Strip trailing spaces and dots in template formatting to prevent WinError 3
|
||||
- *templates*: Use one separator style across a whole folder path
|
||||
- *lang*: Surface orig in errors and flag the original audio track over the API
|
||||
- *tracks*: Ignore leftover PIFF uuid when verifying decryption
|
||||
- *tracks*: Size the no-proxy download session's connection pool
|
||||
- *import*: Scope the merge-back and detect ISM protection
|
||||
- *dl*: Honour --no-proxy-download for attachments
|
||||
- *tools*: Pass -nostdin to all ffmpeg calls
|
||||
- *subtitles*: Strip X-TIMESTAMP-MAP so WebVTT cues are not offset on conversion
|
||||
- *downloader*: Decode content-encoded bodies instead of writing raw
|
||||
- *downloader*: Surface failed downloads instead of returning silently
|
||||
|
||||
### Documentation
|
||||
|
||||
- Restructure documentation into MkDocs Material site
|
||||
- Expand config reference and genericize service names
|
||||
- Correct DRM, muxing, and proxy references (+ case-insensitive proxy prefix fix)
|
||||
- Cleanup and correct documentation
|
||||
- *core*: Drop service tags from framework comments
|
||||
- Cover the TVDB provider, episode ordering and provider order
|
||||
- Split configuration reference into per-area pages
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
- *downloader*: Cut per-segment overhead, bound stalled connections
|
||||
- Little improvements here and there
|
||||
- *pipeline*: Fix pool starvation, unlock vault writes, prep mux
|
||||
- Speed up the code hash with sha1 and a plain file reader
|
||||
|
||||
### Changes
|
||||
|
||||
- *core*: [**breaking**] Bundle download_track args into DownloadContext
|
||||
- *tracks*: Honour the best token and share one match rule
|
||||
|
||||
### Builds
|
||||
|
||||
- *deps*: Cap pycaption below 2.2.27
|
||||
- *mypy*: Enable explicit_package_bases
|
||||
|
||||
## [5.3.0] - 2026-07-01
|
||||
|
||||
|
||||
@@ -394,7 +394,7 @@ Create a download job. Requires `service` and `title_id`; every other field is a
|
||||
| `tag` | string | `null` | Release group tag. |
|
||||
| `tmdb_id` / `imdb_id` / `tvdb_id` / `animeapi_id` | - | `null` | External ID overrides for tagging. |
|
||||
| `tvdb_order` | `official`, `dvd`, `absolute`, `alternate`, `regional` | `null` | Renumber episodes to a TVDB season order. Falls back to the `tvdb_order` config option. |
|
||||
| `enrich` | boolean | `false` | Override title/year from external source, and fill in the original language. Needs one of `tmdb_id`, `imdb_id`, `tvdb_id` or `animeapi_id`; without one the job fails instead of returning `400`. |
|
||||
| `enrich` | boolean | `false` | Override title/year from external source. |
|
||||
| `output_dir` | string | `null` | Override output directory. |
|
||||
| `no_cache` / `reset_cache` | boolean | `false` | Title cache controls. |
|
||||
|
||||
|
||||
@@ -146,15 +146,52 @@ Keep only certain track types, or skip certain track types. Attachments are alwa
|
||||
| `--tag` | Group tag override. |
|
||||
| `--repack` | Add a `REPACK` tag to the filename. |
|
||||
|
||||
### Cross-service muxing
|
||||
|
||||
Take some track types from a different service and mux them with the rest. Each `--cross-*` flag
|
||||
takes a service tag and a URL. Video and chapters replace what the service you download provides;
|
||||
audio and subtitles are merged in, so the best-per-language selection runs across both services'
|
||||
tracks together. See [Cross-service muxing](cross-service-muxing.md) for the full guide.
|
||||
|
||||
| Flag | Description |
|
||||
|---|---|
|
||||
| `--cross-video` | Take video tracks from `SERVICE URL` (replaces the download service's video). |
|
||||
| `--cross-audio` | Merge in audio tracks from `SERVICE URL`. |
|
||||
| `--cross-subtitles` | Merge in subtitle tracks from `SERVICE URL`. |
|
||||
| `--cross-chapters` | Take chapters from `SERVICE URL` (replaces the download service's chapters). |
|
||||
| `--cross-audio-offset` | Shift the cross-sourced audio in the mux, e.g. `10s`, `500ms`, `-5.5s`. A bare number is milliseconds. |
|
||||
| `--cross-subtitle-offset` | Shift the cross-sourced subtitles in the mux. Same format as above. |
|
||||
| `--cross-profile` | Profile used for the cross-service credentials. Defaults to `--profile`. |
|
||||
| `--cross-proxy` | Proxy for every cross-service. Overrides each cross-service's own proxy configuration. |
|
||||
| `--cross-wanted` | Episode to take from the cross-services, e.g. `S01E02`. Fallback for the per-type flags below. Defaults to the same season and episode as the title you download. |
|
||||
| `--cross-video-wanted` | Episode to take video from, e.g. `S01E02`. Overrides `--cross-wanted` for video. |
|
||||
| `--cross-audio-wanted` | Episode to take audio from. Overrides `--cross-wanted` for audio. |
|
||||
| `--cross-subtitles-wanted` | Episode to take subtitles from. Overrides `--cross-wanted` for subtitles. |
|
||||
| `--cross-chapters-wanted` | Episode to take chapters from. Overrides `--cross-wanted` for chapters. |
|
||||
|
||||
```bash
|
||||
unshackle dl --cross-audio EXAMPLE2 "https://example2.com/show/1" EXAMPLE "https://example.com/show/1"
|
||||
```
|
||||
|
||||
Each cross-service authenticates, licenses and decrypts its own tracks with its own CDM, key
|
||||
vaults and (unless `--cross-proxy` is set) its own proxy, so you need credentials for it as well.
|
||||
Offsets are applied by the muxer, which does not re-time the media itself.
|
||||
|
||||
!!! note "Titles must match"
|
||||
For a series, unshackle looks for the same season and episode number on the cross-service.
|
||||
Use `--cross-wanted` (or a per-type flag such as `--cross-audio-wanted`) when the two services
|
||||
number the episodes differently. If no title matches, unshackle logs a warning and keeps the
|
||||
tracks of the service you download.
|
||||
|
||||
### Metadata & tagging
|
||||
|
||||
| Flag | Description |
|
||||
|---|---|
|
||||
| `--tmdb` | TMDB ID (integer). |
|
||||
| `--imdb` | IMDb ID, e.g. `tt1375666`. |
|
||||
| `--tvdb` | TVDB ID (integer). Skips the series lookup that `--tvdb-order` would otherwise do. `--enrich` reads it too. |
|
||||
| `--tvdb` | TVDB ID (integer). Skips the series lookup that `--tvdb-order` would otherwise do. |
|
||||
| `--animeapi` | AnimeAPI ID, e.g. `mal:12345` or `anilist:98765` (defaults to MAL). Back-fills TMDB/IMDb/TVDB. |
|
||||
| `--enrich` | Override show title/year from the external source, and fill in the original language. **Requires** one of `--tmdb`, `--imdb`, `--tvdb`, or `--animeapi`. |
|
||||
| `--enrich` | Override show title/year from the external source. **Requires** one of `--tmdb`, `--imdb`, or `--animeapi`. |
|
||||
| `--tvdb-order` | Renumber episodes to a TVDB season order: `official` (aired), `dvd`, `absolute`, `alternate`, or `regional`. Needs `tvdb_api_key`. |
|
||||
|
||||
#### Episode ordering
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
# Cross-service muxing
|
||||
|
||||
Some titles are on more than one service, and each service is strong at something
|
||||
different: one carries the 4K HDR video, another the better dub, a third the fuller
|
||||
subtitles. Cross-service muxing lets you download the video from one service and pull
|
||||
the audio, subtitles, or chapters from others, then mux the result into a single file.
|
||||
|
||||
!!! warning "This is a power-user feature"
|
||||
unshackle does not check that the services carry the same cut of the title. You are
|
||||
responsible for pairing services that share the same edit. A different cut, a
|
||||
different frame rate, or an extra recap will not line up, and a single offset cannot
|
||||
fix it. See [Limitations](#limitations).
|
||||
|
||||
## How it works
|
||||
|
||||
You download from a **primary** service as normal, the positional `SERVICE URL` at the
|
||||
end of the command. Each `--cross-*` flag names **another** service tag and URL to take a
|
||||
track type from:
|
||||
|
||||
- **Video** and **chapters** *replace* what the primary provides. There is only ever one
|
||||
video source and one set of chapters.
|
||||
- **Audio** and **subtitles** *merge* with the primary's own tracks. Your normal track
|
||||
selection (`-l`, quality, codec, channels) then runs across the combined set, so the
|
||||
best version of each language wins whichever service it came from.
|
||||
|
||||
```bash
|
||||
# Download EXAMPLE's video, but take the audio from EXAMPLE2
|
||||
unshackle dl --cross-audio EXAMPLE2 "https://example2.com/show/1" EXAMPLE "https://example.com/show/1"
|
||||
```
|
||||
|
||||
You can combine several sources in one run:
|
||||
|
||||
```bash
|
||||
# Video from the primary, a dub from one service, subtitles from another
|
||||
unshackle dl \
|
||||
--cross-audio EXAMPLE2 "https://example2.com/show/1" \
|
||||
--cross-subtitles EXAMPLE3 "https://example3.com/show/1" \
|
||||
EXAMPLE "https://example.com/show/1"
|
||||
```
|
||||
|
||||
The full flag list is in the [CLI reference](cli-reference.md#cross-service-muxing).
|
||||
|
||||
## Authentication, DRM, and proxies
|
||||
|
||||
Each cross-service behaves like a download of its own. It authenticates with **its own**
|
||||
credentials, licenses and decrypts with **its own** CDM, and stores keys in **its own**
|
||||
key vault. A PlayReady-only cross-service works even when the primary uses Widevine,
|
||||
because it loads the CDM its own configuration asks for.
|
||||
|
||||
!!! note "You need credentials for every service"
|
||||
A cross-service authenticates the same way it would on a normal download, so its
|
||||
profile, cookies, or credentials must be set up. Use `--cross-profile` to pick a
|
||||
profile for the cross-services (it defaults to `--profile`).
|
||||
|
||||
By default each cross-service resolves **its own** proxy from its configuration, so a
|
||||
geo-restricted source still reaches the right region. Set `--cross-proxy` to force one
|
||||
proxy for every cross-service instead.
|
||||
|
||||
## Choosing the episode
|
||||
|
||||
For a TV title, each cross-service is matched to the **same season and episode** as the
|
||||
title you download. When a service numbers its episodes differently, override the match:
|
||||
|
||||
- `--cross-wanted S01E03` sets a shared override for every cross-service.
|
||||
- `--cross-audio-wanted`, `--cross-video-wanted`, `--cross-subtitles-wanted`, and
|
||||
`--cross-chapters-wanted` are per-type overrides that win over `--cross-wanted`.
|
||||
|
||||
If a cross-service has no title matching the request, unshackle warns and keeps the
|
||||
primary's own tracks for that type.
|
||||
|
||||
## Offsets
|
||||
|
||||
If a cross-service begins with a short buffer the primary does not have, such as an advert
|
||||
or a splash screen, its tracks start a few seconds late. Nudge them back into line:
|
||||
|
||||
```bash
|
||||
# EXAMPLE2's audio starts 3 seconds late; shift it earlier
|
||||
unshackle dl --cross-audio EXAMPLE2 "https://example2.com/show/1" \
|
||||
--cross-audio-offset -3s EXAMPLE "https://example.com/show/1"
|
||||
```
|
||||
|
||||
`--cross-audio-offset` and `--cross-subtitle-offset` accept `10s`, `500ms`, or `-5.5s`; a
|
||||
bare number is milliseconds. The offset is passed to the muxer, which shifts the track's
|
||||
start. It does not re-time or resample the media, so a single offset only corrects a
|
||||
constant lead or lag, not drift that grows through the title.
|
||||
|
||||
## Limitations
|
||||
|
||||
Cross-service muxing assumes the sources are the same cut of the title. The current
|
||||
release does not:
|
||||
|
||||
- **Sync mismatched cuts.** Different edits, ad breaks, or frame rates are out of scope;
|
||||
the offset is a manual nudge for a constant lead, not automatic synchronisation.
|
||||
- **Pin a language to a service.** Merged audio and subtitles are chosen by the normal
|
||||
best-per-language selection. You cannot yet force the English from one service when
|
||||
another service's English scores higher.
|
||||
- **Reuse a cross-service across a season.** Each title in a season download loads and
|
||||
authenticates its cross-services again, so a login-rate-limited service is contacted
|
||||
once per episode.
|
||||
- **Run a cross-service's own post-download steps.** Only the primary service's
|
||||
post-download hooks fire.
|
||||
@@ -583,43 +583,13 @@ tagging and naming:
|
||||
| `--imdb` | `--imdb tt1375666` | Use this IMDb ID. |
|
||||
| `--tvdb` | `--tvdb 73871` | Use this TVDB ID instead of looking the series up. |
|
||||
| `--animeapi` | `--animeapi mal:12345` | Resolve via AnimeAPI (`mal:`/`anilist:` prefix; defaults to MAL). |
|
||||
| `--enrich` | - | Override the show title and year from an external source, and fill in the original language. **Requires** one of `--tmdb`, `--imdb`, `--tvdb`, or `--animeapi`. |
|
||||
| `--enrich` | - | Override the show title and year from an external source. **Requires** one of `--tmdb`, `--imdb`, or `--animeapi`. |
|
||||
| `--tvdb-order` | `--tvdb-order dvd` | Renumber episodes to a TVDB season order. Needs `tvdb_api_key`. |
|
||||
|
||||
```shell title="Force the right IMDb match and enrich the title"
|
||||
unshackle dl --imdb tt1375666 --enrich EXAMPLE 81234567
|
||||
```
|
||||
|
||||
### What each metadata provider supplies
|
||||
|
||||
Providers differ in what they answer with, so `--enrich` reads different fields depending on
|
||||
which ID you gave it. A provider only runs when its key is configured:
|
||||
|
||||
| Provider | Config key | Title and year | Original language | External IDs it returns |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| TMDB | `tmdb_api_key` | yes | yes, alpha-2 such as `ko` | IMDb, TMDB, TVDB |
|
||||
| TVDB | `tvdb_api_key` | yes | yes, alpha-3 such as `kor` | TMDB, TVDB, sometimes IMDb |
|
||||
| OMDb | `omdb_api_key` | yes | yes, as an English name such as `Korean` | IMDb |
|
||||
| IMDxAPI | `imdb_api_enabled` | yes | only when looked up by ID | IMDb |
|
||||
| SIMKL | `simkl_client_id` | yes | no, it publishes a country and no language | IMDb, TMDB, TVDB |
|
||||
|
||||
Whatever the tag looks like, unshackle normalises it before use, so `ko`, `kor` and `Korean`
|
||||
all end up as the same language.
|
||||
|
||||
`--enrich` consults these in a fixed order:
|
||||
|
||||
- `--tmdb` reads TMDB.
|
||||
- `--imdb` tries IMDxAPI, then falls back to OMDb. Since `imdb_api_enabled` is `false` by
|
||||
default, an OMDb key is what makes this path work for most people.
|
||||
- `--tvdb` reads TVDB. It needs `tvdb_api_key`.
|
||||
- `--animeapi` supplies a title, plus whichever IDs AnimeAPI knows for the show. If that
|
||||
includes a TMDB, IMDb or TVDB ID, the year and language come from that provider. If it
|
||||
does not, pair it with `--tmdb`, `--imdb` or `--tvdb`.
|
||||
|
||||
Language is the one field `--enrich` will not overwrite. A service that already reported an
|
||||
original language keeps it, because the platform knows its own catalogue better than a
|
||||
third-party match does. Everything else follows the usual override behaviour.
|
||||
|
||||
### Episode ordering
|
||||
|
||||
A service does not always number a series the way TVDB's aired order does. Some services list
|
||||
|
||||
@@ -4,9 +4,7 @@ Smaller configuration areas: external metadata API keys, caching and update chec
|
||||
|
||||
## External API keys { #external-api-keys }
|
||||
|
||||
All are unset by default and enable optional metadata/geolocation features. For which fields
|
||||
each metadata provider can actually answer with, see
|
||||
[What each metadata provider supplies](../../guide/downloading.md#what-each-metadata-provider-supplies).
|
||||
All are unset by default and enable optional metadata/geolocation features.
|
||||
|
||||
| Key | Type | Default | Description |
|
||||
|-----|------|---------|-------------|
|
||||
@@ -14,7 +12,7 @@ each metadata provider can actually answer with, see
|
||||
| `omdb_api_key` | str | `""` | [OMDb](https://www.omdbapi.com/) API key for IMDb metadata lookups; a more reliable alternative to IMDxAPI. Free keys are available on the OMDb site. |
|
||||
| `tmdb_api_key` | str | `""` | TMDB API key for metadata enrichment and external-ID tags. |
|
||||
| `simkl_client_id` | str | `""` | SIMKL client ID for metadata lookups; an alternative/fallback source to TMDB. |
|
||||
| `tvdb_api_key` | str | `""` | [TheTVDB v4](https://thetvdb.com/api-information) API key; a fallback source to TMDB, strongest on TV series. Also the source `--enrich --tvdb` reads. Free keys are available on the TVDB site. |
|
||||
| `tvdb_api_key` | str | `""` | [TheTVDB v4](https://thetvdb.com/api-information) API key; a fallback source to TMDB, strongest on TV series. Free keys are available on the TVDB site. |
|
||||
| `tvdb_pin` | str | `""` | Subscriber PIN, only needed for a user-supported TVDB key. Leave empty for a normal project key. |
|
||||
| `tvdb_order` | str | `""` | Default for `--tvdb-order`: renumber episodes to a TVDB season order (`official`, `dvd`, `absolute`, `alternate`, `regional`). Empty keeps the numbering the service gives. |
|
||||
| `metadata_providers` | list | *(see below)* | Metadata providers to use, in the order they are tried. |
|
||||
|
||||
@@ -113,6 +113,7 @@ nav:
|
||||
- User Guide:
|
||||
- Downloading: guide/downloading.md
|
||||
- CLI Reference: guide/cli-reference.md
|
||||
- Cross-service Muxing: guide/cross-service-muxing.md
|
||||
- DRM & CDM Setup: guide/drm-and-cdm.md
|
||||
- Proxies & VPN: guide/proxies-and-vpn.md
|
||||
- Key Vaults: guide/vaults.md
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
"""Unit and offline end-to-end tests for cross-service muxing.
|
||||
|
||||
The ``dl`` cross-mux layer takes some track types from a second service and muxes them with the
|
||||
first. These tests cover the behaviour that is easy to get wrong:
|
||||
|
||||
- ``drm_source`` routes each track to the service, title, CDM and vaults that licence it, so a
|
||||
cross-sourced track licenses through its own service and a primary track through the primary's.
|
||||
- Keys from a cross-service cache under that service's own vault, never the primary's.
|
||||
- Audio and subtitles merge into the primary's own tracks (video and chapters replace), and an
|
||||
explicit id shared by both services is namespaced so the two never collide.
|
||||
- A ``sync_offset_ms`` on a track becomes ``--sync 0:<ms>`` in the built mkvmerge command, and is
|
||||
absent when no offset is set.
|
||||
- ``match_cross_title`` honours the per-type ``--cross-*-wanted`` override, falling back to the
|
||||
shared ``--cross-wanted`` and then to the matching season/episode.
|
||||
- The new CLI options parse and bind.
|
||||
|
||||
The offline end-to-end test stands up a synthetic cross-service (its titles and tracks held in
|
||||
memory, so no network or manifest parsing is needed) and drives ``fetch_cross_tracks`` ->
|
||||
``apply_cross_tracks`` -> ``Tracks.mux``, asserting the cross track is merged, muxed with its
|
||||
offset, and routed through the correct service for DRM.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Optional
|
||||
|
||||
import click
|
||||
import pytest
|
||||
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.titles.episode import Episode
|
||||
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
|
||||
from unshackle.core.tracks import tracks as tracks_mod
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
class Svc:
|
||||
"""Stand-in for a service class, only used to satisfy the Title ``service`` type check."""
|
||||
|
||||
|
||||
class CrossSvc:
|
||||
"""A minimal cross-service: its class name drives namespacing and the ``cross_source`` tag."""
|
||||
|
||||
def __init__(self, titles: Optional[list] = None, tracks: Optional[Tracks] = None) -> None:
|
||||
self.session = object()
|
||||
self._titles = titles or []
|
||||
self._tracks = tracks or Tracks()
|
||||
|
||||
def get_titles(self) -> list:
|
||||
return self._titles
|
||||
|
||||
def get_tracks(self, title: Any) -> Tracks:
|
||||
return self._tracks
|
||||
|
||||
def get_chapters(self, title: Any) -> list:
|
||||
return []
|
||||
|
||||
|
||||
class FakeVaults:
|
||||
"""Records added keys so we can prove which vault a key landed in."""
|
||||
|
||||
def __init__(self, name: str) -> None:
|
||||
self.name = name
|
||||
self.keys: dict[str, str] = {}
|
||||
|
||||
def add_key(self, kid: str, key: str, excluding: Any = None) -> int:
|
||||
self.keys[kid] = key
|
||||
return 1
|
||||
|
||||
def get_key(self, kid: str) -> tuple[Optional[str], None]:
|
||||
return self.keys.get(kid), None
|
||||
|
||||
|
||||
def make_audio(track_id: str, *, language: str = "en", offset: Optional[int] = None, path: Any = None) -> Audio:
|
||||
track = Audio(
|
||||
id_=track_id,
|
||||
url=f"https://example.test/{track_id}.m4a",
|
||||
language=language,
|
||||
codec=Audio.Codec.AAC,
|
||||
bitrate=128000,
|
||||
)
|
||||
if offset is not None:
|
||||
track.data["sync_offset_ms"] = offset
|
||||
if path is not None:
|
||||
path.touch() # mkvmerge command building requires the track file to exist
|
||||
track.path = path
|
||||
return track
|
||||
|
||||
|
||||
def make_subtitle(track_id: str, *, language: str = "en", offset: Optional[int] = None, path: Any = None) -> Subtitle:
|
||||
track = Subtitle(
|
||||
id_=track_id,
|
||||
url=f"https://example.test/{track_id}.vtt",
|
||||
language=language,
|
||||
codec=Subtitle.Codec.WebVTT,
|
||||
)
|
||||
if offset is not None:
|
||||
track.data["sync_offset_ms"] = offset
|
||||
if path is not None:
|
||||
path.touch() # mkvmerge command building requires the track file to exist
|
||||
track.path = path
|
||||
return track
|
||||
|
||||
|
||||
def make_video(track_id: str, *, language: str = "en") -> Video:
|
||||
return Video(
|
||||
id_=track_id,
|
||||
url=f"https://example.test/{track_id}.m3u8",
|
||||
language=language,
|
||||
codec=Video.Codec.HEVC,
|
||||
range_=Video.Range.SDR,
|
||||
width=1920,
|
||||
height=1080,
|
||||
bitrate=5000000,
|
||||
)
|
||||
|
||||
|
||||
def make_dl(**overrides: Any) -> dl:
|
||||
"""Build a bare ``dl`` with only the attributes the cross-mux methods read (no heavy __init__)."""
|
||||
inst = dl.__new__(dl)
|
||||
inst.log = logging.getLogger("test.cross")
|
||||
inst.cross_video = None
|
||||
inst.cross_audio = None
|
||||
inst.cross_subtitles = None
|
||||
inst.cross_chapters = None
|
||||
inst.cross_audio_offset = None
|
||||
inst.cross_subtitle_offset = None
|
||||
inst.cross_wanted = None
|
||||
inst.cross_wanted_by_type = {"video": None, "audio": None, "subtitles": None, "chapters": None}
|
||||
inst.cross_track_sources = {}
|
||||
inst.cdm = object()
|
||||
inst.vaults = object()
|
||||
for key, value in overrides.items():
|
||||
setattr(inst, key, value)
|
||||
return inst
|
||||
|
||||
|
||||
def capture_mux_command(monkeypatch: pytest.MonkeyPatch) -> dict:
|
||||
"""Patch mkvmerge discovery and Popen so ``Tracks.mux`` builds a command without running it."""
|
||||
captured: dict = {}
|
||||
|
||||
class FakeStdout:
|
||||
def readline(self) -> str:
|
||||
return ""
|
||||
|
||||
class FakePopen:
|
||||
def __init__(self, cmd: list, **_: Any) -> None:
|
||||
captured["cmd"] = cmd
|
||||
self.stdout = FakeStdout()
|
||||
|
||||
def wait(self) -> int:
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr(tracks_mod.binaries, "MKVToolNix", "/usr/bin/mkvmerge")
|
||||
monkeypatch.setattr(tracks_mod.subprocess, "Popen", FakePopen)
|
||||
return captured
|
||||
|
||||
|
||||
def test_drm_source_routes_cross_and_primary() -> None:
|
||||
d = make_dl()
|
||||
primary_service = SimpleNamespace(session=object())
|
||||
primary_title = object()
|
||||
cross_service = SimpleNamespace(session=object())
|
||||
cross_title = object()
|
||||
cross_cdm = object()
|
||||
cross_vaults = object()
|
||||
|
||||
cross_track = make_audio("cross-1", language="ja")
|
||||
d.cross_track_sources[cross_track.id] = (cross_service, cross_title, cross_cdm, cross_vaults)
|
||||
|
||||
assert d.drm_source(cross_track, primary_service, primary_title) == (
|
||||
cross_service,
|
||||
cross_title,
|
||||
cross_cdm,
|
||||
cross_vaults,
|
||||
)
|
||||
|
||||
primary_track = make_audio("prim-1")
|
||||
assert d.drm_source(primary_track, primary_service, primary_title) == (
|
||||
primary_service,
|
||||
primary_title,
|
||||
d.cdm,
|
||||
d.vaults,
|
||||
)
|
||||
|
||||
|
||||
def test_cross_key_caches_under_owning_vault() -> None:
|
||||
primary_vaults = FakeVaults("primary")
|
||||
cross_vaults = FakeVaults("cross")
|
||||
d = make_dl(vaults=primary_vaults)
|
||||
|
||||
cross_service = CrossSvc()
|
||||
cross_track = make_audio("cross-1", language="ja")
|
||||
d.cross_track_sources[cross_track.id] = (cross_service, object(), object(), cross_vaults)
|
||||
|
||||
# download_track resolves the owning vault through drm_source and threads it into prepare_drm,
|
||||
# which caches licensed keys to exactly that vault.
|
||||
_, _, _, vaults = d.drm_source(cross_track, SimpleNamespace(session=object()), object())
|
||||
assert vaults is cross_vaults
|
||||
|
||||
vaults.add_key("kid-1", "deadbeef")
|
||||
assert cross_vaults.keys == {"kid-1": "deadbeef"}
|
||||
assert primary_vaults.keys == {}
|
||||
|
||||
|
||||
def test_apply_cross_tracks_merges_audio_and_selection_sees_it() -> None:
|
||||
d = make_dl()
|
||||
title = Episode(id_="primary-ep-merge", service=Svc, title="Show", season=1, number=1, language="en")
|
||||
title.tracks.audio.append(make_audio("prim-en", language="en"))
|
||||
|
||||
cross_service = CrossSvc()
|
||||
cross_tracks = Tracks()
|
||||
cross_tracks.audio.append(make_audio("cross-ja", language="ja"))
|
||||
sources = {"audio": (cross_service, object(), cross_tracks, object(), object())}
|
||||
|
||||
d.apply_cross_tracks(title, sources)
|
||||
|
||||
assert sorted(str(a.language) for a in title.tracks.audio) == ["en", "ja"]
|
||||
assert any(a.id == "prim-en" for a in title.tracks.audio) # primary retained, not replaced
|
||||
picked = Tracks.by_language(title.tracks.audio, ["ja"])
|
||||
assert picked and picked[0].id == "cross-ja"
|
||||
|
||||
|
||||
def test_apply_cross_tracks_namespaces_colliding_ids() -> None:
|
||||
d = make_dl()
|
||||
title = Episode(id_="primary-ep-clash", service=Svc, title="Show", season=1, number=1, language="en")
|
||||
title.tracks.audio.append(make_audio("dup", language="en"))
|
||||
|
||||
cross_service = CrossSvc()
|
||||
cross_tracks = Tracks()
|
||||
cross_tracks.audio.append(make_audio("dup", language="ja")) # explicit id shared with the primary's
|
||||
sources = {"audio": (cross_service, object(), cross_tracks, object(), object())}
|
||||
|
||||
d.apply_cross_tracks(title, sources)
|
||||
|
||||
assert sorted(a.id for a in title.tracks.audio) == ["dup", "dup_crosssvc"]
|
||||
# The cross track is routed by its namespaced id; the primary track is not recorded as cross.
|
||||
assert set(d.cross_track_sources) == {"dup_crosssvc"}
|
||||
|
||||
|
||||
def test_apply_cross_tracks_namespaces_video_against_primary_ids() -> None:
|
||||
# A cross video sharing an id with a surviving primary track must not shadow that track's
|
||||
# drm_source entry, or the primary track would license through the cross service.
|
||||
d = make_dl()
|
||||
title = Episode(id_="primary-ep-vclash", service=Svc, title="Show", season=1, number=1, language="en")
|
||||
title.tracks.audio.append(make_audio("dup", language="en"))
|
||||
|
||||
cross_tracks = Tracks()
|
||||
cross_tracks.videos.append(make_video("dup"))
|
||||
sources = {"video": (CrossSvc(), object(), cross_tracks, object(), object())}
|
||||
|
||||
d.apply_cross_tracks(title, sources)
|
||||
|
||||
assert [v.id for v in title.tracks.videos] == ["dup_crosssvc"]
|
||||
assert set(d.cross_track_sources) == {"dup_crosssvc"}
|
||||
prim = title.tracks.audio[0]
|
||||
assert d.drm_source(prim, "PRIMARY", title) == ("PRIMARY", title, d.cdm, d.vaults)
|
||||
|
||||
|
||||
def test_fetch_cross_tracks_clears_stale_sources(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
# Titles are processed one after another; an id recorded for the previous episode must not
|
||||
# linger and shadow one of the next episode's own tracks.
|
||||
import unshackle.commands.dl as dl_mod
|
||||
|
||||
monkeypatch.setattr(dl_mod.Services, "get_tag", lambda name: name)
|
||||
|
||||
d = make_dl(cross_audio=("CROSS", "https://cross/1"))
|
||||
d.cross_track_sources["stale"] = (object(), object(), object(), object())
|
||||
monkeypatch.setattr(d, "load_cross_service", lambda tag, url: (CrossSvc(), object(), object()))
|
||||
|
||||
title = Episode(id_="primary-ep-stale", service=Svc, title="Show", season=1, number=2, language="en")
|
||||
assert d.fetch_cross_tracks(title) == {} # cross catalogue has no S01E02
|
||||
assert d.cross_track_sources == {}
|
||||
|
||||
|
||||
def test_apply_cross_tracks_replaces_video() -> None:
|
||||
d = make_dl()
|
||||
title = Episode(id_="primary-ep-video", service=Svc, title="Show", season=1, number=1, language="en")
|
||||
title.tracks.videos.append(make_video("prim-v"))
|
||||
|
||||
cross_tracks = Tracks()
|
||||
cross_tracks.videos.append(make_video("cross-v"))
|
||||
sources = {"video": (CrossSvc(), object(), cross_tracks, object(), object())}
|
||||
|
||||
d.apply_cross_tracks(title, sources)
|
||||
|
||||
assert [v.id for v in title.tracks.videos] == ["cross-v"]
|
||||
|
||||
|
||||
def test_apply_cross_tracks_records_offset() -> None:
|
||||
d = make_dl(cross_audio_offset=7500)
|
||||
title = Episode(id_="primary-ep-offset", service=Svc, title="Show", season=1, number=1, language="en")
|
||||
|
||||
cross_service = CrossSvc()
|
||||
cross_tracks = Tracks()
|
||||
cross_tracks.audio.append(make_audio("cross-ja", language="ja"))
|
||||
sources = {"audio": (cross_service, object(), cross_tracks, object(), object())}
|
||||
|
||||
d.apply_cross_tracks(title, sources)
|
||||
|
||||
cross = next(a for a in title.tracks.audio if a.id == "cross-ja")
|
||||
assert cross.data["sync_offset_ms"] == 7500
|
||||
|
||||
|
||||
def test_audio_offset_emits_sync(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:
|
||||
captured = capture_mux_command(monkeypatch)
|
||||
track = make_audio("a-off", offset=10000, path=tmp_path / "a.m4a")
|
||||
Tracks(track).mux("Title", delete=False)
|
||||
|
||||
cmd = captured["cmd"]
|
||||
assert "--sync" in cmd
|
||||
assert cmd[cmd.index("--sync") + 1] == "0:10000"
|
||||
|
||||
|
||||
def test_subtitle_offset_emits_sync(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:
|
||||
captured = capture_mux_command(monkeypatch)
|
||||
track = make_subtitle("s-off", offset=-2500, path=tmp_path / "s.vtt")
|
||||
Tracks(track).mux("Title", delete=False)
|
||||
|
||||
cmd = captured["cmd"]
|
||||
assert "--sync" in cmd
|
||||
assert cmd[cmd.index("--sync") + 1] == "0:-2500"
|
||||
|
||||
|
||||
def test_no_offset_no_sync(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:
|
||||
captured = capture_mux_command(monkeypatch)
|
||||
track = make_audio("a-plain", path=tmp_path / "a.m4a")
|
||||
Tracks(track).mux("Title", delete=False)
|
||||
|
||||
assert "--sync" not in captured["cmd"]
|
||||
|
||||
|
||||
def test_match_cross_title_per_type_override_and_fallback() -> None:
|
||||
primary = Episode(id_="primary-ep-match", service=Svc, title="Show", season=1, number=1, language="en")
|
||||
catalogue = [
|
||||
Episode(id_="cross-ep-0101", service=Svc, title="Show", season=1, number=1, language="en"),
|
||||
Episode(id_="cross-ep-0205", service=Svc, title="Show", season=2, number=5, language="en"),
|
||||
]
|
||||
|
||||
# Default: the same season and episode as the title being downloaded.
|
||||
assert make_dl().match_cross_title(primary, catalogue, "audio").id == "cross-ep-0101"
|
||||
|
||||
# Per-type override wins over the default.
|
||||
per_type = {"video": None, "audio": "S02E05", "subtitles": None, "chapters": None}
|
||||
assert make_dl(cross_wanted_by_type=per_type).match_cross_title(primary, catalogue, "audio").id == "cross-ep-0205"
|
||||
|
||||
# A type with no per-type override falls back to the shared --cross-wanted.
|
||||
shared = make_dl(cross_wanted="S02E05")
|
||||
assert shared.match_cross_title(primary, catalogue, "video").id == "cross-ep-0205"
|
||||
|
||||
# Per-type override beats the shared fallback for its own type.
|
||||
mixed = make_dl(
|
||||
cross_wanted="S02E05",
|
||||
cross_wanted_by_type={"video": None, "audio": "S01E01", "subtitles": None, "chapters": None},
|
||||
)
|
||||
assert mixed.match_cross_title(primary, catalogue, "audio").id == "cross-ep-0101"
|
||||
|
||||
|
||||
def test_match_cross_title_rejects_bad_wanted() -> None:
|
||||
primary = Episode(id_="primary-ep-bad", service=Svc, title="Show", season=1, number=1, language="en")
|
||||
with pytest.raises(click.UsageError):
|
||||
make_dl(cross_wanted="episode two").match_cross_title(primary, [], "audio")
|
||||
|
||||
|
||||
def test_cross_cli_options_parse() -> None:
|
||||
command = click.Command("dl", params=list(dl.cli.params), callback=lambda **_: None)
|
||||
ctx = command.make_context(
|
||||
"dl",
|
||||
[
|
||||
"--cross-proxy",
|
||||
"http://p:8080",
|
||||
"--cross-audio-wanted",
|
||||
"S02E05",
|
||||
"--cross-audio-offset",
|
||||
"10s",
|
||||
"--cross-video",
|
||||
"SVC",
|
||||
"https://example.test/1",
|
||||
],
|
||||
)
|
||||
assert ctx.params["cross_proxy"] == "http://p:8080"
|
||||
assert ctx.params["cross_audio_wanted"] == "S02E05"
|
||||
assert ctx.params["cross_audio_offset"] == 10000
|
||||
assert ctx.params["cross_video"] == ("SVC", "https://example.test/1")
|
||||
|
||||
|
||||
def test_cross_mux_end_to_end(monkeypatch: pytest.MonkeyPatch, tmp_path) -> None:
|
||||
import unshackle.commands.dl as dl_mod
|
||||
|
||||
monkeypatch.setattr(dl_mod.Services, "get_tag", lambda name: name)
|
||||
|
||||
primary = Episode(id_="primary-ep-e2e", service=Svc, title="Show", season=1, number=1, language="en")
|
||||
primary.tracks.audio.append(make_audio("prim-en", language="en", path=tmp_path / "prim_en.m4a"))
|
||||
|
||||
cross_episode = Episode(id_="cross-ep-e2e", service=Svc, title="Show", season=1, number=1, language="ja")
|
||||
cross_tracks = Tracks()
|
||||
cross_tracks.audio.append(make_audio("cross-ja", language="ja", path=tmp_path / "cross_ja.m4a"))
|
||||
cross_service = CrossSvc(titles=[cross_episode], tracks=cross_tracks)
|
||||
cross_cdm = object()
|
||||
cross_vaults = object()
|
||||
|
||||
d = make_dl(cross_audio=("CROSS", "https://cross/1"), cross_audio_offset=5000)
|
||||
monkeypatch.setattr(d, "load_cross_service", lambda tag, url: (cross_service, cross_cdm, cross_vaults))
|
||||
|
||||
sources = d.fetch_cross_tracks(primary)
|
||||
assert set(sources) == {"audio"}
|
||||
|
||||
d.apply_cross_tracks(primary, sources)
|
||||
|
||||
# Merged, not replaced: both languages present.
|
||||
assert {str(a.language) for a in primary.tracks.audio} == {"en", "ja"}
|
||||
|
||||
# DRM routes the cross track through the cross service's own service/cdm/vaults.
|
||||
cross_track = next(a for a in primary.tracks.audio if str(a.language) == "ja")
|
||||
svc, ttl, cdm, vaults = d.drm_source(cross_track, SimpleNamespace(session=object()), primary)
|
||||
assert svc is cross_service
|
||||
assert ttl is cross_episode
|
||||
assert cdm is cross_cdm
|
||||
assert vaults is cross_vaults
|
||||
|
||||
# The primary track still routes to the primary's own service/cdm/vaults.
|
||||
prim_track = next(a for a in primary.tracks.audio if str(a.language) == "en")
|
||||
assert d.drm_source(prim_track, "PRIMARY", primary) == ("PRIMARY", primary, d.cdm, d.vaults)
|
||||
|
||||
# The built mux command carries the cross audio's offset.
|
||||
captured = capture_mux_command(monkeypatch)
|
||||
primary.tracks.mux("Show S01E01", delete=False)
|
||||
cmd = captured["cmd"]
|
||||
assert "--sync" in cmd
|
||||
assert cmd[cmd.index("--sync") + 1] == "0:5000"
|
||||
@@ -1,64 +0,0 @@
|
||||
"""--enrich original-language enrichment."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.commands.dl import parse_language
|
||||
from unshackle.core.providers.imdbapi import primary_language as imdb_language
|
||||
from unshackle.core.providers.omdb import primary_language as omdb_language
|
||||
from unshackle.core.providers.tvdb import primary_language as tvdb_language
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("tag", "expected"),
|
||||
[
|
||||
("ja", "ja"), # TMDB alpha-2
|
||||
("jpn", "ja"), # IMDb alpha-3
|
||||
("pt-BR", "pt-BR"),
|
||||
(None, None),
|
||||
("", None),
|
||||
("und", None),
|
||||
("xx-not-a-tag", None),
|
||||
],
|
||||
)
|
||||
def test_parse_language(tag: str | None, expected: str | None) -> None:
|
||||
result = parse_language(tag)
|
||||
assert (str(result) if result else None) == expected
|
||||
|
||||
|
||||
def test_imdb_language_takes_the_first_spoken_language() -> None:
|
||||
data = {"spokenLanguages": [{"code": "jpn", "name": "Japanese"}, {"code": "eng", "name": "English"}]}
|
||||
assert imdb_language(data) == "jpn"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("data", [{}, {"spokenLanguages": []}, {"spokenLanguages": None}])
|
||||
def test_imdb_language_missing(data: dict) -> None:
|
||||
assert imdb_language(data) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("names", "expected"),
|
||||
[
|
||||
("Korean", "ko"),
|
||||
("Korean, English", "ko"), # OMDb lists the main language first
|
||||
("", None),
|
||||
("None", None), # OMDb's literal placeholder for unknown
|
||||
("Not A Language", None),
|
||||
],
|
||||
)
|
||||
def test_omdb_language_from_english_name(names: str, expected: str | None) -> None:
|
||||
assert omdb_language({"Language": names}) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("data", "expected"),
|
||||
[
|
||||
({"primary_language": "kor"}, "kor"), # /search
|
||||
({"originalLanguage": "kor"}, "kor"), # /series/{id}/extended
|
||||
({"primary_language": ""}, None),
|
||||
({}, None),
|
||||
],
|
||||
)
|
||||
def test_tvdb_language_key_variants(data: dict, expected: str | None) -> None:
|
||||
assert tvdb_language(data) == expected
|
||||
@@ -157,27 +157,6 @@ def test_cached_tvdb_result_keeps_enriched_ids() -> None:
|
||||
assert result.external_ids.tmdb_id == 615
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("kind", "path"), [("tv", "/series/73871/extended"), ("movie", "/movies/73871/extended")])
|
||||
def test_get_by_id_supplies_what_enrich_needs(monkeypatch: pytest.MonkeyPatch, kind: str, path: str) -> None:
|
||||
p = TVDBProvider()
|
||||
seen: list[str] = []
|
||||
|
||||
def fake_get(request_path: str, params: dict) -> dict:
|
||||
seen.append(request_path)
|
||||
return {
|
||||
"name": "Cowboy Bebop",
|
||||
"year": "1998",
|
||||
"originalLanguage": "jpn",
|
||||
"remoteIds": [{"sourceName": "IMDB", "id": "tt0213338"}],
|
||||
}
|
||||
|
||||
monkeypatch.setattr(p, "_get", fake_get)
|
||||
result = p.get_by_id(73871, kind)
|
||||
assert seen == [path]
|
||||
assert (result.title, result.year, result.original_language) == ("Cowboy Bebop", 1998, "jpn")
|
||||
assert result.external_ids.imdb_id == "tt0213338"
|
||||
|
||||
|
||||
def test_get_episodes_fails_closed_on_a_truncated_listing(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
p = TVDBProvider()
|
||||
pages: dict[int, object] = {0: {"episodes": [{"id": n} for n in range(500)]}, 1: None}
|
||||
|
||||
@@ -1,110 +0,0 @@
|
||||
import gzip
|
||||
import socket
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
import requests as rq
|
||||
|
||||
from unshackle.core.downloaders.requests import _is_content_encoded, download
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("value", "expected"),
|
||||
[
|
||||
(None, False),
|
||||
("", False),
|
||||
(" ", False),
|
||||
("identity", False),
|
||||
("IDENTITY", False),
|
||||
("identity, identity", False),
|
||||
("gzip", True),
|
||||
("GZIP", True),
|
||||
(" gzip ", True),
|
||||
("x-gzip", True),
|
||||
("br", True),
|
||||
("zstd", True),
|
||||
("deflate", True),
|
||||
("compress", True),
|
||||
("dcb", True),
|
||||
("gzip, br", True),
|
||||
("identity, gzip", True),
|
||||
("gzip, identity", True),
|
||||
("gzip,,", True),
|
||||
("some-future-coding", True),
|
||||
],
|
||||
)
|
||||
def test_is_content_encoded(value, expected):
|
||||
assert _is_content_encoded(value) is expected
|
||||
|
||||
|
||||
PLAIN = b"WEBVTT\n\n" + b"".join(f"{i:05d} cue text\n".encode() for i in range(2000))
|
||||
|
||||
|
||||
class _EncodingServer:
|
||||
"""Serves one gzip body, honouring Range against the encoded representation."""
|
||||
|
||||
def __init__(self):
|
||||
self.encoded = gzip.compress(PLAIN)
|
||||
self.sock = socket.socket()
|
||||
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
self.sock.bind(("127.0.0.1", 0))
|
||||
self.sock.listen(8)
|
||||
self.url = f"http://127.0.0.1:{self.sock.getsockname()[1]}/sub.vtt"
|
||||
threading.Thread(target=self._serve, daemon=True).start()
|
||||
|
||||
def _serve(self):
|
||||
while True:
|
||||
try:
|
||||
conn, _ = self.sock.accept()
|
||||
except OSError:
|
||||
return
|
||||
try:
|
||||
request = conn.recv(65536).decode("latin1")
|
||||
start = next(
|
||||
(
|
||||
int(line.split("=", 1)[1].split("-")[0])
|
||||
for line in request.split("\r\n")
|
||||
if line.lower().startswith("range:")
|
||||
),
|
||||
None,
|
||||
)
|
||||
if start is None:
|
||||
body = self.encoded
|
||||
head = f"HTTP/1.1 200 OK\r\nContent-Length: {len(body)}\r\n"
|
||||
else:
|
||||
body = self.encoded[start:]
|
||||
head = (
|
||||
f"HTTP/1.1 206 Partial Content\r\nContent-Length: {len(body)}\r\n"
|
||||
f"Content-Range: bytes {start}-{len(self.encoded) - 1}/{len(self.encoded)}\r\n"
|
||||
)
|
||||
conn.sendall(
|
||||
(head + "Content-Encoding: gzip\r\nAccept-Ranges: bytes\r\nConnection: close\r\n\r\n").encode()
|
||||
+ body
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def close(self):
|
||||
self.sock.close()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def encoding_server():
|
||||
server = _EncodingServer()
|
||||
yield server
|
||||
server.close()
|
||||
|
||||
|
||||
def test_encoded_body_is_decoded_on_disk(tmp_path, encoding_server):
|
||||
save_path = tmp_path / "sub.vtt"
|
||||
list(download(url=encoding_server.url, save_path=save_path, session=rq.Session()))
|
||||
assert save_path.read_bytes() == PLAIN
|
||||
|
||||
|
||||
def test_encoded_body_discards_a_partial_instead_of_range_resuming(tmp_path, encoding_server):
|
||||
save_path = tmp_path / "sub.vtt"
|
||||
save_path.with_name("sub.vtt.!dev").write_bytes(PLAIN[:5000])
|
||||
list(download(url=encoding_server.url, save_path=save_path, session=rq.Session()))
|
||||
assert save_path.read_bytes() == PLAIN
|
||||
@@ -1,164 +0,0 @@
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
import requests as rq
|
||||
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED
|
||||
from unshackle.core.downloaders.requests import _has_range_header, download
|
||||
from unshackle.core.downloaders.requests import requests as requests_downloader
|
||||
|
||||
# the package re-exports the `requests` function, shadowing the module of the same name
|
||||
downloader = sys.modules[download.__module__]
|
||||
|
||||
BODY = b"".join(f"{i:05d} payload\n".encode() for i in range(500))
|
||||
|
||||
|
||||
class _Server:
|
||||
"""Serves BODY, with a switch for the two failure modes retries have to handle."""
|
||||
|
||||
def __init__(self, mode):
|
||||
self.mode = mode
|
||||
self.sock = socket.socket()
|
||||
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
self.sock.bind(("127.0.0.1", 0))
|
||||
self.sock.listen(8)
|
||||
self.url = f"http://127.0.0.1:{self.sock.getsockname()[1]}/seg.mp4"
|
||||
self.requests = []
|
||||
threading.Thread(target=self._serve, daemon=True).start()
|
||||
|
||||
def _serve(self):
|
||||
while True:
|
||||
try:
|
||||
conn, _ = self.sock.accept()
|
||||
except OSError:
|
||||
return
|
||||
try:
|
||||
request = conn.recv(65536).decode("latin1")
|
||||
headers = dict(
|
||||
(name.strip().lower(), value.strip())
|
||||
for name, _, value in (line.partition(":") for line in request.split("\r\n"))
|
||||
if value
|
||||
)
|
||||
self.requests.append(headers)
|
||||
ranged = "range" in headers
|
||||
if self.mode == "unavailable":
|
||||
conn.sendall(b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
|
||||
elif ranged:
|
||||
conn.sendall(
|
||||
b"HTTP/1.1 416 Range Not Satisfiable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
|
||||
)
|
||||
else:
|
||||
conn.sendall(
|
||||
f"HTTP/1.1 200 OK\r\nContent-Length: {len(BODY)}\r\nConnection: close\r\n\r\n".encode() + BODY
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def close(self):
|
||||
self.sock.close()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_cancel():
|
||||
# the batch failure path sets the process-global cancel; leaking it makes every later
|
||||
# test that waits on the event (the speed limiter) return instantly
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
yield
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def no_retry_wait(monkeypatch):
|
||||
monkeypatch.setattr(downloader, "RETRY_WAIT", 0)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def server(request, no_retry_wait):
|
||||
server = _Server(request.param)
|
||||
yield server
|
||||
server.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", ["unavailable"], indirect=True)
|
||||
def test_exhausted_retries_raise_instead_of_reporting_success(tmp_path, server):
|
||||
save_path = tmp_path / "0.mp4"
|
||||
with pytest.raises(rq.HTTPError):
|
||||
list(download(url=server.url, save_path=save_path, session=rq.Session()))
|
||||
assert len(server.requests) == downloader.MAX_ATTEMPTS
|
||||
assert not save_path.exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", ["unavailable"], indirect=True)
|
||||
def test_cancelled_download_stays_silent(tmp_path, server, monkeypatch):
|
||||
# one attempt only, so a cancel check ordered after the exhaustion raise would fail here
|
||||
monkeypatch.setattr(downloader, "MAX_ATTEMPTS", 1)
|
||||
save_path = tmp_path / "0.mp4"
|
||||
DOWNLOAD_CANCELLED.set()
|
||||
list(download(url=server.url, save_path=save_path, session=rq.Session()))
|
||||
assert not save_path.exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", ["range_unsatisfiable"], indirect=True)
|
||||
def test_stale_partial_restarts_clean_on_416(tmp_path, server):
|
||||
save_path = tmp_path / "0.mp4"
|
||||
save_path.with_name("0.mp4.!dev").write_bytes(b"\x00" * len(BODY))
|
||||
list(download(url=server.url, save_path=save_path, session=rq.Session()))
|
||||
assert save_path.read_bytes() == BODY
|
||||
assert [r.get("range") for r in server.requests] == [f"bytes={len(BODY)}-", None]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", ["range_unsatisfiable"], indirect=True)
|
||||
def test_slice_segment_never_gets_a_resume_range(tmp_path, server):
|
||||
save_path = tmp_path / "0.mp4"
|
||||
save_path.with_name("0.mp4.!dev").write_bytes(b"\x00" * 128)
|
||||
with pytest.raises(OSError):
|
||||
list(download(url=server.url, save_path=save_path, session=rq.Session(), headers={"Range": "bytes=0-127"}))
|
||||
assert [r["range"] for r in server.requests] == ["bytes=0-127"] * downloader.MAX_ATTEMPTS
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", ["range_unsatisfiable"], indirect=True)
|
||||
def test_identity_encoding_requested_unless_the_caller_set_one(tmp_path, server):
|
||||
save_path = tmp_path / "0.mp4"
|
||||
list(download(url=server.url, save_path=save_path, session=rq.Session()))
|
||||
assert server.requests[-1]["accept-encoding"] == "identity"
|
||||
|
||||
list(
|
||||
download(
|
||||
url=server.url, save_path=tmp_path / "1.mp4", session=rq.Session(), headers={"accept-encoding": "gzip"}
|
||||
)
|
||||
)
|
||||
assert server.requests[-1]["accept-encoding"] == "gzip"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("server", ["unavailable"], indirect=True)
|
||||
def test_failed_segment_fails_the_batch(tmp_path, server):
|
||||
# a segment the batch never delivers must raise, not merge short of the segment count
|
||||
with pytest.raises(rq.HTTPError):
|
||||
list(
|
||||
requests_downloader(
|
||||
urls=[server.url, server.url],
|
||||
output_dir=tmp_path,
|
||||
filename="{i:01}.mp4",
|
||||
max_workers=2,
|
||||
)
|
||||
)
|
||||
assert sorted(p.name for p in tmp_path.iterdir() if p.suffix == ".mp4") == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("item", "expected"),
|
||||
[
|
||||
({}, False),
|
||||
({"headers": None}, False),
|
||||
({"headers": {}}, False),
|
||||
({"headers": {"Accept": "*/*"}}, False),
|
||||
({"headers": {"Range": "bytes=0-127"}}, True),
|
||||
({"headers": {"range": "bytes=0-127"}}, True),
|
||||
],
|
||||
)
|
||||
def test_has_range_header(item, expected):
|
||||
assert _has_range_header(item) is expected
|
||||
+400
-84
@@ -27,7 +27,7 @@ from uuid import UUID
|
||||
import click
|
||||
import yaml
|
||||
from click.core import ParameterSource
|
||||
from langcodes import Language, tag_is_valid
|
||||
from langcodes import Language
|
||||
from pymediainfo import MediaInfo
|
||||
from rich.console import Group
|
||||
from rich.padding import Padding
|
||||
@@ -92,6 +92,7 @@ from unshackle.core.utils.bitrate import apply_real_bitrates
|
||||
from unshackle.core.utils.click_types import (
|
||||
AUDIO_CODEC_LIST,
|
||||
LANGUAGE_RANGE,
|
||||
OFFSET,
|
||||
QUALITY_LIST,
|
||||
SEASON_RANGE,
|
||||
SLOW_DELAY_RANGE,
|
||||
@@ -119,14 +120,6 @@ class SkippedSubtitle(TypedDict):
|
||||
DL_OPTION_ALIASES = {"range": "range_", "list": "list_"}
|
||||
|
||||
|
||||
def parse_language(tag: Optional[str]) -> Optional[Language]:
|
||||
"""A provider's original-language tag as a Language, or None if it is absent or not a real tag."""
|
||||
tag = (tag or "").strip()
|
||||
if not tag or not tag_is_valid(tag) or tag.startswith("und"):
|
||||
return None
|
||||
return Language.get(tag)
|
||||
|
||||
|
||||
def normalize_dl_config(dl_config: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Map aliased config keys (e.g. ``range``) to their Click parameter names (``range_``)."""
|
||||
return {DL_OPTION_ALIASES.get(key, key): value for key, value in dl_config.items()}
|
||||
@@ -616,7 +609,7 @@ class dl:
|
||||
"tvdb_id",
|
||||
type=int,
|
||||
default=None,
|
||||
help="Use this TVDB ID for --tvdb-order and --enrich instead of looking the series up automatically.",
|
||||
help="Use this TVDB ID for --tvdb-order instead of looking the series up automatically.",
|
||||
)
|
||||
@click.option(
|
||||
"--tvdb-order",
|
||||
@@ -636,10 +629,7 @@ class dl:
|
||||
"--enrich",
|
||||
is_flag=True,
|
||||
default=False,
|
||||
help=(
|
||||
"Override show title and year from external source, and fill in the original language "
|
||||
"if the service did not provide one. Requires --tmdb, --imdb, --tvdb, or --animeapi."
|
||||
),
|
||||
help="Override show title and year from external source. Requires --tmdb, --imdb, or --animeapi.",
|
||||
)
|
||||
@click.option(
|
||||
"--imdb",
|
||||
@@ -768,6 +758,93 @@ class dl:
|
||||
default=False,
|
||||
help="Continue with best available quality if requested resolutions are not available.",
|
||||
)
|
||||
@click.option(
|
||||
"--cross-video",
|
||||
nargs=2,
|
||||
type=(str, str),
|
||||
default=None,
|
||||
metavar="SERVICE URL",
|
||||
help="Take video tracks from another service instead of this one.",
|
||||
)
|
||||
@click.option(
|
||||
"--cross-audio",
|
||||
nargs=2,
|
||||
type=(str, str),
|
||||
default=None,
|
||||
metavar="SERVICE URL",
|
||||
help="Take audio tracks from another service instead of this one.",
|
||||
)
|
||||
@click.option(
|
||||
"--cross-subtitles",
|
||||
nargs=2,
|
||||
type=(str, str),
|
||||
default=None,
|
||||
metavar="SERVICE URL",
|
||||
help="Take subtitle tracks from another service instead of this one.",
|
||||
)
|
||||
@click.option(
|
||||
"--cross-chapters",
|
||||
nargs=2,
|
||||
type=(str, str),
|
||||
default=None,
|
||||
metavar="SERVICE URL",
|
||||
help="Take chapters from another service instead of this one.",
|
||||
)
|
||||
@click.option(
|
||||
"--cross-audio-offset",
|
||||
type=OFFSET,
|
||||
default=None,
|
||||
help="Shift cross-sourced audio in the mux, e.g. 10s, 500ms or -5.5s.",
|
||||
)
|
||||
@click.option(
|
||||
"--cross-subtitle-offset",
|
||||
type=OFFSET,
|
||||
default=None,
|
||||
help="Shift cross-sourced subtitles in the mux, e.g. 10s, 500ms or -5.5s.",
|
||||
)
|
||||
@click.option(
|
||||
"--cross-profile",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Profile used for cross-service credentials. Defaults to --profile.",
|
||||
)
|
||||
@click.option(
|
||||
"--cross-proxy",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Proxy for every cross-service. Overrides each cross-service's own proxy configuration.",
|
||||
)
|
||||
@click.option(
|
||||
"--cross-video-wanted",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Episode to take video from the cross-service, e.g. S01E02. Overrides --cross-wanted for video.",
|
||||
)
|
||||
@click.option(
|
||||
"--cross-audio-wanted",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Episode to take audio from the cross-service, e.g. S01E02. Overrides --cross-wanted for audio.",
|
||||
)
|
||||
@click.option(
|
||||
"--cross-subtitles-wanted",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Episode to take subtitles from the cross-service, e.g. S01E02. Overrides --cross-wanted for subtitles.",
|
||||
)
|
||||
@click.option(
|
||||
"--cross-chapters-wanted",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Episode to take chapters from the cross-service, e.g. S01E02. Overrides --cross-wanted for chapters.",
|
||||
)
|
||||
@click.option(
|
||||
"--cross-wanted",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Episode to take from the cross-services, e.g. S01E02. Default fallback when no per-type override "
|
||||
"is given; otherwise the matching season and episode.",
|
||||
)
|
||||
@click.option(
|
||||
"--remote",
|
||||
is_flag=True,
|
||||
@@ -806,6 +883,19 @@ class dl:
|
||||
animeapi_id: Optional[str] = None,
|
||||
enrich: bool = False,
|
||||
output_dir: Optional[Path] = None,
|
||||
cross_video: Optional[tuple[str, str]] = None,
|
||||
cross_audio: Optional[tuple[str, str]] = None,
|
||||
cross_subtitles: Optional[tuple[str, str]] = None,
|
||||
cross_chapters: Optional[tuple[str, str]] = None,
|
||||
cross_audio_offset: Optional[int] = None,
|
||||
cross_subtitle_offset: Optional[int] = None,
|
||||
cross_profile: Optional[str] = None,
|
||||
cross_proxy: Optional[str] = None,
|
||||
cross_video_wanted: Optional[str] = None,
|
||||
cross_audio_wanted: Optional[str] = None,
|
||||
cross_subtitles_wanted: Optional[str] = None,
|
||||
cross_chapters_wanted: Optional[str] = None,
|
||||
cross_wanted: Optional[str] = None,
|
||||
*_: Any,
|
||||
**__: Any,
|
||||
):
|
||||
@@ -859,6 +949,24 @@ class dl:
|
||||
self.animeapi_title: Optional[str] = None
|
||||
self.output_dir = output_dir
|
||||
|
||||
self.cross_video = ctx.params.get("cross_video", cross_video)
|
||||
self.cross_audio = ctx.params.get("cross_audio", cross_audio)
|
||||
self.cross_subtitles = ctx.params.get("cross_subtitles", cross_subtitles)
|
||||
self.cross_chapters = ctx.params.get("cross_chapters", cross_chapters)
|
||||
self.cross_audio_offset = ctx.params.get("cross_audio_offset", cross_audio_offset)
|
||||
self.cross_subtitle_offset = ctx.params.get("cross_subtitle_offset", cross_subtitle_offset)
|
||||
self.cross_profile = ctx.params.get("cross_profile", cross_profile) or profile
|
||||
self.cross_proxy = ctx.params.get("cross_proxy", cross_proxy)
|
||||
self.cross_wanted = ctx.params.get("cross_wanted", cross_wanted)
|
||||
self.cross_wanted_by_type: dict[str, Optional[str]] = {
|
||||
"video": ctx.params.get("cross_video_wanted", cross_video_wanted),
|
||||
"audio": ctx.params.get("cross_audio_wanted", cross_audio_wanted),
|
||||
"subtitles": ctx.params.get("cross_subtitles_wanted", cross_subtitles_wanted),
|
||||
"chapters": ctx.params.get("cross_chapters_wanted", cross_chapters_wanted),
|
||||
}
|
||||
# Held outside track.data because the values are live objects, not exportable metadata.
|
||||
self.cross_track_sources: dict[str, tuple[Service, Title_T, Any, Vaults]] = {}
|
||||
|
||||
if animeapi_id:
|
||||
from unshackle.core.utils.animeapi import resolve_animeapi
|
||||
|
||||
@@ -871,10 +979,8 @@ class dl:
|
||||
if not self.tvdb_id and anime_ids.tvdb_id:
|
||||
self.tvdb_id = anime_ids.tvdb_id
|
||||
|
||||
if self.enrich and not (self.tmdb_id or self.imdb_id or self.tvdb_id or self.animeapi_title):
|
||||
raise click.UsageError(
|
||||
"--enrich requires --tmdb, --imdb, --tvdb, or --animeapi to provide a metadata source."
|
||||
)
|
||||
if self.enrich and not (self.tmdb_id or self.imdb_id or self.animeapi_title):
|
||||
raise click.UsageError("--enrich requires --tmdb, --imdb, or --animeapi to provide a metadata source.")
|
||||
|
||||
# Initialize debug logger with service name if debug logging is enabled
|
||||
if config.debug or logging.root.level == logging.DEBUG:
|
||||
@@ -1263,6 +1369,10 @@ class dl:
|
||||
config=self.service_config, cdm=self.cdm, proxy_providers=self.proxy_providers, profile=self.profile
|
||||
)
|
||||
|
||||
# A service reads dl-level options off ctx.parent.params, so a cross-service is handed a
|
||||
# copy of ours rather than a hand-written set of defaults that drifts as options are added.
|
||||
self.dl_params: dict[str, Any] = dict(ctx.params)
|
||||
|
||||
if repack:
|
||||
config.repack = True
|
||||
|
||||
@@ -1274,6 +1384,195 @@ class dl:
|
||||
# able to keep `self` as the first positional
|
||||
self.cli._result_callback = self.result
|
||||
|
||||
@property
|
||||
def has_cross_mux(self) -> bool:
|
||||
return any((self.cross_video, self.cross_audio, self.cross_subtitles, self.cross_chapters))
|
||||
|
||||
def build_vaults(self, vault_tag: str) -> Vaults:
|
||||
"""Build and load a Vaults keyed by a service tag, so its keys cache under that owner."""
|
||||
vaults = Vaults(vault_tag)
|
||||
for vault in config.key_vaults:
|
||||
vault_type = vault["type"]
|
||||
vault_name = vault.get("name", vault_type)
|
||||
vault_copy = vault.copy()
|
||||
del vault_copy["type"]
|
||||
|
||||
if vault_type.lower() == "api" and "decrypt_labs" in vault_name.lower():
|
||||
if not vault_copy.get("token") and config.decrypt_labs_api_key:
|
||||
vault_copy["token"] = config.decrypt_labs_api_key
|
||||
|
||||
if vault_type.lower() == "sqlite":
|
||||
vaults.load_critical(vault_type, **vault_copy)
|
||||
else:
|
||||
vaults.load(vault_type, **vault_copy)
|
||||
return vaults
|
||||
|
||||
def load_cross_service(self, tag: str, url: str) -> tuple[Service, Any, Vaults]:
|
||||
"""Load and authenticate another service plus its own CDM and vaults, for muxing its tracks."""
|
||||
service_cls: Any = Services.load(tag)
|
||||
|
||||
service_config_path = Services.get_path(tag) / config.filenames.config
|
||||
service_config = (
|
||||
yaml.safe_load(service_config_path.read_text(encoding="utf8")) if service_config_path.exists() else {}
|
||||
)
|
||||
|
||||
# Stand in for the dl group Click would have invoked the service under.
|
||||
parent_ctx = click.Context(self.cli, info_name="dl")
|
||||
parent_params = {**self.dl_params, "profile": self.cross_profile}
|
||||
if self.cross_proxy:
|
||||
parent_params["proxy"] = self.cross_proxy
|
||||
parent_params["no_proxy"] = False
|
||||
parent_ctx.params = parent_params
|
||||
|
||||
# Keys licensed for this service cache under its own vault, not the primary's; its CDM binds
|
||||
# to those same vaults so lookups and writes stay with the owning service.
|
||||
cross_vaults = self.build_vaults(Services.get_vault_tag(tag))
|
||||
cross_cdm: Any = self.get_cdm(tag, self.cross_profile, vaults=cross_vaults)
|
||||
|
||||
ctx = click.Context(service_cls.cli, parent=parent_ctx, info_name=tag)
|
||||
ctx.obj = ContextData(
|
||||
config=service_config,
|
||||
cdm=cross_cdm,
|
||||
proxy_providers=self.proxy_providers,
|
||||
profile=self.cross_profile,
|
||||
)
|
||||
|
||||
kwargs = {param.name: param.default for param in service_cls.cli.params if param.name}
|
||||
kwargs["title"] = url
|
||||
|
||||
service: Service = service_cls(ctx, **kwargs)
|
||||
service.authenticate(
|
||||
self.get_cookie_jar(tag, self.cross_profile), self.get_credentials(tag, self.cross_profile)
|
||||
)
|
||||
return service, cross_cdm, cross_vaults
|
||||
|
||||
def match_cross_title(self, title: Title_T, cross_titles: Iterable[Title_T], track_type: str) -> Optional[Title_T]:
|
||||
"""Find the counterpart of a title in another service's catalogue for a given track type."""
|
||||
if isinstance(title, Movie):
|
||||
return next((x for x in cross_titles if isinstance(x, Movie)), None)
|
||||
|
||||
if not isinstance(title, Episode):
|
||||
return None
|
||||
|
||||
season, number = title.season, title.number
|
||||
# Per-type override wins; --cross-wanted is the shared fallback; else the matching S/E.
|
||||
wanted = self.cross_wanted_by_type.get(track_type) or self.cross_wanted
|
||||
if wanted:
|
||||
match = re.match(r"S(\d+)E(\d+)$", wanted, re.IGNORECASE)
|
||||
if not match:
|
||||
raise click.UsageError(f"cross-wanted must look like S01E02, not {wanted!r}")
|
||||
season, number = int(match.group(1)), int(match.group(2))
|
||||
|
||||
return next(
|
||||
(x for x in cross_titles if isinstance(x, Episode) and x.season == season and x.number == number), None
|
||||
)
|
||||
|
||||
def fetch_cross_tracks(self, title: Title_T) -> dict[str, tuple[Service, Title_T, Tracks, Any, Vaults]]:
|
||||
"""Resolve every --cross-* option to the service, title, tracks, CDM and vaults it names."""
|
||||
specs = (
|
||||
("video", self.cross_video),
|
||||
("audio", self.cross_audio),
|
||||
("subtitles", self.cross_subtitles),
|
||||
("chapters", self.cross_chapters),
|
||||
)
|
||||
|
||||
# Sources are per-title; a stale id recorded for a previous episode must not shadow one of
|
||||
# this episode's own tracks in drm_source.
|
||||
self.cross_track_sources.clear()
|
||||
|
||||
# One service may supply several track types; load and authenticate it only once, and reuse
|
||||
# a matched title's tracks (a per-type --cross-*-wanted may point types at different titles).
|
||||
loaded: dict[tuple[str, str], tuple[Service, Any, Vaults, list[Title_T]]] = {}
|
||||
track_pools: dict[int, Tracks] = {}
|
||||
sources: dict[str, tuple[Service, Title_T, Tracks, Any, Vaults]] = {}
|
||||
|
||||
for track_type, spec in specs:
|
||||
if not spec:
|
||||
continue
|
||||
|
||||
key = (Services.get_tag(spec[0]), spec[1])
|
||||
if key not in loaded:
|
||||
self.log.info(f"Cross-mux: loading {key[0]}")
|
||||
service, cdm, vaults = self.load_cross_service(*key)
|
||||
loaded[key] = (service, cdm, vaults, list(service.get_titles()))
|
||||
service, cdm, vaults, titles = loaded[key]
|
||||
|
||||
cross_title = self.match_cross_title(title, titles, track_type)
|
||||
if not cross_title:
|
||||
self.log.warning(f"Cross-mux: {key[0]} has no title matching {title}, keeping this service's own.")
|
||||
continue
|
||||
|
||||
if id(cross_title) not in track_pools:
|
||||
self.log.info(f"Cross-mux: getting {track_type} from {key[0]}")
|
||||
tracks = service.get_tracks(cross_title)
|
||||
tracks.chapters = service.get_chapters(cross_title)
|
||||
track_pools[id(cross_title)] = tracks
|
||||
|
||||
sources[track_type] = (service, cross_title, track_pools[id(cross_title)], cdm, vaults)
|
||||
|
||||
return sources
|
||||
|
||||
def apply_cross_tracks(
|
||||
self, title: Title_T, sources: dict[str, tuple[Service, Title_T, Tracks, Any, Vaults]]
|
||||
) -> None:
|
||||
"""Merge cross-sourced audio/subtitles into this title (video/chapters replace) and record sources."""
|
||||
|
||||
def adopt(
|
||||
tracks: Iterable[AnyTrack],
|
||||
service: Service,
|
||||
cross_title: Title_T,
|
||||
cdm: Any,
|
||||
vaults: Vaults,
|
||||
offset: Optional[int],
|
||||
) -> None:
|
||||
for track in tracks:
|
||||
# Track.download() already prefers track.session over the primary service's.
|
||||
track.session = service.session
|
||||
self.cross_track_sources[track.id] = (service, cross_title, cdm, vaults)
|
||||
track.data["cross_source"] = service.__class__.__name__
|
||||
if offset:
|
||||
track.data["sync_offset_ms"] = offset
|
||||
|
||||
# Ids must stay unique across every track kept for this title, or a cross track's entry in
|
||||
# cross_track_sources would shadow a primary track's and route its DRM to the wrong service.
|
||||
seen_ids = {t.id for t in (*title.tracks.audio, *title.tracks.subtitles)}
|
||||
|
||||
def namespace(tracks: Iterable[AnyTrack], service: Service) -> None:
|
||||
for track in tracks:
|
||||
if track.id in seen_ids:
|
||||
track.id = f"{track.id}_{service.__class__.__name__.lower()}"
|
||||
seen_ids.add(track.id)
|
||||
|
||||
# Exactly one video source and chapters are singular, so those replace outright.
|
||||
if "video" in sources:
|
||||
service, cross_title, cross_tracks, cdm, vaults = sources["video"]
|
||||
namespace(cross_tracks.videos, service)
|
||||
title.tracks.videos = cross_tracks.videos
|
||||
adopt(title.tracks.videos, service, cross_title, cdm, vaults, None)
|
||||
|
||||
# Audio and subtitles merge so best-per-language selection runs across the primary's own
|
||||
# tracks and the cross-sourced ones together.
|
||||
seen_ids.update(t.id for t in title.tracks.videos)
|
||||
|
||||
if "audio" in sources:
|
||||
service, cross_title, cross_tracks, cdm, vaults = sources["audio"]
|
||||
namespace(cross_tracks.audio, service)
|
||||
adopt(cross_tracks.audio, service, cross_title, cdm, vaults, self.cross_audio_offset)
|
||||
title.tracks.audio.extend(cross_tracks.audio)
|
||||
|
||||
if "subtitles" in sources:
|
||||
service, cross_title, cross_tracks, cdm, vaults = sources["subtitles"]
|
||||
namespace(cross_tracks.subtitles, service)
|
||||
adopt(cross_tracks.subtitles, service, cross_title, cdm, vaults, self.cross_subtitle_offset)
|
||||
title.tracks.subtitles.extend(cross_tracks.subtitles)
|
||||
|
||||
if "chapters" in sources:
|
||||
title.tracks.chapters = sources["chapters"][2].chapters
|
||||
|
||||
def drm_source(self, track: AnyTrack, service: Service, title: Title_T) -> tuple[Service, Title_T, Any, Vaults]:
|
||||
"""The service, title, CDM and vaults that licence a track; the primary's unless cross-sourced."""
|
||||
return self.cross_track_sources.get(track.id, (service, title, self.cdm, self.vaults))
|
||||
|
||||
@with_task_temp
|
||||
def result(
|
||||
self,
|
||||
@@ -1526,7 +1825,6 @@ class dl:
|
||||
|
||||
enrich_title: Optional[str] = None
|
||||
enrich_year: Optional[int] = None
|
||||
enrich_lang: Optional[Language] = None
|
||||
|
||||
if self.animeapi_title:
|
||||
enrich_title = self.animeapi_title
|
||||
@@ -1539,46 +1837,33 @@ class dl:
|
||||
enrich_year = providers.get_year_by_id(
|
||||
self.tmdb_id, kind, title_cacher, cache_title_id, cache_region, cache_account_hash
|
||||
)
|
||||
enrich_lang = parse_language(
|
||||
providers.get_language_by_id(
|
||||
self.tmdb_id, kind, title_cacher, cache_title_id, cache_region, cache_account_hash
|
||||
)
|
||||
)
|
||||
elif self.imdb_id:
|
||||
for name in ("imdbapi", "omdb"):
|
||||
provider = providers.get_provider(name)
|
||||
imdb_result = provider.get_by_id(self.imdb_id, kind) if provider else None
|
||||
imdbapi = providers.get_provider("imdbapi")
|
||||
if imdbapi:
|
||||
imdb_result = imdbapi.get_by_id(self.imdb_id, kind)
|
||||
if imdb_result:
|
||||
if not enrich_title:
|
||||
enrich_title = imdb_result.title
|
||||
enrich_year = imdb_result.year
|
||||
enrich_lang = parse_language(imdb_result.original_language)
|
||||
break
|
||||
elif self.tvdb_id:
|
||||
provider = providers.get_provider("tvdb")
|
||||
tvdb_result = provider.get_by_id(self.tvdb_id, kind) if provider else None
|
||||
if tvdb_result:
|
||||
if not enrich_title:
|
||||
enrich_title = tvdb_result.title
|
||||
enrich_year = tvdb_result.year
|
||||
enrich_lang = parse_language(tvdb_result.original_language)
|
||||
|
||||
if enrich_lang:
|
||||
self.log.info(f"Original language from metadata: {enrich_lang}")
|
||||
elif not (enrich_title or enrich_year):
|
||||
self.log.warning("--enrich found no metadata; is the provider's API key configured?")
|
||||
|
||||
if enrich_title or enrich_year or enrich_lang:
|
||||
for t in titles if isinstance(titles, (Series, Movies)) else [titles]:
|
||||
if enrich_title or enrich_year:
|
||||
if isinstance(titles, (Series, Movies)):
|
||||
for t in titles:
|
||||
if enrich_title:
|
||||
if isinstance(t, Episode):
|
||||
t.title = enrich_title
|
||||
else:
|
||||
t.name = enrich_title
|
||||
if enrich_year and not t.year:
|
||||
t.year = enrich_year
|
||||
else:
|
||||
if enrich_title:
|
||||
if isinstance(t, Episode):
|
||||
t.title = enrich_title
|
||||
if isinstance(titles, Episode):
|
||||
titles.title = enrich_title
|
||||
else:
|
||||
t.name = enrich_title
|
||||
if enrich_year and not t.year:
|
||||
t.year = enrich_year
|
||||
if enrich_lang and not t.language:
|
||||
t.language = enrich_lang
|
||||
titles.name = enrich_title
|
||||
if enrich_year and not titles.year:
|
||||
titles.year = enrich_year
|
||||
|
||||
if self.tvdb_order and isinstance(titles, Series):
|
||||
titles = self.apply_tvdb_order(titles, title_cacher, cache_title_id, cache_region, cache_account_hash)
|
||||
@@ -2387,6 +2672,22 @@ class dl:
|
||||
level="INFO", operation="get_tracks", service=self.service, context=tracks_info
|
||||
)
|
||||
|
||||
if self.has_cross_mux:
|
||||
with console.status("Getting Cross-Service Tracks...", spinner="dots"):
|
||||
try:
|
||||
cross_sources = self.fetch_cross_tracks(title)
|
||||
except Exception as e:
|
||||
if self.debug_logger:
|
||||
self.debug_logger.log_error(
|
||||
"cross_mux", e, service=self.service, context={"title": str(title)}
|
||||
)
|
||||
raise
|
||||
|
||||
if cross_sources:
|
||||
self.apply_cross_tracks(title, cross_sources)
|
||||
applied = ", ".join(f"{k} from {v[0].__class__.__name__}" for k, v in cross_sources.items())
|
||||
self.log.info(f"Cross-mux: using {applied}")
|
||||
|
||||
# strip SDH subs to non-SDH if no equivalent same-lang non-SDH is available
|
||||
# uses a loose check, e.g, wont strip en-US SDH sub if a non-SDH en-GB is available
|
||||
# Check if automatic SDH stripping is enabled in config
|
||||
@@ -3067,36 +3368,39 @@ class dl:
|
||||
with SyncLive(Padding(download_table, (1, 5)), console=console, refresh_per_second=20):
|
||||
|
||||
def download_track(track: AnyTrack, i: int) -> None:
|
||||
drm_service, drm_title, drm_cdm, drm_vaults = self.drm_source(track, service, title)
|
||||
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,
|
||||
title=drm_title,
|
||||
certificate=partial(
|
||||
service.get_widevine_service_certificate,
|
||||
title=title,
|
||||
drm_service.get_widevine_service_certificate,
|
||||
title=drm_title,
|
||||
track=track,
|
||||
),
|
||||
licence=partial(
|
||||
service.get_playready_license
|
||||
if is_playready_cdm(self.cdm)
|
||||
else service.get_widevine_license,
|
||||
title=title,
|
||||
drm_service.get_playready_license
|
||||
if is_playready_cdm(drm_cdm)
|
||||
else drm_service.get_widevine_license,
|
||||
title=drm_title,
|
||||
track=track,
|
||||
),
|
||||
clearkey_licence=partial(
|
||||
service.get_clearkey_license,
|
||||
title=title,
|
||||
drm_service.get_clearkey_license,
|
||||
title=drm_title,
|
||||
track=track,
|
||||
),
|
||||
cdm_only=cdm_only,
|
||||
vaults_only=vaults_only,
|
||||
export=export_path,
|
||||
service_session=service.session,
|
||||
service_session=drm_service.session,
|
||||
cdm=drm_cdm,
|
||||
vaults=drm_vaults,
|
||||
),
|
||||
cdm=self.cdm,
|
||||
cdm=drm_cdm,
|
||||
max_workers=workers,
|
||||
progress=tracks_progress_callables[i],
|
||||
)
|
||||
@@ -3936,6 +4240,8 @@ class dl:
|
||||
vaults_only: bool = False,
|
||||
export: Optional[Path] = None,
|
||||
service_session: Optional[Any] = None,
|
||||
cdm: Optional[object] = None,
|
||||
vaults: Optional[Vaults] = None,
|
||||
) -> None:
|
||||
"""
|
||||
Prepare the DRM by getting decryption data like KIDs, Keys, and such.
|
||||
@@ -3944,6 +4250,9 @@ class dl:
|
||||
if not drm:
|
||||
return
|
||||
|
||||
cdm = cdm if cdm is not None else self.cdm
|
||||
vaults = vaults if vaults is not None else self.vaults
|
||||
|
||||
server_cdm = getattr(self, "server_cdm", False)
|
||||
|
||||
if server_cdm:
|
||||
@@ -4004,26 +4313,38 @@ class dl:
|
||||
|
||||
if not server_cdm:
|
||||
if isinstance(drm, Widevine):
|
||||
if not is_widevine_cdm(self.cdm):
|
||||
widevine_cdm = self.get_cdm(self.service, self.profile, drm="widevine", quality=track_quality)
|
||||
if not is_widevine_cdm(cdm):
|
||||
widevine_cdm = self.get_cdm(
|
||||
self.service, self.profile, drm="widevine", quality=track_quality, vaults=vaults
|
||||
)
|
||||
if widevine_cdm and is_widevine_cdm(widevine_cdm):
|
||||
if track_quality:
|
||||
self.log.info(f"Switching to Widevine CDM for Widevine {track_quality}p content")
|
||||
else:
|
||||
self.log.info("Switching to Widevine CDM for Widevine content")
|
||||
self.cdm = widevine_cdm
|
||||
if cdm is self.cdm:
|
||||
# Persist the switch only for the primary CDM so its later tracks skip the
|
||||
# re-load; a cross-sourced CDM stays local and must not clobber the primary's.
|
||||
self.cdm = widevine_cdm
|
||||
cdm = widevine_cdm
|
||||
else:
|
||||
raise ValueError(f"Title needs a Widevine CDM but {self.service} is configured with PlayReady.")
|
||||
|
||||
elif isinstance(drm, PlayReady):
|
||||
if not is_playready_cdm(self.cdm):
|
||||
playready_cdm = self.get_cdm(self.service, self.profile, drm="playready", quality=track_quality)
|
||||
if not is_playready_cdm(cdm):
|
||||
playready_cdm = self.get_cdm(
|
||||
self.service, self.profile, drm="playready", quality=track_quality, vaults=vaults
|
||||
)
|
||||
if playready_cdm and is_playready_cdm(playready_cdm):
|
||||
if track_quality:
|
||||
self.log.info(f"Switching to PlayReady CDM for PlayReady {track_quality}p content")
|
||||
else:
|
||||
self.log.info("Switching to PlayReady CDM for PlayReady content")
|
||||
self.cdm = playready_cdm
|
||||
if cdm is self.cdm:
|
||||
# Persist the switch only for the primary CDM so its later tracks skip the
|
||||
# re-load; a cross-sourced CDM stays local and must not clobber the primary's.
|
||||
self.cdm = playready_cdm
|
||||
cdm = playready_cdm
|
||||
else:
|
||||
raise ValueError(f"Title needs a PlayReady CDM but {self.service} is configured with Widevine.")
|
||||
|
||||
@@ -4088,15 +4409,13 @@ class dl:
|
||||
continue
|
||||
|
||||
if not cdm_only:
|
||||
content_key, vault_used = self.vaults.get_key(kid)
|
||||
content_key, vault_used = vaults.get_key(kid)
|
||||
if content_key:
|
||||
drm.content_keys[kid] = content_key
|
||||
label = f"[text2]{kid.hex}:{content_key}{is_track_kid} from {vault_used}"
|
||||
if not any(f"{kid.hex}:{content_key}" in x.label for x in cek_tree.children):
|
||||
cek_tree.add(label)
|
||||
pending_vault_writes.append(
|
||||
partial(self.vaults.add_key, kid, content_key, excluding=vault_used)
|
||||
)
|
||||
pending_vault_writes.append(partial(vaults.add_key, kid, content_key, excluding=vault_used))
|
||||
self.LICENSE_KEY_CACHE[kid] = content_key
|
||||
|
||||
if self.debug_logger:
|
||||
@@ -4150,9 +4469,9 @@ class dl:
|
||||
|
||||
try:
|
||||
if self.service == "NF":
|
||||
drm.get_NF_content_keys(cdm=self.cdm, licence=licence, certificate=certificate)
|
||||
drm.get_NF_content_keys(cdm=cdm, licence=licence, certificate=certificate)
|
||||
else:
|
||||
drm.get_content_keys(cdm=self.cdm, licence=licence, certificate=certificate)
|
||||
drm.get_content_keys(cdm=cdm, licence=licence, certificate=certificate)
|
||||
except Exception as e:
|
||||
if drm.content_keys:
|
||||
self.log.debug(f"License call failed but keys already in content_keys: {e}")
|
||||
@@ -4289,15 +4608,13 @@ class dl:
|
||||
continue
|
||||
|
||||
if not cdm_only:
|
||||
content_key, vault_used = self.vaults.get_key(kid)
|
||||
content_key, vault_used = vaults.get_key(kid)
|
||||
if content_key:
|
||||
drm.content_keys[kid] = content_key
|
||||
label = f"[text2]{kid.hex}:{content_key}{is_track_kid} from {vault_used}"
|
||||
if not any(f"{kid.hex}:{content_key}" in x.label for x in cek_tree.children):
|
||||
cek_tree.add(label)
|
||||
pending_vault_writes.append(
|
||||
partial(self.vaults.add_key, kid, content_key, excluding=vault_used)
|
||||
)
|
||||
pending_vault_writes.append(partial(vaults.add_key, kid, content_key, excluding=vault_used))
|
||||
self.LICENSE_KEY_CACHE[kid] = content_key
|
||||
|
||||
if self.debug_logger:
|
||||
@@ -4340,7 +4657,7 @@ class dl:
|
||||
from_vaults = drm.content_keys.copy()
|
||||
|
||||
try:
|
||||
drm.get_content_keys(cdm=self.cdm, licence=licence, certificate=certificate)
|
||||
drm.get_content_keys(cdm=cdm, licence=licence, certificate=certificate)
|
||||
except Exception as e:
|
||||
if drm.content_keys:
|
||||
self.log.debug(f"License call failed but keys already in content_keys: {e}")
|
||||
@@ -4441,15 +4758,13 @@ class dl:
|
||||
continue
|
||||
|
||||
if not cdm_only:
|
||||
content_key, vault_used = self.vaults.get_key(kid)
|
||||
content_key, vault_used = vaults.get_key(kid)
|
||||
if content_key:
|
||||
drm.content_keys[kid] = content_key
|
||||
label = f"[text2]{kid.hex}:{content_key}{is_track_kid} from {vault_used}"
|
||||
if not any(f"{kid.hex}:{content_key}" in x.label for x in cek_tree.children):
|
||||
cek_tree.add(label)
|
||||
pending_vault_writes.append(
|
||||
partial(self.vaults.add_key, kid, content_key, excluding=vault_used)
|
||||
)
|
||||
pending_vault_writes.append(partial(vaults.add_key, kid, content_key, excluding=vault_used))
|
||||
self.LICENSE_KEY_CACHE[kid] = content_key
|
||||
elif vaults_only:
|
||||
msg = f"No Vault has a Key for {kid.hex} and --vaults-only was used"
|
||||
@@ -4639,6 +4954,7 @@ class dl:
|
||||
profile: Optional[str] = None,
|
||||
drm: Optional[str] = None,
|
||||
quality: Optional[int] = None,
|
||||
vaults: Optional[Vaults] = None,
|
||||
) -> Optional[object]:
|
||||
"""
|
||||
Get CDM for a specified service (either Local or Remote CDM).
|
||||
@@ -4731,4 +5047,4 @@ class dl:
|
||||
|
||||
from unshackle.core.cdm import load_cdm
|
||||
|
||||
return load_cdm(cdm_name, service_name=service, vaults=self.vaults)
|
||||
return load_cdm(cdm_name, service_name=service, vaults=vaults if vaults is not None else self.vaults)
|
||||
|
||||
@@ -764,7 +764,7 @@ async def download(request: web.Request) -> web.Response:
|
||||
description: Anime database ID via AnimeAPI, e.g. mal:12345 (default - None)
|
||||
enrich:
|
||||
type: boolean
|
||||
description: Override show title and year from external source, and fill in the original language. Requires one of tmdb_id, imdb_id, tvdb_id or animeapi_id (default - false)
|
||||
description: Override show title and year from external source (default - false)
|
||||
no_folder:
|
||||
type: boolean
|
||||
description: Disable folder creation for TV shows (default - false)
|
||||
@@ -794,7 +794,7 @@ async def download(request: web.Request) -> web.Response:
|
||||
description: Use this IMDB ID (e.g. tt1375666) for tagging (default - None)
|
||||
tvdb_id:
|
||||
type: integer
|
||||
description: Use this TVDB ID for tagging, episode ordering and enrichment (default - None)
|
||||
description: Use this TVDB ID for tagging and episode ordering (default - None)
|
||||
tvdb_order:
|
||||
type: string
|
||||
enum: [official, dvd, absolute, alternate, regional]
|
||||
|
||||
@@ -161,29 +161,6 @@ def _is_rnet_session(session: Any) -> bool:
|
||||
return isinstance(session, RnetSession)
|
||||
|
||||
|
||||
def _is_content_encoded(value: Optional[str]) -> bool:
|
||||
"""
|
||||
Check a Content-Encoding value for any coding other than absent or `identity`.
|
||||
|
||||
Reading .raw skips urllib3's decoding, so an encoded body has to go through
|
||||
iter_content or the compressed bytes land on disk as the payload. Codings
|
||||
urllib3 cannot decode still count: an allowlist fails open on whatever token
|
||||
a server sends next, and the cost of guessing wrong is a corrupt file.
|
||||
"""
|
||||
return any(coding.strip() not in ("", "identity") for coding in (value or "").lower().split(","))
|
||||
|
||||
|
||||
def _has_range_header(item: dict[str, Any]) -> bool:
|
||||
"""
|
||||
Whether the caller asked for a byte-range slice of a parent resource
|
||||
(DASH SegmentBase, HLS EXT-X-BYTERANGE).
|
||||
|
||||
Resume and ranged-parallel requests must leave such a Range alone. Replacing it
|
||||
fetches the parent's bytes instead of the slice's, which corrupts the merge.
|
||||
"""
|
||||
return any(str(k).lower() == "range" for k in (item.get("headers") or {}))
|
||||
|
||||
|
||||
def _probe_ranged(url: str, session: Any, **kwargs: Any) -> tuple[int, bool]:
|
||||
headers = {**(kwargs.get("headers") or {}), "Range": "bytes=0-0"}
|
||||
rest = {k: v for k, v in kwargs.items() if k != "headers"}
|
||||
@@ -198,7 +175,8 @@ def _probe_ranged(url: str, session: Any, **kwargs: Any) -> tuple[int, bool]:
|
||||
try:
|
||||
if resp.status_code != 206:
|
||||
return 0, False
|
||||
if _is_content_encoded(resp.headers.get("Content-Encoding") or resp.headers.get("content-encoding")):
|
||||
ce = (resp.headers.get("Content-Encoding") or resp.headers.get("content-encoding") or "").lower()
|
||||
if ce in ("gzip", "deflate", "br"):
|
||||
return 0, False
|
||||
content_range = resp.headers.get("Content-Range") or resp.headers.get("content-range") or ""
|
||||
total = content_range.rsplit("/", 1)[-1].strip()
|
||||
@@ -235,9 +213,6 @@ def _dispatch_parts(
|
||||
f.truncate(total_size)
|
||||
|
||||
events: Queue[dict[str, Any]] = Queue()
|
||||
# scoped to this file's parts only: setting the process-global cancel here would
|
||||
# poison the plain-download fallback and silently stand down sibling tracks
|
||||
abort = threading.Event()
|
||||
|
||||
def _worker(start: int, end: int) -> None:
|
||||
for ev in download(
|
||||
@@ -246,7 +221,6 @@ def _dispatch_parts(
|
||||
session=session,
|
||||
part_offset=start,
|
||||
part_end=end,
|
||||
abort=abort,
|
||||
**kwargs,
|
||||
):
|
||||
events.put(ev)
|
||||
@@ -290,7 +264,7 @@ def _dispatch_parts(
|
||||
exc = fut.exception()
|
||||
if exc:
|
||||
worker_error = True
|
||||
abort.set()
|
||||
DOWNLOAD_CANCELLED.set()
|
||||
raise exc
|
||||
|
||||
advance = 0
|
||||
@@ -326,15 +300,13 @@ def download(
|
||||
part_offset: Optional[int] = None,
|
||||
part_end: Optional[int] = None,
|
||||
claimed: Optional[Callable[[], bool]] = None,
|
||||
abort: Optional[threading.Event] = None,
|
||||
**kwargs: Any,
|
||||
) -> Generator[dict[str, Any], None, None]:
|
||||
"""
|
||||
Download a file with optimized I/O.
|
||||
|
||||
Supports both requests.Session and RnetSession for TLS fingerprinting.
|
||||
RnetSession streams natively; requests.Session reads the raw socket, except
|
||||
on a content-encoded body, which has to go through iter_content to be decoded.
|
||||
Uses raw socket reads for requests.Session and native rnet streaming for RnetSession.
|
||||
|
||||
Yields the following download status updates while chunks are downloading:
|
||||
|
||||
@@ -358,8 +330,6 @@ def download(
|
||||
part_end: Inclusive end byte of the part. Required when `part_offset` is set.
|
||||
claimed: Optional predicate checked before every attempt; when it returns True
|
||||
the download stops silently (another worker already delivered this file).
|
||||
abort: Optional event that silently stops this download when set, without
|
||||
touching the process-global cancel.
|
||||
kwargs: Any extra keyword arguments to pass to the session.get() call. Use this
|
||||
for one-time request changes like a header, cookie, or proxy. For example,
|
||||
to request Byte-ranges use e.g., `headers={"Range": "bytes=0-128"}`.
|
||||
@@ -388,15 +358,12 @@ def download(
|
||||
|
||||
_time = time.time
|
||||
use_raw = _is_requests_session(session)
|
||||
item_range = _has_range_header(kwargs)
|
||||
|
||||
attempts = 1
|
||||
written = 0
|
||||
while True:
|
||||
if claimed is not None and claimed():
|
||||
return
|
||||
if abort is not None and abort.is_set():
|
||||
return
|
||||
if not part_mode:
|
||||
written = 0
|
||||
last_speed_refresh = _time()
|
||||
@@ -409,56 +376,33 @@ def download(
|
||||
request_kwargs.setdefault("read_timeout", READ_TIMEOUT)
|
||||
else:
|
||||
request_kwargs.setdefault("timeout", (CONNECT_TIMEOUT, READ_TIMEOUT))
|
||||
req_headers = dict(request_kwargs.get("headers", {}) or {})
|
||||
if not any(str(k).lower() == "accept-encoding" for k in req_headers):
|
||||
req_headers["Accept-Encoding"] = "identity"
|
||||
if part_mode:
|
||||
req_headers = dict(request_kwargs.get("headers", {}) or {})
|
||||
req_headers["Range"] = f"bytes={part_offset + written}-{part_end}"
|
||||
elif resume_offset > 0 and not item_range:
|
||||
request_kwargs["headers"] = req_headers
|
||||
elif resume_offset > 0:
|
||||
req_headers = dict(request_kwargs.get("headers", {}) or {})
|
||||
req_headers["Range"] = f"bytes={resume_offset}-"
|
||||
request_kwargs["headers"] = req_headers
|
||||
request_kwargs["headers"] = req_headers
|
||||
|
||||
stream = session.get(url, stream=True, **request_kwargs)
|
||||
|
||||
if (not part_mode) and (not item_range) and resume_offset > 0 and stream.status_code == 416:
|
||||
try:
|
||||
stream.close()
|
||||
except Exception:
|
||||
pass
|
||||
tmp_file.unlink(missing_ok=True)
|
||||
resume_offset = 0
|
||||
continue
|
||||
|
||||
stream.raise_for_status()
|
||||
|
||||
resumed = (not part_mode) and (not item_range) and resume_offset > 0 and stream.status_code == 206
|
||||
resumed = (not part_mode) and resume_offset > 0 and stream.status_code == 206
|
||||
if (not part_mode) and resume_offset > 0 and not resumed:
|
||||
resume_offset = 0
|
||||
if part_mode and stream.status_code != 206:
|
||||
raise IOError(f"expected 206 for ranged part, got {stream.status_code}")
|
||||
if item_range and not part_mode and stream.status_code != 206:
|
||||
raise IOError(f"expected 206 for byte-range segment, got {stream.status_code}")
|
||||
content_encoded = False
|
||||
if use_rnet:
|
||||
content_length = stream.content_length or 0
|
||||
else:
|
||||
content_encoded = _is_content_encoded(stream.headers.get("Content-Encoding"))
|
||||
try:
|
||||
content_length = int(stream.headers.get("Content-Length", "0"))
|
||||
if content_encoded:
|
||||
if stream.headers.get("Content-Encoding", "").lower() in ["gzip", "deflate", "br"]:
|
||||
content_length = 0
|
||||
except ValueError:
|
||||
content_length = 0
|
||||
|
||||
if resumed and content_encoded:
|
||||
try:
|
||||
stream.close()
|
||||
except Exception:
|
||||
pass
|
||||
tmp_file.unlink(missing_ok=True)
|
||||
resume_offset = 0
|
||||
continue
|
||||
|
||||
limiter = _speed_limiter
|
||||
chunk_size = _adaptive_chunk_size(content_length)
|
||||
if limiter:
|
||||
@@ -482,12 +426,15 @@ def download(
|
||||
with open(save_path if part_mode else tmp_file, file_mode, buffering=file_buffering) as f:
|
||||
if part_mode:
|
||||
f.seek(part_offset + written)
|
||||
elif not resumed and content_length > 0:
|
||||
f.truncate(content_length)
|
||||
f.seek(0)
|
||||
|
||||
_write = f.write
|
||||
|
||||
if use_rnet:
|
||||
chunks = stream.stream()
|
||||
elif use_raw and not content_encoded:
|
||||
elif use_raw:
|
||||
_read1 = getattr(stream.raw, "read1", None) if claimed is not None and RACER_READ1 else None
|
||||
if _read1 is not None:
|
||||
chunks = iter(lambda: _read1(chunk_size), b"")
|
||||
@@ -502,7 +449,7 @@ def download(
|
||||
for chunk in chunks:
|
||||
if DOWNLOAD_CANCELLED.is_set():
|
||||
break
|
||||
if (claimed is not None and claimed()) or (abort is not None and abort.is_set()):
|
||||
if claimed is not None and claimed():
|
||||
# close the handle or Windows can't delete the stray .!dev at merge (WinError 32)
|
||||
try:
|
||||
stream.close()
|
||||
@@ -537,6 +484,9 @@ def download(
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not part_mode and not resumed and content_length > 0 and written != content_length:
|
||||
f.truncate(written)
|
||||
|
||||
if DOWNLOAD_CANCELLED.is_set() and (not content_length or written < content_length):
|
||||
# cancelled mid-stream: keep the partial .!dev for resume, never finalize
|
||||
return
|
||||
@@ -562,11 +512,11 @@ def download(
|
||||
if claimed is not None and claimed():
|
||||
# a superseded loser's error must not retry or kill the batch
|
||||
return
|
||||
if DOWNLOAD_CANCELLED.is_set() or (abort is not None and abort.is_set()):
|
||||
if DOWNLOAD_CANCELLED.is_set() or attempts == MAX_ATTEMPTS:
|
||||
if part_mode and not DOWNLOAD_CANCELLED.is_set():
|
||||
raise
|
||||
return
|
||||
if attempts == MAX_ATTEMPTS:
|
||||
raise
|
||||
if not part_mode and not item_range:
|
||||
if not part_mode:
|
||||
resume_offset = tmp_file.stat().st_size if tmp_file.exists() else 0
|
||||
time.sleep(RETRY_WAIT)
|
||||
attempts += 1
|
||||
@@ -701,7 +651,7 @@ def requests(
|
||||
url_item = urls[0]
|
||||
try:
|
||||
ranged_used = False
|
||||
if max_workers > 1 and _speed_limiter is None and not _has_range_header(url_item):
|
||||
if max_workers > 1 and _speed_limiter is None:
|
||||
total_size, supports_ranges = _probe_ranged(url_item["url"], session)
|
||||
if supports_ranges and total_size >= RANGE_PARALLEL_MIN_SIZE:
|
||||
try:
|
||||
@@ -733,20 +683,6 @@ def requests(
|
||||
DOWNLOAD_CANCELLED.set()
|
||||
yield dict(downloaded="[yellow]CANCELLED")
|
||||
raise
|
||||
except Exception as e:
|
||||
yield dict(downloaded="[red]FAILED")
|
||||
if debug_logger:
|
||||
debug_logger.log(
|
||||
level="ERROR",
|
||||
operation="downloader_failed",
|
||||
message=f"Download failed: {e}",
|
||||
error=e,
|
||||
context={
|
||||
"url_count": len(urls),
|
||||
"output_dir": str(output_dir),
|
||||
},
|
||||
)
|
||||
raise
|
||||
else:
|
||||
# Segmented download with thread pool
|
||||
# Speed is tracked here on the main thread, not in workers
|
||||
@@ -766,63 +702,43 @@ def requests(
|
||||
seg_lock = threading.Lock()
|
||||
seg_start: dict[int, float] = {}
|
||||
seg_done: set[int] = set()
|
||||
seg_active: dict[int, int] = {}
|
||||
seg_durations: list[float] = []
|
||||
hedged: set[int] = set()
|
||||
|
||||
def _download_worker(index: int, url_item: dict[str, Any], hedge: bool = False) -> None:
|
||||
with seg_lock:
|
||||
seg_active[index] = seg_active.get(index, 0) + 1
|
||||
left = False
|
||||
try:
|
||||
item = dict(url_item)
|
||||
save_path = item.pop("save_path")
|
||||
if save_path.exists(): # finished in a previous run
|
||||
item = dict(url_item)
|
||||
save_path = item.pop("save_path")
|
||||
if save_path.exists(): # finished in a previous run
|
||||
with seg_lock:
|
||||
if index in seg_done:
|
||||
return
|
||||
seg_done.add(index)
|
||||
event_queue.put(dict(file_downloaded=save_path, written=save_path.stat().st_size))
|
||||
event_queue.put(dict(advance=1))
|
||||
return
|
||||
# each racer writes to its own target so a loser never touches the final file;
|
||||
# the .!dev suffix keeps strays visible to the manifest parsers' cleanup
|
||||
target = save_path.with_name(f"{save_path.name}.{'h' if hedge else 'p'}.!dev")
|
||||
if not hedge:
|
||||
seg_start[index] = time.time()
|
||||
for event in download(
|
||||
session=session,
|
||||
segmented=segmented_batch,
|
||||
save_path=target,
|
||||
claimed=lambda: index in seg_done,
|
||||
**item,
|
||||
):
|
||||
if "file_downloaded" in event:
|
||||
with seg_lock:
|
||||
if index in seg_done:
|
||||
target.unlink(missing_ok=True)
|
||||
return
|
||||
seg_done.add(index)
|
||||
event_queue.put(dict(file_downloaded=save_path, written=save_path.stat().st_size))
|
||||
event_queue.put(dict(advance=1))
|
||||
return
|
||||
# each racer writes to its own target so a loser never touches the final file;
|
||||
# the .!dev suffix keeps strays visible to the manifest parsers' cleanup
|
||||
target = save_path.with_name(f"{save_path.name}.{'h' if hedge else 'p'}.!dev")
|
||||
if not hedge:
|
||||
seg_start[index] = time.time()
|
||||
for event in download(
|
||||
session=session,
|
||||
segmented=segmented_batch,
|
||||
save_path=target,
|
||||
claimed=lambda: index in seg_done,
|
||||
**item,
|
||||
):
|
||||
if "file_downloaded" in event:
|
||||
with seg_lock:
|
||||
if index in seg_done:
|
||||
target.unlink(missing_ok=True)
|
||||
return
|
||||
seg_done.add(index)
|
||||
if not hedge:
|
||||
seg_durations.append(time.time() - seg_start[index])
|
||||
os.replace(target, save_path)
|
||||
event = dict(event, file_downloaded=save_path)
|
||||
event_queue.put(event)
|
||||
except Exception:
|
||||
# leaving this racer and reading the survivor count must be one critical
|
||||
# section, or two racers failing together each see the other as the survivor
|
||||
# and the segment goes missing without an exception
|
||||
with seg_lock:
|
||||
seg_active[index] -= 1
|
||||
left = True
|
||||
survivor = seg_active[index] > 0 or index in seg_done
|
||||
if survivor:
|
||||
return
|
||||
raise
|
||||
finally:
|
||||
if not left:
|
||||
with seg_lock:
|
||||
seg_active[index] -= 1
|
||||
if not hedge:
|
||||
seg_durations.append(time.time() - seg_start[index])
|
||||
os.replace(target, save_path)
|
||||
event = dict(event, file_downloaded=save_path)
|
||||
event_queue.put(event)
|
||||
|
||||
futures = [pool.submit(_download_worker, i, url) for i, url in enumerate(urls)]
|
||||
pending = set(futures)
|
||||
|
||||
@@ -196,29 +196,6 @@ def get_year_by_id(
|
||||
return result.year
|
||||
|
||||
|
||||
def get_language_by_id(
|
||||
tmdb_id: int,
|
||||
kind: str,
|
||||
title_cacher: Optional[TitleCacher] = None,
|
||||
cache_title_id: Optional[str] = None,
|
||||
cache_region: Optional[str] = None,
|
||||
cache_account_hash: Optional[str] = None,
|
||||
) -> Optional[str]:
|
||||
"""Get original language by TMDB ID."""
|
||||
if title_cacher and cache_title_id:
|
||||
cached = title_cacher.get_cached_provider("tmdb", cache_title_id, kind, cache_region, cache_account_hash)
|
||||
language = ((cached or {}).get("detail") or {}).get("original_language")
|
||||
if language:
|
||||
log.debug("Using cached TMDB original language: %s", language)
|
||||
return language
|
||||
|
||||
tmdb = get_provider("tmdb")
|
||||
if not tmdb:
|
||||
return None
|
||||
result = tmdb.get_by_id(tmdb_id, kind)
|
||||
return result.original_language if result else None
|
||||
|
||||
|
||||
def fetch_external_ids(
|
||||
tmdb_id: int,
|
||||
kind: str,
|
||||
|
||||
@@ -36,7 +36,6 @@ class MetadataResult:
|
||||
year: Optional[int] = None
|
||||
kind: Optional[str] = None # "movie" or "tv"
|
||||
external_ids: ExternalIds = field(default_factory=ExternalIds)
|
||||
original_language: Optional[str] = None # alpha-2 or alpha-3, whichever the provider speaks
|
||||
source: str = "" # provider name, e.g. "tmdb", "simkl", "imdbapi"
|
||||
raw: Optional[dict] = None # original API response for caching
|
||||
|
||||
|
||||
@@ -15,12 +15,6 @@ KIND_TO_TYPES: dict[str, list[str]] = {
|
||||
}
|
||||
|
||||
|
||||
def primary_language(data: dict) -> Optional[str]:
|
||||
"""IMDb orders spokenLanguages most prominent first, and only detail responses carry it."""
|
||||
langs = data.get("spokenLanguages") or []
|
||||
return langs[0].get("code") if langs else None
|
||||
|
||||
|
||||
class IMDBApiProvider(MetadataProvider):
|
||||
"""IMDb metadata provider using IMDxAPI (api.tiffara.com, free, no API key)."""
|
||||
|
||||
@@ -96,7 +90,6 @@ class IMDBApiProvider(MetadataProvider):
|
||||
year=result_year,
|
||||
kind=kind,
|
||||
external_ids=ExternalIds(imdb_id=imdb_id),
|
||||
original_language=primary_language(best_match),
|
||||
source="imdbapi",
|
||||
raw=best_match,
|
||||
)
|
||||
@@ -122,7 +115,6 @@ class IMDBApiProvider(MetadataProvider):
|
||||
year=result_year,
|
||||
kind=kind,
|
||||
external_ids=ExternalIds(imdb_id=data.get("id")),
|
||||
original_language=primary_language(data),
|
||||
source="imdbapi",
|
||||
raw=data,
|
||||
)
|
||||
|
||||
@@ -4,7 +4,6 @@ from difflib import SequenceMatcher
|
||||
from typing import Optional, Union
|
||||
|
||||
import requests
|
||||
from langcodes import Language
|
||||
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, _clean, fuzzy_match
|
||||
@@ -16,17 +15,6 @@ KIND_TO_TYPE: dict[str, str] = {
|
||||
}
|
||||
|
||||
|
||||
def primary_language(data: dict) -> Optional[str]:
|
||||
"""OMDb gives English language names, most prominent first, e.g. 'Korean, English'."""
|
||||
name = (data.get("Language") or "").split(",")[0].strip()
|
||||
if not name:
|
||||
return None
|
||||
try:
|
||||
return str(Language.find(name))
|
||||
except LookupError:
|
||||
return None
|
||||
|
||||
|
||||
def _parse_year(value: Optional[str]) -> Optional[int]:
|
||||
# OMDb years look like "2017", "2008–2013" or "2023–"
|
||||
if value and len(value) >= 4 and value[:4].isdigit():
|
||||
@@ -115,7 +103,6 @@ class OMDBProvider(MetadataProvider):
|
||||
year=_parse_year(best_match.get("Year")),
|
||||
kind=kind,
|
||||
external_ids=ExternalIds(imdb_id=imdb_id),
|
||||
original_language=primary_language(detail or best_match),
|
||||
source="omdb",
|
||||
raw=detail or best_match,
|
||||
)
|
||||
@@ -134,7 +121,6 @@ class OMDBProvider(MetadataProvider):
|
||||
year=_parse_year(data.get("Year")),
|
||||
kind=kind,
|
||||
external_ids=ExternalIds(imdb_id=data.get("imdbID")),
|
||||
original_language=primary_language(data),
|
||||
source="omdb",
|
||||
raw=data,
|
||||
)
|
||||
|
||||
@@ -90,7 +90,6 @@ class TMDBProvider(MetadataProvider):
|
||||
year=result_year,
|
||||
kind=kind,
|
||||
external_ids=ext,
|
||||
original_language=(detail or {}).get("original_language"),
|
||||
source="tmdb",
|
||||
raw={"detail": detail or {}, "external_ids": ext_raw or {}},
|
||||
)
|
||||
@@ -109,7 +108,6 @@ class TMDBProvider(MetadataProvider):
|
||||
year=year,
|
||||
kind=kind,
|
||||
external_ids=ExternalIds(tmdb_id=int(provider_id), tmdb_kind=kind),
|
||||
original_language=detail.get("original_language"),
|
||||
source="tmdb",
|
||||
raw=detail,
|
||||
)
|
||||
|
||||
@@ -9,12 +9,6 @@ import requests
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, _clean, _strip_year
|
||||
|
||||
|
||||
def primary_language(data: dict) -> Optional[str]:
|
||||
"""Search results spell the key primary_language, the extended record originalLanguage."""
|
||||
return data.get("primary_language") or data.get("originalLanguage") or None
|
||||
|
||||
|
||||
KIND_TO_TYPE: dict[str, str] = {"movie": "movie", "tv": "series"}
|
||||
KIND_TO_PATH: dict[str, str] = {"movie": "movies", "tv": "series"}
|
||||
|
||||
@@ -159,7 +153,6 @@ class TVDBProvider(MetadataProvider):
|
||||
year=_parse_int(best.get("year")),
|
||||
kind=kind,
|
||||
external_ids=ext,
|
||||
original_language=primary_language(best),
|
||||
source="tvdb",
|
||||
raw=best,
|
||||
)
|
||||
@@ -183,7 +176,6 @@ class TVDBProvider(MetadataProvider):
|
||||
year=_parse_int(detail.get("year")),
|
||||
kind=kind,
|
||||
external_ids=ext,
|
||||
original_language=primary_language(detail),
|
||||
source="tvdb",
|
||||
raw=detail,
|
||||
)
|
||||
|
||||
@@ -631,25 +631,25 @@ class Tracks:
|
||||
audio_default = i == preferred_audio_idx
|
||||
else:
|
||||
audio_default = at.is_original_lang
|
||||
cl.extend(
|
||||
[
|
||||
"--track-name",
|
||||
f"0:{at.get_track_name() or ''}",
|
||||
"--language",
|
||||
f"0:{at.language}",
|
||||
"--default-track",
|
||||
f"0:{audio_default}",
|
||||
"--visual-impaired-flag",
|
||||
f"0:{at.descriptive}",
|
||||
"--original-flag",
|
||||
f"0:{at.is_original_lang}",
|
||||
"--compression",
|
||||
"0:none", # disable extra compression
|
||||
"(",
|
||||
str(at.path),
|
||||
")",
|
||||
]
|
||||
)
|
||||
audio_args = [
|
||||
"--track-name",
|
||||
f"0:{at.get_track_name() or ''}",
|
||||
"--language",
|
||||
f"0:{at.language}",
|
||||
"--default-track",
|
||||
f"0:{audio_default}",
|
||||
"--visual-impaired-flag",
|
||||
f"0:{at.descriptive}",
|
||||
"--original-flag",
|
||||
f"0:{at.is_original_lang}",
|
||||
"--compression",
|
||||
"0:none", # disable extra compression
|
||||
]
|
||||
|
||||
if at.data.get("sync_offset_ms"):
|
||||
audio_args.extend(["--sync", f"0:{at.data['sync_offset_ms']}"])
|
||||
|
||||
cl.extend(audio_args + ["(", str(at.path), ")"])
|
||||
|
||||
if not skip_subtitles:
|
||||
for i, st in enumerate(self.subtitles):
|
||||
@@ -660,29 +660,29 @@ class Tracks:
|
||||
default = i == preferred_subtitle_idx
|
||||
else:
|
||||
default = bool(self.audio and is_close_match(st.language, [self.audio[0].language]) and st.forced)
|
||||
cl.extend(
|
||||
[
|
||||
"--track-name",
|
||||
f"0:{st.get_track_name() or ''}",
|
||||
"--language",
|
||||
f"0:{st.language}",
|
||||
"--sub-charset",
|
||||
"0:UTF-8",
|
||||
"--forced-track",
|
||||
f"0:{st.forced}",
|
||||
"--default-track",
|
||||
f"0:{default}",
|
||||
"--hearing-impaired-flag",
|
||||
f"0:{st.sdh}",
|
||||
"--original-flag",
|
||||
f"0:{st.is_original_lang}",
|
||||
"--compression",
|
||||
"0:none", # disable extra compression (probably zlib)
|
||||
"(",
|
||||
str(st.path),
|
||||
")",
|
||||
]
|
||||
)
|
||||
subtitle_args = [
|
||||
"--track-name",
|
||||
f"0:{st.get_track_name() or ''}",
|
||||
"--language",
|
||||
f"0:{st.language}",
|
||||
"--sub-charset",
|
||||
"0:UTF-8",
|
||||
"--forced-track",
|
||||
f"0:{st.forced}",
|
||||
"--default-track",
|
||||
f"0:{default}",
|
||||
"--hearing-impaired-flag",
|
||||
f"0:{st.sdh}",
|
||||
"--original-flag",
|
||||
f"0:{st.is_original_lang}",
|
||||
"--compression",
|
||||
"0:none", # disable extra compression (probably zlib)
|
||||
]
|
||||
|
||||
if st.data.get("sync_offset_ms"):
|
||||
subtitle_args.extend(["--sync", f"0:{st.data['sync_offset_ms']}"])
|
||||
|
||||
cl.extend(subtitle_args + ["(", str(st.path), ")"])
|
||||
|
||||
if self.chapters:
|
||||
chapters_path = config.directories.temp / config.filenames.chapters.format(
|
||||
|
||||
@@ -454,9 +454,9 @@ def try_ensure_utf8(data: bytes) -> bytes:
|
||||
"""
|
||||
Try to ensure that the given data is encoded in UTF-8.
|
||||
|
||||
Gzip or zlib compressed input is decompressed first, detected by magic bytes.
|
||||
Callers hand in bytes read from files and from responses they fetched
|
||||
themselves, so there is no Content-Encoding header left to consult.
|
||||
Automatically decompresses gzip/deflate/zlib data before encoding detection.
|
||||
This handles cases where HTTP responses are saved with raw Content-Encoding
|
||||
(e.g., when decode_content=False is used for performance).
|
||||
|
||||
Parameters:
|
||||
data: Input data that may or may not yet be UTF-8 or another encoding.
|
||||
@@ -464,11 +464,13 @@ def try_ensure_utf8(data: bytes) -> bytes:
|
||||
Returns the input data encoded in UTF-8 if successful. If unable to detect the
|
||||
encoding of the input data, then the original data is returned as-received.
|
||||
"""
|
||||
# Decompress gzip data (magic bytes: 1f 8b)
|
||||
if data[:2] == b"\x1f\x8b":
|
||||
try:
|
||||
data = gzip.decompress(data)
|
||||
except Exception:
|
||||
pass
|
||||
# Decompress raw deflate/zlib data (common zlib headers: 78 01, 78 5e, 78 9c, 78 da)
|
||||
elif data[:1] == b"\x78" and len(data) > 1 and data[1:2] in (b"\x01", b"\x5e", b"\x9c", b"\xda"):
|
||||
try:
|
||||
data = zlib.decompress(data)
|
||||
|
||||
@@ -425,10 +425,30 @@ class SlowDelayRange(click.ParamType):
|
||||
return (low, high)
|
||||
|
||||
|
||||
class OffsetType(click.ParamType):
|
||||
"""Parses a time offset like '10s', '500ms' or '-5.5s' into milliseconds. A bare number is milliseconds."""
|
||||
|
||||
name = "offset"
|
||||
|
||||
_PATTERN = re.compile(r"^(-?\d+(?:\.\d+)?)\s*(s|ms)?$")
|
||||
|
||||
def convert(self, value: Any, param: Optional[click.Parameter], ctx: Optional[click.Context]) -> int:
|
||||
if isinstance(value, int):
|
||||
return value
|
||||
|
||||
match = self._PATTERN.match(str(value).strip())
|
||||
if not match:
|
||||
self.fail(f"'{value}' is not a valid offset. Use format: 10s, 500ms or -5.5s", param, ctx)
|
||||
|
||||
number = float(match.group(1))
|
||||
return int(number * 1000) if match.group(2) == "s" else int(number)
|
||||
|
||||
|
||||
SEASON_RANGE = SeasonRange()
|
||||
LANGUAGE_RANGE = LanguageRange()
|
||||
QUALITY_LIST = QualityList()
|
||||
AUDIO_CODEC_LIST = AudioCodecList(Audio.Codec)
|
||||
SLOW_DELAY_RANGE = SlowDelayRange()
|
||||
OFFSET = OffsetType()
|
||||
|
||||
# VIDEO_CODEC_CHOICE will be created dynamically when imported
|
||||
|
||||
Reference in New Issue
Block a user