Compare commits

..
14 Commits
Author SHA1 Message Date
imSp4rky 3dcc584b2f chore(changelog): update changelog and cleanup readme 2026-06-03 11:11:23 -06:00
imSp4rky 538deac63e fix(session): proxy auth on http targets and string params support
Drop the manually-set Proxy-Authorization header in the Service base class. It was malformed (base64 of user:pass with no "Basic" scheme) and redundant: both rnet (Proxy.all) and requests authenticate from the credentials embedded in the proxy URL. The broken header was tunnelled harmlessly on HTTPS (CONNECT) but handed to the proxy on plaintext-http forward requests, causing HTTP 407 (e.g. http MPD/segment URLs behind an authenticated geofence proxy).

Also make RnetSession._build_url accept the same params shapes as requests (mapping, sequence of pairs, or a pre-built str/bytes query). urlencode() previously raised TypeError on a string params value.
2026-05-30 18:13:55 +00:00
imSp4rky 0561623825 docs: simplify README with demo and requirements 2026-05-29 19:01:57 -06:00
imSp4rky 4ce0dd5bb9 chore(changelog): update version date and add new features and fixes for 5.1.0 2026-05-29 18:27:31 -06:00
imSp4rky 191c4f47e0 refactor: remove dead aria2c and n_m3u8dl_re downloader code
The legacy aria2c, curl-impersonate, and N_m3u8DL-RE downloader backends were replaced by the unified in-process requests/rnet downloader. This strips the leftover references those removals missed.
2026-05-29 18:25:56 -06:00
imSp4rky accfe9cee1 refactor(dl): declare hybrid_base_only flag and extract standalone mux helper
Make the DV-ingredient marker a declared Video attribute (sibling of needs_duration_fix) instead of a runtime-stamped attribute read via getattr, so the flag is explicit and type-checked.

Extract mux_video_standalone() to replace the duplicated per-track mux logic shared by the hybrid and normal-mode paths, removing the copy-paste and the getattr probes. Behavior unchanged.
2026-05-29 17:13:29 -06:00
imSp4rky 5899c1eec8 refactor(example): showcase full unshackle feature surface 2026-05-29 12:54:37 -06:00
imSp4rky 6bc601db39 fix(dl): mux all requested ranges and select highest DV alongside hybrid
When -r included HYBRID, the dl pipeline only muxed the hybrid output and dropped every other downloaded range. DV was also treated purely as a hybrid ingredient pool, so an explicitly requested DV range never produced a standalone deliverable - only the lowest DV (the RPU ingredient) was selected.

- Select the best DV per resolution as a standalone deliverable when DV is in -r, while still using the lowest DV as the hybrid ingredient (dv_is_deliverable).
- Flag the ingredient-only DV (hybrid_base_only) so it is downloaded for the hybrid build but skipped during standalone muxing.
- Mux every requested range standalone after hybrid processing; build hybrids from deepcopied ingredients so the originals stay muxable.
- Add Tracks.merge_video_selections to de-dup the ingredient/deliverable overlap so a shared DV track is not downloaded or muxed twice.
2026-05-28 21:25:30 -06:00
imSp4rky fb8dc0bd9d refactor(ip_info): simplify lookup and trim cache
Cache only country/country_code (drop full IP/org/asn), bump CACHE_KEY and auto-purge stale cache versions. Dedup the three provider parsers into one normalize(). Use a plain retry-free requests session for lookups instead of the TLS-fingerprinted session, carrying only the proxy over, so a 429 returns directly and hands over to the next provider reliably.
2026-05-27 22:48:39 -06:00
imSp4rky 40104be738 fix(dash): inherit SegmentTemplate attributes across AdaptationSet/Representation
A SegmentTemplate can sit at both the AdaptationSet and Representation levels, with shared attrs like @timescale only on the outer node. The parser picked one or the other, dropping the outer node when an inner existed - so @timescale defaulted to 1 and only the first segment was emitted.

Merge instead: Representation node as base, inheriting any attribute or SegmentTimeline it omits from the AdaptationSet node (per ISO/IEC 23009-1).
2026-05-27 12:12:42 -06:00
imSp4rky 96fd971af0 feat(import): include cover-art attachments in --export/--import
Export URL-backed attachments per title and rebuild them on import so they ride along into the muxed output. Local font attachments are skipped (not portable).
2026-05-26 17:37:44 -06:00
imSp4rky 1cb0e4b766 feat(naming): per-service title_map remapping (#106)
Add services.<TAG>.title_map exact-match dict to rewrite service-provided titles before naming/output. Shared remap_titles helper applied on local dl, import, and client-side dl --remote (server stays raw so clients can override names for services they don't have installed locally).
2026-05-26 14:08:52 -06:00
imSp4rky f4544b4a70 fix(hls): resolve per-rendition KID in no-EXT-X-KEY fallback
Manifests that signal DRM only via EXT-X-SESSION-DATA share one session_drm across all renditions, carrying just the manifest-level KID. The fallback licensing path licensed without the track's real KID, so --vaults-only only looked up the shared KID and could not find the rendition's key even when the vault held it (--cdm-only masked this since the license returns all keys). Resolve the KID from the init segment's tenc box and pass it through, matching the EXT-X-KEY path.
2026-05-26 14:04:06 -06:00
imSp4rky f1febe7e43 chore(release): bump version to 5.1.0 2026-05-26 10:54:14 -06:00
26 changed files with 1010 additions and 565 deletions
+80 -18
View File
@@ -6,6 +6,67 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
This changelog is automatically generated using [git-cliff](https://git-cliff.org).
## [5.1.0] - 2026-05-29
### Features
- *ip-info*: Consolidate IP lookup, add ipinfo.io token support
- *dl*: Cache content keys in-memory to skip duplicate license requests
- *mux*: Add muxing.default_language to override default track per type
- *hls*: Detect DV-composite tracks and restore signaling post-mux
- *video*: Normalize SPS VUI to match manifest-derived range
- *api*: Sync /api/download with dl CLI flags and add serve.* defaults
- *vaults*: Tolerate vault failures during key get/add
- *tracks*: Configurable audio codec priority for tie-breaking
- *dl*: Live countdown for --slow delay
- *dl*: Gate s_lang/a_lang miss behind --best-available
- *dl*: Add real bitrate probing (-rvb/-rab)
- *import*: Reconstruct downloads from an --export sidecar
- *naming*: Per-service title_map remapping
- *import*: Include cover-art attachments in --export/--import
### Bug Fixes
- *manifests*: Clean stale .!dev resume markers before merge
- *sanitize*: Preserve parentheses, strip unidecode bracket artifacts
- *tracks*: Honor --worst in hybrid range selection
- *dl*: Re-pick DV/HDR10 when HYBRID falls back under best_available
- *proxies/nordvpn*: Use *.proxy.nordvpn.com for HTTPS proxy
- *template_formatter*: Preserve dash separator around empty conditional
- *dl*: Prefer Atmos in -l best/all language selection
- *title*: Detect Atmos across all audio tracks for filename template
- *title*: Use original-language audio for filename metadata
- *service*: Render request_input prompt via rich console
- *titles*: Normalize odd resolutions in filename quality token
- *api*: Propagate Click default=None through service instantiation
- *api*: Load real CDM for service init in list/session/download flows
- *vaults*: Enable WAL on SQLite vault to fix concurrent locks
- *hybrid*: Correct static L6 source and reset stale L5 active area
- *cli*: Report broken command/service loads once and cleanly
- *hls*: Resolve per-rendition KID in no-EXT-X-KEY fallback
- *dash*: Inherit SegmentTemplate attributes across AdaptationSet/Representation
- *dl*: Mux all requested ranges and select highest DV alongside hybrid
- *session*: Proxy auth on http targets and string params support
### Documentation
- Update docs to match current codebase
- *output*: Document muxing.default_language override
- Simplify README with demo and requirements
### Changes
- *routes, subtitle, track*: Improve code readability by formatting list structures
- *hybrid*: Extract dovi_tool and run_step helpers
- *ip_info*: Simplify lookup and trim cache
- *example*: Showcase full unshackle feature surface
- *dl*: Declare hybrid_base_only flag and extract standalone mux helper
- Remove dead aria2c and n_m3u8dl_re downloader code
### Maintenance
- *pre-commit*: Update hook versions in .pre-commit-config.yaml
## [5.0.0] - 2026-05-04
### Features
@@ -624,21 +685,22 @@ This changelog is automatically generated using [git-cliff](https://git-cliff.or
- Reorganize Planned Features section in README for clarity
- Improve track selection logic in dl.py
[5.0.0]: https://github.com/unshackle-dl/unshackle-dev/compare/4.0.0..5.0.0
[4.0.0]: https://github.com/unshackle-dl/unshackle-dev/compare/3.0.0..4.0.0
[3.0.0]: https://github.com/unshackle-dl/unshackle-dev/compare/2.3.0..3.0.0
[2.3.0]: https://github.com/unshackle-dl/unshackle-dev/compare/2.2.0..2.3.0
[2.2.0]: https://github.com/unshackle-dl/unshackle-dev/compare/2.1.0..2.2.0
[2.1.0]: https://github.com/unshackle-dl/unshackle-dev/compare/2.0.0..2.1.0
[2.0.0]: https://github.com/unshackle-dl/unshackle-dev/compare/1.4.8..2.0.0
[1.4.8]: https://github.com/unshackle-dl/unshackle-dev/compare/1.4.7..1.4.8
[1.4.7]: https://github.com/unshackle-dl/unshackle-dev/compare/1.4.6..1.4.7
[1.4.6]: https://github.com/unshackle-dl/unshackle-dev/compare/1.4.5..1.4.6
[1.4.5]: https://github.com/unshackle-dl/unshackle-dev/compare/1.4.4..1.4.5
[1.4.4]: https://github.com/unshackle-dl/unshackle-dev/compare/1.4.2..1.4.4
[1.4.2]: https://github.com/unshackle-dl/unshackle-dev/compare/1.4.1..1.4.2
[1.4.1]: https://github.com/unshackle-dl/unshackle-dev/compare/1.4.0..1.4.1
[1.4.0]: https://github.com/unshackle-dl/unshackle-dev/compare/1.3.0..1.4.0
[1.3.0]: https://github.com/unshackle-dl/unshackle-dev/compare/1.2.0..1.3.0
[1.2.0]: https://github.com/unshackle-dl/unshackle-dev/compare/1.1.0..1.2.0
[1.1.0]: https://github.com/unshackle-dl/unshackle-dev/compare/1.0.1..1.1.0
[unreleased]: https://github.com/unshackle-dl/unshackle/compare/5.0.0..HEAD
[5.0.0]: https://github.com/unshackle-dl/unshackle/compare/4.0.0..5.0.0
[4.0.0]: https://github.com/unshackle-dl/unshackle/compare/3.0.0..4.0.0
[3.0.0]: https://github.com/unshackle-dl/unshackle/compare/2.3.0..3.0.0
[2.3.0]: https://github.com/unshackle-dl/unshackle/compare/2.2.0..2.3.0
[2.2.0]: https://github.com/unshackle-dl/unshackle/compare/2.1.0..2.2.0
[2.1.0]: https://github.com/unshackle-dl/unshackle/compare/2.0.0..2.1.0
[2.0.0]: https://github.com/unshackle-dl/unshackle/compare/1.4.8..2.0.0
[1.4.8]: https://github.com/unshackle-dl/unshackle/compare/1.4.7..1.4.8
[1.4.7]: https://github.com/unshackle-dl/unshackle/compare/1.4.6..1.4.7
[1.4.6]: https://github.com/unshackle-dl/unshackle/compare/1.4.5..1.4.6
[1.4.5]: https://github.com/unshackle-dl/unshackle/compare/1.4.4..1.4.5
[1.4.4]: https://github.com/unshackle-dl/unshackle/compare/1.4.2..1.4.4
[1.4.2]: https://github.com/unshackle-dl/unshackle/compare/1.4.1..1.4.2
[1.4.1]: https://github.com/unshackle-dl/unshackle/compare/1.4.0..1.4.1
[1.4.0]: https://github.com/unshackle-dl/unshackle/compare/1.3.0..1.4.0
[1.3.0]: https://github.com/unshackle-dl/unshackle/compare/1.2.0..1.3.0
[1.2.0]: https://github.com/unshackle-dl/unshackle/compare/1.1.0..1.2.0
[1.1.0]: https://github.com/unshackle-dl/unshackle/compare/1.0.1..1.1.0
+28 -85
View File
@@ -8,102 +8,45 @@
</a>
</p>
## What is unshackle?
<p align="center">
<a href="#install">Install</a> &nbsp;·&nbsp;
<a href="https://github.com/unshackle-dl/unshackle/wiki">Wiki</a> &nbsp;·&nbsp;
<a href="docs/">Docs</a> &nbsp;·&nbsp;
<a href="https://discord.gg/mHYyPaCbFK">Discord</a>
</p>
unshackle is a fork of [Devine](https://github.com/devine-dl/devine/), a powerful archival tool for downloading movies, TV shows, and music from streaming services. Built with a focus on modularity and extensibility, it provides a robust framework for content acquisition with support for DRM-protected content.
---
## Key Features
A modular archival tool for movies, TV, and music. Fork of [Devine](https://github.com/devine-dl/devine/) with DASH/HLS/ISM parsing, Widevine & PlayReady DRM, and a REST API.
- 🚀 **Easy Installation** - Simple UV installation
- 🎥 **Multi-Media Support** - Movies, TV episodes, and music
- 🛠️ **Built-in Parsers** - DASH/HLS and ISM manifest support
- 🔒 **DRM Support** - Widevine and PlayReady integration
- 🌈 **HDR10+DV Hybrid** - Hybrid Dolby Vision injection via [dovi_tool](https://github.com/quietvoid/dovi_tool)
- 💾 **Flexible Storage** - Local and remote key vaults
- 👥 **Multi-Profile Auth** - Support for cookies and credentials
- 🤖 **Smart Naming** - Automatic P2P-style filename structure
- ⚙️ **Configurable** - YAML-based configuration
- ❤️ **Open Source** - Fully open-source with community contributions welcome
<p align="center">
<a href="https://asciinema.org/a/ldMiqYFFTgPAOxW7">
<img src="https://asciinema.org/a/ldMiqYFFTgPAOxW7.svg" alt="unshackle demo" width="700">
</a>
</p>
## Quick Start
### Installation
This installs the latest version directly from the GitHub repository:
## Install
```shell
git clone https://github.com/unshackle-dl/unshackle.git
cd unshackle
uv sync
uv run unshackle --help
```
### Install unshackle as a global (per-user) tool
```bash
uv tool install git+https://github.com/unshackle-dl/unshackle.git
# Then run:
uvx unshackle --help # or just `unshackle` once PATH updated
unshackle --help
```
> [!NOTE]
> After installation, you may need to add the installation path to your PATH environment variable if prompted.
> [!TIP]
> Prefer `uv run unshackle ...` inside a clone to keep the virtual environment active.
> **Recommended:** Use `uv run unshackle` instead of direct command execution to ensure proper virtual environment activation.
### Requirements
## Planned Features
External tools on your `PATH` (recommended versions):
- 🖥️ **Web UI Access & Control** - Manage and control unshackle from a modern web interface.
- 🔄 **Sonarr/Radarr Interactivity** - Direct integration for automated personal downloads.
- ⚙️ **Better ISM Support** - Improve on ISM support for multiple services
- 🔉 **ATMOS** - Better Atmos Support/Selection
- 🎵 **Music** - Cleanup Audio Tagging using the [tags.py](unshackle/core/utils/tags.py) for artist/track name etc.
- [Python](https://www.python.org/) - 3.10 - 3.12
- [uv](https://docs.astral.sh/uv/) - ≥ 0.5
- [FFmpeg](https://ffmpeg.org/) - ≥ 6.0
- [MKVToolNix](https://mkvtoolnix.download/) - ≥ 80
- [shaka-packager](https://github.com/shaka-project/shaka-packager/releases/tag/v2.6.1) - 2.6.1
- [Bento4](https://github.com/axiomatic-systems/Bento4) - ≥ 1.6.0-639
- [dovi_tool](https://github.com/quietvoid/dovi_tool) - ≥ 2.1
### Basic Usage
## License
```shell
# Check available commands
uv run unshackle --help
# Configure your settings
git clone https://github.com/unshackle-dl/unshackle.git
cd unshackle
uv sync
uv run unshackle --help
# Download content (requires configured services)
uv run unshackle dl SERVICE_NAME CONTENT_ID
```
## Documentation
For comprehensive setup guides, configuration options, and advanced usage:
📖 **[Visit our WIKI](https://github.com/unshackle-dl/unshackle/wiki)**
The WIKI contains detailed information on:
- Service configuration
- DRM configuration
- Advanced features and troubleshooting
For guidance on creating services, see our [WIKI documentation](https://github.com/unshackle-dl/unshackle/wiki).
## End User License Agreement
unshackle and it's community pages should be treated with the same kindness as other projects.
Please refrain from spam or asking for questions that infringe upon a Service's End User License Agreement.
1. Do not use unshackle for any purposes of which you do not have the rights to do so.
2. Do not share or request infringing content; this includes widevine Provision Keys, Content Encryption Keys,
or Service API Calls or Code.
3. The Core codebase is meant to stay Free and Open-Source while the Service code should be kept private.
4. Do not sell any part of this project, neither alone nor as part of a bundle.
If you paid for this software or received it as part of a bundle following payment, you should demand your money
back immediately.
5. Be kind to one another and do not single anyone out.
## Licensing
This software is licensed under the terms of [GNU General Public License, Version 3.0](LICENSE).
You can find a copy of the license in the LICENSE file in the root folder.
[GPL-3.0](LICENSE). Do not use unshackle for content you lack the rights to. Keep the core free and open; keep service code private. Be kind.
+24 -1
View File
@@ -27,7 +27,7 @@ EXAMPLE:
You can override many global configuration options on a per-service basis by nesting them under the
service tag in the `services` section. Supported override keys include: `dl`, `subtitle`, `muxing`,
`headers`, `proxy_map`, and more.
`headers`, `proxy_map`, `title_map`, and more.
Overrides are merged with global config (not replaced) -- only specified keys are overridden, others
use global defaults. CLI arguments always take priority over service-specific config.
@@ -47,6 +47,29 @@ services:
Note: unshackle uses a single unified `requests`-based downloader. The legacy `aria2c`,
`n_m3u8dl_re`, and `curl_impersonate` override sections have been removed.
### title_map (dict)
Rewrites service-provided titles before naming and output. Some services name a title differently
from how you want it stored, which can break library matching (e.g. a regional variant reusing the
international name). Keys are the exact title string the service returns; values are the desired
output title.
```yaml
services:
EXAMPLE:
title_map:
Service Title: Desired Title
```
Episodes are matched on their show title, Movies and Songs on their name. The remap is applied
after the title cache (so edits take effect without a cache reset) and before any `--enrich`
override (so an explicit enrich still wins).
It applies on the local `dl` path, the `import` command, and the remote client (`dl --remote`).
For remote services the **client's** `title_map` is applied to the titles returned by the server,
so you can rename titles for services you don't have installed locally. The server sends raw
titles and does not remap, leaving the final name fully under the client's control.
### Service Class Conventions
Each service directory under `unshackle/services/` exports a class extending
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "unshackle"
version = "5.0.0"
version = "5.1.0"
description = "Modular Movie, TV, and Music Archival Software."
authors = [{ name = "unshackle team" }]
requires-python = ">=3.10,<3.13"
View File
+171
View File
@@ -0,0 +1,171 @@
"""Track-selection tests for HYBRID + DV behaviour.
Covers the selection primitives that back `-r ...,DV,HYBRID` downloads:
- ``Tracks.select_hybrid`` — picks the HDR base layer per resolution and the
single lowest DV track used as a hybrid ingredient.
- ``Tracks.merge_video_selections`` — de-duplicates the ingredient/deliverable
overlap so a DV track that is chosen as both is not muxed/downloaded twice.
The full ``dl`` selection pipeline (range filtering, the ``dv_is_deliverable``
partition, the ``hybrid_base_only`` ingredient flag and the standalone mux loop)
is orchestration glue inside the Click command; these tests lock down the pure
units it relies on plus the documented end-state of a realistic ATV-style ladder.
"""
from __future__ import annotations
import pytest
from unshackle.core.tracks import Tracks, Video
def make_video(track_id: str, *, range_: Video.Range, height: int, bitrate: int, codec: Video.Codec) -> Video:
return Video(
id_=track_id,
url=f"https://example.test/{track_id}.m3u8",
language="en",
codec=codec,
range_=range_,
width=int(height * 16 / 9),
height=height,
bitrate=bitrate,
)
@pytest.fixture
def ladder() -> list[Video]:
"""Mirrors the reported ATV ladder: HDR10+, DV and SDR at multiple resolutions."""
H = Video.Codec.HEVC
A = Video.Codec.AVC
return [
make_video("hdr10p-2160", range_=Video.Range.HDR10P, height=2160, bitrate=25_516_000, codec=H),
make_video("hdr10p-1080", range_=Video.Range.HDR10P, height=1080, bitrate=9_096_000, codec=H),
make_video("dv-2160", range_=Video.Range.DV, height=2160, bitrate=25_511_000, codec=H),
make_video("dv-1080", range_=Video.Range.DV, height=1080, bitrate=9_152_000, codec=H),
make_video("dv-360", range_=Video.Range.DV, height=360, bitrate=1_328_000, codec=H),
make_video("sdr-2160", range_=Video.Range.SDR, height=2160, bitrate=21_501_000, codec=H),
make_video("sdr-1080-avc", range_=Video.Range.SDR, height=1080, bitrate=10_793_000, codec=A),
make_video("sdr-1080-hevc", range_=Video.Range.SDR, height=1080, bitrate=5_768_000, codec=H),
]
def ids(tracks: list[Video]) -> set[str]:
return {t.id for t in tracks}
# ---------------------------------------------------------------------------
# select_hybrid
# ---------------------------------------------------------------------------
def test_select_hybrid_picks_base_per_resolution_and_lowest_dv(ladder: list[Video]) -> None:
chosen = list(filter(Tracks().select_hybrid(ladder, [2160, 1080]), ladder))
# HDR10+ base at each requested resolution, plus the single lowest DV ingredient.
assert ids(chosen) == {"hdr10p-2160", "hdr10p-1080", "dv-360"}
def test_select_hybrid_ingredient_is_lowest_dv_regardless_of_quality(ladder: list[Video]) -> None:
# Even when only 2160 is requested, the ingredient is the globally lowest DV.
chosen = list(filter(Tracks().select_hybrid(ladder, [2160]), ladder))
assert ids(chosen) == {"hdr10p-2160", "dv-360"}
def test_select_hybrid_prefers_hdr10p_over_hdr10() -> None:
H = Video.Codec.HEVC
tracks = [
make_video("hdr10-2160", range_=Video.Range.HDR10, height=2160, bitrate=20_000_000, codec=H),
make_video("hdr10p-2160", range_=Video.Range.HDR10P, height=2160, bitrate=20_000_000, codec=H),
make_video("dv-360", range_=Video.Range.DV, height=360, bitrate=1_000_000, codec=H),
]
chosen = list(filter(Tracks().select_hybrid(tracks, [2160]), tracks))
assert ids(chosen) == {"hdr10p-2160", "dv-360"}
def test_select_hybrid_base_picks_highest_bitrate_then_worst_flips() -> None:
H = Video.Codec.HEVC
tracks = [
make_video("hdr10p-2160-lo", range_=Video.Range.HDR10P, height=2160, bitrate=18_000_000, codec=H),
make_video("hdr10p-2160-hi", range_=Video.Range.HDR10P, height=2160, bitrate=25_000_000, codec=H),
make_video("dv-360", range_=Video.Range.DV, height=360, bitrate=1_000_000, codec=H),
]
best = list(filter(Tracks().select_hybrid(tracks, [2160]), tracks))
assert ids(best) == {"hdr10p-2160-hi", "dv-360"}
worst = list(filter(Tracks().select_hybrid(tracks, [2160], worst=True), tracks))
assert ids(worst) == {"hdr10p-2160-lo", "dv-360"}
def test_select_hybrid_no_dv_selects_only_base() -> None:
H = Video.Codec.HEVC
tracks = [make_video("hdr10p-2160", range_=Video.Range.HDR10P, height=2160, bitrate=20_000_000, codec=H)]
chosen = list(filter(Tracks().select_hybrid(tracks, [2160]), tracks))
assert ids(chosen) == {"hdr10p-2160"}
# ---------------------------------------------------------------------------
# merge_video_selections (the dedup fix)
# ---------------------------------------------------------------------------
def test_merge_dedups_shared_ingredient_and_deliverable() -> None:
H = Video.Codec.HEVC
dv = make_video("dv-1080", range_=Video.Range.DV, height=1080, bitrate=9_000_000, codec=H)
hdr = make_video("hdr10p-2160", range_=Video.Range.HDR10P, height=2160, bitrate=20_000_000, codec=H)
sdr = make_video("sdr-2160", range_=Video.Range.SDR, height=2160, bitrate=21_000_000, codec=H)
# dv is both the hybrid ingredient and an explicit DV deliverable (same object).
merged = Tracks.merge_video_selections([hdr, dv], [sdr, dv])
assert [t.id for t in merged] == ["hdr10p-2160", "dv-1080", "sdr-2160"]
def test_merge_preserves_order_and_keeps_distinct_dv() -> None:
H = Video.Codec.HEVC
ingredient = make_video("dv-360", range_=Video.Range.DV, height=360, bitrate=1_000_000, codec=H)
deliverable = make_video("dv-2160", range_=Video.Range.DV, height=2160, bitrate=25_000_000, codec=H)
merged = Tracks.merge_video_selections([ingredient], [deliverable])
assert [t.id for t in merged] == ["dv-360", "dv-2160"]
def test_merge_dedup_uses_track_identity_by_id() -> None:
# Tracks compare equal by id; merge must treat same-id tracks as one.
H = Video.Codec.HEVC
a = make_video("same", range_=Video.Range.DV, height=1080, bitrate=9_000_000, codec=H)
b = make_video("same", range_=Video.Range.DV, height=1080, bitrate=9_000_000, codec=H)
assert a == b
assert len(Tracks.merge_video_selections([a], [b])) == 1
# ---------------------------------------------------------------------------
# documented end-state for the reported command
# ---------------------------------------------------------------------------
def test_hybrid_plus_dv_deliverable_end_state(ladder: list[Video]) -> None:
"""`-r SDR,HDR10P,DV,HYBRID -q 2160,1080`: hybrid base + lowest DV ingredient,
de-duplicated against the best-DV-per-resolution deliverables and SDR."""
quality = [2160, 1080]
hybrid_selected = list(filter(Tracks().select_hybrid(ladder, quality), ladder))
# Deliverables: best DV and SDR per requested resolution (what the dl Cartesian picks).
def best_per_res(range_: Video.Range, codec: Video.Codec | None = None) -> list[Video]:
out = []
for res in quality:
cands = [t for t in ladder if t.range == range_ and t.height == res and (codec is None or t.codec == codec)]
if cands:
out.append(max(cands, key=lambda t: t.bitrate))
return out
dv_deliverable = best_per_res(Video.Range.DV)
sdr_deliverable = [t for t in ladder if t.range == Video.Range.SDR]
final = Tracks.merge_video_selections(hybrid_selected, dv_deliverable + sdr_deliverable)
# No duplicates, and the lowest DV ingredient coexists with the DV deliverables.
assert len(final) == len({t.id for t in final})
assert "dv-360" in ids(final) # ingredient retained for hybrid build
assert {"dv-2160", "dv-1080"} <= ids(final) # standalone DV deliverables
assert {"hdr10p-2160", "hdr10p-1080"} <= ids(final)
assert {"sdr-2160", "sdr-1080-avc", "sdr-1080-hevc"} <= ids(final)
+55 -41
View File
@@ -718,7 +718,6 @@ class dl:
for name, binary in [
("shaka_packager", binaries.ShakaPackager),
("mp4decrypt", binaries.Mp4decrypt),
("n_m3u8dl_re", binaries.N_m3u8DL_RE),
("mkvmerge", binaries.MKVToolNix),
("ffmpeg", binaries.FFMPEG),
("ffprobe", binaries.FFProbe),
@@ -744,11 +743,6 @@ class dl:
output = (r.stdout or "") + (r.stderr or "")
lines = [line.strip() for line in output.split("\n") if line.strip()]
version = " | ".join(lines[:2]) if lines else None
elif name == "n_m3u8dl_re":
r = subprocess.run(
[str(binary), "--version"], capture_output=True, text=True, timeout=5
)
version = (r.stdout or r.stderr or "").strip().split("\n")[0]
except Exception:
version = "<error getting version>"
binary_versions[name] = {"path": str(binary), "version": version}
@@ -1703,11 +1697,13 @@ class dl:
has_hybrid = any(r == Video.Range.HYBRID for r in range_)
non_hybrid_ranges = [r for r in range_ if r != Video.Range.HYBRID]
# DV is both a hybrid ingredient (lowest track) and, when explicitly
# requested, a standalone deliverable (best track per resolution).
dv_is_deliverable = Video.Range.DV in non_hybrid_ranges
if quality:
missing_resolutions = []
if has_hybrid:
# Split tracks: hybrid candidates vs non-hybrid
hybrid_candidate_tracks = [
v
for v in title.tracks.videos
@@ -1717,20 +1713,19 @@ class dl:
v
for v in title.tracks.videos
if v.range not in (Video.Range.HDR10, Video.Range.HDR10P, Video.Range.DV)
or (dv_is_deliverable and v.range == Video.Range.DV)
]
# Apply hybrid selection to HDR10+DV tracks
hybrid_filter = title.tracks.select_hybrid(hybrid_candidate_tracks, quality, worst=worst)
hybrid_selected = list(filter(hybrid_filter, hybrid_candidate_tracks))
if non_hybrid_ranges and non_hybrid_tracks:
# Also filter non-hybrid tracks by resolution
non_hybrid_selected = [
v
for v in non_hybrid_tracks
if any(v.height == res or int(v.width * (9 / 16)) == res for res in quality)
]
title.tracks.videos = hybrid_selected + non_hybrid_selected
title.tracks.videos = Tracks.merge_video_selections(hybrid_selected, non_hybrid_selected)
else:
title.tracks.videos = hybrid_selected
else:
@@ -1771,6 +1766,7 @@ class dl:
v
for v in title.tracks.videos
if v.range not in (Video.Range.HDR10, Video.Range.HDR10P, Video.Range.DV)
or (dv_is_deliverable and v.range == Video.Range.DV)
]
if not quality:
@@ -1813,7 +1809,16 @@ class dl:
if match and match not in non_hybrid_selected:
non_hybrid_selected.append(match)
title.tracks.videos = hybrid_selected + non_hybrid_selected
title.tracks.videos = Tracks.merge_video_selections(hybrid_selected, non_hybrid_selected)
# Flag the lowest DV track as ingredient-only so mux skips it standalone,
# unless it is itself the chosen DV deliverable (single DV rendition).
selected_dv = [v for v in title.tracks.videos if v.range == Video.Range.DV]
if selected_dv:
ingredient_dv = min(selected_dv, key=lambda v: v.height)
deliverable_dv = [v for v in non_hybrid_selected if v.range == Video.Range.DV]
if not (dv_is_deliverable and ingredient_dv in deliverable_dv):
ingredient_dv.hybrid_base_only = True
else:
selected_videos: list[Video] = []
if video_multi_lang:
@@ -2473,12 +2478,33 @@ class dl:
task_tracks = clone_tracks_for_audio(base_tracks, codec_audio_tracks)
multiplex_tasks.append((task_id, task_tracks, audio_codec))
# Check if we're in hybrid mode
def mux_video_standalone(video_track: Optional[Video]) -> None:
if video_track and video_track.dv_compatible_bitstream:
apply_dv_fixup(video_track)
task_description = "Multiplexing"
if video_track:
if len(quality) > 1:
task_description += f" {video_track.height}p"
if len(range_) > 1:
task_description += f" {video_track.range.name}"
if len(vcodec) > 1:
task_description += f" {video_track.codec.name}"
task_tracks = Tracks(title.tracks) + title.tracks.chapters + title.tracks.attachments
if video_track:
task_tracks.videos = [video_track]
enqueue_mux_tasks(task_description, task_tracks)
if any(r == Video.Range.HYBRID for r in range_) and title.tracks.videos:
# Hybrid mode: process DV and HDR10 tracks separately for each resolution
self.log.info("Processing Hybrid HDR10+DV tracks...")
# Group video tracks by resolution (prefer HDR10+ over HDR10 as base)
# Snapshot videos before hybrid tracks are added so the originals
# can still be muxed standalone afterwards.
original_videos = list(title.tracks.videos)
# Prefer HDR10+ over HDR10 as the hybrid base layer.
resolutions_processed = set()
base_tracks_list = [
v for v in title.tracks.videos if v.range in (Video.Range.HDR10P, Video.Range.HDR10)
@@ -2489,38 +2515,33 @@ class dl:
resolution = hdr10_track.height
if resolution in resolutions_processed:
continue
resolutions_processed.add(resolution)
# Find matching DV track for this resolution (use the lowest DV resolution)
# DV layer only supplies RPU metadata, so the lowest resolution suffices.
matching_dv = min(dv_tracks, key=lambda v: v.height) if dv_tracks else None
if matching_dv:
# Create track pair for this resolution
resolution_tracks = [hdr10_track, matching_dv]
resolutions_processed.add(resolution)
# Operate on copies so the originals stay muxable standalone.
resolution_tracks = [deepcopy(hdr10_track), deepcopy(matching_dv)]
for track in resolution_tracks:
track.needs_duration_fix = True
# Run the hybrid processing for this resolution
Hybrid(resolution_tracks, self.service)
# Create unique output filename for this resolution
hybrid_filename = f"HDR10-DV-{resolution}p.hevc"
hybrid_output_path = config.directories.temp / hybrid_filename
hybrid_temp_paths.append(hybrid_output_path)
# The Hybrid class creates HDR10-DV.hevc, rename it for this resolution
# Hybrid always writes HDR10-DV.hevc; rename it per resolution.
default_output = config.directories.temp / "HDR10-DV.hevc"
if default_output.exists():
# If a previous run left this behind, replace it to avoid move() failures.
hybrid_output_path.unlink(missing_ok=True)
shutil.move(str(default_output), str(hybrid_output_path))
# Create tracks with the hybrid video output for this resolution
task_description = f"Multiplexing Hybrid HDR10+DV {resolution}p"
task_tracks = Tracks(title.tracks) + title.tracks.chapters + title.tracks.attachments
# Create a new video track for the hybrid output
hybrid_track = deepcopy(hdr10_track)
hybrid_track.id = f"hybrid_{hdr10_track.id}_{resolution}"
hybrid_track.path = hybrid_output_path
@@ -2531,27 +2552,17 @@ class dl:
enqueue_mux_tasks(task_description, task_tracks)
# Mux every requested range standalone, skipping the ingredient-only DV.
for video_track in original_videos:
if video_track.hybrid_base_only:
continue
mux_video_standalone(video_track)
console.print()
else:
# Normal mode: process each video track separately
for video_track in title.tracks.videos or [None]:
if video_track and getattr(video_track, "dv_compatible_bitstream", False):
apply_dv_fixup(video_track)
task_description = "Multiplexing"
if video_track:
if len(quality) > 1:
task_description += f" {video_track.height}p"
if len(range_) > 1:
task_description += f" {video_track.range.name}"
if len(vcodec) > 1:
task_description += f" {video_track.codec.name}"
task_tracks = Tracks(title.tracks) + title.tracks.chapters + title.tracks.attachments
if video_track:
task_tracks.videos = [video_track]
enqueue_mux_tasks(task_description, task_tracks)
mux_video_standalone(video_track)
try:
with Live(Padding(progress, (0, 5, 1, 5)), console=console):
@@ -2829,6 +2840,9 @@ class dl:
{"timestamp": chapter.timestamp, "name": chapter.name} for chapter in (title.tracks.chapters or [])
]
if "attachments" not in tinfo:
tinfo["attachments"] = [a.to_dict() for a in (title.tracks.attachments or []) if a.url]
export.write_text(json.dumps(doc, indent=4, ensure_ascii=False), encoding="utf8")
def prepare_drm(
-9
View File
@@ -68,15 +68,6 @@ def check() -> None:
"desc": "HDR10+ metadata",
"cat": "HDR",
},
# Downloaders
{"name": "aria2c", "binary": binaries.Aria2, "required": False, "desc": "Multi-thread DL", "cat": "Download"},
{
"name": "N_m3u8DL-RE",
"binary": binaries.N_m3u8DL_RE,
"required": False,
"desc": "HLS/DASH/ISM",
"cat": "Download",
},
# Subtitle Tools
{
"name": "SubtitleEdit",
+1 -1
View File
@@ -1 +1 @@
__version__ = "5.0.0"
__version__ = "5.1.0"
+2 -2
View File
@@ -413,7 +413,7 @@ def serialize_video_track(track: Video, include_url: bool = False) -> Dict[str,
codec_name = track.codec.name if hasattr(track.codec, "name") else str(track.codec)
range_name = track.range.name if hasattr(track.range, "name") else str(track.range)
# Get descriptor for N_m3u8DL-RE compatibility (HLS, DASH, URL, etc.)
# Serialize the manifest descriptor (HLS, DASH, URL, etc.)
descriptor_name = None
if hasattr(track, "descriptor") and track.descriptor:
descriptor_name = track.descriptor.name if hasattr(track.descriptor, "name") else str(track.descriptor)
@@ -442,7 +442,7 @@ def serialize_audio_track(track: Audio, include_url: bool = False) -> Dict[str,
"""Convert audio track to JSON-serializable dict."""
codec_name = track.codec.name if hasattr(track.codec, "name") else str(track.codec)
# Get descriptor for N_m3u8DL-RE compatibility
# Serialize the manifest descriptor (HLS, DASH, URL, etc.)
descriptor_name = None
if hasattr(track, "descriptor") and track.descriptor:
descriptor_name = track.descriptor.name if hasattr(track.descriptor, "name") else str(track.descriptor)
-4
View File
@@ -45,12 +45,10 @@ ShakaPackager = find(
f"packager-{__shaka_platform}-arm64",
f"packager-{__shaka_platform}-x64",
)
Aria2 = find("aria2c", "aria2")
CCExtractor = find("ccextractor", "ccextractorwin", "ccextractorwinfull")
HolaProxy = find("hola-proxy")
MPV = find("mpv")
Caddy = find("caddy")
N_m3u8DL_RE = find("N_m3u8DL-RE", "n-m3u8dl-re")
MKVToolNix = find("mkvmerge")
Mkvpropedit = find("mkvpropedit")
DoviTool = find("dovi_tool")
@@ -66,12 +64,10 @@ __all__ = (
"FFPlay",
"SubtitleEdit",
"ShakaPackager",
"Aria2",
"CCExtractor",
"HolaProxy",
"MPV",
"Caddy",
"N_m3u8DL_RE",
"MKVToolNix",
"Mkvpropedit",
"DoviTool",
+22 -2
View File
@@ -16,8 +16,9 @@ from unshackle.core.credential import Credential
from unshackle.core.drm import drm_from_dict
from unshackle.core.manifests import DASH, HLS, ISM
from unshackle.core.remote_service import RemoteService, _build_title, _resolve_proxy
from unshackle.core.titles import Episode, Movies, Series, Title_T, Titles_T
from unshackle.core.titles import Episode, Movies, Series, Title_T, Titles_T, remap_titles
from unshackle.core.tracks import Audio, Chapter, Chapters, Tracks, Video
from unshackle.core.tracks.attachment import Attachment
from unshackle.core.tracks.track import Track
log = logging.getLogger("import")
@@ -123,7 +124,9 @@ class ImportService:
return self.titles
def get_titles_cached(self, title_id: Optional[str] = None) -> Titles_T:
return self.get_titles()
"""Apply the service's title_map to titles reconstructed from the export sidecar."""
title_map = (config.services.get(self.service_tag) or {}).get("title_map") or {}
return remap_titles(self.get_titles(), title_map)
def get_tracks(self, title: Title_T) -> Tracks:
"""Reconstruct the title's tracks from the export.
@@ -164,6 +167,23 @@ class ImportService:
track.drm = drm
tracks.add(track)
for attachment in entry.get("attachments") or []:
url = attachment.get("url")
if not url:
continue
try:
tracks.attachments.append(
Attachment.from_url(
url,
name=attachment.get("name"),
mime_type=attachment.get("mime_type"),
description=attachment.get("description"),
session=self.session,
)
)
except Exception as e:
self.log.warning(f"Skipping attachment '{attachment.get('name')}': {e}")
self.tracks_by_title[title_id] = tracks
return tracks
+28 -5
View File
@@ -7,7 +7,7 @@ import math
import re
import shutil
import sys
from copy import copy
from copy import deepcopy
from functools import partial
from pathlib import Path
from typing import Any, Callable, Optional, Union
@@ -587,6 +587,32 @@ class DASH:
return False
return True
@staticmethod
def _merge_segment_templates(adaptation_set: Element, representation: Element) -> Optional[Element]:
"""
Build the effective SegmentTemplate for a Representation by cascading the
AdaptationSet > Representation levels (ISO/IEC 23009-1 5.3.9.1).
The Representation-level node, when present, is the base; attributes and the
SegmentTimeline child it does not declare are inherited from the AdaptationSet-level
node. Returns None if no SegmentTemplate exists at either level.
"""
levels = [node.find("SegmentTemplate") for node in (adaptation_set, representation)]
present = [node for node in levels if node is not None]
if not present:
return None
merged = deepcopy(present[-1])
for ancestor in reversed(present[:-1]):
for attr, value in ancestor.attrib.items():
if merged.get(attr) is None:
merged.set(attr, value)
if merged.find("SegmentTimeline") is None:
timeline = ancestor.find("SegmentTimeline")
if timeline is not None:
merged.append(deepcopy(timeline))
return merged
@staticmethod
def _get_period_segments(
period: Element,
@@ -621,9 +647,7 @@ class DASH:
period_duration = period.get("duration") or manifest.get("mediaPresentationDuration")
init_data: Optional[bytes] = None
segment_template = representation.find("SegmentTemplate")
if segment_template is None:
segment_template = adaptation_set.find("SegmentTemplate")
segment_template = DASH._merge_segment_templates(adaptation_set, representation)
segment_list = representation.find("SegmentList")
if segment_list is None:
@@ -639,7 +663,6 @@ class DASH:
track_kid: Optional[UUID] = None
if segment_template is not None:
segment_template = copy(segment_template)
start_number = int(segment_template.get("startNumber") or 1)
end_number = int(segment_template.get("endNumber") or 0) or None
segment_timeline = segment_template.find("SegmentTimeline")
+2 -34
View File
@@ -490,39 +490,6 @@ class HLS:
return None
@staticmethod
def _finalize_n_m3u8dl_re_output(*, track: AnyTrack, save_dir: Path, save_path: Path) -> Path:
"""
Finalize output from N_m3u8DL-RE.
We call N_m3u8DL-RE with `--save-name track.id`, so the final file should be `{track.id}.*` under `save_dir`.
This moves that output to `save_path` (preserving the real suffix) and, for subtitles, updates `track.codec`
to match the produced file extension.
"""
matches = [p for p in save_dir.rglob(f"{track.id}.*") if p.is_file()]
if not matches:
raise FileNotFoundError(f"No output files produced by N_m3u8DL-RE for save-name={track.id} in: {save_dir}")
primary = max(matches, key=lambda p: p.stat().st_size)
final_save_path = save_path.with_suffix(primary.suffix) if primary.suffix else save_path
final_save_path.parent.mkdir(parents=True, exist_ok=True)
if primary.absolute() != final_save_path.absolute():
final_save_path.unlink(missing_ok=True)
shutil.move(str(primary), str(final_save_path))
if isinstance(track, Subtitle):
ext = final_save_path.suffix.lower().lstrip(".")
try:
track.codec = Subtitle.Codec.from_mime(ext)
except ValueError:
pass
shutil.rmtree(save_dir, ignore_errors=True)
return final_save_path
@staticmethod
def download_track(
track: AnyTrack,
@@ -609,8 +576,9 @@ class HLS:
try:
if not license_widevine:
raise ValueError("license_widevine func must be supplied to use DRM")
track_kid = HLS.get_track_kid_from_init(master, track, session) or session_drm.kid
progress(downloaded="LICENSING")
license_widevine(session_drm)
license_widevine(session_drm, track_kid=track_kid)
progress(downloaded="[yellow]LICENSED")
except Exception: # noqa
DOWNLOAD_CANCELLED.set() # skip pending track downloads
+8 -2
View File
@@ -25,7 +25,7 @@ from unshackle.core.config import config
from unshackle.core.console import console
from unshackle.core.constants import AnyTrack
from unshackle.core.credential import Credential
from unshackle.core.titles import Title_T, Titles_T
from unshackle.core.titles import Title_T, Titles_T, remap_titles
from unshackle.core.titles.episode import Episode, Series
from unshackle.core.titles.movie import Movie, Movies
from unshackle.core.tracks import Audio, Chapter, Chapters, Subtitle, Tracks, Video
@@ -573,7 +573,13 @@ class RemoteService:
return self._titles
def get_titles_cached(self, title_id: str = None) -> Titles_T:
return self.get_titles()
"""Apply the client's local title_map to titles fetched from the remote server.
Lets users rename titles for remote services they don't have installed locally.
The server sends raw titles; the client's own ``services.<TAG>.title_map`` wins.
"""
title_map = (config.services.get(self.service_tag) or {}).get("title_map") or {}
return remap_titles(self.get_titles(), title_map)
def get_tracks(self, title: Title_T) -> Tracks:
title_id = str(title.id)
+18 -13
View File
@@ -1,4 +1,3 @@
import base64
import logging
from abc import ABCMeta, abstractmethod
from collections.abc import Callable, Generator
@@ -27,7 +26,7 @@ from unshackle.core.credential import Credential
from unshackle.core.drm import DRM_T
from unshackle.core.search_result import SearchResult
from unshackle.core.title_cacher import TitleCacher, get_account_hash, get_region_from_proxy
from unshackle.core.titles import Title_T, Titles_T
from unshackle.core.titles import Title_T, Titles_T, remap_titles
from unshackle.core.tracks import Chapters, Tracks
from unshackle.core.tracks.video import Video
from unshackle.core.utils.ip_info import get_ip_info
@@ -213,15 +212,10 @@ class Service(metaclass=ABCMeta):
if proxy:
self.session.proxies.update({"all": proxy})
proxy_parse = urlparse(proxy)
if proxy_parse.username and proxy_parse.password:
self.session.headers.update(
{
"Proxy-Authorization": base64.b64encode(
f"{proxy_parse.username}:{proxy_parse.password}".encode("utf8")
).decode()
}
)
# Don't set Proxy-Authorization manually: both rnet (Proxy.all) and
# requests authenticate from the credentials embedded in the proxy URL.
# A manual header here was malformed (no "Basic " scheme) and broke
# plaintext-http forward-proxy requests with HTTP 407.
# Always verify proxy IP - proxies can change exit nodes
try:
proxy_ip_info = get_ip_info(self.session)
@@ -482,7 +476,7 @@ class Service(metaclass=ABCMeta):
else:
# If we can't determine title_id, just call get_titles directly
self.log.debug("Cannot determine title_id for caching, bypassing cache")
return self.get_titles()
return self.apply_title_map(self.get_titles())
# Get cache control flags from context
no_cache = False
@@ -495,7 +489,7 @@ class Service(metaclass=ABCMeta):
account_hash = get_account_hash(self.credential)
# Use title cache to get titles with fallback support
return self.title_cache.get_cached_titles(
titles = self.title_cache.get_cached_titles(
title_id=str(title_id),
fetch_function=self.get_titles,
region=self.current_region,
@@ -503,6 +497,17 @@ class Service(metaclass=ABCMeta):
no_cache=no_cache,
reset_cache=reset_cache,
)
return self.apply_title_map(titles)
def apply_title_map(self, titles: Titles_T) -> Titles_T:
"""
Rewrite service-provided titles using the per-service ``title_map`` config.
``title_map`` lives under ``services.<TAG>`` in unshackle.yaml. Applied after the
title cache so config edits take effect without a cache reset, and before any
``--enrich`` override so enrich wins. See ``remap_titles`` for the match rules.
"""
return remap_titles(titles, (self.config or {}).get("title_map") or {})
@abstractmethod
def get_tracks(self, title: Title_T) -> Tracks:
+14 -5
View File
@@ -523,15 +523,24 @@ class RnetSession:
self.cookies._flush_to_client()
return self._client
def _build_url(self, url: str, params: Optional[dict] = None) -> str:
"""URL-encode params dict into the URL (rnet ignores params kwarg)."""
def _build_url(self, url: str, params: Optional[Any] = None) -> str:
"""Encode params into the URL (rnet ignores the params kwarg).
Accepts the same shapes as requests: a mapping, a sequence of pairs, or a
pre-built query string/bytes. A string is appended verbatim (already encoded);
urlencode() would raise TypeError on it.
"""
if not params:
return url
if isinstance(params, bytes):
extra = params.decode("utf-8")
elif isinstance(params, str):
extra = params
else:
extra = urlencode(params, doseq=True)
parsed = urlparse(url)
separator = "&" if parsed.query else ""
query = (
parsed.query + separator + urlencode(params, doseq=True) if parsed.query else urlencode(params, doseq=True)
)
query = parsed.query + separator + extra if parsed.query else extra
return urlunparse(parsed._replace(query=query))
def get_sleep_time(self, response: Optional[RnetResponse], attempt: int) -> Optional[float]:
+37 -1
View File
@@ -8,4 +8,40 @@ Title_T = Union[Movie, Episode, Song]
Titles_T = Union[Movies, Series, Album]
__all__ = ("Episode", "Series", "Movie", "Movies", "Album", "Song", "Title_T", "Titles_T")
def remap_titles(titles: Titles_T, title_map: dict) -> Titles_T:
"""
Rewrite titles in-place using an exact-match ``title_map``.
Some services name a title differently from how the user wants it stored, which can
break library matching. ``title_map`` maps a source title string to the desired output
title. Episodes are matched on their ``title`` (the show name), Movies and Songs on
their ``name``. Returns the same collection for convenient chaining.
"""
if not title_map or not titles:
return titles
def remap_one(title: Title_T) -> None:
attr = "title" if isinstance(title, Episode) else "name"
current = getattr(title, attr, None)
if current and current in title_map:
setattr(title, attr, title_map[current])
if hasattr(titles, "__iter__"):
for title in titles:
remap_one(title)
else:
remap_one(titles)
return titles
__all__ = (
"Episode",
"Series",
"Movie",
"Movies",
"Album",
"Song",
"Title_T",
"Titles_T",
"remap_titles",
)
+4
View File
@@ -125,6 +125,10 @@ class Attachment:
def __str__(self) -> str:
return " | ".join(filter(bool, ["ATT", self.name, self.mime_type, self.description]))
def to_dict(self) -> dict[str, Optional[str]]:
"""Serialise a URL-backed attachment for export/import."""
return {"url": self.url, "name": self.name, "mime_type": self.mime_type, "description": self.description}
@property
def id(self) -> str:
"""Compute an ID from the attachment data."""
+14
View File
@@ -325,6 +325,20 @@ class Tracks:
new_tracks.attachments = list(self.attachments)
return new_tracks
@staticmethod
def merge_video_selections(*groups: list[Video]) -> list[Video]:
"""Concatenate video selections, dropping duplicates (by track id, order-preserving).
A DV track can be chosen as both the hybrid ingredient (lowest) and an explicit
deliverable; without dedup the same track would be muxed/downloaded twice.
"""
merged: list[Video] = []
for group in groups:
for video in group:
if video not in merged:
merged.append(video)
return merged
def select_hybrid(self, tracks, quality, worst: bool = False):
# Prefer HDR10+ over HDR10 as the base layer (preserves dynamic metadata)
base_ranges = (Video.Range.HDR10P, Video.Range.HDR10)
+1
View File
@@ -296,6 +296,7 @@ class Video(Track):
self.closed_captions: list[dict[str, Any]] = closed_captions or []
self.needs_duration_fix = False
self.dv_compatible_bitstream = dv_compatible_bitstream
self.hybrid_base_only = False
def to_dict(self) -> dict[str, Any]:
data = super().to_dict()
+123 -105
View File
@@ -8,101 +8,113 @@ import requests
from unshackle.core.cacher import Cacher
CACHE_KEY = "ip_info_v2"
CACHE_KEY = "ip_info_v3"
CACHE_TTL = 86400 # 24 hours
PROVIDER_STATE_KEY = "ip_provider_state"
RATE_LIMIT_COOLDOWN = 300 # 5 minutes
REQUEST_TIMEOUT = 10
# Only these keys are persisted to the global cache.
GEO_CACHE_KEYS = ("country", "country_code")
Fetcher = Callable[[requests.Session], Optional[dict]]
log = logging.getLogger("ip_info")
class _RateLimited(Exception):
class RateLimited(Exception):
"""Raised by a provider fetcher when the upstream returns 429."""
def _empty() -> dict:
def normalize(
*,
country_code: str,
ip: str = "",
region: str = "",
city: str = "",
org: str = "",
asn: str = "",
as_name: str = "",
continent_code: str = "",
) -> Optional[dict]:
"""Build the canonical IP-info dict, or None if no country code is present."""
code = country_code.strip()
if not code:
return None
return {
"ip": "",
"country": "",
"country_code": "",
"region": "",
"city": "",
"org": "",
"asn": "",
"as_name": "",
"continent_code": "",
"ip": ip,
"country": code.lower(),
"country_code": code.upper(),
"region": region,
"city": city,
"org": org,
"asn": asn,
"as_name": as_name,
"continent_code": continent_code.upper(),
}
def _parse_ipinfo_lite(data: dict) -> Optional[dict]:
code = (data.get("country_code") or "").strip()
if not code:
return None
def parse_ipinfo_lite(data: dict) -> Optional[dict]:
asn = (data.get("asn") or "").strip()
as_name = (data.get("as_name") or "").strip()
org = f"{asn} {as_name}".strip() if (asn or as_name) else ""
out = _empty()
out.update(
{
"ip": data.get("ip") or "",
"country": code.lower(),
"country_code": code.upper(),
"org": org,
"asn": asn,
"as_name": as_name,
"continent_code": (data.get("continent_code") or "").upper(),
}
return normalize(
country_code=data.get("country_code") or "",
ip=data.get("ip") or "",
org=f"{asn} {as_name}".strip(),
asn=asn,
as_name=as_name,
continent_code=data.get("continent_code") or "",
)
return out
def _parse_ipinfo(data: dict) -> Optional[dict]:
code = (data.get("country") or "").strip()
if not code:
return None
out = _empty()
out.update(
{
"ip": data.get("ip") or "",
"country": code.lower(),
"country_code": code.upper(),
"region": data.get("region") or "",
"city": data.get("city") or "",
"org": data.get("org") or "",
}
def parse_ipinfo(data: dict) -> Optional[dict]:
return normalize(
country_code=data.get("country") or "",
ip=data.get("ip") or "",
region=data.get("region") or "",
city=data.get("city") or "",
org=data.get("org") or "",
)
return out
def _parse_ip_api_in(data: dict) -> Optional[dict]:
code = (data.get("country_code") or "").strip()
if not code:
return None
def parse_ip_api_in(data: dict) -> Optional[dict]:
asn = (data.get("asn") or "").strip()
org_name = (data.get("organization") or "").strip()
org = f"{asn} {org_name}".strip() if (asn or org_name) else ""
out = _empty()
out.update(
{
"ip": data.get("ip") or "",
"country": code.lower(),
"country_code": code.upper(),
"region": data.get("region") or "",
"city": data.get("city") or "",
"org": org,
"asn": asn,
"as_name": org_name,
"continent_code": (data.get("continent_code") or "").upper(),
}
return normalize(
country_code=data.get("country_code") or "",
ip=data.get("ip") or "",
region=data.get("region") or "",
city=data.get("city") or "",
org=f"{asn} {org_name}".strip(),
asn=asn,
as_name=org_name,
continent_code=data.get("continent_code") or "",
)
return out
def _check(response: requests.Response) -> Optional[dict]:
"""Raise _RateLimited on 429, return parsed JSON on 200, else None."""
def lookup_session(source: Optional[requests.Session]) -> requests.Session:
"""
Build a plain, retry-free requests session for IP geolocation.
Geolocation needs no TLS fingerprinting, so we skip the impersonated rnet
session and the base session's urllib3 retry loop — both retry 429 internally,
which hides the response and defeats fast provider handover. With a bare session
a 429 comes straight back so we can move to the next provider immediately. Only
the proxy is carried over so proxied lookups still report the proxy's exit IP.
"""
sess = requests.Session()
proxies = getattr(source, "proxies", None)
if proxies:
proxy = proxies.get("all") or proxies.get("https") or proxies.get("http")
if proxy:
sess.proxies.update({"http": proxy, "https": proxy})
return sess
def json_or_raise(response: requests.Response) -> Optional[dict]:
"""Raise RateLimited on 429, return parsed JSON on 200, else None."""
if response.status_code == 429:
raise _RateLimited()
raise RateLimited()
if response.status_code != 200:
return None
try:
@@ -111,50 +123,62 @@ def _check(response: requests.Response) -> Optional[dict]:
return None
def _fetch_ipinfo_lite(token: str) -> Fetcher:
def fetch_ipinfo_lite(token: str) -> Fetcher:
headers = {"Authorization": f"Bearer {token}"}
def fetch(session: requests.Session) -> Optional[dict]:
payload = _check(session.get("https://api.ipinfo.io/lite/me", headers=headers, timeout=REQUEST_TIMEOUT))
return _parse_ipinfo_lite(payload) if payload else None
payload = json_or_raise(session.get("https://api.ipinfo.io/lite/me", headers=headers, timeout=REQUEST_TIMEOUT))
return parse_ipinfo_lite(payload) if payload else None
return fetch
def _fetch_ipinfo(session: requests.Session) -> Optional[dict]:
payload = _check(session.get("https://ipinfo.io/json", timeout=REQUEST_TIMEOUT))
return _parse_ipinfo(payload) if payload else None
def fetch_ipinfo(session: requests.Session) -> Optional[dict]:
payload = json_or_raise(session.get("https://ipinfo.io/json", timeout=REQUEST_TIMEOUT))
return parse_ipinfo(payload) if payload else None
def _fetch_ip_api_in(session: requests.Session) -> Optional[dict]:
def fetch_ip_api_in(session: requests.Session) -> Optional[dict]:
"""ip-api.in has no /me endpoint — resolve IP via ipify first, then look it up."""
ip_resp = session.get("https://api.ipify.org", timeout=REQUEST_TIMEOUT)
if ip_resp.status_code == 429:
raise _RateLimited()
if ip_resp.status_code != 200:
return None
ip = (ip_resp.text or "").strip()
raise RateLimited()
ip = (ip_resp.text or "").strip() if ip_resp.status_code == 200 else ""
if not ip:
return None
payload = _check(session.get(f"https://ip-api.in/api/v1/ip/{ip}", timeout=REQUEST_TIMEOUT))
payload = json_or_raise(session.get(f"https://ip-api.in/api/v1/ip/{ip}", timeout=REQUEST_TIMEOUT))
if not payload or not payload.get("success"):
return None
return _parse_ip_api_in(payload.get("data") or {})
return parse_ip_api_in(payload.get("data") or {})
def _build_providers() -> list[tuple[str, Fetcher]]:
"""Return ordered (name, fetcher) pairs. Token read at call time."""
def build_providers() -> list[tuple[str, Fetcher]]:
"""Return ordered (name, fetcher) pairs. Token is read at call time."""
from unshackle.core.config import config
providers: list[tuple[str, Fetcher]] = []
token = (getattr(config, "ipinfo_api_key", "") or "").strip()
if token:
providers.append(("ipinfo_lite", _fetch_ipinfo_lite(token)))
providers.append(("ipinfo", _fetch_ipinfo))
providers.append(("ip_api_in", _fetch_ip_api_in))
providers.append(("ipinfo_lite", fetch_ipinfo_lite(token)))
providers.append(("ipinfo", fetch_ipinfo))
providers.append(("ip_api_in", fetch_ip_api_in))
return providers
def purge_stale_cache() -> None:
"""Delete superseded ip_info cache files (older CACHE_KEY versions)."""
from unshackle.core.config import config
global_dir = config.directories.cache / "global"
for stale in global_dir.glob("ip_info_v*.json"):
if stale.stem != CACHE_KEY:
stale.unlink(missing_ok=True)
def load_provider_state(cacher: Cacher) -> dict[str, Any]:
return cacher.data if cacher and not cacher.expired and isinstance(cacher.data, dict) else {}
def get_ip_info(
session: Optional[requests.Session] = None,
*,
@@ -164,9 +188,10 @@ def get_ip_info(
Look up IP/geolocation info via ipinfo.io (Lite when `ipinfo_api_key` configured)
with fallback to ip-api.in.
Returns a normalized dict with keys: `ip`, `country` (lowercase ISO2),
`country_code` (uppercase ISO2), `region`, `city`, `org`, `asn`, `as_name`,
`continent_code`, and `_provider`. Returns None if every provider fails.
Live lookups return a dict with `ip`, `country` (lowercase ISO2), `country_code`
(uppercase ISO2), `region`, `city`, `org`, `asn`, `as_name`, `continent_code` and
`_provider`. Cached lookups return only `country`/`country_code` (see GEO_CACHE_KEYS).
Returns None if every provider fails.
Args:
session: Optional requests session. If a proxied session is passed, the
@@ -175,36 +200,29 @@ def get_ip_info(
cached: When True, read/write a 24h Cacher-backed entry. Use only for
local IP lookups — never with a proxied session.
"""
log = logging.getLogger("ip_info")
cache = None
if cached:
purge_stale_cache()
cache = Cacher("global").get(CACHE_KEY)
if cache and not cache.expired and cache.data:
return cache.data
else:
cache = None
state_cache = Cacher("global").get(PROVIDER_STATE_KEY)
state: dict[str, Any] = (
state_cache.data if state_cache and not state_cache.expired and isinstance(state_cache.data, dict) else {}
)
providers = _build_providers()
state = load_provider_state(state_cache)
now = time.time()
def _cooldown_key(item: tuple[str, Fetcher]) -> int:
info = state.get(item[0]) or {}
return 1 if (now - info.get("rate_limited_at", 0)) < RATE_LIMIT_COOLDOWN else 0
def on_cooldown(item: tuple[str, Fetcher]) -> int:
rate_limited_at = (state.get(item[0]) or {}).get("rate_limited_at", 0)
return 1 if (now - rate_limited_at) < RATE_LIMIT_COOLDOWN else 0
providers.sort(key=_cooldown_key)
sess = session or requests.Session()
providers = sorted(build_providers(), key=on_cooldown)
sess = lookup_session(session)
for name, fetcher in providers:
log.debug(f"Trying IP provider: {name}")
try:
normalized = fetcher(sess)
except _RateLimited:
except RateLimited:
log.warning(f"Provider {name} returned 429 (rate limited), trying next provider")
entry = state.setdefault(name, {})
entry["rate_limited_at"] = now
@@ -225,8 +243,8 @@ def get_ip_info(
if name in state and state[name].pop("rate_limited_at", None) is not None:
state_cache.set(state, expiration=RATE_LIMIT_COOLDOWN)
if cached and cache is not None:
cache.set(normalized, expiration=CACHE_TTL)
if cache is not None:
cache.set({k: normalized.get(k, "") for k in GEO_CACHE_KEYS}, expiration=CACHE_TTL)
return normalized
+333 -186
View File
@@ -1,3 +1,5 @@
from __future__ import annotations
import base64
import hashlib
import json
@@ -5,239 +7,339 @@ import re
from collections.abc import Generator
from datetime import datetime
from http.cookiejar import CookieJar
from typing import Optional, Union
from typing import Any, Optional, Union
import click
from langcodes import Language
from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm
from unshackle.core.constants import AnyTrack
from unshackle.core.credential import Credential
from unshackle.core.manifests import DASH
# from unshackle.core.manifests import HLS
from unshackle.core.manifests import DASH # also: HLS, ISM - see get_tracks() alternates
from unshackle.core.search_result import SearchResult
from unshackle.core.service import Service
from unshackle.core.titles import Episode, Movie, Movies, Series, Title_T, Titles_T
from unshackle.core.tracks import Chapter, Subtitle, Tracks, Video
from unshackle.core.titles import Album, Episode, Movie, Movies, Series, Song, Title_T, Titles_T
from unshackle.core.tracks import Attachment, Chapter, Chapters, Subtitle, Tracks, Video
from unshackle.core.utilities import is_close_match
class EXAMPLE(Service):
"""
Service code for domain.com
Version: 1.0.0
\b
Reference service for domain.com - a deliberately exhaustive showcase of
EVERYTHING an unshackle service can touch. It is NOT meant to run against a
real API; it exists so a new service author can see one canonical example of
every framework feature in one place.
Authorization: Cookies
\b
Version: 2.0.0
Author: sp4rk.y
Authorization: Cookies + Credentials
Geofence: US, UK
Robustness:
Widevine:
L1: 2160p, HDR10, HDR10+, DV
L3: 1080p, SDR
PlayReady:
SL3000: 2160p
ClearKey: 1080p (DRM-free fallback)
Security: FHD@L3
\b
Tips:
- Input may be a full URL or a bare ID/slug:
https://domain.com/details/20914 -> 20914
- -m / --movie forces movie parsing when the API type is ambiguous.
- -d / --device selects a client profile block from config.yaml.
Use full URL (for example - https://domain.com/details/20914) or title ID (for example - 20914).
\b
Feature map (where to look):
__init__ TrackRequest read/override, CDM-aware codec gating
authenticate cookies AND credentials, JWT decode, token cache+refresh
search SearchResult generator
get_titles Movies / Series / Album (music) + data passthrough
get_tracks DASH variant fan-out (default) + HLS/ISM alternates
_fetch_dash_manifest range override, HDR10+ flip, DV-composite, Atmos,
descriptive audio, channel fixups, cover-art attachment,
VUI normalize, bitrate-window awareness
get_chapters Chapters() with named + unnamed markers
get_widevine_* service cert + license (per-segment PSSH via `track`)
get_playready_license PlayReady challenge POST
get_clearkey DRM-free / ClearKey fallback (commented alternate)
"""
TITLE_RE = r"^(?:https?://?domain\.com/details/)?(?P<title_id>[^/]+)"
# ALIASES: extra CLI tags that resolve to this service (e.g. `dl EX ...`).
ALIASES = ("EX", "DOMAIN")
# GEOFENCE: regions required; the framework warns/blocks if proxy region mismatches.
GEOFENCE = ("US", "UK")
NO_SUBTITLES = True
# TITLE_RE: named groups (?P<...>) parsed in get_titles(). Accepts URL or bare id.
TITLE_RE = r"^(?:https?://(?:www\.)?domain\.com/details/)?(?P<title_id>[^/?#]+)"
# NO_SUBTITLES: service-level idiom telling the pipeline subs are handled in-band.
NO_SUBTITLES = False
# Map our API's range strings <-> unshackle's Video.Range enum.
VIDEO_RANGE_MAP = {
"SDR": "sdr",
"HDR10": "hdr10",
"DV": "dolby_vision",
Video.Range.SDR: "sdr",
Video.Range.HLG: "hlg",
Video.Range.HDR10: "hdr10",
Video.Range.HDR10P: "hdr10plus",
Video.Range.DV: "dolby_vision",
}
@staticmethod
@click.command(name="EXAMPLE", short_help="https://domain.com")
@click.command(name="EXAMPLE", short_help="https://domain.com", help=__doc__)
@click.argument("title", type=str)
@click.option("-m", "--movie", is_flag=True, default=False, help="Specify if it's a movie")
@click.option("-d", "--device", type=str, default="android_tv", help="Select device from the config file")
@click.option("-m", "--movie", is_flag=True, default=False, help="Treat the title as a movie.")
@click.option(
"-d",
"--device",
type=click.Choice(["android_tv", "web", "ios"], case_sensitive=False),
default="android_tv",
help="Client profile block to use from config.yaml.",
)
@click.pass_context
def cli(ctx, **kwargs):
def cli(ctx: click.Context, **kwargs: Any) -> EXAMPLE:
return EXAMPLE(ctx, **kwargs)
def __init__(self, ctx, title, movie, device):
super().__init__(ctx)
def __init__(self, ctx: click.Context, title: str, movie: bool, device: str):
# Store CLI args BEFORE super().__init__ if the base needs them; here order
# doesn't matter, but storing first is the common convention.
self.title = title
self.movie = movie
self.device = device
# super().__init__ wires up self.config, self.log, self.session (rnet TLS),
# self.cache, self.title_cache, self.request_input, self.current_region,
# and builds self.track_request from the global `dl` flags.
super().__init__(ctx)
# The selected CDM (Widevine OR PlayReady). May be None for DRM-free runs.
self.cdm = ctx.obj.cdm
# self.track_request is set by Service.__init__() from CLI params
# Contains: codecs (list[Video.Codec]), ranges (list[Video.Range]), best_available (bool)
# `is_playready_cdm` / `is_widevine_cdm` (unshackle.core.cdm.detect) classify
# BOTH local CDMs (pyplayready / pywidevine) AND remote/wrapper CDMs by
# inspecting the object - never hand-roll `isinstance` checks in a service.
# Many services pick a device profile / manifest variant off this, because a
# PlayReady box and a Widevine box often need different stream endpoints.
self.is_playready = is_playready_cdm(self.cdm)
self.is_widevine = is_widevine_cdm(self.cdm)
# Override codec for HDR ranges (HDR requires HEVC)
# Swap the client profile to match the CDM - a PlayReady box and a Widevine
# box frequently register as different device types with the service.
if self.is_playready:
self.device = "playready_tv"
self.log.info(" + PlayReady CDM detected - using PlayReady device profile")
elif self.is_widevine:
self.log.info(" + Widevine CDM detected")
# `dl` global flags live on the parent context. Profile picks cookie/cred set.
self.profile = (ctx.parent.params.get("profile") if ctx.parent else None) or "default"
# self.track_request.codecs : list[Video.Codec] (empty == accept any)
# self.track_request.ranges : list[Video.Range] (defaults to [SDR])
#
# Services may REWRITE the request before tracks are fetched. Two common rules:
# 1) HDR/DV needs HEVC on this service - force it.
if any(r != Video.Range.SDR for r in self.track_request.ranges):
self.track_request.codecs = [Video.Codec.HEVC]
# Override for L3 CDM limitations
if self.cdm and self.cdm.security_level == 3:
# 2) CDM-aware gating. A Widevine L3 box can't pull UHD/HDR here, so clamp it.
# (security_level is a Widevine concept; PlayReady exposes SL via its own API.)
if self.is_widevine and getattr(self.cdm, "security_level", None) == 3:
self.log.warning(" ! L3 CDM detected - clamping to AVC/SDR")
self.track_request.codecs = [Video.Codec.AVC]
self.track_request.ranges = [Video.Range.SDR]
if self.config is None:
raise Exception("Config is missing!")
profile_name = ctx.parent.params.get("profile")
self.profile = profile_name or "default"
raise EnvironmentError("config.yaml is missing for this service.")
def authenticate(self, cookies: Optional[CookieJar] = None, credential: Optional[Credential] = None) -> None:
# Loads the cookie jar into self.session and stores self.credential.
super().authenticate(cookies, credential)
if not cookies:
raise EnvironmentError("Service requires Cookies for Authentication.")
jwt_token = next((cookie.value for cookie in cookies if cookie.name == "streamco_token"), None)
payload = json.loads(base64.urlsafe_b64decode(jwt_token.split(".")[1] + "==").decode("utf-8"))
profile_id = payload.get("profileId", None)
# Per-device UA from config. Never hardcode UAs in code.
self.session.headers.update({"user-agent": self.config["client"][self.device]["user_agent"]})
# Token cache keyed by device + profile so multiple profiles don't collide.
cache = self.cache.get(f"tokens_{self.device}_{self.profile}")
if cache:
if cache.data["expires_in"] > int(datetime.now().timestamp()):
self.log.info("Using cached tokens")
else:
self.log.info("Refreshing tokens")
refresh = self.session.post(
url=self.config["endpoints"]["refresh"], data={"refresh_token": cache.data["refresh_data"]}
).json()
cache.set(data=refresh)
else:
self.log.info("Retrieving new tokens")
token = self.session.post(
url=self.config["endpoints"]["login"],
data={
"token": jwt_token,
"profileId": profile_id,
},
if cache and cache.data.get("expires_in", 0) > int(datetime.now().timestamp()):
self.log.info(" + Using cached tokens")
elif cache and cache.data.get("refresh_token"):
self.log.info(" + Refreshing tokens")
refresh = self.session.post(
url=self.config["endpoints"]["refresh"],
data={"refresh_token": cache.data["refresh_token"]},
).json()
cache.set(data=refresh, expiration=refresh.get("expires_in"))
else:
# Two interchangeable auth paths shown: a cookie-borne JWT, or email/pass.
if cookies:
jwt_token = next((c.value for c in cookies if c.name == "streamco_token"), None)
if not jwt_token:
raise EnvironmentError("Cookie 'streamco_token' not found in jar.")
payload = json.loads(base64.urlsafe_b64decode(jwt_token.split(".")[1] + "==").decode())
body = {"token": jwt_token, "profileId": payload.get("profileId")}
elif credential:
# `request_input` works locally AND over `serve` (InputBridge relays it).
otp = self.request_input("Enter the OTP sent to your device: ")
body = {"username": credential.username, "password": credential.password, "otp": otp}
else:
raise EnvironmentError("Service requires either Cookies or Credentials.")
cache.set(data=token)
token = self.session.post(url=self.config["endpoints"]["login"], data=body).json()
cache.set(data=token, expiration=token.get("expires_in"))
self.token = cache.data["token"]
self.user_id = cache.data["userId"]
self.user_id = cache.data.get("userId")
def search(self) -> Generator[SearchResult, None, None]:
search = self.session.get(
url=self.config["endpoints"]["search"], params={"q": self.title, "token": self.token}
results = self.session.get(
url=self.config["endpoints"]["search"],
params={"q": self.title, "token": self.token},
).json()
for result in search["entries"]:
for result in results["entries"]:
yield SearchResult(
id_=result["id"],
title=result["title"],
label="SERIES" if result["programType"] == "series" else "MOVIE",
url=result["url"],
description=result.get("description"),
label="SERIES" if result["programType"] == "series" else result["programType"].upper(),
url=result.get("url"),
)
def get_titles(self) -> Titles_T:
self.title = re.match(self.TITLE_RE, self.title).group(1)
match = re.match(self.TITLE_RE, self.title)
if not match:
raise ValueError("Could not parse a title ID - is the URL/ID correct?")
title_id = match.group("title_id")
metadata = self.session.get(
url=self.config["endpoints"]["metadata"].format(title_id=self.title), params={"token": self.token}
url=self.config["endpoints"]["metadata"].format(title_id=title_id),
params={"token": self.token},
).json()
if metadata["programType"] == "movie":
self.movie = True
program_type = metadata.get("programType")
# Resolve the title's ORIGINAL recorded language from API metadata. Stored on
# every Title as `language` and later handed to `to_tracks(language=...)`, which
# is the single source of truth the manifest parsers use to flag is_original_lang.
# This drives `-l best/all` original-audio selection and the filename language token.
original_lang = Language.find(metadata["languages"][0])
if self.movie:
# MUSIC - Album of Song titles. Showcases the music branch of the title system.
if program_type == "album":
return Album(
[
Song(
id_=tr["id"],
service=self.__class__,
name=tr["title"],
artist=metadata["artist"],
album=metadata["title"],
track=tr["trackNumber"],
disc=tr.get("discNumber", 1),
year=metadata["releaseYear"],
language=original_lang,
data=tr,
)
for tr in metadata["tracks"]
]
)
# MOVIE
if self.movie or program_type == "movie":
return Movies(
[
Movie(
id_=metadata["id"],
service=self.__class__,
name=metadata["title"],
description=metadata["description"],
year=metadata["releaseYear"] if metadata["releaseYear"] > 0 else None,
language=Language.find(metadata["languages"][0]),
data=metadata,
description=metadata.get("description"),
year=metadata["releaseYear"] if metadata.get("releaseYear", 0) > 0 else None,
# `language` should be the ORIGINAL audio language - drives the
# filename metadata token, not the user's preferred -l language.
language=original_lang,
data=metadata, # passthrough - read later as title.data
)
]
)
else:
episodes = []
for season in metadata["seasons"]:
if "Trailers" not in season["title"]:
season_data = self.session.get(url=season["url"], params={"token": self.token}).json()
for episode in season_data["entries"]:
episodes.append(
Episode(
id_=episode["id"],
service=self.__class__,
title=metadata["title"],
season=episode["season"],
number=episode["episode"],
name=episode["title"],
description=episode["description"],
year=metadata["releaseYear"] if metadata["releaseYear"] > 0 else None,
language=Language.find(metadata["languages"][0]),
data=episode,
)
)
return Series(episodes)
# DASH Example: Service requires separate API calls per codec/range.
# Uses _get_tracks_for_variants() which iterates codecs x ranges,
# handles HYBRID (HDR10+DV), and best_available fallback.
# SERIES - flatten seasons into Episodes (skip trailer "seasons").
episodes = []
for season in metadata["seasons"]:
if "Trailers" in season["title"]:
continue
season_data = self.session.get(url=season["url"], params={"token": self.token}).json()
for ep in season_data["entries"]:
episodes.append(
Episode(
id_=ep["id"],
service=self.__class__,
title=metadata["title"],
season=ep["season"],
number=ep["episode"],
name=ep.get("title"),
description=ep.get("description"),
year=metadata["releaseYear"] if metadata.get("releaseYear", 0) > 0 else None,
language=original_lang,
data=ep,
)
)
return Series(episodes)
# DEFAULT (shown live): this service needs a SEPARATE manifest per codec/range,
# so we fan out with the base helper `_get_tracks_for_variants`. It walks every
# codec x range in the TrackRequest, handles HYBRID (HDR10 + DV merge), and -
# when --best-available is set - skips combos the service can't deliver.
def get_tracks(self, title: Title_T) -> Tracks:
def _fetch_variant(
title: Title_T,
codec: Optional[Video.Codec],
range_: Video.Range,
) -> Tracks:
def _fetch_variant(title: Title_T, codec: Optional[Video.Codec], range_: Video.Range) -> Tracks:
vcodec_str = "H265" if codec == Video.Codec.HEVC else "H264"
range_str = range_.name
video_format = self.VIDEO_RANGE_MAP.get(range_str, "sdr")
self.log.info(f" + Fetching {vcodec_str} {range_str} manifest")
tracks = self._fetch_dash_manifest(title, vcodec=vcodec_str, video_format=video_format)
expected_range = {
"HDR10": Video.Range.HDR10,
"DV": Video.Range.DV,
}.get(range_str)
if expected_range and not any(v.range == expected_range for v in tracks.videos):
raise ValueError(f"{range_str} requested but no {range_str} tracks available")
self.log.info(f" + Fetching {vcodec_str} {range_.name} manifest")
tracks = self._fetch_dash_manifest(title, vcodec=vcodec_str, range_=range_)
# Guard: if we asked for HDR/DV but the manifest came back SDR-only, raise
# so the helper can fall back (best-available) or fail loudly otherwise.
if range_ in (Video.Range.HDR10, Video.Range.HDR10P, Video.Range.DV):
if not any(v.range == range_ for v in tracks.videos):
raise ValueError(f"{range_.name} requested but unavailable")
return tracks
return self._get_tracks_for_variants(title, _fetch_variant)
# HLS Example: Service returns all codecs/ranges in one master playlist.
# No need for _get_tracks_for_variants, dl.py filters by user selection.
# ── ALTERNATE A - HLS (one master playlist returns every codec/range) ───────
# When a service exposes a single master playlist, you do NOT need the variant
# fan-out; dl.py filters by the user's selection. Just parse and return:
#
# def get_tracks(self, title: Title_T) -> Tracks:
# playback = self.session.get(
# url=self.config["endpoints"]["playback"].format(title_id=title.id),
# params={"token": self.token},
# ).json()
# return HLS.from_url(
# url=playback["manifest_url"],
# session=self.session,
# ).to_tracks(title.language)
# def get_tracks(self, title: Title_T) -> Tracks:
# playback = self.session.get(
# url=self.config["endpoints"]["playback"].format(title_id=title.id),
# params={"token": self.token},
# ).json()
# return HLS.from_url(url=playback["manifest_url"], session=self.session) \
# .to_tracks(language=title.language)
#
# ── ALTERNATE B - ISM (Microsoft Smooth Streaming) ──────────────────────────
# from unshackle.core.manifests import ISM
# return ISM.from_url(url=ism_url, session=self.session).to_tracks(title.language)
def _fetch_dash_manifest(
self,
title: Title_T,
vcodec: str = "H264",
video_format: str = "sdr",
self, title: Title_T, vcodec: str = "H264", range_: Video.Range = Video.Range.SDR
) -> Tracks:
video_format = self.VIDEO_RANGE_MAP.get(range_, "sdr")
streams = self.session.post(
url=self.config["endpoints"]["streams"],
params={
"token": self.token,
"guid": title.id,
},
params={"token": self.token, "guid": title.id},
data={
"type": self.config["client"][self.device]["type"],
"video_format": video_format,
"video_codec": vcodec,
# Ask the API for the protection system our CDM actually speaks.
"drm": "playready" if self.is_playready else "widevine",
},
).json()["media"]
# Stash DRM bits for the license callbacks (per-title, set just-in-time).
self.license_data = {
"url": streams["drm"]["url"],
"data": streams["drm"]["data"],
@@ -246,64 +348,107 @@ class EXAMPLE(Service):
manifest_url = streams["url"].split("?")[0]
self.log.debug(f"Manifest URL: {manifest_url}")
# DASH parser auto-extracts PSSH, segment timelines, SIDX, multi-period dedup.
# Passing `language=title.language` (the ORIGINAL recorded language resolved in
# get_titles) is what lets the parser flag is_original_lang on each track: for
# every track it runs is_close_match(track_language, [title.language]) and sets
# the flag. It also backfills that language onto any track the manifest leaves
# unlabelled. HLS/ISM accept the same `language=` arg identically.
tracks = DASH.from_url(url=manifest_url, session=self.session).to_tracks(language=title.language)
range_enum = {
"hdr10": Video.Range.HDR10,
"dolby_vision": Video.Range.DV,
}.get(video_format, Video.Range.SDR)
for video in tracks.videos:
video.range = range_enum
# The manifest can't always be trusted for range - stamp what we asked for.
video.range = range_
tracks.audio = [
track for track in tracks.audio if "clear" not in track.data["dash"]["representation"].get("id")
]
# HDR10+ is a BITSTREAM feature the manifest often labels as plain HDR10.
# If this service is known to ship HDR10+ SEI, flip it so mediainfo agrees.
if range_ == Video.Range.HDR10P:
video.range = Video.Range.HDR10P
for track in tracks.audio:
if track.channels == 6.0:
track.channels = 5.1
track_label = track.data["dash"]["adaptation_set"].get("label")
if track_label and "Audio Description" in track_label:
track.descriptive = True
# DV-composite: a stream carrying DV RPU NALs inside a container that only
# signals HEVC. Setting this flag makes DVFixup round-trip the bitstream
# through dovi_tool so the muxed MKV is recognised as Dolby Vision.
if range_ == Video.Range.DV and vcodec == "H265":
video.dv_compatible_bitstream = True
# normalize_vui() runs automatically post-repackage on HDR tracks to rewrite
# stale BT.709 SPS colour primaries; nothing to call here, just be aware.
# Drop "clear"/unencrypted decoy renditions the API sometimes returns.
tracks.audio = [a for a in tracks.audio if "clear" not in (a.data["dash"]["representation"].get("id") or "")]
for audio in tracks.audio:
# Normalize odd channel counts (6.0 -> 5.1) for correct filename tokens.
if audio.channels == 6.0:
audio.channels = 5.1
# Mark descriptive / audio-description tracks from the AdaptationSet label.
label = audio.data["dash"]["adaptation_set"].get("label") or ""
if "Audio Description" in label or "description" in label.lower():
audio.descriptive = True
# Atmos: the framework detects JOC for filename/-l selection; if the API
# tells us explicitly we can set it eagerly.
if audio.data.get("isAtmos"):
audio.joc = 16
# is_original_lang was set by to_tracks (via the language= arg). Use it to
# label the original audio so it reads "Original" in selection/output.
if audio.is_original_lang:
audio.name = "Original"
# Subtitles built by hand (not via to_tracks) skip the parser's is_original_lang
# pass, so determine it ourselves with the same helper the parser uses.
tracks.subtitles.clear()
if streams.get("captions"):
for subtitle in streams["captions"]:
tracks.add(
Subtitle(
id_=hashlib.md5(subtitle["url"].encode()).hexdigest()[0:6],
url=subtitle["url"],
codec=Subtitle.Codec.from_mime("vtt"),
language=Language.get(subtitle["language"]),
sdh=True,
)
for sub in streams.get("captions", []):
sub_lang = Language.get(sub["language"])
tracks.add(
Subtitle(
id_=hashlib.md5(sub["url"].encode()).hexdigest()[0:6],
url=sub["url"],
codec=Subtitle.Codec.from_mime("vtt"),
language=sub_lang,
is_original_lang=is_close_match(sub_lang, [title.language]),
sdh=sub.get("sdh", False),
forced=sub.get("forced", False),
)
)
if cover := title.data.get("coverUrl"):
tracks.add(
Attachment(
url=cover,
name="cover",
description="Cover art",
session=self.session,
)
)
# Cache chapter data now so get_chapters() needs no extra request.
if not self.movie:
title.data["chapters"] = self.session.get(
url=self.config["endpoints"]["metadata"].format(title_id=title.id),
params={"token": self.token},
).json()["chapters"]
title.data["chapters"] = (
self.session.get(
url=self.config["endpoints"]["metadata"].format(title_id=title.id),
params={"token": self.token},
)
.json()
.get("chapters", [])
)
return tracks
def get_chapters(self, title: Title_T) -> list[Chapter]:
chapters = []
if title.data.get("chapters", []):
for chapter in title.data["chapters"]:
if chapter["name"] == "Intro":
chapters.append(Chapter(timestamp=chapter["start"], name="Opening"))
chapters.append(Chapter(timestamp=chapter["end"]))
if chapter["name"] == "Credits":
chapters.append(Chapter(timestamp=chapter["start"], name="Credits"))
def get_chapters(self, title: Title_T) -> Chapters:
chapters = Chapters()
for chapter in title.data.get("chapters", []):
if chapter["name"] == "Intro":
chapters.add(Chapter(timestamp=chapter["start"], name="Opening"))
chapters.add(Chapter(timestamp=chapter["end"])) # unnamed marker = chapter break
elif chapter["name"] == "Credits":
chapters.add(Chapter(timestamp=chapter["start"], name="Credits"))
return chapters
def get_widevine_service_certificate(self, **_: any) -> str:
def get_widevine_service_certificate(self, **_: Any) -> Optional[str]:
# Returning the service cert enables privacy-mode license requests.
return self.config.get("certificate")
def get_widevine_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> Optional[Union[bytes, str]]:
# `track` is passed so you can use its per-segment PSSH if the service rotates keys.
license_url = self.license_data.get("url") or self.config["endpoints"].get("widevine_license")
if not license_url:
raise ValueError("Widevine license endpoint not configured")
@@ -311,32 +456,34 @@ class EXAMPLE(Service):
response = self.session.post(
url=license_url,
data=challenge,
params={
"session": self.license_data.get("session"),
"userId": self.user_id,
},
params={"session": self.license_data.get("session"), "userId": self.user_id},
headers={
"dt-custom-data": self.license_data.get("data"),
"user-agent": self.config["client"][self.device]["license_user_agent"],
},
)
response.raise_for_status()
# Services return the license either as raw bytes or wrapped in JSON.
try:
return response.json().get("license")
except ValueError:
return response.json()["license"]
except (ValueError, KeyError):
return response.content
def get_playready_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> Optional[Union[bytes, str]]:
def get_playready_license(
self, *, challenge: bytes, title: Title_T, track: AnyTrack
) -> Optional[Union[bytes, str]]:
license_url = self.config["endpoints"].get("playready_license")
if not license_url:
raise ValueError("PlayReady license endpoint not configured")
response = self.session.post(
url=license_url,
data=challenge,
headers={
"user-agent": self.config["client"][self.device]["license_user_agent"],
},
headers={"user-agent": self.config["client"][self.device]["license_user_agent"]},
)
response.raise_for_status()
return response.content
# For ClearKey or unencrypted content there is no license callback; instead the
# KID:KEY pair comes from the manifest or a side endpoint and is attached to the
# track's DRM directly. Vaults (`self.cache` is separate) cache KID:KEY so repeat
# downloads skip the license round-trip entirely.
+29 -2
View File
@@ -1,12 +1,39 @@
# Reference config for the EXAMPLE showcase service.
# Access in code as self.config["endpoints"]["..."] — never hardcode URLs.
endpoints:
login: https://api.domain.com/v1/login
refresh: https://api.domain.com/v1/token/refresh
search: https://api.domain.com/v1/search
metadata: https://api.domain.com/v1/metadata/{title_id}.json
streams: https://api.domain.com/v1/streams
playready_license: https://api.domain.com/v1/license/playready
playback: https://api.domain.com/v1/playback/{title_id} # HLS alternate
widevine_license: https://api.domain.com/v1/license/widevine
playready_license: https://api.domain.com/v1/license/playready
# Base64 Widevine service certificate (enables privacy-mode license requests).
certificate: null
# Per-device client profiles, selected via -d/--device (click.Choice in cli()).
client:
android_tv:
user_agent: USER_AGENT
license_user_agent: LICENSE_USER_AGENT
type: DATA
type: DASH
web:
user_agent: USER_AGENT
license_user_agent: LICENSE_USER_AGENT
type: DASH
# Auto-selected when a PlayReady CDM is detected (see __init__ is_playready_cdm).
playready_tv:
user_agent: USER_AGENT
license_user_agent: LICENSE_USER_AGENT
type: DASH
ios:
user_agent: USER_AGENT
license_user_agent: LICENSE_USER_AGENT
type: HLS
# Optional: title_map remaps API titles to canonical filename titles (per-service, #106).
# title_map:
# "Show (US)": "Show"
+14 -47
View File
@@ -395,29 +395,13 @@ key_vaults:
# no_push: false # Default behavior - vault both provides and receives keys
# Choose what software to use to download data
downloader: aria2c
# Options: requests | aria2c | curl_impersonate | n_m3u8dl_re
# Can also be a mapping:
# downloader:
# NF: requests
# AMZN: n_m3u8dl_re
# DSNP: n_m3u8dl_re
# default: requests
downloader: requests
# Options: requests
# Downloading now uses the unified in-process requests/rnet downloader; the legacy
# aria2c, curl_impersonate, and n_m3u8dl_re backends have been removed.
# aria2c downloader configuration
aria2c:
max_concurrent_downloads: 4
max_connection_per_server: 3
split: 5
file_allocation: falloc # none | prealloc | falloc | trunc
# N_m3u8DL-RE downloader configuration
n_m3u8dl_re:
thread_count: 16
ad_keyword: "advertisement"
use_proxy: true
# curl_impersonate downloader configuration
# rnet TLS impersonation preset (not a downloader). Selects the browser
# fingerprint the HTTP session impersonates.
curl_impersonate:
browser: chrome120
@@ -555,9 +539,8 @@ remote_services:
# Per-service overrides for remote services
# Override downloader, decryption tool, or CDM settings per service on the client
services:
# Example: Use n_m3u8dl_re for HLS services, mp4decrypt for specific services
# Example: Override the decryption tool for specific services
# EXAMPLE_SERVICE:
# downloader: n_m3u8dl_re # Override client downloader (requests, aria2c, n_m3u8dl_re, curl_impersonate)
# decryption: mp4decrypt # Override decryption tool (shaka, mp4decrypt)
# Example: Multiple servers
@@ -567,7 +550,6 @@ remote_services:
# server_cdm: true
# services:
# EXAMPLE:
# downloader: n_m3u8dl_re
# decryption: mp4decrypt
# eu-server:
# url: "https://eu.example.com:8786"
@@ -581,7 +563,7 @@ services:
# You can override ANY global configuration option on a per-service basis
# This allows fine-tuned control for services with special requirements
# Supported overrides: dl, aria2c, n_m3u8dl_re, curl_impersonate, subtitle, muxing, headers, etc.
# Supported overrides: dl, curl_impersonate, subtitle, muxing, headers, etc.
# Example: Comprehensive service configuration showing all features
EXAMPLE:
@@ -627,20 +609,6 @@ services:
lang: ["en", "es-419"] # Different language priority for this service
sub_format: srt # Force SRT subtitle format
# Override n_m3u8dl_re downloader settings
n_m3u8dl_re:
thread_count: 8 # Lower thread count for rate-limited service (global default: 16)
use_proxy: true # Force proxy usage for this service
retry_count: 10 # More retries for unstable connections
ad_keyword: "advertisement" # Service-specific ad filtering
# Override aria2c downloader settings
aria2c:
max_concurrent_downloads: 2 # Limit concurrent downloads (global default: 4)
max_connection_per_server: 1 # Single connection per server
split: 3 # Fewer splits (global default: 5)
file_allocation: none # Faster allocation for this service
# Override subtitle processing for this service
subtitle:
conversion_method: pycaption # Use specific subtitle converter
@@ -655,6 +623,11 @@ services:
muxing:
set_title: true
# Remap service-provided titles before naming/output
# Keyed by the exact title the service returns -> desired output title.
title_map:
Service Title: Desired Title
# Example: Service with different regions per profile
SERVICE_NAME:
profiles:
@@ -670,18 +643,12 @@ services:
dl:
downloads: 2 # Limit concurrent downloads
workers: 4 # Reduce workers to avoid rate limits
n_m3u8dl_re:
thread_count: 4 # Very low thread count
retry_count: 20 # More retries for flaky service
aria2c:
max_concurrent_downloads: 1 # Download tracks one at a time
max_connection_per_server: 1 # Single connection only
# Notes on service-specific overrides:
# - Overrides are merged with global config, not replaced
# - Only specified keys are overridden, others use global defaults
# - Reserved keys (profiles, api_key, certificate, etc.) are NOT treated as overrides
# - Any dict-type config option can be overridden (dl, aria2c, n_m3u8dl_re, subtitle, etc.)
# - Any dict-type config option can be overridden (dl, subtitle, muxing, headers, etc.)
# - CLI arguments always take priority over service-specific config
# External proxy provider services
Generated
+1 -1
View File
@@ -1748,7 +1748,7 @@ wheels = [
[[package]]
name = "unshackle"
version = "5.0.0"
version = "5.1.0"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },