mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-28 20:05:10 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5bc92b5517 |
@@ -10,7 +10,6 @@ This changelog is automatically generated using [git-cliff](https://git-cliff.or
|
||||
|
||||
### Features
|
||||
|
||||
- *dl*: Exclude a language with a `-` prefix on -l, -vl, -al, -sl and -fsl
|
||||
- *api*: Report per-episode and per-track progress on download jobs
|
||||
- *api*: Add job retry/priority/clear, history, config and maintenance endpoints
|
||||
- *api*: Expose choice values and multiple flag in service cli_params
|
||||
@@ -20,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
|
||||
|
||||
@@ -55,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. |
|
||||
|
||||
|
||||
@@ -90,13 +90,13 @@ unshackle dl [OPTIONS] SERVICE [SERVICE ARGS...]
|
||||
|
||||
| Flag | Default | Description |
|
||||
|---|---|---|
|
||||
| `-l`, `--lang` | `orig` | Language(s) for **both** video and audio. `orig` = the title's original language; e.g. `orig,en`. A `-` prefix excludes, e.g. `all,-es`. |
|
||||
| `-vl`, `--v-lang` | - | Video-only language (overrides `-l` for video). A `-` prefix excludes. |
|
||||
| `-al`, `--a-lang` | - | Audio-only language (overrides `-l` for audio). A `-` prefix excludes. |
|
||||
| `-sl`, `--s-lang` | `all` | Subtitle language(s). A `-` prefix excludes, e.g. `all,-es`. |
|
||||
| `-l`, `--lang` | `orig` | Language(s) for **both** video and audio. `orig` = the title's original language; e.g. `orig,en`. |
|
||||
| `-vl`, `--v-lang` | - | Video-only language (overrides `-l` for video). |
|
||||
| `-al`, `--a-lang` | - | Audio-only language (overrides `-l` for audio). |
|
||||
| `-sl`, `--s-lang` | `all` | Subtitle language(s). |
|
||||
| `--require-subs` | - | Required subtitle langs; keeps **all** subs only if these exist. **Cannot combine with `--s-lang`.** |
|
||||
| `-fs`, `--forced-subs` | off | Include forced subtitle tracks. |
|
||||
| `-fsl`, `--forced-s-lang` | none | Language(s) wanted for forced subtitles; implies `-fs`. A `-` prefix excludes. |
|
||||
| `-fsl`, `--forced-s-lang` | none | Language(s) wanted for forced subtitles; implies `-fs`. |
|
||||
| `--exact-lang` | off | Exact matching only: `-l es-419` matches `es-419`, not `es-ES`. Applies to selection and to sort order. |
|
||||
| `--sub-format` | - | Output subtitle format (`SRT`/`srt`, `VTT`/`webvtt`, `ASS`/`ssa`, `TTML`, `SMI`, ...), or `original` to keep the source format. |
|
||||
|
||||
@@ -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.
|
||||
@@ -254,47 +254,6 @@ it is used. You can override each stream type independently:
|
||||
unshackle dl -al en EXAMPLE 81234567
|
||||
```
|
||||
|
||||
### Excluding languages
|
||||
|
||||
Put a `-` in front of a language to remove it from the selection. This works on `-l`,
|
||||
`-vl`, `-al`, `-sl`, and `-fsl`, in the same way as it works on `-w` / `--wanted`.
|
||||
|
||||
```shell title="Every subtitle language except Spanish"
|
||||
unshackle dl -sl all,-es EXAMPLE 81234567
|
||||
```
|
||||
|
||||
The exclusions are subtracted from the languages the flag would otherwise select, and the
|
||||
order of the values does not matter. If you give only exclusions, the flag keeps its own
|
||||
default: `-sl -es` is the same as `-sl all,-es`, and `-l -es` is the same as `-l orig,-es`.
|
||||
|
||||
```shell title="Only exclusions"
|
||||
# every subtitle language except Spanish and French
|
||||
unshackle dl -sl -es,-fr EXAMPLE 81234567
|
||||
|
||||
# the original audio language, unless it is Spanish
|
||||
unshackle dl -l -es EXAMPLE 81234567
|
||||
```
|
||||
|
||||
`-vl` and `-al` have no default of their own: they cascade to `-l`. An override that names
|
||||
a language replaces `-l` for that stream type, exclusions included. An override that gives
|
||||
only exclusions adds them to the ones from `-l`.
|
||||
|
||||
```shell title="Cascade"
|
||||
# video keeps the Japanese track; only the audio drops Spanish
|
||||
unshackle dl -l en,-es -vl ja EXAMPLE 81234567
|
||||
```
|
||||
|
||||
!!! note "Rules for exclusion tokens"
|
||||
- `orig` is resolved per title, so `-sl -orig` drops the subtitles in the title's
|
||||
original language.
|
||||
- `--exact-lang` applies to exclusions with the same matching rules as selection:
|
||||
`-es` removes exactly the tracks that `es` would select. Without it, `-es` also
|
||||
removes `es-419` and `es-ES`.
|
||||
- Tracks with no language tag are never excluded.
|
||||
- `-all` is rejected. Name the languages you do not want instead.
|
||||
- The comma form is the documented style. `-sl -es` also works, but a shell can read
|
||||
a lone `-es` as another option.
|
||||
|
||||
### Sort order
|
||||
|
||||
`-l` and `-sl` **select** languages: naming some removes the rest. To keep every language
|
||||
@@ -337,10 +296,6 @@ every available subtitle language is downloaded.
|
||||
unshackle dl -sl en,es EXAMPLE 81234567
|
||||
```
|
||||
|
||||
To keep the default and drop one language, use the `-` prefix described in
|
||||
[Excluding languages](#excluding-languages). `-sl all,-es` keeps every subtitle language
|
||||
except Spanish, forced Spanish subtitles included.
|
||||
|
||||
### Requiring subtitles
|
||||
|
||||
`--require-subs` takes a list of languages that **must** exist. If they all exist, *all*
|
||||
@@ -356,8 +311,7 @@ download on the presence of a specific subtitle track.
|
||||
Without this flag, forced subs are dropped from selection.
|
||||
- `-fsl` / `--forced-s-lang`: keep forced subtitles only in these languages (implies
|
||||
`-fs`). Works independently of `--s-lang`, so `-sl all -fsl en` grabs every full
|
||||
subtitle but only the English forced track. It accepts exclusions too: `-fsl all,-es`
|
||||
keeps every forced subtitle except the Spanish one, and `-fsl -es` means the same.
|
||||
subtitle but only the English forced track.
|
||||
- `--sub-format`: set the output subtitle format, converting only when necessary.
|
||||
Accepts codec names/values and common aliases (`srt`, `vtt`, `ass`, `ssa`, `ttml`,
|
||||
etc.), or the literal `original` to keep the source format.
|
||||
@@ -629,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
|
||||
@@ -711,12 +635,12 @@ authoritative list.
|
||||
| `--range` | `-r` | Color range(s); default `SDR`. |
|
||||
| `--channels` | `-c` | Audio channel layout. |
|
||||
| `--noatmos` | `-naa` | Exclude Atmos audio. |
|
||||
| `--lang` | `-l` | Video + audio language(s); default `orig`. `-` excludes, e.g. `all,-es`. |
|
||||
| `--a-lang` | `-al` | Audio-only language override. `-` excludes. |
|
||||
| `--v-lang` | `-vl` | Video-only language override. `-` excludes. |
|
||||
| `--s-lang` | `-sl` | Subtitle language(s); default `all`. `-` excludes, e.g. `all,-es`. |
|
||||
| `--lang` | `-l` | Video + audio language(s); default `orig`. |
|
||||
| `--a-lang` | `-al` | Audio-only language override. |
|
||||
| `--v-lang` | `-vl` | Video-only language override. |
|
||||
| `--s-lang` | `-sl` | Subtitle language(s); default `all`. |
|
||||
| `--forced-subs` | `-fs` | Include forced subtitles. |
|
||||
| `--forced-s-lang` | `-fsl` | Forced subtitle language(s); implies `-fs`. `-` excludes. |
|
||||
| `--forced-s-lang` | `-fsl` | Forced subtitle language(s); implies `-fs`. |
|
||||
| `--sub-format` | | Output subtitle format. |
|
||||
| `--wanted` | `-w` | Episode/season range. |
|
||||
| `--select-titles` | | Interactively pick episodes or films. |
|
||||
|
||||
@@ -67,10 +67,10 @@ Subtitle selection happens through `dl` flags. The most important is language se
|
||||
|
||||
| Flag | Purpose |
|
||||
| --- | --- |
|
||||
| `-sl`, `--s-lang` | Language(s) wanted for subtitles. Defaults to `all`. A `-` prefix excludes, e.g. `all,-es`. |
|
||||
| `-sl`, `--s-lang` | Language(s) wanted for subtitles. Defaults to `all`. |
|
||||
| `--require-subs` | Require these languages to exist; if present, download **all** subtitles. Cannot be combined with `--s-lang`. |
|
||||
| `-fs`, `--forced-subs` | Include forced subtitle tracks (excluded by default). |
|
||||
| `-fsl`, `--forced-s-lang` | Language(s) wanted for forced subtitles; implies `-fs`. A `-` prefix excludes. |
|
||||
| `-fsl`, `--forced-s-lang` | Language(s) wanted for forced subtitles; implies `-fs`. |
|
||||
| `--exact-lang` | Exact language matching, with no regional variants. |
|
||||
| `-S`, `--subs-only` | Download only subtitle tracks. |
|
||||
| `-ns`, `--no-subs` | Do not download subtitle tracks at all. |
|
||||
|
||||
@@ -31,9 +31,9 @@ Common keys (a useful subset; every `dl` flag works):
|
||||
|
||||
| Key | Type | Default | Sets |
|
||||
|-----|------|---------|------|
|
||||
| `lang` | list | `["orig"]` | Video/audio language(s); `orig` = original language. A `-` prefix excludes, e.g. `[all, -es]`. |
|
||||
| `a_lang` / `v_lang` | list | `[]` | Audio- / video-only language override. A `-` prefix excludes. |
|
||||
| `s_lang` | list | `["all"]` | Subtitle language(s). A `-` prefix excludes, e.g. `[all, -es]`. |
|
||||
| `lang` | list | `["orig"]` | Video/audio language(s); `orig` = original language. |
|
||||
| `a_lang` / `v_lang` | list | `[]` | Audio- / video-only language override. |
|
||||
| `s_lang` | list | `["all"]` | Subtitle language(s). |
|
||||
| `quality` | list | `[]` (best) | Resolution(s), e.g. `[1080]`. |
|
||||
| `vcodec` | list | `[]` (any) | Video codec(s), e.g. `[H265]`. |
|
||||
| `acodec` | list | `[]` (any) | Audio codec(s), e.g. `[EC3]`. |
|
||||
@@ -41,7 +41,7 @@ Common keys (a useful subset; every `dl` flag works):
|
||||
| `channels` | float | *(unset)* | Audio channels, e.g. `6` for 5.1. |
|
||||
| `sub_format` | str | *(unset)* | Convert subtitles to this format (`srt`, `vtt`, `original`, ...). |
|
||||
| `forced_subs` | bool | `false` | Include forced subtitle tracks. |
|
||||
| `forced_s_lang` | list | `[]` | Forced subtitle language(s); implies `forced_subs`. A `-` prefix excludes. |
|
||||
| `forced_s_lang` | list | `[]` | Forced subtitle language(s); implies `forced_subs`. |
|
||||
| `no_subs` / `no_audio` / `no_chapters` | bool | `false` | Skip that track type. |
|
||||
| `downloads` | int | `1` | Tracks downloaded concurrently. |
|
||||
| `workers` | int | *(downloader default)* | Threads per track. |
|
||||
@@ -61,18 +61,6 @@ dl:
|
||||
downloads: 2
|
||||
```
|
||||
|
||||
!!! note "Language exclusions in YAML"
|
||||
The language keys accept the same `-` exclusion tokens as the command line. Give them
|
||||
as a list or as one comma-separated string.
|
||||
|
||||
```yaml
|
||||
dl:
|
||||
s_lang: [all, -es]
|
||||
a_lang: "orig,-es"
|
||||
```
|
||||
|
||||
See [Excluding languages](../../guide/downloading.md#excluding-languages) for the rules.
|
||||
|
||||
!!! note "Per-service overrides"
|
||||
A `dl` block nested under a service in [`services`](services.md) takes the same keys and
|
||||
applies to that service only.
|
||||
|
||||
@@ -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"
|
||||
@@ -7,13 +7,7 @@ import click
|
||||
import pytest
|
||||
|
||||
from unshackle.core.tracks.subtitle import Subtitle
|
||||
from unshackle.core.utils.click_types import (
|
||||
LANGUAGE_RANGE,
|
||||
QUALITY_LIST,
|
||||
SLOW_DELAY_RANGE,
|
||||
SeasonRange,
|
||||
SubtitleCodecChoice,
|
||||
)
|
||||
from unshackle.core.utils.click_types import QUALITY_LIST, SLOW_DELAY_RANGE, SeasonRange, SubtitleCodecChoice
|
||||
|
||||
choice = SubtitleCodecChoice(Subtitle.Codec)
|
||||
|
||||
@@ -66,23 +60,6 @@ def test_slow_delay_range_accepts_bool(value, expected):
|
||||
assert SLOW_DELAY_RANGE.convert(value, None, None) == expected
|
||||
|
||||
|
||||
# --- LanguageRange ----------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"value,expected",
|
||||
[
|
||||
("all,-es", ["all", "-es"]),
|
||||
("-es", ["-es"]),
|
||||
("all, -es ; -fr", ["all", "-es", "-fr"]),
|
||||
(["all", "-es"], ["all", "-es"]),
|
||||
],
|
||||
)
|
||||
def test_language_range_passes_exclusion_tokens_through(value, expected):
|
||||
"""The '-' prefix is resolved at filter time, so the type must keep the token intact."""
|
||||
assert LANGUAGE_RANGE.convert(value) == expected
|
||||
|
||||
|
||||
# --- SeasonRange ------------------------------------------------------------
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -1,80 +0,0 @@
|
||||
"""Tests for the `-` exclusion prefix on the language flags (-l, -vl, -al, -sl, -fsl)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from langcodes import Language
|
||||
|
||||
from unshackle.core.utilities import excluded_language_tags, partition_exclusions
|
||||
from unshackle.core.utils.click_types import LANGUAGE_RANGE
|
||||
|
||||
# --- partition_exclusions ---------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"tokens,expected",
|
||||
[
|
||||
(["all", "-es"], (["all"], ["es"])),
|
||||
(["-es"], ([], ["es"])),
|
||||
(["en", "ja"], (["en", "ja"], [])),
|
||||
(["-es", "-fr", "en"], (["en"], ["es", "fr"])),
|
||||
([], ([], [])),
|
||||
(None, ([], [])),
|
||||
],
|
||||
)
|
||||
def test_partition_splits_on_the_leading_dash(tokens, expected):
|
||||
assert partition_exclusions(tokens) == expected
|
||||
|
||||
|
||||
def test_partition_keeps_the_written_order_and_drops_repeats():
|
||||
assert partition_exclusions(["ja", "en", "ja", "-es", "-es"]) == (["ja", "en"], ["es"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("token", ["-", " - ", "", " "])
|
||||
def test_partition_skips_tokens_with_no_value(token):
|
||||
assert partition_exclusions(["en", token]) == (["en"], [])
|
||||
|
||||
|
||||
def test_partition_trims_whitespace_around_a_token():
|
||||
assert partition_exclusions([" en ", "- es "]) == (["en"], ["es"])
|
||||
|
||||
|
||||
def test_partition_reads_the_tokens_language_range_produces():
|
||||
assert partition_exclusions(LANGUAGE_RANGE.convert("all,-es;-fr")) == (["all"], ["es", "fr"])
|
||||
|
||||
|
||||
# --- excluded_language_tags ---------------------------------------------------
|
||||
|
||||
|
||||
def test_close_match_excludes_the_regional_variants():
|
||||
assert excluded_language_tags(["es"], ["es-419", "es-ES", "en-US"]) == {"es-419", "es-ES"}
|
||||
|
||||
|
||||
def test_exact_match_prefers_the_string_equal_tag():
|
||||
# same string preference as selection: an exact 'es' only takes 'es' when it exists
|
||||
assert excluded_language_tags(["es"], ["es", "es-ES", "es-419"], exact=True) == {"es"}
|
||||
|
||||
|
||||
def test_exact_match_falls_back_to_the_paradigm_variant():
|
||||
# no literal 'es' available, so 'es' resolves the way an exact '-sl es' selection would
|
||||
assert excluded_language_tags(["es"], ["es-ES", "es-419"], exact=True) == {"es-ES"}
|
||||
|
||||
|
||||
def test_exact_match_keeps_an_unnamed_regional_variant():
|
||||
assert excluded_language_tags(["es-ES"], ["es-ES", "es-419"], exact=True) == {"es-ES"}
|
||||
|
||||
|
||||
def test_language_objects_are_accepted():
|
||||
assert excluded_language_tags(["es"], [Language.get("es")]) == {"es"}
|
||||
|
||||
|
||||
def test_an_untagged_track_is_never_excluded():
|
||||
assert excluded_language_tags(["es"], [None, "en-US"]) == set()
|
||||
|
||||
|
||||
def test_no_exclusions_excludes_nothing():
|
||||
assert excluded_language_tags([], ["es-419", "en-US"]) == set()
|
||||
|
||||
|
||||
def test_an_unmatched_language_is_kept():
|
||||
assert excluded_language_tags(["es", "fr"], ["en-US", "ja-JP"]) == set()
|
||||
@@ -150,24 +150,3 @@ def test_language_range_yaml_shapes(value, expected):
|
||||
ctx = make_ctx()
|
||||
apply_service_dl_overrides(ctx, {"v_lang": value}, log)
|
||||
assert ctx.params["v_lang"] == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"value,expected",
|
||||
[
|
||||
("all,-es", ["all", "-es"]),
|
||||
("-es", ["-es"]),
|
||||
(["all", "-es"], ["all", "-es"]),
|
||||
],
|
||||
)
|
||||
def test_language_exclusion_tokens_survive_the_override_convert(value, expected):
|
||||
"""A service dl override is re-converted, so its exclusion tokens must reach the filter stage intact."""
|
||||
ctx = make_ctx()
|
||||
apply_service_dl_overrides(ctx, {"v_lang": value}, log)
|
||||
assert ctx.params["v_lang"] == expected
|
||||
|
||||
|
||||
def test_cli_exclusion_beats_service_config():
|
||||
ctx = make_ctx(["-vl", "-es"])
|
||||
apply_service_dl_overrides(ctx, {"v_lang": ["en"]}, log)
|
||||
assert ctx.params["v_lang"] == ["-es"]
|
||||
|
||||
@@ -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
|
||||
+409
-201
@@ -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
|
||||
@@ -74,7 +74,6 @@ from unshackle.core.tracks.hybrid import Hybrid
|
||||
from unshackle.core.tracks.track import assert_fragments_decrypted, has_encrypted_sample_entry
|
||||
from unshackle.core.utilities import (
|
||||
as_requested,
|
||||
excluded_language_tags,
|
||||
find_font_with_fallbacks,
|
||||
find_missing_langs,
|
||||
get_debug_logger,
|
||||
@@ -84,7 +83,6 @@ from unshackle.core.utilities import (
|
||||
is_exact_match,
|
||||
keep_forced_subtitle,
|
||||
log_event,
|
||||
partition_exclusions,
|
||||
resolve_sort_langs,
|
||||
suggest_font_packages,
|
||||
time_elapsed_since,
|
||||
@@ -94,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,
|
||||
@@ -121,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()}
|
||||
@@ -534,7 +525,7 @@ class dl:
|
||||
"--lang",
|
||||
type=LANGUAGE_RANGE,
|
||||
default="orig",
|
||||
help="Language(s) wanted for Video and Audio (comma-separated). Use 'orig' to select the original language, e.g. 'orig,en' for both original and English. Prefix a value with '-' to exclude it, e.g. 'all,-es'.",
|
||||
help="Language(s) wanted for Video and Audio (comma-separated). Use 'orig' to select the original language, e.g. 'orig,en' for both original and English.",
|
||||
)
|
||||
@click.option(
|
||||
"--latest-episode",
|
||||
@@ -547,22 +538,16 @@ class dl:
|
||||
"--v-lang",
|
||||
type=LANGUAGE_RANGE,
|
||||
default=[],
|
||||
help="Language wanted for Video. You would use this if the video language doesn't match the audio. Prefix a value with '-' to exclude it, e.g. 'all,-es'.",
|
||||
help="Language wanted for Video. You would use this if the video language doesn't match the audio.",
|
||||
)
|
||||
@click.option(
|
||||
"-al",
|
||||
"--a-lang",
|
||||
type=LANGUAGE_RANGE,
|
||||
default=[],
|
||||
help="Language wanted for Audio, overrides -l/--lang for audio tracks. Prefix a value with '-' to exclude it, e.g. 'all,-es'.",
|
||||
)
|
||||
@click.option(
|
||||
"-sl",
|
||||
"--s-lang",
|
||||
type=LANGUAGE_RANGE,
|
||||
default=["all"],
|
||||
help="Language wanted for Subtitles. Prefix a value with '-' to exclude it, e.g. 'all,-es'.",
|
||||
help="Language wanted for Audio, overrides -l/--lang for audio tracks.",
|
||||
)
|
||||
@click.option("-sl", "--s-lang", type=LANGUAGE_RANGE, default=["all"], help="Language wanted for Subtitles.")
|
||||
@click.option(
|
||||
"--require-subs",
|
||||
type=LANGUAGE_RANGE,
|
||||
@@ -575,7 +560,7 @@ class dl:
|
||||
"--forced-s-lang",
|
||||
type=LANGUAGE_RANGE,
|
||||
default=[],
|
||||
help="Languages wanted for forced subtitles, implies -fs. Keeps forced subs only in these languages. Prefix a value with '-' to exclude it, e.g. 'all,-es'.",
|
||||
help="Languages wanted for forced subtitles, implies -fs. Keeps forced subs only in these languages.",
|
||||
)
|
||||
@click.option(
|
||||
"--exact-lang",
|
||||
@@ -624,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",
|
||||
@@ -644,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",
|
||||
@@ -776,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,
|
||||
@@ -814,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,
|
||||
):
|
||||
@@ -867,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
|
||||
|
||||
@@ -879,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:
|
||||
@@ -1271,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
|
||||
|
||||
@@ -1282,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,
|
||||
@@ -1348,51 +1639,14 @@ class dl:
|
||||
self._remote_service = service if self.server_cdm else None
|
||||
start_time = time.time()
|
||||
|
||||
lang, lang_excl = partition_exclusions(lang)
|
||||
v_lang, v_lang_excl = partition_exclusions(v_lang)
|
||||
a_lang, a_lang_excl = partition_exclusions(a_lang)
|
||||
s_lang, s_lang_excl = partition_exclusions(s_lang)
|
||||
forced_s_lang, fsl_excl = partition_exclusions(forced_s_lang)
|
||||
for flag, excludes in (
|
||||
("-l/--lang", lang_excl),
|
||||
("-vl/--v-lang", v_lang_excl),
|
||||
("-al/--a-lang", a_lang_excl),
|
||||
("-sl/--s-lang", s_lang_excl),
|
||||
("-fsl/--forced-s-lang", fsl_excl),
|
||||
):
|
||||
if any(token.lower() == "all" for token in excludes):
|
||||
self.log.error(f"{flag}: 'all' cannot be excluded. Name the languages to exclude instead.")
|
||||
sys.exit(1)
|
||||
# exclusion-only use falls back to the flag's own default; -vl/-al have none, they cascade to -l
|
||||
if lang_excl and not lang:
|
||||
lang = ["orig"]
|
||||
if s_lang_excl and not s_lang:
|
||||
s_lang = ["all"]
|
||||
# an override that names languages replaces -l entirely, so it must not inherit its exclusions
|
||||
video_excl = list(dict.fromkeys(v_lang_excl + ([] if v_lang else lang_excl)))
|
||||
audio_excl = list(dict.fromkeys(a_lang_excl + ([] if a_lang else lang_excl)))
|
||||
|
||||
ctx = getattr(service, "ctx", None)
|
||||
parent_params = ctx.parent.params if ctx and ctx.parent else None
|
||||
if parent_params is not None:
|
||||
# services read the raw ctx params, they must never see a '-xx' token
|
||||
for name, includes, excludes in (
|
||||
("lang", lang, lang_excl),
|
||||
("v_lang", v_lang, v_lang_excl),
|
||||
("a_lang", a_lang, a_lang_excl),
|
||||
("s_lang", s_lang, s_lang_excl),
|
||||
("forced_s_lang", forced_s_lang, fsl_excl),
|
||||
):
|
||||
if excludes and name in parent_params:
|
||||
parent_params[name] = includes
|
||||
|
||||
if forced_s_lang or fsl_excl:
|
||||
if forced_s_lang:
|
||||
# services read forced_subs from raw ctx params, so the implication must be pushed there too
|
||||
forced_subs = True
|
||||
if "all" in forced_s_lang:
|
||||
forced_s_lang = []
|
||||
if parent_params is not None:
|
||||
parent_params["forced_subs"] = True
|
||||
ctx = getattr(service, "ctx", None)
|
||||
if ctx and ctx.parent:
|
||||
ctx.parent.params["forced_subs"] = True
|
||||
|
||||
if skip_dl:
|
||||
DOWNLOAD_LICENCE_ONLY.set()
|
||||
@@ -1571,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
|
||||
@@ -1584,52 +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}")
|
||||
if not (enrich_title or enrich_year or enrich_lang):
|
||||
self.log.warning("--enrich found no metadata; is the provider's API key configured?")
|
||||
elif missing := [
|
||||
name
|
||||
for name, value in (("title", enrich_title), ("year", enrich_year), ("language", enrich_lang))
|
||||
if not value
|
||||
]:
|
||||
self.log.warning(f"--enrich source did not provide {', '.join(missing)}; those fields are unchanged.")
|
||||
|
||||
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)
|
||||
@@ -1900,18 +2134,6 @@ class dl:
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
song_excl = [
|
||||
str(song.language) if t == "orig" else t for t in audio_excl if t != "orig" or song.language
|
||||
]
|
||||
if song_excl:
|
||||
drop = excluded_language_tags(song_excl, [t.language for t in song.tracks.audio], exact_lang)
|
||||
song.tracks.select_audio(lambda x: str(x.language) not in drop)
|
||||
if not song.tracks.audio:
|
||||
self.log.error(
|
||||
f"Every Audio Track for {song.name} was excluded by -{', -'.join(song_excl)}..."
|
||||
)
|
||||
sys.exit(1)
|
||||
|
||||
audio_languages = a_lang or lang
|
||||
if audio_languages:
|
||||
processed_lang = []
|
||||
@@ -2450,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
|
||||
@@ -2563,23 +2801,6 @@ class dl:
|
||||
title.tracks.chapters = []
|
||||
|
||||
with console.status("Selecting tracks...", spinner="dots"):
|
||||
|
||||
def resolve_excludes(excludes: list[str], _title: Title_T = title) -> list[str]:
|
||||
"""Resolve 'orig' against this title. An unresolvable 'orig' excludes nothing."""
|
||||
resolved: list[str] = []
|
||||
for token in excludes:
|
||||
value = str(_title.language) if token == "orig" else token
|
||||
if token == "orig" and not _title.language:
|
||||
continue
|
||||
if value not in resolved:
|
||||
resolved.append(value)
|
||||
return resolved
|
||||
|
||||
video_excl_r = resolve_excludes(video_excl)
|
||||
audio_excl_r = resolve_excludes(audio_excl)
|
||||
s_excl_r = resolve_excludes(s_lang_excl)
|
||||
fsl_excl_r = resolve_excludes(fsl_excl)
|
||||
|
||||
if isinstance(title, (Movie, Episode)):
|
||||
# filter video tracks
|
||||
if keep_videos and vcodec:
|
||||
@@ -2626,15 +2847,6 @@ class dl:
|
||||
self.log.error(f"No Video Track in {vbitrate_min}-{vbitrate_max}kbps range...")
|
||||
sys.exit(1)
|
||||
|
||||
if keep_videos and video_excl_r:
|
||||
drop = excluded_language_tags(
|
||||
video_excl_r, [t.language for t in title.tracks.videos], exact_lang
|
||||
)
|
||||
title.tracks.select_video(lambda x: str(x.language) not in drop)
|
||||
if not title.tracks.videos:
|
||||
self.log.error(f"Every Video Track was excluded by -{', -'.join(video_excl_r)}...")
|
||||
sys.exit(1)
|
||||
|
||||
effective_video_lang = v_lang or lang
|
||||
video_languages = [lang for lang in effective_video_lang if lang != "best"]
|
||||
video_multi_lang = (
|
||||
@@ -2915,12 +3127,6 @@ class dl:
|
||||
fsl = [t for t in forced_s_lang if t != "orig"]
|
||||
if "orig" in forced_s_lang and title.language:
|
||||
fsl.append(str(title.language))
|
||||
if keep_subtitles and s_excl_r:
|
||||
# applies to forced subs too: an excluded language is unwanted in any form
|
||||
drop = excluded_language_tags(
|
||||
s_excl_r, [t.language for t in title.tracks.subtitles], exact_lang
|
||||
)
|
||||
title.tracks.select_subtitles(lambda x: str(x.language) not in drop)
|
||||
if keep_subtitles and require_subs:
|
||||
missing_langs = [
|
||||
lang
|
||||
@@ -2988,11 +3194,6 @@ class dl:
|
||||
)
|
||||
elif not forced_subs:
|
||||
title.tracks.select_subtitles(lambda x: not x.forced)
|
||||
if fsl_excl_r:
|
||||
drop = excluded_language_tags(
|
||||
fsl_excl_r, [t.language for t in title.tracks.subtitles if t.forced], exact_lang
|
||||
)
|
||||
title.tracks.select_subtitles(lambda x: not (x.forced and str(x.language) in drop))
|
||||
|
||||
# filter audio tracks
|
||||
# might have no audio tracks if part of the video, e.g. transport stream hls
|
||||
@@ -3029,14 +3230,6 @@ class dl:
|
||||
if not title.tracks.audio:
|
||||
self.log.error(f"No Audio Track in {abitrate_min}-{abitrate_max}kbps range...")
|
||||
sys.exit(1)
|
||||
if audio_excl_r:
|
||||
drop = excluded_language_tags(
|
||||
audio_excl_r, [t.language for t in title.tracks.audio], exact_lang
|
||||
)
|
||||
title.tracks.select_audio(lambda x: str(x.language) not in drop)
|
||||
if not title.tracks.audio:
|
||||
self.log.error(f"Every Audio Track was excluded by -{', -'.join(audio_excl_r)}...")
|
||||
sys.exit(1)
|
||||
audio_languages = a_lang or lang
|
||||
if audio_languages:
|
||||
processed_lang = []
|
||||
@@ -3175,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],
|
||||
)
|
||||
@@ -4044,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.
|
||||
@@ -4052,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:
|
||||
@@ -4112,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.")
|
||||
|
||||
@@ -4196,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:
|
||||
@@ -4258,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}")
|
||||
@@ -4397,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:
|
||||
@@ -4448,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}")
|
||||
@@ -4549,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"
|
||||
@@ -4747,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).
|
||||
@@ -4839,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)
|
||||
|
||||
@@ -665,22 +665,22 @@ async def download(request: web.Request) -> web.Response:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
description: Language for video and audio (use 'orig' for original; a '-' prefix excludes, e.g. ["all", "-es"]) (default - ["orig"])
|
||||
description: Language for video and audio (use 'orig' for original) (default - ["orig"])
|
||||
v_lang:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
description: Language for video tracks only (a '-' prefix excludes) (default - [])
|
||||
description: Language for video tracks only (default - [])
|
||||
a_lang:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
description: Language for audio tracks only (a '-' prefix excludes) (default - [])
|
||||
description: Language for audio tracks only (default - [])
|
||||
s_lang:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
description: Language for subtitle tracks (a '-' prefix excludes, e.g. ["all", "-es"]) (default - ["all"])
|
||||
description: Language for subtitle tracks (default - ["all"])
|
||||
require_subs:
|
||||
type: array
|
||||
items:
|
||||
@@ -693,7 +693,7 @@ async def download(request: web.Request) -> web.Response:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
description: Languages wanted for forced subtitles, implies forced_subs (a '-' prefix excludes) (default - [])
|
||||
description: Languages wanted for forced subtitles, implies forced_subs (default - [])
|
||||
exact_lang:
|
||||
type: boolean
|
||||
description: Use exact language matching (no variants) (default - false)
|
||||
@@ -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(
|
||||
|
||||
@@ -164,49 +164,6 @@ def is_exact_match(language: Union[str, Language], languages: Sequence[Union[str
|
||||
return closest_match(language, list(map(str, languages)))[1] <= LANGUAGE_EXACT_DISTANCE
|
||||
|
||||
|
||||
def partition_exclusions(tokens: Optional[Sequence[str]]) -> tuple[list[str], list[str]]:
|
||||
"""
|
||||
Split selection tokens into wanted values and values excluded with a leading '-'.
|
||||
|
||||
Both sides keep the order they were written in and drop later repeats. A bare '-'
|
||||
carries no value and is skipped.
|
||||
|
||||
Example:
|
||||
>>> partition_exclusions(["all", "-es"])
|
||||
(['all'], ['es'])
|
||||
"""
|
||||
includes: list[str] = []
|
||||
excludes: list[str] = []
|
||||
for raw in tokens or []:
|
||||
token = str(raw).strip()
|
||||
if not token or token == "-":
|
||||
continue
|
||||
target = includes
|
||||
if token.startswith("-"):
|
||||
token = token[1:].strip()
|
||||
if not token:
|
||||
continue
|
||||
target = excludes
|
||||
if token not in target:
|
||||
target.append(token)
|
||||
return includes, excludes
|
||||
|
||||
|
||||
def excluded_language_tags(
|
||||
excludes: Sequence[str],
|
||||
available: Sequence[Union[str, Language, None]],
|
||||
exact: bool = False,
|
||||
) -> set[str]:
|
||||
"""
|
||||
The language tags out of `available` that the exclusion tokens remove.
|
||||
|
||||
Matches through matching_languages so an exclusion drops exactly the tracks the same
|
||||
token would select, including its exact-mode string preference. Untagged tracks are
|
||||
never excluded.
|
||||
"""
|
||||
return {tag for token in excludes for tag in matching_languages(token, available, exact)}
|
||||
|
||||
|
||||
def keep_forced_subtitle(
|
||||
forced: bool,
|
||||
language: Union[str, Language],
|
||||
@@ -497,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.
|
||||
@@ -507,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