mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-28 20:05:10 +00:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0cec6c9686 | ||
|
|
d6f3958a16 | ||
|
|
79ad70a9cf | ||
|
|
8a7022a091 | ||
|
|
8d3785b460 | ||
|
|
97fa834b1e | ||
|
|
d7e08e979b | ||
|
|
d448ee8ff9 |
@@ -10,6 +10,7 @@ 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
|
||||
@@ -19,6 +20,24 @@ 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
|
||||
|
||||
@@ -36,23 +55,52 @@ 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. |
|
||||
| `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`. |
|
||||
| `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`. |
|
||||
| `-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). |
|
||||
| `-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`. |
|
||||
| `--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`. |
|
||||
| `-fsl`, `--forced-s-lang` | none | Language(s) wanted for forced subtitles; implies `-fs`. A `-` prefix excludes. |
|
||||
| `--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. |
|
||||
|
||||
@@ -152,9 +152,9 @@ Keep only certain track types, or skip certain track types. Attachments are alwa
|
||||
|---|---|
|
||||
| `--tmdb` | TMDB ID (integer). |
|
||||
| `--imdb` | IMDb ID, e.g. `tt1375666`. |
|
||||
| `--tvdb` | TVDB ID (integer). Skips the series lookup that `--tvdb-order` would otherwise do. |
|
||||
| `--tvdb` | TVDB ID (integer). Skips the series lookup that `--tvdb-order` would otherwise do. `--enrich` reads it too. |
|
||||
| `--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. **Requires** one of `--tmdb`, `--imdb`, or `--animeapi`. |
|
||||
| `--enrich` | Override show title/year from the external source, and fill in the original language. **Requires** one of `--tmdb`, `--imdb`, `--tvdb`, or `--animeapi`. |
|
||||
| `--tvdb-order` | Renumber episodes to a TVDB season order: `official` (aired), `dvd`, `absolute`, `alternate`, or `regional`. Needs `tvdb_api_key`. |
|
||||
|
||||
#### Episode ordering
|
||||
|
||||
@@ -254,6 +254,47 @@ 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
|
||||
@@ -296,6 +337,10 @@ 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*
|
||||
@@ -311,7 +356,8 @@ 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.
|
||||
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.
|
||||
- `--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.
|
||||
@@ -583,13 +629,43 @@ 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. **Requires** one of `--tmdb`, `--imdb`, or `--animeapi`. |
|
||||
| `--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`. |
|
||||
| `--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
|
||||
@@ -635,12 +711,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`. |
|
||||
| `--a-lang` | `-al` | Audio-only language override. |
|
||||
| `--v-lang` | `-vl` | Video-only language override. |
|
||||
| `--s-lang` | `-sl` | Subtitle language(s); default `all`. |
|
||||
| `--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`. |
|
||||
| `--forced-subs` | `-fs` | Include forced subtitles. |
|
||||
| `--forced-s-lang` | `-fsl` | Forced subtitle language(s); implies `-fs`. |
|
||||
| `--forced-s-lang` | `-fsl` | Forced subtitle language(s); implies `-fs`. `-` excludes. |
|
||||
| `--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`. |
|
||||
| `-sl`, `--s-lang` | Language(s) wanted for subtitles. Defaults to `all`. A `-` prefix excludes, e.g. `all,-es`. |
|
||||
| `--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`. |
|
||||
| `-fsl`, `--forced-s-lang` | Language(s) wanted for forced subtitles; implies `-fs`. A `-` prefix excludes. |
|
||||
| `--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_lang` / `v_lang` | list | `[]` | Audio- / video-only language override. |
|
||||
| `s_lang` | list | `["all"]` | Subtitle language(s). |
|
||||
| `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]`. |
|
||||
| `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`. |
|
||||
| `forced_s_lang` | list | `[]` | Forced subtitle language(s); implies `forced_subs`. A `-` prefix excludes. |
|
||||
| `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,6 +61,18 @@ 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,7 +4,9 @@ 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.
|
||||
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).
|
||||
|
||||
| Key | Type | Default | Description |
|
||||
|-----|------|---------|-------------|
|
||||
@@ -12,7 +14,7 @@ All are unset by default and enable optional metadata/geolocation features.
|
||||
| `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. 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. Also the source `--enrich --tvdb` reads. 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. |
|
||||
|
||||
@@ -7,7 +7,13 @@ import click
|
||||
import pytest
|
||||
|
||||
from unshackle.core.tracks.subtitle import Subtitle
|
||||
from unshackle.core.utils.click_types import QUALITY_LIST, SLOW_DELAY_RANGE, SeasonRange, SubtitleCodecChoice
|
||||
from unshackle.core.utils.click_types import (
|
||||
LANGUAGE_RANGE,
|
||||
QUALITY_LIST,
|
||||
SLOW_DELAY_RANGE,
|
||||
SeasonRange,
|
||||
SubtitleCodecChoice,
|
||||
)
|
||||
|
||||
choice = SubtitleCodecChoice(Subtitle.Codec)
|
||||
|
||||
@@ -60,6 +66,23 @@ 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 ------------------------------------------------------------
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"""--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
|
||||
@@ -0,0 +1,80 @@
|
||||
"""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,3 +150,24 @@ 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,6 +157,27 @@ 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}
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
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
|
||||
@@ -0,0 +1,164 @@
|
||||
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
|
||||
+168
-33
@@ -27,7 +27,7 @@ from uuid import UUID
|
||||
import click
|
||||
import yaml
|
||||
from click.core import ParameterSource
|
||||
from langcodes import Language
|
||||
from langcodes import Language, tag_is_valid
|
||||
from pymediainfo import MediaInfo
|
||||
from rich.console import Group
|
||||
from rich.padding import Padding
|
||||
@@ -74,6 +74,7 @@ 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,
|
||||
@@ -83,6 +84,7 @@ from unshackle.core.utilities import (
|
||||
is_exact_match,
|
||||
keep_forced_subtitle,
|
||||
log_event,
|
||||
partition_exclusions,
|
||||
resolve_sort_langs,
|
||||
suggest_font_packages,
|
||||
time_elapsed_since,
|
||||
@@ -119,6 +121,14 @@ 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()}
|
||||
@@ -524,7 +534,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.",
|
||||
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'.",
|
||||
)
|
||||
@click.option(
|
||||
"--latest-episode",
|
||||
@@ -537,16 +547,22 @@ 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.",
|
||||
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'.",
|
||||
)
|
||||
@click.option(
|
||||
"-al",
|
||||
"--a-lang",
|
||||
type=LANGUAGE_RANGE,
|
||||
default=[],
|
||||
help="Language wanted for Audio, overrides -l/--lang for audio tracks.",
|
||||
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'.",
|
||||
)
|
||||
@click.option("-sl", "--s-lang", type=LANGUAGE_RANGE, default=["all"], help="Language wanted for Subtitles.")
|
||||
@click.option(
|
||||
"--require-subs",
|
||||
type=LANGUAGE_RANGE,
|
||||
@@ -559,7 +575,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.",
|
||||
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'.",
|
||||
)
|
||||
@click.option(
|
||||
"--exact-lang",
|
||||
@@ -608,7 +624,7 @@ class dl:
|
||||
"tvdb_id",
|
||||
type=int,
|
||||
default=None,
|
||||
help="Use this TVDB ID for --tvdb-order instead of looking the series up automatically.",
|
||||
help="Use this TVDB ID for --tvdb-order and --enrich instead of looking the series up automatically.",
|
||||
)
|
||||
@click.option(
|
||||
"--tvdb-order",
|
||||
@@ -628,7 +644,10 @@ class dl:
|
||||
"--enrich",
|
||||
is_flag=True,
|
||||
default=False,
|
||||
help="Override show title and year from external source. Requires --tmdb, --imdb, or --animeapi.",
|
||||
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."
|
||||
),
|
||||
)
|
||||
@click.option(
|
||||
"--imdb",
|
||||
@@ -860,8 +879,10 @@ 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.animeapi_title):
|
||||
raise click.UsageError("--enrich requires --tmdb, --imdb, or --animeapi to provide a metadata source.")
|
||||
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."
|
||||
)
|
||||
|
||||
# Initialize debug logger with service name if debug logging is enabled
|
||||
if config.debug or logging.root.level == logging.DEBUG:
|
||||
@@ -1327,14 +1348,51 @@ class dl:
|
||||
self._remote_service = service if self.server_cdm else None
|
||||
start_time = time.time()
|
||||
|
||||
if forced_s_lang:
|
||||
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:
|
||||
# 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 = []
|
||||
ctx = getattr(service, "ctx", None)
|
||||
if ctx and ctx.parent:
|
||||
ctx.parent.params["forced_subs"] = True
|
||||
if parent_params is not None:
|
||||
parent_params["forced_subs"] = True
|
||||
|
||||
if skip_dl:
|
||||
DOWNLOAD_LICENCE_ONLY.set()
|
||||
@@ -1513,6 +1571,7 @@ 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
|
||||
@@ -1525,33 +1584,52 @@ 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:
|
||||
imdbapi = providers.get_provider("imdbapi")
|
||||
if imdbapi:
|
||||
imdb_result = imdbapi.get_by_id(self.imdb_id, kind)
|
||||
for name in ("imdbapi", "omdb"):
|
||||
provider = providers.get_provider(name)
|
||||
imdb_result = provider.get_by_id(self.imdb_id, kind) if provider else None
|
||||
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_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_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:
|
||||
if isinstance(titles, Episode):
|
||||
titles.title = enrich_title
|
||||
if isinstance(t, Episode):
|
||||
t.title = enrich_title
|
||||
else:
|
||||
titles.name = enrich_title
|
||||
if enrich_year and not titles.year:
|
||||
titles.year = enrich_year
|
||||
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
|
||||
|
||||
if self.tvdb_order and isinstance(titles, Series):
|
||||
titles = self.apply_tvdb_order(titles, title_cacher, cache_title_id, cache_region, cache_account_hash)
|
||||
@@ -1822,6 +1900,18 @@ 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 = []
|
||||
@@ -2473,6 +2563,23 @@ 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:
|
||||
@@ -2519,6 +2626,15 @@ 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 = (
|
||||
@@ -2799,6 +2915,12 @@ 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
|
||||
@@ -2866,6 +2988,11 @@ 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
|
||||
@@ -2902,6 +3029,14 @@ 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 = []
|
||||
|
||||
@@ -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) (default - ["orig"])
|
||||
description: Language for video and audio (use 'orig' for original; a '-' prefix excludes, e.g. ["all", "-es"]) (default - ["orig"])
|
||||
v_lang:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
description: Language for video tracks only (default - [])
|
||||
description: Language for video tracks only (a '-' prefix excludes) (default - [])
|
||||
a_lang:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
description: Language for audio tracks only (default - [])
|
||||
description: Language for audio tracks only (a '-' prefix excludes) (default - [])
|
||||
s_lang:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
description: Language for subtitle tracks (default - ["all"])
|
||||
description: Language for subtitle tracks (a '-' prefix excludes, e.g. ["all", "-es"]) (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 (default - [])
|
||||
description: Languages wanted for forced subtitles, implies forced_subs (a '-' prefix excludes) (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 (default - false)
|
||||
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)
|
||||
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 and episode ordering (default - None)
|
||||
description: Use this TVDB ID for tagging, episode ordering and enrichment (default - None)
|
||||
tvdb_order:
|
||||
type: string
|
||||
enum: [official, dvd, absolute, alternate, regional]
|
||||
|
||||
@@ -161,6 +161,29 @@ 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"}
|
||||
@@ -175,8 +198,7 @@ def _probe_ranged(url: str, session: Any, **kwargs: Any) -> tuple[int, bool]:
|
||||
try:
|
||||
if resp.status_code != 206:
|
||||
return 0, False
|
||||
ce = (resp.headers.get("Content-Encoding") or resp.headers.get("content-encoding") or "").lower()
|
||||
if ce in ("gzip", "deflate", "br"):
|
||||
if _is_content_encoded(resp.headers.get("Content-Encoding") or resp.headers.get("content-encoding")):
|
||||
return 0, False
|
||||
content_range = resp.headers.get("Content-Range") or resp.headers.get("content-range") or ""
|
||||
total = content_range.rsplit("/", 1)[-1].strip()
|
||||
@@ -213,6 +235,9 @@ 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(
|
||||
@@ -221,6 +246,7 @@ def _dispatch_parts(
|
||||
session=session,
|
||||
part_offset=start,
|
||||
part_end=end,
|
||||
abort=abort,
|
||||
**kwargs,
|
||||
):
|
||||
events.put(ev)
|
||||
@@ -264,7 +290,7 @@ def _dispatch_parts(
|
||||
exc = fut.exception()
|
||||
if exc:
|
||||
worker_error = True
|
||||
DOWNLOAD_CANCELLED.set()
|
||||
abort.set()
|
||||
raise exc
|
||||
|
||||
advance = 0
|
||||
@@ -300,13 +326,15 @@ 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.
|
||||
Uses raw socket reads for requests.Session and native rnet streaming for RnetSession.
|
||||
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.
|
||||
|
||||
Yields the following download status updates while chunks are downloading:
|
||||
|
||||
@@ -330,6 +358,8 @@ 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"}`.
|
||||
@@ -358,12 +388,15 @@ 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()
|
||||
@@ -376,33 +409,56 @@ 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}"
|
||||
request_kwargs["headers"] = req_headers
|
||||
elif resume_offset > 0:
|
||||
req_headers = dict(request_kwargs.get("headers", {}) or {})
|
||||
elif resume_offset > 0 and not item_range:
|
||||
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 resume_offset > 0 and stream.status_code == 206
|
||||
resumed = (not part_mode) and (not item_range) 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 stream.headers.get("Content-Encoding", "").lower() in ["gzip", "deflate", "br"]:
|
||||
if content_encoded:
|
||||
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:
|
||||
@@ -426,15 +482,12 @@ 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:
|
||||
elif use_raw and not content_encoded:
|
||||
_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"")
|
||||
@@ -449,7 +502,7 @@ def download(
|
||||
for chunk in chunks:
|
||||
if DOWNLOAD_CANCELLED.is_set():
|
||||
break
|
||||
if claimed is not None and claimed():
|
||||
if (claimed is not None and claimed()) or (abort is not None and abort.is_set()):
|
||||
# close the handle or Windows can't delete the stray .!dev at merge (WinError 32)
|
||||
try:
|
||||
stream.close()
|
||||
@@ -484,9 +537,6 @@ 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
|
||||
@@ -512,11 +562,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 attempts == MAX_ATTEMPTS:
|
||||
if part_mode and not DOWNLOAD_CANCELLED.is_set():
|
||||
raise
|
||||
if DOWNLOAD_CANCELLED.is_set() or (abort is not None and abort.is_set()):
|
||||
return
|
||||
if not part_mode:
|
||||
if attempts == MAX_ATTEMPTS:
|
||||
raise
|
||||
if not part_mode and not item_range:
|
||||
resume_offset = tmp_file.stat().st_size if tmp_file.exists() else 0
|
||||
time.sleep(RETRY_WAIT)
|
||||
attempts += 1
|
||||
@@ -651,7 +701,7 @@ def requests(
|
||||
url_item = urls[0]
|
||||
try:
|
||||
ranged_used = False
|
||||
if max_workers > 1 and _speed_limiter is None:
|
||||
if max_workers > 1 and _speed_limiter is None and not _has_range_header(url_item):
|
||||
total_size, supports_ranges = _probe_ranged(url_item["url"], session)
|
||||
if supports_ranges and total_size >= RANGE_PARALLEL_MIN_SIZE:
|
||||
try:
|
||||
@@ -683,6 +733,20 @@ 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
|
||||
@@ -702,43 +766,63 @@ 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:
|
||||
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:
|
||||
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
|
||||
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)
|
||||
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
|
||||
|
||||
futures = [pool.submit(_download_worker, i, url) for i, url in enumerate(urls)]
|
||||
pending = set(futures)
|
||||
|
||||
@@ -196,6 +196,29 @@ 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,6 +36,7 @@ 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,6 +15,12 @@ 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)."""
|
||||
|
||||
@@ -90,6 +96,7 @@ 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,
|
||||
)
|
||||
@@ -115,6 +122,7 @@ 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,6 +4,7 @@ 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
|
||||
@@ -15,6 +16,17 @@ 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():
|
||||
@@ -103,6 +115,7 @@ 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,
|
||||
)
|
||||
@@ -121,6 +134,7 @@ 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,6 +90,7 @@ 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 {}},
|
||||
)
|
||||
@@ -108,6 +109,7 @@ 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,6 +9,12 @@ 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"}
|
||||
|
||||
@@ -153,6 +159,7 @@ class TVDBProvider(MetadataProvider):
|
||||
year=_parse_int(best.get("year")),
|
||||
kind=kind,
|
||||
external_ids=ext,
|
||||
original_language=primary_language(best),
|
||||
source="tvdb",
|
||||
raw=best,
|
||||
)
|
||||
@@ -176,6 +183,7 @@ class TVDBProvider(MetadataProvider):
|
||||
year=_parse_int(detail.get("year")),
|
||||
kind=kind,
|
||||
external_ids=ext,
|
||||
original_language=primary_language(detail),
|
||||
source="tvdb",
|
||||
raw=detail,
|
||||
)
|
||||
|
||||
@@ -164,6 +164,49 @@ 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],
|
||||
@@ -454,9 +497,9 @@ def try_ensure_utf8(data: bytes) -> bytes:
|
||||
"""
|
||||
Try to ensure that the given data is encoded in UTF-8.
|
||||
|
||||
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).
|
||||
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.
|
||||
|
||||
Parameters:
|
||||
data: Input data that may or may not yet be UTF-8 or another encoding.
|
||||
@@ -464,13 +507,11 @@ 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)
|
||||
|
||||
Reference in New Issue
Block a user