mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-28 11:55:07 +00:00
Compare commits
19
Commits
b0ae88812c
..
5.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3dcc584b2f | ||
|
|
538deac63e | ||
|
|
0561623825 | ||
|
|
4ce0dd5bb9 | ||
|
|
191c4f47e0 | ||
|
|
accfe9cee1 | ||
|
|
5899c1eec8 | ||
|
|
6bc601db39 | ||
|
|
fb8dc0bd9d | ||
|
|
40104be738 | ||
|
|
96fd971af0 | ||
|
|
1cb0e4b766 | ||
|
|
f4544b4a70 | ||
|
|
f1febe7e43 | ||
|
|
b3a6db915b | ||
|
|
5e3ffdeaa1 | ||
|
|
7017bd0460 | ||
|
|
13f924f825 | ||
|
|
7654e91ebc |
@@ -226,6 +226,7 @@ cython_debug/
|
||||
.github/copilot-instructions.md
|
||||
CLAUDE.md
|
||||
AGENTS.md
|
||||
graphify-out/
|
||||
|
||||
# CodeQL local analysis
|
||||
.codeql-db/
|
||||
|
||||
+80
-18
@@ -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
|
||||
|
||||
@@ -8,102 +8,45 @@
|
||||
</a>
|
||||
</p>
|
||||
|
||||
## What is unshackle?
|
||||
<p align="center">
|
||||
<a href="#install">Install</a> ·
|
||||
<a href="https://github.com/unshackle-dl/unshackle/wiki">Wiki</a> ·
|
||||
<a href="docs/">Docs</a> ·
|
||||
<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.
|
||||
|
||||
@@ -86,6 +86,8 @@ to a CLI option on the `dl` command. CLI arguments always take priority over con
|
||||
| `abitrate` | int | highest | Audio bitrate in kbps |
|
||||
| `vbitrate_range` | str | none | Video bitrate window in kbps, format `MIN-MAX` (e.g., `6000-7000`) |
|
||||
| `abitrate_range` | str | none | Audio bitrate window in kbps, format `MIN-MAX` |
|
||||
| `real_video_bitrate` | bool | `false` | Probe actual media size to compute true video bitrates, overriding the manifest's declared value (`-rvb`). See [Real bitrate probing](#real-bitrate-probing) |
|
||||
| `real_audio_bitrate` | bool | `false` | Same as above for audio tracks (`-rab`). Slower than video (more renditions) |
|
||||
| `range_` | str or list | `SDR` | Color range(s): `SDR`, `HDR10`, `HDR10+`, `HLG`, `DV`, `HYBRID` |
|
||||
| `channels` | float | any | Audio channels (e.g., `5.1`, `7.1`) |
|
||||
| `worst` | bool | `false` | Select the lowest bitrate track within the specified quality. Requires `quality` |
|
||||
@@ -152,6 +154,38 @@ to a CLI option on the `dl` command. CLI arguments always take priority over con
|
||||
| `skip_dl` | bool | `false` | Skip download, only get decryption keys |
|
||||
| `cdm_only` | bool | `null` | Only use CDM (`true`) or only vaults (`false`) |
|
||||
|
||||
### Real bitrate probing
|
||||
|
||||
Some services declare inaccurate `bandwidth`/`BANDWIDTH` in their manifests — often
|
||||
a peak or nominal figure that is far from the real average. Because `track.bitrate`
|
||||
drives the track listing, sorting, and `--vbitrate` / `--vbitrate-range` selection,
|
||||
a wrong value picks the wrong track.
|
||||
|
||||
`-rvb` / `--real-video-bitrate` (and `-rab` / `--real-audio-bitrate` for audio)
|
||||
probe the actual media size and overwrite `track.bitrate` with the measured value
|
||||
(`bytes * 8 / duration`) before listing and selection. So `-rvb --list` shows the
|
||||
true numbers, and `-rvb --vbitrate-range 6000-7000` selects against them. Without
|
||||
the flag, behaviour is unchanged (the manifest value is used).
|
||||
|
||||
How it works:
|
||||
|
||||
- **Single-file tracks** (one whole file per rendition — e.g. DASH `SegmentBase`
|
||||
or services that collapse to a `BaseURL`) are measured **exactly**: the whole
|
||||
file size over the track duration.
|
||||
- **Multi-segment tracks** (most HLS) are a **sampled estimate** — a spread of
|
||||
segments is probed and extrapolated, typically within a few percent. Segment
|
||||
bytes include container overhead, so MPEG-TS HLS reads a few percent above the
|
||||
demuxed stream (this is the real *delivered* size).
|
||||
- Only the top renditions per quality tier are probed (video grouped by
|
||||
codec + range, audio by codec + channels + language), in parallel, then extended
|
||||
downward only as far as needed to keep ranking correct. This keeps the pass fast
|
||||
even when a service exposes dozens of renditions.
|
||||
- Tracks whose duration cannot be determined fall back to `ffprobe`; probe failures
|
||||
are non-fatal and leave the manifest bitrate in place.
|
||||
|
||||
Per-track before→after values are logged at debug level (run with `-d`); the
|
||||
corrected values always appear in the Available Tracks panel.
|
||||
|
||||
You can also set per-service `dl` overrides (see [Service Integration & Authentication Configuration](SERVICE_CONFIG.md)):
|
||||
|
||||
```yaml
|
||||
|
||||
+24
-1
@@ -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
@@ -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"
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.utilities import find_missing_langs
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"requested,available,expected",
|
||||
[
|
||||
(["en"], ["en"], []),
|
||||
(["en", "ja"], ["en", "ja", "fr"], []),
|
||||
(["en", "fil"], ["en"], ["fil"]),
|
||||
(["en", "ko", "ja"], ["en"], ["ko", "ja"]),
|
||||
(["fil"], ["en", "ja"], ["fil"]),
|
||||
(["fil", "ko"], ["en"], ["fil", "ko"]),
|
||||
(["es"], ["es-419"], []),
|
||||
(["es-419"], ["es"], []),
|
||||
(["en"], ["en-US"], []),
|
||||
(["all"], [], []),
|
||||
(["best"], [], []),
|
||||
(["orig"], [], []),
|
||||
(["all", "en"], ["en"], []),
|
||||
(["best", "fil"], ["en"], ["fil"]),
|
||||
([], ["en"], []),
|
||||
(["en"], [], ["en"]),
|
||||
(["en"], [None, "en"], []),
|
||||
(["en"], [None], ["en"]),
|
||||
(["zh"], ["zh-Hans"], []),
|
||||
(["zh-CN"], ["zh-Hans"], []),
|
||||
(["zh-Hans"], ["zh-CN"], []),
|
||||
(["zh-TW"], ["zh-Hant"], []),
|
||||
(["zh-Hant"], ["zh-TW"], []),
|
||||
(["zh"], ["zh-Hant"], ["zh"]),
|
||||
(["zh-Hans"], ["zh-Hant"], ["zh-Hans"]),
|
||||
(["zh-CN"], ["zh-TW"], ["zh-CN"]),
|
||||
(["zh-HK"], ["zh-Hant"], []),
|
||||
(["zh"], ["cmn"], []),
|
||||
(["cmn"], ["zh"], []),
|
||||
(["zh"], ["yue"], ["zh"]),
|
||||
(["yue"], ["zh-HK"], ["yue"]),
|
||||
(["fil"], ["tl"], []),
|
||||
(["tl"], ["fil"], []),
|
||||
(["fil"], ["tgl"], []),
|
||||
(["tgl"], ["fil"], []),
|
||||
(["fil"], ["fil-PH"], []),
|
||||
(["tl"], ["fil-PH"], []),
|
||||
],
|
||||
)
|
||||
def test_close_match(requested, available, expected):
|
||||
assert find_missing_langs(requested, available, exact=False) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"requested,available,expected",
|
||||
[
|
||||
(["es"], ["es-419"], ["es"]),
|
||||
(["es-419"], ["es"], ["es-419"]),
|
||||
(["en"], ["en-US"], []),
|
||||
(["en-US"], ["en"], []),
|
||||
(["en"], ["en-GB"], ["en"]),
|
||||
(["en-US"], ["en-GB"], ["en-US"]),
|
||||
(["en-US"], ["en-US"], []),
|
||||
(["en-US", "en-GB"], ["en-US"], ["en-GB"]),
|
||||
(["en"], ["en"], []),
|
||||
(["all", "es-419"], ["es"], ["es-419"]),
|
||||
(["zh"], ["zh-Hans"], []),
|
||||
(["zh-CN"], ["zh-Hans"], []),
|
||||
(["zh-TW"], ["zh-Hant"], []),
|
||||
(["zh"], ["cmn"], []),
|
||||
(["zh-HK"], ["zh-Hant"], ["zh-HK"]),
|
||||
(["zh-Hans"], ["zh-Hant"], ["zh-Hans"]),
|
||||
(["zh-CN"], ["zh-TW"], ["zh-CN"]),
|
||||
(["fil"], ["tl"], []),
|
||||
(["tl"], ["fil"], []),
|
||||
(["fil"], ["tgl"], []),
|
||||
(["fil"], ["fil-PH"], []),
|
||||
(["tl"], ["fil-PH"], []),
|
||||
],
|
||||
)
|
||||
def test_exact_match(requested, available, expected):
|
||||
assert find_missing_langs(requested, available, exact=True) == expected
|
||||
|
||||
|
||||
def test_order_preserved():
|
||||
assert find_missing_langs(["ja", "ko", "fr"], ["en"], exact=False) == ["ja", "ko", "fr"]
|
||||
|
||||
|
||||
def test_duplicates_in_request():
|
||||
assert find_missing_langs(["fil", "fil", "en"], ["en"], exact=False) == ["fil", "fil"]
|
||||
|
||||
|
||||
def test_zh_catalogue_simplified_only_misses_traditional():
|
||||
assert find_missing_langs(["zh-Hant", "zh-TW"], ["en", "zh-Hans"], exact=False) == ["zh-Hant", "zh-TW"]
|
||||
|
||||
|
||||
def test_mixed_zh_fil_request():
|
||||
assert find_missing_langs(["en", "zh-Hans", "fil"], ["en", "tl"], exact=False) == ["zh-Hans"]
|
||||
|
||||
|
||||
def test_zh_cn_request_with_tw_catalogue():
|
||||
assert find_missing_langs(["zh-CN"], ["zh-TW"], exact=False) == ["zh-CN"]
|
||||
assert find_missing_langs(["zh-CN"], ["zh-TW"], exact=True) == ["zh-CN"]
|
||||
@@ -0,0 +1,78 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.utilities import is_close_match, is_exact_match
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"needle,haystack,expected",
|
||||
[
|
||||
("en", ["en"], True),
|
||||
("fr", ["en", "de"], False),
|
||||
("es", ["es-419"], True),
|
||||
("es", ["es-ES"], True),
|
||||
("es-419", ["es"], True),
|
||||
("en", ["en-US"], True),
|
||||
("en-US", ["en-GB"], True),
|
||||
("EN", ["en"], True),
|
||||
("en", ["EN"], True),
|
||||
("ja", ["ko"], False),
|
||||
("fil", ["en", "fr", "de"], False),
|
||||
("en", [], False),
|
||||
("en", [None, "en"], True),
|
||||
("en", [None], False),
|
||||
("zh", ["zh-Hans"], True),
|
||||
("zh-CN", ["zh-Hans"], True),
|
||||
("zh-Hans", ["zh-CN"], True),
|
||||
("zh-TW", ["zh-Hant"], True),
|
||||
("zh-Hant", ["zh-TW"], True),
|
||||
("zh", ["zh-Hant"], False),
|
||||
("zh-Hans", ["zh-Hant"], False),
|
||||
("zh-CN", ["zh-TW"], False),
|
||||
("zh-HK", ["zh-Hant"], True),
|
||||
("zh", ["cmn"], True),
|
||||
("cmn", ["zh"], True),
|
||||
("zh", ["yue"], False),
|
||||
("yue", ["zh-HK"], False),
|
||||
("fil", ["tl"], True),
|
||||
("tl", ["fil"], True),
|
||||
("fil", ["tgl"], True),
|
||||
("tgl", ["fil"], True),
|
||||
("fil", ["fil-PH"], True),
|
||||
("tl", ["fil-PH"], True),
|
||||
],
|
||||
)
|
||||
def test_is_close_match(needle, haystack, expected):
|
||||
assert is_close_match(needle, haystack) is expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"needle,haystack,expected",
|
||||
[
|
||||
("es", ["es-419"], False),
|
||||
("es-419", ["es"], False),
|
||||
("es-419", ["es-419"], True),
|
||||
("en-US", ["en-GB"], False),
|
||||
("en-US", ["en-US"], True),
|
||||
("en", ["en"], True),
|
||||
("EN", ["en"], True),
|
||||
("fr", ["de"], False),
|
||||
("fil", ["en"], False),
|
||||
("en", [], False),
|
||||
("zh", ["zh-Hans"], True),
|
||||
("zh-CN", ["zh-Hans"], True),
|
||||
("zh-TW", ["zh-Hant"], True),
|
||||
("zh", ["cmn"], True),
|
||||
("zh-HK", ["zh-Hant"], False),
|
||||
("zh-Hans", ["zh-Hant"], False),
|
||||
("zh-CN", ["zh-TW"], False),
|
||||
("fil", ["tl"], True),
|
||||
("tl", ["fil"], True),
|
||||
("fil", ["tgl"], True),
|
||||
("fil", ["fil-PH"], True),
|
||||
("tl", ["fil-PH"], True),
|
||||
],
|
||||
)
|
||||
def test_is_exact_match(needle, haystack, expected):
|
||||
assert is_exact_match(needle, haystack) is expected
|
||||
@@ -24,7 +24,6 @@ def _run(coro):
|
||||
|
||||
|
||||
def test_skips_when_client_does_not_accept_gzip() -> None:
|
||||
payload = b"x" * 4096
|
||||
body_json = json.dumps({"data": "x" * 4096}).encode()
|
||||
|
||||
async def handler(req): # noqa: ARG001
|
||||
|
||||
@@ -6,13 +6,8 @@ import json
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.api.errors import (
|
||||
APIError,
|
||||
APIErrorCode,
|
||||
build_error_response,
|
||||
categorize_exception,
|
||||
handle_api_exception,
|
||||
)
|
||||
from unshackle.core.api.errors import (APIError, APIErrorCode, build_error_response, categorize_exception,
|
||||
handle_api_exception)
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
@@ -5,16 +5,9 @@ from __future__ import annotations
|
||||
import pytest
|
||||
from langcodes import Language
|
||||
|
||||
from unshackle.core.api.handlers import (
|
||||
sanitize_log,
|
||||
serialize_audio_track,
|
||||
serialize_drm,
|
||||
serialize_subtitle_track,
|
||||
serialize_title,
|
||||
serialize_video_track,
|
||||
validate_download_parameters,
|
||||
validate_service,
|
||||
)
|
||||
from unshackle.core.api.handlers import (sanitize_log, serialize_audio_track, serialize_drm, serialize_subtitle_track,
|
||||
serialize_title, serialize_video_track, validate_download_parameters,
|
||||
validate_service)
|
||||
from unshackle.core.titles.episode import Episode
|
||||
from unshackle.core.titles.movie import Movie
|
||||
from unshackle.core.tracks import Audio, Subtitle, Video
|
||||
|
||||
@@ -6,16 +6,8 @@ from enum import Enum
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.remote_service import (
|
||||
_build_title,
|
||||
_build_tracks,
|
||||
_deserialize_audio,
|
||||
_deserialize_subtitle,
|
||||
_deserialize_video,
|
||||
_enum_get,
|
||||
_match_track,
|
||||
_reconstruct_drm,
|
||||
)
|
||||
from unshackle.core.remote_service import (_build_title, _build_tracks, _deserialize_audio, _deserialize_subtitle,
|
||||
_deserialize_video, _enum_get, _match_track, _reconstruct_drm)
|
||||
from unshackle.core.titles.episode import Episode
|
||||
from unshackle.core.titles.movie import Movie
|
||||
from unshackle.core.tracks import Audio, Subtitle, Video
|
||||
|
||||
@@ -105,7 +105,7 @@ async def test_get_session_store_returns_singleton() -> None:
|
||||
async def test_max_sessions_evicts_oldest(store: SessionStore, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(type(store), "_max_sessions", property(lambda _: 2))
|
||||
|
||||
a = await store.create("A", _FakeService(), session_id="a")
|
||||
await store.create("A", _FakeService(), session_id="a")
|
||||
await asyncio.sleep(0.01)
|
||||
b = await store.create("B", _FakeService(), session_id="b")
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
@@ -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)
|
||||
+220
-91
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import html
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
@@ -22,7 +23,6 @@ from typing import Any, Callable, Optional
|
||||
from uuid import UUID
|
||||
|
||||
import click
|
||||
import jsonpickle
|
||||
import yaml
|
||||
from langcodes import Language
|
||||
from pymediainfo import MediaInfo
|
||||
@@ -56,9 +56,11 @@ from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
|
||||
from unshackle.core.tracks.attachment import Attachment
|
||||
from unshackle.core.tracks.dv_fixup import apply_dv_fixup
|
||||
from unshackle.core.tracks.hybrid import Hybrid
|
||||
from unshackle.core.utilities import (find_font_with_fallbacks, get_debug_logger, get_system_fonts, init_debug_logger,
|
||||
is_close_match, suggest_font_packages, time_elapsed_since)
|
||||
from unshackle.core.utilities import (find_font_with_fallbacks, find_missing_langs, get_debug_logger,
|
||||
get_system_fonts, init_debug_logger, is_close_match, suggest_font_packages,
|
||||
time_elapsed_since)
|
||||
from unshackle.core.utils import tags
|
||||
from unshackle.core.utils.bitrate import apply_real_bitrates
|
||||
from unshackle.core.utils.click_types import (AUDIO_CODEC_LIST, LANGUAGE_RANGE, QUALITY_LIST, SEASON_RANGE,
|
||||
SLOW_DELAY_RANGE, ContextData, MultipleChoice, MultipleVideoCodecChoice,
|
||||
SubtitleCodecChoice)
|
||||
@@ -418,6 +420,22 @@ class dl:
|
||||
"--tag", type=str, default=None, help="Set the Group Tag to be used, overriding the one in config if any."
|
||||
)
|
||||
@click.option("--repack", is_flag=True, default=False, help="Add REPACK tag to the output filename.")
|
||||
@click.option(
|
||||
"-rvb",
|
||||
"--real-video-bitrate",
|
||||
is_flag=True,
|
||||
default=False,
|
||||
help="Probe actual media size to compute true video bitrates (top renditions per codec/range), "
|
||||
"overriding the manifest's declared bitrate.",
|
||||
)
|
||||
@click.option(
|
||||
"-rab",
|
||||
"--real-audio-bitrate",
|
||||
is_flag=True,
|
||||
default=False,
|
||||
help="Probe actual media size to compute true audio bitrates (top renditions per codec/channels/language), "
|
||||
"overriding the manifest's declared bitrate. Slower than --real-video-bitrate (more renditions).",
|
||||
)
|
||||
@click.option(
|
||||
"--tmdb",
|
||||
"tmdb_id",
|
||||
@@ -490,6 +508,14 @@ class dl:
|
||||
default=False,
|
||||
help="Export track info and decryption keys to a JSON file in the exports directory.",
|
||||
)
|
||||
@click.option(
|
||||
"--import",
|
||||
"import_file",
|
||||
type=str,
|
||||
default=None,
|
||||
hidden=True,
|
||||
help="Internal: path to an export JSON to reconstruct a download from (used by 'unshackle import').",
|
||||
)
|
||||
@click.option(
|
||||
"--cdm-only/--vaults-only",
|
||||
is_flag=True,
|
||||
@@ -625,6 +651,7 @@ class dl:
|
||||
)
|
||||
|
||||
self.profile = profile
|
||||
self.proxy_requested = bool(proxy)
|
||||
self.tmdb_id = tmdb_id
|
||||
self.imdb_id = imdb_id
|
||||
self.enrich = enrich
|
||||
@@ -691,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),
|
||||
@@ -717,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}
|
||||
@@ -1050,6 +1071,8 @@ class dl:
|
||||
worst: bool,
|
||||
best_available: bool,
|
||||
split_audio: Optional[bool] = None,
|
||||
real_video_bitrate: bool = False,
|
||||
real_audio_bitrate: bool = False,
|
||||
*_: Any,
|
||||
**__: Any,
|
||||
) -> None:
|
||||
@@ -1065,6 +1088,7 @@ class dl:
|
||||
if export:
|
||||
config.directories.exports.mkdir(parents=True, exist_ok=True)
|
||||
export_path = config.directories.exports / f"export_{self.service}_{int(time.time())}.json"
|
||||
self.export_service = service
|
||||
else:
|
||||
export_path = None
|
||||
|
||||
@@ -1540,6 +1564,24 @@ class dl:
|
||||
),
|
||||
)
|
||||
|
||||
if real_video_bitrate:
|
||||
with console.status("Probing real video bitrates...", spinner="dots"):
|
||||
apply_real_bitrates(
|
||||
title.tracks.videos,
|
||||
service.session,
|
||||
log=self.log,
|
||||
group_key=lambda t: (t.codec, t.range),
|
||||
)
|
||||
|
||||
if real_audio_bitrate:
|
||||
with console.status("Probing real audio bitrates...", spinner="dots"):
|
||||
apply_real_bitrates(
|
||||
title.tracks.audio,
|
||||
service.session,
|
||||
log=self.log,
|
||||
group_key=lambda t: (t.codec, t.channels, str(t.language), t.descriptive),
|
||||
)
|
||||
|
||||
with console.status("Sorting tracks by language and bitrate...", spinner="dots"):
|
||||
video_sort_lang = v_lang or lang
|
||||
processed_video_sort_lang = []
|
||||
@@ -1655,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
|
||||
@@ -1669,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:
|
||||
@@ -1723,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:
|
||||
@@ -1765,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:
|
||||
@@ -1872,19 +1925,34 @@ class dl:
|
||||
|
||||
match_func = is_exact_match if exact_lang else is_close_match
|
||||
|
||||
missing_langs = [
|
||||
lang_
|
||||
for lang_ in s_lang
|
||||
if not any(match_func(lang_, [sub.language]) for sub in title.tracks.subtitles)
|
||||
]
|
||||
missing_langs = find_missing_langs(
|
||||
s_lang,
|
||||
[sub.language for sub in title.tracks.subtitles],
|
||||
exact=exact_lang,
|
||||
)
|
||||
if missing_langs:
|
||||
self.log.error(", ".join(missing_langs) + " not found in tracks")
|
||||
sys.exit(1)
|
||||
missing_str = ", ".join(missing_langs)
|
||||
if best_available:
|
||||
remaining = [tok for tok in s_lang if tok not in missing_langs]
|
||||
if remaining:
|
||||
self.log.warning(
|
||||
f"{missing_str} not found in subtitle tracks, continuing with: {', '.join(remaining)}"
|
||||
)
|
||||
s_lang = remaining
|
||||
else:
|
||||
self.log.warning(
|
||||
f"{missing_str} not found in subtitle tracks, continuing without subtitles"
|
||||
)
|
||||
title.tracks.subtitles = []
|
||||
else:
|
||||
self.log.error(missing_str + " not found in tracks")
|
||||
sys.exit(1)
|
||||
|
||||
title.tracks.select_subtitles(lambda x: match_func(x.language, s_lang))
|
||||
if not title.tracks.subtitles:
|
||||
self.log.error(f"There's no {s_lang} Subtitle Track...")
|
||||
sys.exit(1)
|
||||
if s_lang and title.tracks.subtitles:
|
||||
title.tracks.select_subtitles(lambda x: match_func(x.language, s_lang))
|
||||
if not title.tracks.subtitles and not best_available:
|
||||
self.log.error(f"There's no {s_lang} Subtitle Track...")
|
||||
sys.exit(1)
|
||||
|
||||
if not forced_subs:
|
||||
title.tracks.select_subtitles(lambda x: not x.forced)
|
||||
@@ -1941,6 +2009,30 @@ class dl:
|
||||
if language not in processed_lang:
|
||||
processed_lang.append(language)
|
||||
|
||||
if not any(tok in processed_lang for tok in ("best", "all")):
|
||||
missing_a_langs = find_missing_langs(
|
||||
processed_lang,
|
||||
[a.language for a in title.tracks.audio],
|
||||
exact=exact_lang,
|
||||
)
|
||||
if missing_a_langs:
|
||||
missing_str = ", ".join(missing_a_langs)
|
||||
if best_available:
|
||||
remaining = [tok for tok in processed_lang if tok not in missing_a_langs]
|
||||
if remaining:
|
||||
self.log.warning(
|
||||
f"{missing_str} not found in audio tracks, continuing with: {', '.join(remaining)}"
|
||||
)
|
||||
processed_lang = remaining
|
||||
else:
|
||||
self.log.error(
|
||||
f"{missing_str} not found in audio tracks and no fallback available"
|
||||
)
|
||||
sys.exit(1)
|
||||
else:
|
||||
self.log.error(missing_str + " not found in audio tracks")
|
||||
sys.exit(1)
|
||||
|
||||
if "best" in processed_lang or "all" in processed_lang:
|
||||
unique_languages = {track.language for track in title.tracks.audio}
|
||||
selected_audio = []
|
||||
@@ -2386,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)
|
||||
@@ -2402,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
|
||||
@@ -2444,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):
|
||||
@@ -2669,52 +2767,83 @@ class dl:
|
||||
|
||||
console.print(Padding(f"Processed all titles in [progress.elapsed]{dl_time}", (0, 5, 1, 5)))
|
||||
|
||||
def _write_export(self, export: Path, title: Title_T, track: AnyTrack, drm: Any) -> None:
|
||||
"""Write decryption keys and track info to the export JSON file."""
|
||||
@staticmethod
|
||||
def title_to_meta(title: Title_T) -> dict[str, Any]:
|
||||
"""Capture the title fields needed to rebuild a Title for output naming on import."""
|
||||
from unshackle.core.titles import Episode, Movie
|
||||
|
||||
meta: dict[str, Any] = {
|
||||
"id": str(title.id),
|
||||
"language": str(title.language) if getattr(title, "language", None) else None,
|
||||
}
|
||||
if isinstance(title, Episode):
|
||||
meta.update(
|
||||
type="episode",
|
||||
series_title=title.title,
|
||||
season=title.season,
|
||||
number=title.number,
|
||||
name=title.name,
|
||||
year=title.year,
|
||||
)
|
||||
elif isinstance(title, Movie):
|
||||
meta.update(type="movie", name=title.name, year=title.year)
|
||||
else:
|
||||
meta.update(type="movie", name=str(title))
|
||||
return meta
|
||||
|
||||
def write_export(self, export: Path, title: Title_T, track: AnyTrack, drm: Any) -> None:
|
||||
"""Write a shareable v2 export usable by ``unshackle import``.
|
||||
|
||||
Carries no session/cookies/dl-flags. Region (country code) is stored only when the
|
||||
export used ``--proxy``, as an import geofence. Each track records only the licensed
|
||||
DRM system; content keys live once under the track's ``keys``.
|
||||
"""
|
||||
with self.EXPORT_LOCK:
|
||||
keys = {}
|
||||
doc: dict[str, Any] = {}
|
||||
if export.is_file():
|
||||
keys = jsonpickle.loads(export.read_text(encoding="utf8")) or {}
|
||||
if str(title) not in keys:
|
||||
keys[str(title)] = {}
|
||||
doc = json.loads(export.read_text(encoding="utf8")) or {}
|
||||
|
||||
title_data = keys[str(title)]
|
||||
doc.setdefault("version", 2)
|
||||
doc.setdefault("service", self.service)
|
||||
if "region" not in doc and getattr(self, "proxy_requested", False):
|
||||
region = getattr(getattr(self, "export_service", None), "current_region", None)
|
||||
if region:
|
||||
doc["region"] = region
|
||||
|
||||
if title.tracks.manifest_url and "manifest" not in title_data:
|
||||
title_data["manifest"] = title.tracks.manifest_url
|
||||
titles = doc.setdefault("titles", {})
|
||||
tinfo = titles.setdefault(str(title.id), {})
|
||||
tinfo.setdefault("meta", self.title_to_meta(title))
|
||||
|
||||
if isinstance(track, Video):
|
||||
section = "video"
|
||||
elif isinstance(track, Audio):
|
||||
section = "audio"
|
||||
else:
|
||||
section = "other"
|
||||
if title.tracks.manifest_url:
|
||||
tinfo.setdefault("manifest_url", title.tracks.manifest_url)
|
||||
|
||||
if section not in title_data:
|
||||
title_data[section] = {}
|
||||
if str(track) not in title_data[section]:
|
||||
title_data[section][str(track)] = {}
|
||||
all_tracks = [*title.tracks.videos, *title.tracks.audio, *title.tracks.subtitles]
|
||||
if "manifest_type" not in tinfo:
|
||||
tinfo["manifest_type"] = next(
|
||||
(t.descriptor.name for t in all_tracks if t.descriptor != Video.Descriptor.URL), None
|
||||
)
|
||||
|
||||
track_data = title_data[section][str(track)]
|
||||
track_data["url"] = track.url
|
||||
track_data["descriptor"] = track.descriptor.name
|
||||
tracks_map = tinfo.setdefault("tracks", {})
|
||||
if not tracks_map:
|
||||
for t in all_tracks:
|
||||
tracks_map[str(t.id)] = t.to_dict()
|
||||
|
||||
if "keys" not in track_data:
|
||||
track_data["keys"] = {}
|
||||
track_data = tracks_map.setdefault(str(track.id), track.to_dict())
|
||||
if hasattr(drm, "to_dict"):
|
||||
track_data["drm"] = [drm.to_dict()]
|
||||
keys = track_data.setdefault("keys", {})
|
||||
for kid, key in drm.content_keys.items():
|
||||
track_data["keys"][kid.hex] = key
|
||||
keys[kid.hex] = key
|
||||
|
||||
if "subtitles" not in title_data:
|
||||
subs = {}
|
||||
for sub in title.tracks.subtitles:
|
||||
subs[str(sub)] = {"url": sub.url}
|
||||
if subs:
|
||||
title_data["subtitles"] = subs
|
||||
if "chapters" not in tinfo:
|
||||
tinfo["chapters"] = [
|
||||
{"timestamp": chapter.timestamp, "name": chapter.name} for chapter in (title.tracks.chapters or [])
|
||||
]
|
||||
|
||||
section_order = ["manifest", "video", "audio", "subtitles", "other"]
|
||||
keys[str(title)] = {k: title_data[k] for k in section_order if k in title_data}
|
||||
if "attachments" not in tinfo:
|
||||
tinfo["attachments"] = [a.to_dict() for a in (title.tracks.attachments or []) if a.url]
|
||||
|
||||
export.write_text(jsonpickle.dumps(keys, indent=4), encoding="utf8")
|
||||
export.write_text(json.dumps(doc, indent=4, ensure_ascii=False), encoding="utf8")
|
||||
|
||||
def prepare_drm(
|
||||
self,
|
||||
@@ -2996,7 +3125,7 @@ class dl:
|
||||
table.add_row(cek_tree)
|
||||
|
||||
if export:
|
||||
self._write_export(export, title, track, drm)
|
||||
self.write_export(export, title, track, drm)
|
||||
|
||||
elif isinstance(drm, PlayReady):
|
||||
if self.debug_logger:
|
||||
@@ -3167,7 +3296,7 @@ class dl:
|
||||
table.add_row(cek_tree)
|
||||
|
||||
if export:
|
||||
self._write_export(export, title, track, drm)
|
||||
self.write_export(export, title, track, drm)
|
||||
|
||||
elif isinstance(drm, MonaLisa):
|
||||
with self.DRM_TABLE_LOCK:
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import click
|
||||
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.constants import context_settings
|
||||
|
||||
|
||||
class ImportCommand:
|
||||
@staticmethod
|
||||
@click.command(
|
||||
name="import",
|
||||
short_help="Reconstruct a download (download, decrypt, mux) from an --export JSON file.",
|
||||
context_settings={**context_settings, "ignore_unknown_options": True},
|
||||
)
|
||||
@click.argument("export_file", type=Path)
|
||||
@click.argument("dl_args", nargs=-1, type=click.UNPROCESSED)
|
||||
@click.pass_context
|
||||
def cli(ctx: click.Context, export_file: Path, dl_args: tuple[str, ...]) -> None:
|
||||
"""
|
||||
Reconstruct an exported download without re-contacting the service.
|
||||
|
||||
Re-fetches the manifest, injects the stored keys, then downloads/decrypts/muxes as a
|
||||
normal `dl` run. Any `dl` options after the file are forwarded verbatim:
|
||||
|
||||
unshackle import export.json -r HDR10 --proxy US
|
||||
"""
|
||||
if not export_file.is_file():
|
||||
raise click.ClickException(f"Export file not found: {export_file}")
|
||||
|
||||
try:
|
||||
data: dict[str, Any] = json.loads(export_file.read_text(encoding="utf8"))
|
||||
except json.JSONDecodeError as e:
|
||||
raise click.ClickException(f"Export file is not valid JSON: {e}")
|
||||
|
||||
if data.get("version") != 2:
|
||||
raise click.ClickException(
|
||||
f"Unsupported export version {data.get('version')!r}. "
|
||||
"Re-create the export with a current build of unshackle."
|
||||
)
|
||||
|
||||
service_tag = data.get("service")
|
||||
if not service_tag:
|
||||
raise click.ClickException("Export file is missing the 'service' tag.")
|
||||
|
||||
args = [*dl_args, "--import", str(export_file), service_tag]
|
||||
dl.cli.main(args=args, prog_name="unshackle dl", standalone_mode=False)
|
||||
|
||||
|
||||
globals()["import"] = ImportCommand
|
||||
@@ -1 +1 @@
|
||||
__version__ = "5.0.0"
|
||||
__version__ = "5.1.0"
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import click
|
||||
@@ -5,11 +7,56 @@ import click
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.utilities import import_module_by_path
|
||||
|
||||
log = logging.getLogger("commands")
|
||||
|
||||
_COMMANDS = sorted(
|
||||
(path for path in config.directories.commands.glob("*.py") if path.stem.lower() != "__init__"), key=lambda x: x.stem
|
||||
)
|
||||
|
||||
_MODULES = {path.stem: getattr(import_module_by_path(path), path.stem) for path in _COMMANDS}
|
||||
|
||||
def load_command(path: Path) -> object:
|
||||
"""Load one command module, returning its stem-named attribute.
|
||||
|
||||
Raises a concise, single-line error naming the command and the real cause so
|
||||
a broken command never surfaces as a raw traceback pointing at the loader.
|
||||
"""
|
||||
try:
|
||||
module = import_module_by_path(path)
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"{path.stem}: failed to import — {type(e).__name__}: {e} ({path})") from e
|
||||
try:
|
||||
return getattr(module, path.stem)
|
||||
except AttributeError as e:
|
||||
raise RuntimeError(
|
||||
f"{path.stem}: no object named '{path.stem}' found in {path} — it must match the filename"
|
||||
) from e
|
||||
|
||||
|
||||
def load_commands(paths: list[Path]) -> tuple[dict[str, object], list[str]]:
|
||||
"""Load every command, returning the good ones plus a list of load errors.
|
||||
|
||||
Importing this module must never raise (it runs at CLI startup, before Rich
|
||||
is installed, so a raise here prints an ugly pre-setup traceback). Instead we
|
||||
collect failures and surface them once, cleanly, when the CLI is used.
|
||||
"""
|
||||
modules: dict[str, object] = {}
|
||||
errors: list[str] = []
|
||||
for path in paths:
|
||||
try:
|
||||
modules[path.stem] = load_command(path)
|
||||
except Exception as e:
|
||||
errors.append(str(e))
|
||||
return modules, errors
|
||||
|
||||
|
||||
_MODULES, LOAD_ERRORS = load_commands(_COMMANDS)
|
||||
|
||||
|
||||
def check_load_errors() -> None:
|
||||
"""Raise a single clean error if any command failed to load."""
|
||||
if LOAD_ERRORS:
|
||||
joined = "\n".join(f" - {err}" for err in LOAD_ERRORS)
|
||||
raise click.ClickException(f"Failed to load {len(LOAD_ERRORS)} command(s):\n{joined}")
|
||||
|
||||
|
||||
class Commands(click.MultiCommand):
|
||||
@@ -17,10 +64,12 @@ class Commands(click.MultiCommand):
|
||||
|
||||
def list_commands(self, ctx: click.Context) -> list[str]:
|
||||
"""Returns a list of command names from the command filenames."""
|
||||
check_load_errors()
|
||||
return [x.stem.replace("_", "-") for x in _COMMANDS]
|
||||
|
||||
def get_command(self, ctx: click.Context, name: str) -> Optional[click.Command]:
|
||||
"""Load the command code and return the main click command function."""
|
||||
check_load_errors()
|
||||
module = _MODULES.get(name) or _MODULES.get(name.replace("-", "_"))
|
||||
if not module:
|
||||
raise click.ClickException(f"Unable to find command by the name '{name}'")
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
from typing import Union
|
||||
import base64
|
||||
from typing import Any, Union
|
||||
from uuid import UUID
|
||||
|
||||
from unshackle.core.drm.clearkey import ClearKey
|
||||
from unshackle.core.drm.monalisa import MonaLisa
|
||||
@@ -8,4 +10,35 @@ from unshackle.core.drm.widevine import Widevine
|
||||
DRM_T = Union[ClearKey, Widevine, PlayReady, MonaLisa]
|
||||
|
||||
|
||||
__all__ = ("ClearKey", "Widevine", "PlayReady", "MonaLisa", "DRM_T")
|
||||
def drm_from_dict(data: dict[str, Any]) -> Union[Widevine, PlayReady]:
|
||||
"""Reconstruct a Widevine/PlayReady DRM instance from its ``to_dict()`` form.
|
||||
|
||||
Rebuilds the PSSH from the stored base64 and re-injects any saved content keys
|
||||
so the resulting object can decrypt without contacting a license server.
|
||||
"""
|
||||
system = data.get("system")
|
||||
pssh_b64 = data.get("pssh_b64")
|
||||
kids = data.get("kids") or []
|
||||
content_keys = data.get("content_keys") or {}
|
||||
|
||||
if not pssh_b64:
|
||||
raise ValueError("Cannot reconstruct DRM without a stored PSSH.")
|
||||
|
||||
if system == "PlayReady":
|
||||
from pyplayready.system.pssh import PSSH as PlayReadyPSSH
|
||||
|
||||
drm: Union[Widevine, PlayReady] = PlayReady(pssh=PlayReadyPSSH(base64.b64decode(pssh_b64)), pssh_b64=pssh_b64)
|
||||
elif system == "Widevine":
|
||||
from pywidevine.pssh import PSSH as WidevinePSSH
|
||||
|
||||
drm = Widevine(pssh=WidevinePSSH(pssh_b64), kid=kids[0] if kids else None)
|
||||
else:
|
||||
raise ValueError(f"Unsupported DRM system for reconstruction: {system!r}")
|
||||
|
||||
for kid_hex, key in content_keys.items():
|
||||
drm.content_keys[UUID(hex=kid_hex)] = key
|
||||
|
||||
return drm
|
||||
|
||||
|
||||
__all__ = ("ClearKey", "Widevine", "PlayReady", "MonaLisa", "DRM_T", "drm_from_dict")
|
||||
|
||||
@@ -247,6 +247,17 @@ class PlayReady:
|
||||
def kid(self) -> Optional[UUID]:
|
||||
return next(iter(self.kids), None)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""Serialise this DRM instance for export/import (PSSH + KIDs).
|
||||
|
||||
Content keys are stored once at the export's track level, not duplicated here.
|
||||
"""
|
||||
return {
|
||||
"system": "PlayReady",
|
||||
"pssh_b64": self.pssh_b64,
|
||||
"kids": [kid.hex for kid in self.kids],
|
||||
}
|
||||
|
||||
@property
|
||||
def kids(self) -> list[UUID]:
|
||||
return self._kids
|
||||
|
||||
@@ -180,6 +180,17 @@ class Widevine:
|
||||
return [self._kid]
|
||||
return []
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""Serialise this DRM instance for export/import (PSSH + KIDs).
|
||||
|
||||
Content keys are stored once at the export's track level, not duplicated here.
|
||||
"""
|
||||
return {
|
||||
"system": "Widevine",
|
||||
"pssh_b64": self.pssh.dumps(),
|
||||
"kids": [kid.hex for kid in self.kids],
|
||||
}
|
||||
|
||||
def get_content_keys(self, cdm: WidevineCdm, certificate: Callable, licence: Callable) -> None:
|
||||
"""
|
||||
Create a CDM Session and obtain Content Keys for this DRM Instance.
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from http.cookiejar import CookieJar
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional, Union
|
||||
from uuid import UUID
|
||||
|
||||
import click
|
||||
import requests
|
||||
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import AnyTrack
|
||||
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, 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")
|
||||
|
||||
PARSERS = {"DASH": DASH, "HLS": HLS, "ISM": ISM}
|
||||
|
||||
|
||||
class ImportService:
|
||||
"""Reconstructs a download from an export JSON.
|
||||
|
||||
Auth and licensing are skipped; tracks are rebuilt from the export and keys injected
|
||||
directly. ``_server_cdm``/``_server_cdm_type`` keep their underscores: dl.py reads them
|
||||
via getattr as the server-CDM contract that skips client licensing.
|
||||
"""
|
||||
|
||||
ALIASES: tuple[str, ...] = ()
|
||||
GEOFENCE: tuple[str, ...] = ()
|
||||
NO_SUBTITLES: bool = False
|
||||
|
||||
def __init__(self, ctx: click.Context, service_tag: str, title: str, import_file: Optional[str]) -> None:
|
||||
self.__class__.__name__ = service_tag
|
||||
self.service_tag = service_tag
|
||||
self.title_id = title
|
||||
self.ctx = ctx
|
||||
self.log = logging.getLogger(service_tag)
|
||||
self.credential: Optional[Credential] = None
|
||||
self.current_region: Optional[str] = None
|
||||
self.title_cache = None
|
||||
|
||||
if not import_file:
|
||||
raise click.ClickException("No export file was provided to import from.")
|
||||
export_path = Path(import_file)
|
||||
if not export_path.is_file():
|
||||
raise click.ClickException(f"Export file not found: {export_path}")
|
||||
|
||||
self.data: dict[str, Any] = json.loads(export_path.read_text(encoding="utf8"))
|
||||
version = self.data.get("version")
|
||||
if version != 2:
|
||||
raise click.ClickException(
|
||||
f"Unsupported export version {version!r}. Re-create the export with a current build."
|
||||
)
|
||||
|
||||
self.titles_data: dict[str, Any] = self.data.get("titles", {})
|
||||
self.region: Optional[str] = self.data.get("region")
|
||||
self.titles: Optional[Titles_T] = None
|
||||
self.tracks_by_title: dict[str, Tracks] = {}
|
||||
|
||||
self._server_cdm = True
|
||||
self._server_cdm_type = "widevine"
|
||||
|
||||
self.session = self.build_session(ctx, self.region)
|
||||
|
||||
@staticmethod
|
||||
def build_session(ctx: click.Context, region: Optional[str] = None) -> requests.Session:
|
||||
"""Session for re-fetching the manifest.
|
||||
|
||||
Honours the importer's ``--proxy``; otherwise falls back to the export region as a
|
||||
geofence. An explicit proxy that fails to resolve raises; a region fallback warns.
|
||||
"""
|
||||
session = requests.Session()
|
||||
session.headers.update(config.headers)
|
||||
|
||||
params = ctx.parent.params if ctx.parent else {}
|
||||
if params.get("no_proxy"):
|
||||
return session
|
||||
|
||||
explicit = params.get("proxy")
|
||||
proxy_query = explicit or region
|
||||
if not proxy_query:
|
||||
return session
|
||||
|
||||
try:
|
||||
proxy = _resolve_proxy(proxy_query)
|
||||
except Exception as e:
|
||||
if explicit:
|
||||
raise click.ClickException(f"Failed to resolve proxy '{proxy_query}': {e}")
|
||||
log.warning(f"Could not auto-select a proxy for export region '{region}': {e}. Continuing without proxy.")
|
||||
proxy = None
|
||||
|
||||
if proxy:
|
||||
session.proxies.update({"all": proxy})
|
||||
if not explicit:
|
||||
log.info(f"No --proxy given; using export region '{region}' via your proxy provider.")
|
||||
return session
|
||||
|
||||
@property
|
||||
def title(self) -> str:
|
||||
return self.title_id
|
||||
|
||||
def authenticate(self, cookies: Optional[CookieJar] = None, credential: Optional[Credential] = None) -> None:
|
||||
self.credential = credential
|
||||
|
||||
def get_titles(self) -> Titles_T:
|
||||
if self.titles is not None:
|
||||
return self.titles
|
||||
titles_list = [
|
||||
_build_title(entry.get("meta", {}), self.service_tag, fallback_id=title_id)
|
||||
for title_id, entry in self.titles_data.items()
|
||||
]
|
||||
self.titles = (
|
||||
Series(titles_list) if titles_list and isinstance(titles_list[0], Episode) else Movies(titles_list)
|
||||
)
|
||||
return self.titles
|
||||
|
||||
def get_titles_cached(self, title_id: Optional[str] = None) -> Titles_T:
|
||||
"""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.
|
||||
|
||||
DASH/ISM: re-fetch and re-parse the manifest and return the full ladder (the importer
|
||||
picks quality with normal dl flags; keys are injected by KID later). HLS/URL: rebuild
|
||||
from the stored per-track dicts, since the variant is re-fetched from track.url at
|
||||
download time and ATV-style master playlists carry unstable per-fetch tokens.
|
||||
"""
|
||||
title_id = str(title.id)
|
||||
if title_id in self.tracks_by_title:
|
||||
return self.tracks_by_title[title_id]
|
||||
|
||||
entry = self.titles_data.get(title_id, {})
|
||||
tracks_map: dict[str, Any] = entry.get("tracks") or {}
|
||||
manifest_url = entry.get("manifest_url")
|
||||
manifest_type = entry.get("manifest_type")
|
||||
|
||||
tracks = Tracks()
|
||||
tracks.manifest_url = manifest_url
|
||||
|
||||
parser = PARSERS.get(manifest_type or "")
|
||||
if manifest_url and parser is not None and manifest_type in ("DASH", "ISM"):
|
||||
try:
|
||||
parsed = parser.from_url(url=manifest_url, session=self.session).to_tracks(language=title.language)
|
||||
except Exception as e:
|
||||
raise click.ClickException(
|
||||
f"Failed to re-fetch/parse the {manifest_type} manifest for '{title}'. "
|
||||
f"The manifest URL may have expired since export. ({e})"
|
||||
)
|
||||
for track in parsed:
|
||||
tracks.add(track)
|
||||
else:
|
||||
for track_dict in tracks_map.values():
|
||||
track = Track.from_dict(track_dict)
|
||||
drm = self.rebuild_drm(track_dict)
|
||||
if drm:
|
||||
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
|
||||
|
||||
def key_pool(self) -> dict[UUID, str]:
|
||||
"""All exported KID:KEY pairs across every title, as {UUID: key_hex}."""
|
||||
pool: dict[UUID, str] = {}
|
||||
for entry in self.titles_data.values():
|
||||
for track_dict in (entry.get("tracks") or {}).values():
|
||||
for kid_hex, key in (track_dict.get("keys") or {}).items():
|
||||
pool[UUID(hex=kid_hex)] = key
|
||||
return pool
|
||||
|
||||
def rebuild_drm(self, track_dict: dict[str, Any]) -> Optional[list[Any]]:
|
||||
"""Rebuild a DRM object (from stored PSSH, falling back to a stub) with the exported keys."""
|
||||
keys = track_dict.get("keys") or {}
|
||||
drm_dicts = track_dict.get("drm") or []
|
||||
if not drm_dicts and not keys:
|
||||
return None
|
||||
|
||||
drm_obj = None
|
||||
if drm_dicts:
|
||||
try:
|
||||
drm_obj = drm_from_dict(drm_dicts[0])
|
||||
except Exception as e:
|
||||
self.log.debug(f"Falling back to DRM stub (PSSH rebuild failed: {e})")
|
||||
|
||||
if drm_obj is None and keys:
|
||||
drm_type = (drm_dicts[0].get("system", "Widevine").lower()) if drm_dicts else "widevine"
|
||||
drm_obj = RemoteService._create_drm_stub(drm_type, list(keys.keys()))
|
||||
|
||||
if drm_obj is None:
|
||||
return None
|
||||
|
||||
for kid_hex, key in keys.items():
|
||||
drm_obj.content_keys[UUID(hex=kid_hex)] = key
|
||||
return [drm_obj]
|
||||
|
||||
def resolve_server_keys(self, title: Title_T) -> None:
|
||||
"""Inject exported keys into the selected encrypted tracks by KID (no network).
|
||||
|
||||
Called by dl.py after selection. Only encrypted video/audio are touched; encrypted
|
||||
DASH tracks (no DRM at parse time) get a stub holding the keys, which
|
||||
DASH.download_track preserves. decrypt() applies the key whose KID matches the media.
|
||||
"""
|
||||
pool = self.key_pool()
|
||||
if not pool:
|
||||
return
|
||||
|
||||
system = self.exported_drm_system()
|
||||
kid_hexes = [kid.hex for kid in pool]
|
||||
|
||||
for track in title.tracks:
|
||||
if not isinstance(track, (Video, Audio)) or not self.track_is_encrypted(track):
|
||||
continue
|
||||
drm_obj = track.drm[0] if track.drm else RemoteService._create_drm_stub(system, kid_hexes)
|
||||
for kid, key in pool.items():
|
||||
drm_obj.content_keys[kid] = key
|
||||
track.drm = [drm_obj]
|
||||
self._server_cdm_type = drm_obj.__class__.__name__.lower()
|
||||
|
||||
@staticmethod
|
||||
def track_is_encrypted(track: Any) -> bool:
|
||||
"""True if the track carries DRM or its DASH manifest declares ContentProtection."""
|
||||
if track.drm:
|
||||
return True
|
||||
dash = track.data.get("dash") if getattr(track, "data", None) else None
|
||||
if dash:
|
||||
for element in (dash.get("representation"), dash.get("adaptation_set")):
|
||||
if element is not None and element.findall("ContentProtection"):
|
||||
return True
|
||||
return False
|
||||
|
||||
def exported_drm_system(self) -> str:
|
||||
"""The DRM system the exporter licensed (e.g. 'playready'), defaulting to widevine."""
|
||||
for entry in self.titles_data.values():
|
||||
for track_dict in (entry.get("tracks") or {}).values():
|
||||
for drm_dict in track_dict.get("drm") or []:
|
||||
if drm_dict.get("system"):
|
||||
return drm_dict["system"].lower()
|
||||
return "widevine"
|
||||
|
||||
def get_chapters(self, title: Title_T) -> Chapters:
|
||||
entry = self.titles_data.get(str(title.id), {})
|
||||
return Chapters(
|
||||
[Chapter(ch["timestamp"], ch.get("name")) for ch in (entry.get("chapters") or []) if ch.get("timestamp")]
|
||||
)
|
||||
|
||||
def get_widevine_service_certificate(self, **_: Any) -> Optional[str]:
|
||||
return None
|
||||
|
||||
def get_widevine_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> Optional[Union[bytes, str]]:
|
||||
raise RuntimeError("ImportService should not request a license; keys come from the export.")
|
||||
|
||||
def get_playready_license(
|
||||
self, *, challenge: bytes, title: Title_T, track: AnyTrack
|
||||
) -> Optional[Union[bytes, str]]:
|
||||
raise RuntimeError("ImportService should not request a license; keys come from the export.")
|
||||
|
||||
def on_segment_downloaded(self, track: AnyTrack, segment: Any) -> None:
|
||||
pass
|
||||
|
||||
def on_track_downloaded(self, track: AnyTrack) -> None:
|
||||
pass
|
||||
|
||||
def on_track_decrypted(self, track: AnyTrack, drm: Any, segment: Any = None) -> None:
|
||||
pass
|
||||
|
||||
def on_track_repacked(self, track: AnyTrack) -> None:
|
||||
pass
|
||||
|
||||
def on_track_multiplex(self, track: AnyTrack) -> None:
|
||||
pass
|
||||
|
||||
def close(self) -> None:
|
||||
try:
|
||||
self.session.close()
|
||||
except Exception:
|
||||
pass
|
||||
@@ -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")
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
@@ -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:
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
@@ -9,6 +10,8 @@ from unshackle.core.config import config
|
||||
from unshackle.core.service import Service
|
||||
from unshackle.core.utilities import import_module_by_path
|
||||
|
||||
log = logging.getLogger("services")
|
||||
|
||||
_service_dirs = config.directories.services
|
||||
if not isinstance(_service_dirs, list):
|
||||
_service_dirs = [_service_dirs]
|
||||
@@ -18,9 +21,59 @@ _SERVICES = sorted(
|
||||
key=lambda x: x.parent.stem,
|
||||
)
|
||||
|
||||
_MODULES = {path.parent.stem: getattr(import_module_by_path(path), path.parent.stem) for path in _SERVICES}
|
||||
|
||||
_ALIASES = {tag: getattr(module, "ALIASES") for tag, module in _MODULES.items()}
|
||||
def load_service(path: Path) -> object:
|
||||
"""Load one Service module, returning its tag-named class.
|
||||
|
||||
Raises a concise, single-line error naming the Service and the real cause so
|
||||
a broken Service never surfaces as a raw traceback pointing at the loader.
|
||||
"""
|
||||
tag = path.parent.stem
|
||||
try:
|
||||
module = import_module_by_path(path)
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"{tag}: failed to import — {type(e).__name__}: {e} ({path})") from e
|
||||
try:
|
||||
return getattr(module, tag)
|
||||
except AttributeError as e:
|
||||
raise RuntimeError(
|
||||
f"{tag}: no class named '{tag}' found in {path} — the class name must match the directory name"
|
||||
) from e
|
||||
|
||||
|
||||
def load_services(paths: list[Path]) -> tuple[dict[str, object], list[str]]:
|
||||
"""Load every Service, returning the good ones plus a list of load errors.
|
||||
|
||||
Importing this module must never raise: it is imported by several commands,
|
||||
and a failed import is not cached by Python, so raising here would re-run and
|
||||
re-report for every command. Instead we collect failures and let the caller
|
||||
surface them once, cleanly, at the point services are actually used.
|
||||
"""
|
||||
modules: dict[str, object] = {}
|
||||
errors: list[str] = []
|
||||
for path in paths:
|
||||
try:
|
||||
modules[path.parent.stem] = load_service(path)
|
||||
except Exception as e:
|
||||
errors.append(str(e))
|
||||
return modules, errors
|
||||
|
||||
|
||||
_MODULES, LOAD_ERRORS = load_services(_SERVICES)
|
||||
|
||||
_ALIASES = {tag: getattr(module, "ALIASES", ()) for tag, module in _MODULES.items()}
|
||||
|
||||
|
||||
def check_load_errors() -> None:
|
||||
"""Raise a single clean error if any Service failed to load.
|
||||
|
||||
Called when services are actually needed (listing/resolving) so the message
|
||||
is rendered once by Click, without a traceback and without cascading through
|
||||
every command that imports this module.
|
||||
"""
|
||||
if LOAD_ERRORS:
|
||||
joined = "\n".join(f" - {err}" for err in LOAD_ERRORS)
|
||||
raise click.ClickException(f"Failed to load {len(LOAD_ERRORS)} service(s):\n{joined}")
|
||||
|
||||
|
||||
class Services(click.MultiCommand):
|
||||
@@ -64,12 +117,18 @@ class Services(click.MultiCommand):
|
||||
if remote_tag not in tags:
|
||||
tags.append(remote_tag)
|
||||
return tags
|
||||
check_load_errors()
|
||||
return Services.get_tags()
|
||||
|
||||
def get_command(self, ctx: click.Context, name: str) -> click.Command:
|
||||
"""Load the Service and return the Click CLI method."""
|
||||
check_load_errors()
|
||||
tag = Services.get_tag(name)
|
||||
|
||||
import_file = ctx.params.get("import_file") or (ctx.parent and ctx.parent.params.get("import_file"))
|
||||
if import_file:
|
||||
return Services._make_import_command(tag, ctx)
|
||||
|
||||
remote = ctx.params.get("remote") or (ctx.parent and ctx.parent.params.get("remote"))
|
||||
if remote:
|
||||
return Services._make_remote_command(tag, ctx)
|
||||
@@ -141,6 +200,24 @@ class Services(click.MultiCommand):
|
||||
|
||||
return remote_cli
|
||||
|
||||
@staticmethod
|
||||
def _make_import_command(tag: str, ctx: click.Context) -> click.Command:
|
||||
"""Create a synthetic command that yields an ImportService from an export JSON.
|
||||
|
||||
Mirrors how remote services are wired so dl.py's result() runs unchanged.
|
||||
"""
|
||||
|
||||
@click.command(name=tag, short_help="Reconstruct a download from an export JSON.")
|
||||
@click.argument("title", type=str, required=False, default="")
|
||||
@click.pass_context
|
||||
def import_cli(ctx: click.Context, title: str, **kwargs: object) -> object:
|
||||
from unshackle.core.import_service import ImportService
|
||||
|
||||
import_file = ctx.params.get("import_file") or (ctx.parent and ctx.parent.params.get("import_file"))
|
||||
return ImportService(ctx, tag, title, import_file)
|
||||
|
||||
return import_cli
|
||||
|
||||
@staticmethod
|
||||
def _fetch_remote_service_info(tag: str, ctx: click.Context) -> dict | None:
|
||||
"""Fetch service info for a specific service from the remote server."""
|
||||
|
||||
@@ -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]:
|
||||
|
||||
@@ -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",
|
||||
)
|
||||
|
||||
@@ -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."""
|
||||
|
||||
@@ -126,6 +126,31 @@ class Audio(Track):
|
||||
self.joc = joc
|
||||
self.descriptive = bool(descriptive)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
data = super().to_dict()
|
||||
data.update(
|
||||
{
|
||||
"codec": self.codec.name if self.codec else None,
|
||||
"bitrate": self.bitrate,
|
||||
"channels": self.channels,
|
||||
"joc": self.joc,
|
||||
"descriptive": self.descriptive,
|
||||
}
|
||||
)
|
||||
return data
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict[str, Any]) -> Audio:
|
||||
kwargs = Track.base_kwargs_from_dict(data)
|
||||
return cls(
|
||||
**kwargs,
|
||||
codec=Audio.Codec[data["codec"]] if data.get("codec") else None,
|
||||
bitrate=data.get("bitrate"),
|
||||
channels=data.get("channels"),
|
||||
joc=data.get("joc"),
|
||||
descriptive=data.get("descriptive", False),
|
||||
)
|
||||
|
||||
@property
|
||||
def atmos(self) -> bool:
|
||||
"""Return True if the audio track contains Dolby Atmos."""
|
||||
|
||||
@@ -6,6 +6,7 @@ import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from rich.padding import Padding
|
||||
from rich.rule import Rule
|
||||
@@ -341,11 +342,7 @@ class Hybrid:
|
||||
for crop in crop_results:
|
||||
crop_counts[crop] = crop_counts.get(crop, 0) + 1
|
||||
most_common = max(crop_counts, key=crop_counts.get)
|
||||
left, top, right, bottom = most_common
|
||||
|
||||
# If all borders are 0 there's nothing to correct
|
||||
if left == 0 and top == 0 and right == 0 and bottom == 0:
|
||||
return
|
||||
left, top, right, bottom = most_common # frame instead of leaving phantom bars from the source.
|
||||
|
||||
l5_json = {
|
||||
"active_area": {
|
||||
@@ -390,8 +387,24 @@ class Hybrid:
|
||||
)
|
||||
self.rpu_file = "RPU_L5.bin"
|
||||
|
||||
@staticmethod
|
||||
def sanitize_l6(
|
||||
max_mdl: Optional[int], min_mdl: Optional[int], max_cll: Optional[int], max_fall: Optional[int]
|
||||
) -> tuple[Optional[int], Optional[int], Optional[int], Optional[int]]:
|
||||
"""Clamp static L6 values to a valid relationship.
|
||||
|
||||
MaxCLL must not exceed the mastering-display peak (some sources, e.g. ATV
|
||||
HDR10+, ship MaxCLL 10000 on a 1000-nit master), and MaxFALL must not exceed
|
||||
MaxCLL. A value of 0 means "unknown" and is preserved as-is.
|
||||
"""
|
||||
if max_mdl and max_cll and max_cll > max_mdl:
|
||||
max_cll = max_mdl
|
||||
if max_cll and max_fall and max_fall > max_cll:
|
||||
max_fall = max_cll
|
||||
return max_mdl, min_mdl, max_cll, max_fall
|
||||
|
||||
def level_6(self):
|
||||
"""Edit RPU Level 6 values using actual luminance data from the RPU."""
|
||||
"""Edit RPU Level 6 values using the static L6 luminance data from the RPU."""
|
||||
if os.path.isfile(config.directories.temp / "RPU_L6.bin"):
|
||||
return
|
||||
|
||||
@@ -413,17 +426,33 @@ class Hybrid:
|
||||
max_mdl = None
|
||||
min_mdl = None
|
||||
|
||||
in_l6 = False
|
||||
for line in info_text.splitlines():
|
||||
if "RPU content light level (L1):" in line:
|
||||
parts = line.split("MaxCLL:")[1].split(",")
|
||||
max_cll = int(float(parts[0].strip().split()[0]))
|
||||
if len(parts) > 1 and "MaxFALL:" in parts[1]:
|
||||
max_fall = int(float(parts[1].split("MaxFALL:")[1].strip().split()[0]))
|
||||
elif "RPU mastering display:" in line:
|
||||
mastering = line.split(":", 1)[1].strip()
|
||||
stripped = line.strip()
|
||||
if "L6 metadata" in stripped:
|
||||
in_l6 = True
|
||||
if stripped.startswith("RPU mastering display:"):
|
||||
mastering = stripped.split(":", 1)[1].strip()
|
||||
min_lum, max_lum = mastering.split("/")[0], mastering.split("/")[1].split(" ")[0]
|
||||
min_mdl = int(float(min_lum) * 10000)
|
||||
max_mdl = int(float(max_lum))
|
||||
elif in_l6 and "MaxCLL:" in stripped and max_cll is None:
|
||||
max_cll = int(float(stripped.split("MaxCLL:")[1].split("nits")[0].strip().rstrip(",")))
|
||||
if "MaxFALL:" in stripped:
|
||||
max_fall = int(float(stripped.split("MaxFALL:")[1].split("nits")[0].strip().rstrip(",")))
|
||||
|
||||
if any(v is None for v in (max_cll, max_fall, max_mdl, min_mdl)):
|
||||
base_max_mdl, base_min_mdl, base_cll, base_fall = self._probe_hdr_metadata()
|
||||
if max_cll is None:
|
||||
max_cll = base_cll
|
||||
if max_fall is None:
|
||||
max_fall = base_fall
|
||||
if max_mdl is None:
|
||||
max_mdl = base_max_mdl
|
||||
if min_mdl is None:
|
||||
min_mdl = base_min_mdl
|
||||
|
||||
max_mdl, min_mdl, max_cll, max_fall = self.sanitize_l6(max_mdl, min_mdl, max_cll, max_fall)
|
||||
|
||||
if any(v is None for v in (max_cll, max_fall, max_mdl, min_mdl)):
|
||||
if self.debug_logger:
|
||||
@@ -638,6 +667,7 @@ class Hybrid:
|
||||
with console.status("Converting HDR10+ metadata to Dolby Vision...", spinner="dots"):
|
||||
# Extract actual HDR metadata from the source stream
|
||||
max_mdl, min_mdl, max_cll, max_fall = self._probe_hdr_metadata()
|
||||
max_mdl, min_mdl, max_cll, max_fall = self.sanitize_l6(max_mdl, min_mdl, max_cll, max_fall)
|
||||
|
||||
# First create the extra metadata JSON for dovi_tool
|
||||
extra_metadata = {
|
||||
|
||||
@@ -195,6 +195,29 @@ class Subtitle(Track):
|
||||
# Called after Track has been converted to another format
|
||||
self.OnConverted: Optional[Callable[[Subtitle.Codec], None]] = None
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
data = super().to_dict()
|
||||
data.update(
|
||||
{
|
||||
"codec": self.codec.name if self.codec else None,
|
||||
"cc": self.cc,
|
||||
"sdh": self.sdh,
|
||||
"forced": self.forced,
|
||||
}
|
||||
)
|
||||
return data
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict[str, Any]) -> Subtitle:
|
||||
kwargs = Track.base_kwargs_from_dict(data)
|
||||
return cls(
|
||||
**kwargs,
|
||||
codec=Subtitle.Codec[data["codec"]] if data.get("codec") else None,
|
||||
cc=data.get("cc", False),
|
||||
sdh=data.get("sdh", False),
|
||||
forced=data.get("forced", False),
|
||||
)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return " | ".join(
|
||||
filter(
|
||||
|
||||
@@ -439,6 +439,57 @@ class Track:
|
||||
self.path = target
|
||||
return target
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""Serialise the track for export/import (identity/URL/descriptor/language).
|
||||
|
||||
DRM is not serialised here; the export writer attaches the licensed DRM + keys.
|
||||
Subclasses add their own codec/quality fields.
|
||||
"""
|
||||
data: dict[str, Any] = {
|
||||
"type": self.__class__.__name__,
|
||||
"id": self.id,
|
||||
"url": self.url,
|
||||
"language": str(self.language),
|
||||
"is_original_lang": self.is_original_lang,
|
||||
"descriptor": self.descriptor.name,
|
||||
"needs_repack": self.needs_repack,
|
||||
"name": self.name,
|
||||
"edition": self.edition,
|
||||
}
|
||||
return data
|
||||
|
||||
@staticmethod
|
||||
def base_kwargs_from_dict(data: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Build the shared Track constructor kwargs from a ``to_dict()`` payload.
|
||||
|
||||
DRM is not reconstructed here — ``to_dict`` does not serialise it, and the import
|
||||
flow attaches the licensed DRM + content keys separately.
|
||||
"""
|
||||
return {
|
||||
"url": data["url"],
|
||||
"language": data.get("language") or "und",
|
||||
"is_original_lang": data.get("is_original_lang", False),
|
||||
"descriptor": Track.Descriptor[data.get("descriptor", "URL")],
|
||||
"needs_repack": data.get("needs_repack", False),
|
||||
"name": data.get("name"),
|
||||
"edition": data.get("edition") or None,
|
||||
"id_": data.get("id"),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict[str, Any]) -> "Track":
|
||||
"""Reconstruct the correct Track subclass from a ``to_dict()`` payload."""
|
||||
from unshackle.core.tracks.audio import Audio
|
||||
from unshackle.core.tracks.subtitle import Subtitle
|
||||
from unshackle.core.tracks.video import Video
|
||||
|
||||
track_type = data.get("type")
|
||||
builders = {"Video": Video, "Audio": Audio, "Subtitle": Subtitle}
|
||||
builder = builders.get(track_type)
|
||||
if builder is None:
|
||||
raise ValueError(f"Cannot reconstruct unsupported track type: {track_type!r}")
|
||||
return builder.from_dict(data)
|
||||
|
||||
def get_track_name(self) -> Optional[str]:
|
||||
"""Get the Track Name."""
|
||||
return self.name
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -296,6 +296,38 @@ 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()
|
||||
data.update(
|
||||
{
|
||||
"codec": self.codec.name if self.codec else None,
|
||||
"range": self.range.name if self.range else None,
|
||||
"bitrate": self.bitrate,
|
||||
"width": self.width,
|
||||
"height": self.height,
|
||||
"fps": str(self.fps) if self.fps else None,
|
||||
"scan_type": self.scan_type.name if self.scan_type else None,
|
||||
"dv_compatible_bitstream": self.dv_compatible_bitstream,
|
||||
}
|
||||
)
|
||||
return data
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict[str, Any]) -> Video:
|
||||
kwargs = Track.base_kwargs_from_dict(data)
|
||||
return cls(
|
||||
**kwargs,
|
||||
codec=Video.Codec[data["codec"]] if data.get("codec") else None,
|
||||
range_=Video.Range[data["range"]] if data.get("range") else None,
|
||||
bitrate=data.get("bitrate"),
|
||||
width=data.get("width"),
|
||||
height=data.get("height"),
|
||||
fps=data.get("fps"),
|
||||
scan_type=Video.ScanType[data["scan_type"]] if data.get("scan_type") else None,
|
||||
dv_compatible_bitstream=data.get("dv_compatible_bitstream", False),
|
||||
)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return " | ".join(
|
||||
|
||||
@@ -160,6 +160,18 @@ 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 find_missing_langs(
|
||||
requested: Sequence[str],
|
||||
available: Sequence[Union[str, Language, None]],
|
||||
*,
|
||||
exact: bool = False,
|
||||
) -> list[str]:
|
||||
"""Return requested language tokens with no match in available languages."""
|
||||
match_func = is_exact_match if exact else is_close_match
|
||||
skip = {"all", "best", "orig"}
|
||||
return [tok for tok in requested if tok not in skip and not match_func(tok, available)]
|
||||
|
||||
|
||||
def get_boxes(data: bytes, box_type: bytes, as_bytes: bool = False) -> Box: # type: ignore
|
||||
"""
|
||||
Scan a byte array for a wanted MP4/ISOBMFF box, then parse and yield each find.
|
||||
|
||||
@@ -0,0 +1,441 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import subprocess
|
||||
from collections import OrderedDict, defaultdict
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Callable, Hashable, Optional, Union
|
||||
from urllib.parse import urljoin
|
||||
|
||||
from requests import Session
|
||||
|
||||
from unshackle.core.binaries import FFProbe
|
||||
from unshackle.core.session import RnetSession
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from unshackle.core.tracks import Track
|
||||
|
||||
# Default ISM timescale (ticks per second) per the Smooth Streaming spec.
|
||||
ISM_DEFAULT_TIMESCALE = 10_000_000
|
||||
|
||||
# Bytes fetched to locate an mp4 moov box when probing duration via ffprobe.
|
||||
MOOV_PROBE_BYTES = 4 * 1024 * 1024
|
||||
|
||||
# Network timeout (seconds) for probe requests.
|
||||
PROBE_TIMEOUT = 15
|
||||
|
||||
|
||||
@dataclass
|
||||
class Segment:
|
||||
"""One probe target: a media URL, optional byte range, its size, and duration."""
|
||||
|
||||
url: str
|
||||
# The original byte-range string (e.g. "0-1023"), preserved as the segment's
|
||||
# identity so distinct ranges of one file are never confused with each other.
|
||||
byte_range: Optional[str]
|
||||
# Size in bytes when derivable without a request (from a byte range); else None.
|
||||
known_size: Optional[int]
|
||||
duration: float
|
||||
|
||||
|
||||
def measure_real_bitrate(
|
||||
track: "Track",
|
||||
session: Union[Session, RnetSession],
|
||||
*,
|
||||
samples: int = 40,
|
||||
log: logging.Logger,
|
||||
) -> Optional[int]:
|
||||
"""
|
||||
Probe a track's actual media size to compute its real average bitrate.
|
||||
|
||||
Manifests often declare an inaccurate bandwidth (DASH ``@bandwidth`` is a
|
||||
leaky-bucket ceiling, not an average). This measures the true bitrate
|
||||
(bits/sec) from real media byte sizes and durations using ``bytes * 8 / sec``.
|
||||
|
||||
Single-file tracks are measured exactly. Segmented tracks probe up to
|
||||
``samples`` segments spread across the track and extrapolate; byte-range
|
||||
segments need no request. Returns bits/sec, or ``None`` if it cannot be
|
||||
measured. Never raises — a probe failure must not abort a download.
|
||||
"""
|
||||
from unshackle.core.tracks.track import Track
|
||||
|
||||
try:
|
||||
if track.descriptor == Track.Descriptor.DASH:
|
||||
segments = extract_dash(track, session)
|
||||
elif track.descriptor == Track.Descriptor.HLS:
|
||||
segments = extract_hls(track, session)
|
||||
elif track.descriptor == Track.Descriptor.ISM:
|
||||
segments = extract_ism(track, session)
|
||||
else:
|
||||
# Descriptor.URL: a single file. Some services (e.g. AMZN) parse a DASH
|
||||
# manifest then collapse each representation to its single BaseURL and
|
||||
# flip the descriptor to URL, leaving the manifest (and its duration) in
|
||||
# track.data — recover the duration from there, else probe the file.
|
||||
segments = extract_url(track, session, log=log)
|
||||
if not segments:
|
||||
log.debug(f"{track.id}: cannot measure real bitrate (no known duration)")
|
||||
return None
|
||||
except Exception as e:
|
||||
log.warning(f"{track.id}: failed to derive segments for real bitrate ({e})")
|
||||
return None
|
||||
|
||||
if not segments:
|
||||
return None
|
||||
|
||||
items = dedupe(segments)
|
||||
chosen = pick_samples(items, samples)
|
||||
|
||||
total_bytes = 0
|
||||
total_seconds = 0.0
|
||||
for segment in chosen:
|
||||
if segment.duration <= 0:
|
||||
continue
|
||||
size = segment.known_size if segment.known_size is not None else probe_size(segment, session)
|
||||
if not size:
|
||||
continue
|
||||
total_bytes += size
|
||||
total_seconds += segment.duration
|
||||
|
||||
log.debug(
|
||||
f"{track.id}: real-bitrate probe desc={track.descriptor.name} "
|
||||
f"n_seg={len(segments)} n_unique={len(items)} n_chosen={len(chosen)} "
|
||||
f"sampled_bytes={total_bytes} sampled_seconds={round(total_seconds, 4)}"
|
||||
)
|
||||
|
||||
if total_seconds <= 0 or total_bytes <= 0:
|
||||
log.warning(f"{track.id}: real bitrate probe returned no usable data")
|
||||
return None
|
||||
|
||||
return round(total_bytes * 8 / total_seconds)
|
||||
|
||||
|
||||
def apply_real_bitrates(
|
||||
tracks: list["Track"],
|
||||
session: Union[Session, RnetSession],
|
||||
*,
|
||||
log: logging.Logger,
|
||||
group_key: Callable[["Track"], Hashable],
|
||||
per_group: int = 5,
|
||||
workers: int = 8,
|
||||
) -> None:
|
||||
"""
|
||||
Probe real bitrates and overwrite ``track.bitrate`` for the tracks worth probing.
|
||||
|
||||
Probing every rendition is slow when a service exposes dozens. Tracks are
|
||||
grouped by ``group_key`` (a quality tier), and only the ``per_group`` highest
|
||||
declared-bitrate tracks per group are probed, in parallel. Each group is then
|
||||
extended downward: while the lowest probed bitrate in a group sits below the
|
||||
next unprobed track's declared bitrate (so that track could outrank a probed
|
||||
one), the next track is probed too — until the probed set is safely above the
|
||||
rest. Unprobed tracks keep their manifest-declared bitrate.
|
||||
"""
|
||||
groups: defaultdict[Hashable, list["Track"]] = defaultdict(list)
|
||||
for track in tracks:
|
||||
groups[group_key(track)].append(track)
|
||||
for group in groups.values():
|
||||
group.sort(key=lambda t: getattr(t, "bitrate", None) or 0, reverse=True)
|
||||
|
||||
# Initial pass: top per_group of every group, all probed concurrently.
|
||||
initial = [track for group in groups.values() for track in group[:per_group]]
|
||||
probe_batch(initial, session, log=log, workers=workers)
|
||||
|
||||
# Extend each group downward until unprobed tracks can't outrank probed ones.
|
||||
for group in groups.values():
|
||||
probed = min(per_group, len(group))
|
||||
while probed < len(group):
|
||||
lowest_probed = min((getattr(t, "bitrate", None) or 0) for t in group[:probed])
|
||||
next_declared = getattr(group[probed], "bitrate", None) or 0
|
||||
if next_declared <= lowest_probed:
|
||||
break
|
||||
probe_batch([group[probed]], session, log=log, workers=workers)
|
||||
probed += 1
|
||||
|
||||
|
||||
def probe_batch(
|
||||
tracks: list["Track"],
|
||||
session: Union[Session, RnetSession],
|
||||
*,
|
||||
log: logging.Logger,
|
||||
workers: int,
|
||||
) -> None:
|
||||
"""Probe each track concurrently and overwrite its bitrate with the measured value."""
|
||||
if not tracks:
|
||||
return
|
||||
|
||||
def probe_one(track: "Track") -> tuple["Track", Optional[int]]:
|
||||
return track, measure_real_bitrate(track, track.session or session, log=log)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=min(workers, len(tracks))) as executor:
|
||||
for track, measured in executor.map(probe_one, tracks):
|
||||
if not measured:
|
||||
continue
|
||||
declared = getattr(track, "bitrate", None)
|
||||
if declared and declared != measured:
|
||||
log.debug(f"{track.id}: bitrate {declared // 1000} → {measured // 1000} kb/s (real)")
|
||||
setattr(track, "bitrate", measured)
|
||||
|
||||
|
||||
def dedupe(segments: list[Segment]) -> list[Segment]:
|
||||
"""
|
||||
Collapse segments that address the same bytes so each object is measured once.
|
||||
|
||||
Manifests sometimes wrap a single file in several segment entries sharing one
|
||||
URL — with no byte range (a ``SegmentTemplate`` whose media pattern has no
|
||||
``$Number$``) or with the same range. Each resolves to the whole file, so
|
||||
counting them all would multiply the size by the segment count. Segments
|
||||
sharing the same ``(url, byte_range)`` are merged into one entry whose duration
|
||||
is the sum they cover. Distinct byte ranges of one file (different offsets) are
|
||||
kept individual so their sizes still add up to the full track.
|
||||
"""
|
||||
merged: OrderedDict[tuple[str, Optional[str]], Segment] = OrderedDict()
|
||||
for segment in segments:
|
||||
key = (segment.url, segment.byte_range)
|
||||
existing = merged.get(key)
|
||||
if existing is None:
|
||||
merged[key] = Segment(segment.url, segment.byte_range, segment.known_size, segment.duration)
|
||||
else:
|
||||
existing.duration += segment.duration
|
||||
return list(merged.values())
|
||||
|
||||
|
||||
def pick_samples(segments: list[Segment], samples: int) -> list[Segment]:
|
||||
"""Pick up to ``samples`` segments spread evenly across the track."""
|
||||
count = len(segments)
|
||||
if count <= samples:
|
||||
return segments
|
||||
step = count / samples
|
||||
indices = sorted({int(i * step) for i in range(samples)})
|
||||
return [segments[i] for i in indices]
|
||||
|
||||
|
||||
def probe_size(segment: Segment, session: Union[Session, RnetSession]) -> Optional[int]:
|
||||
"""Return a segment's byte size via HEAD, falling back to a ranged GET. Validates status."""
|
||||
try:
|
||||
res = session.head(segment.url, allow_redirects=True, timeout=PROBE_TIMEOUT)
|
||||
if getattr(res, "status_code", 0) in (200, 206):
|
||||
content_length = res.headers.get("Content-Length")
|
||||
if content_length:
|
||||
return int(content_length)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Some hosts block or mishandle HEAD; ask for a single byte and read the total.
|
||||
# Require a 206 so a server that ignores Range (returning the whole 200 body)
|
||||
# is not mistaken for a valid size or downloaded wholesale.
|
||||
try:
|
||||
res = session.get(segment.url, headers={"Range": "bytes=0-0"}, timeout=PROBE_TIMEOUT)
|
||||
if getattr(res, "status_code", 0) == 206:
|
||||
content_range = res.headers.get("Content-Range")
|
||||
if content_range and "/" in content_range:
|
||||
total = content_range.rsplit("/", 1)[-1].strip()
|
||||
if total.isdigit():
|
||||
return int(total)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def range_size(byte_range: Optional[str]) -> Optional[int]:
|
||||
"""Size in bytes of a ``start-end`` media range, inclusive."""
|
||||
if not byte_range or "-" not in byte_range:
|
||||
return None
|
||||
start_s, _, end_s = byte_range.partition("-")
|
||||
try:
|
||||
start = int(start_s) if start_s else 0
|
||||
if not end_s:
|
||||
return None
|
||||
return int(end_s) - start + 1
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def uniform_segments(
|
||||
raw_segments: list[tuple[str, Optional[str]]],
|
||||
total_duration: Optional[float],
|
||||
) -> list[Segment]:
|
||||
"""
|
||||
Build Segments giving each an equal share of the total duration.
|
||||
|
||||
Used for DASH: ``DASH._get_period_segments`` returns timeline *start times*
|
||||
rather than per-segment durations, so they cannot be trusted. Segment lengths
|
||||
are near-uniform in practice, so the track duration (from
|
||||
``mediaPresentationDuration``) split evenly is both correct and timeline-safe.
|
||||
"""
|
||||
count = len(raw_segments)
|
||||
if not count or not total_duration or total_duration <= 0:
|
||||
return []
|
||||
per_segment = total_duration / count
|
||||
return [Segment(url, byte_range, range_size(byte_range), per_segment) for url, byte_range in raw_segments]
|
||||
|
||||
|
||||
def extract_dash(track: "Track", session: Union[Session, RnetSession]) -> list[Segment]:
|
||||
from unshackle.core.manifests import DASH
|
||||
|
||||
data = track.data["dash"]
|
||||
manifest = data["manifest"]
|
||||
rep_id = data.get("representation_id") or data["representation"].get("id")
|
||||
filtered_period_ids = data.get("filtered_period_ids", [])
|
||||
track_url = track.url if isinstance(track.url, str) else track.url[0]
|
||||
|
||||
content_periods = [p for p in manifest.findall("Period") if DASH._is_content_period(p, filtered_period_ids)]
|
||||
|
||||
raw_segments: list[tuple[str, Optional[str]]] = []
|
||||
for period in content_periods:
|
||||
matched_rep = matched_as = None
|
||||
for as_ in period.findall("AdaptationSet"):
|
||||
if DASH.is_trick_mode(as_):
|
||||
continue
|
||||
for rep in as_.findall("Representation"):
|
||||
if rep.get("id") == rep_id:
|
||||
matched_rep, matched_as = rep, as_
|
||||
break
|
||||
if matched_rep is not None:
|
||||
break
|
||||
if matched_rep is None or matched_as is None:
|
||||
continue
|
||||
|
||||
_, period_segments, _, _, _ = DASH._get_period_segments(
|
||||
period=period,
|
||||
adaptation_set=matched_as,
|
||||
representation=matched_rep,
|
||||
manifest=manifest,
|
||||
track=track,
|
||||
track_url=track_url,
|
||||
session=session,
|
||||
)
|
||||
raw_segments.extend(period_segments)
|
||||
|
||||
total_duration: Optional[float] = None
|
||||
mpd_duration = manifest.get("mediaPresentationDuration")
|
||||
if mpd_duration:
|
||||
total_duration = DASH.pt_to_sec(mpd_duration)
|
||||
|
||||
return uniform_segments(raw_segments, total_duration)
|
||||
|
||||
|
||||
def extract_hls(track: "Track", session: Union[Session, RnetSession]) -> list[Segment]:
|
||||
import m3u8
|
||||
|
||||
playlist_url = track.url if isinstance(track.url, str) else track.url[0]
|
||||
res = session.get(playlist_url, timeout=PROBE_TIMEOUT)
|
||||
playlist = m3u8.loads(res.text, uri=playlist_url)
|
||||
|
||||
out: list[Segment] = []
|
||||
for segment in playlist.segments:
|
||||
url = urljoin(segment.base_uri or "", segment.uri)
|
||||
byte_range = segment.byterange # "<length>[@<offset>]"
|
||||
known_size: Optional[int] = None
|
||||
if byte_range:
|
||||
length = byte_range.split("@")[0].strip()
|
||||
if length.isdigit():
|
||||
known_size = int(length)
|
||||
# EXTINF durations are reliable, so they are used directly (unlike DASH).
|
||||
out.append(Segment(url, byte_range, known_size, float(segment.duration or 0)))
|
||||
return out
|
||||
|
||||
|
||||
def extract_ism(track: "Track", session: Union[Session, RnetSession]) -> list[Segment]:
|
||||
data = track.data["ism"]
|
||||
segments: list[str] = data.get("segments") or []
|
||||
manifest = data["manifest"]
|
||||
|
||||
timescale = int(manifest.get("TimeScale") or ISM_DEFAULT_TIMESCALE)
|
||||
duration_ticks = int(manifest.get("Duration") or 0)
|
||||
total_duration = (duration_ticks / timescale) if timescale else 0.0
|
||||
|
||||
return uniform_segments([(url, None) for url in segments], total_duration)
|
||||
|
||||
|
||||
def extract_url(track: "Track", session: Union[Session, RnetSession], *, log: logging.Logger) -> list[Segment]:
|
||||
"""Single-file track: one whole-file URL with the duration from leftover manifest data."""
|
||||
url = track.url if isinstance(track.url, str) else (track.url[0] if track.url else None)
|
||||
if not url:
|
||||
return []
|
||||
|
||||
duration: Optional[float] = None
|
||||
dash_data = track.data.get("dash")
|
||||
if dash_data and dash_data.get("manifest") is not None:
|
||||
from unshackle.core.manifests import DASH
|
||||
|
||||
mpd_duration = dash_data["manifest"].get("mediaPresentationDuration")
|
||||
if mpd_duration:
|
||||
duration = DASH.pt_to_sec(mpd_duration)
|
||||
else:
|
||||
ism_data = track.data.get("ism")
|
||||
if ism_data and ism_data.get("manifest") is not None:
|
||||
manifest = ism_data["manifest"]
|
||||
timescale = int(manifest.get("TimeScale") or ISM_DEFAULT_TIMESCALE)
|
||||
duration_ticks = int(manifest.get("Duration") or 0)
|
||||
if timescale and duration_ticks:
|
||||
duration = duration_ticks / timescale
|
||||
|
||||
if not duration or duration <= 0:
|
||||
# Services like AMZN clear the manifest data after collapsing to a single
|
||||
# file; fall back to reading the duration straight from the remote file.
|
||||
duration = ffprobe_duration(url, session, log=log)
|
||||
|
||||
if not duration or duration <= 0:
|
||||
return []
|
||||
return [Segment(url, None, None, duration)]
|
||||
|
||||
|
||||
def ffprobe_duration(url: str, session: Union[Session, RnetSession], *, log: logging.Logger) -> Optional[float]:
|
||||
"""
|
||||
Read a single-file track's duration (seconds) without a manifest.
|
||||
|
||||
The bundled ffprobe segfaults on network input, so the file's ``moov`` box is
|
||||
fetched over HTTP with the session (keeping the service's proxy/headers) and
|
||||
piped to ffprobe as local bytes. The head of the file is tried first (VOD is
|
||||
usually faststart), then the tail as a fallback for moov-at-end files.
|
||||
"""
|
||||
head = ranged_get(url, session, f"bytes=0-{MOOV_PROBE_BYTES - 1}")
|
||||
duration = probe_bytes_duration(head, log)
|
||||
if duration:
|
||||
return duration
|
||||
|
||||
size = probe_size(Segment(url, None, None, 0.0), session)
|
||||
if size and size > MOOV_PROBE_BYTES:
|
||||
tail = ranged_get(url, session, f"bytes={size - MOOV_PROBE_BYTES}-{size - 1}")
|
||||
duration = probe_bytes_duration(tail, log)
|
||||
return duration
|
||||
|
||||
|
||||
def ranged_get(url: str, session: Union[Session, RnetSession], byte_range: str) -> Optional[bytes]:
|
||||
"""Fetch a byte range, only accepting a real 206 partial response (never a full 200 body)."""
|
||||
try:
|
||||
res = session.get(url, headers={"Range": byte_range}, timeout=PROBE_TIMEOUT)
|
||||
if getattr(res, "status_code", 0) != 206:
|
||||
return None
|
||||
content = getattr(res, "content", None)
|
||||
return content if content else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def probe_bytes_duration(data: Optional[bytes], log: logging.Logger) -> Optional[float]:
|
||||
"""Pipe media bytes to ffprobe and return the format/stream duration in seconds."""
|
||||
if not data:
|
||||
return None
|
||||
ffprobe_bin = str(FFProbe) if FFProbe else "ffprobe"
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[ffprobe_bin, "-v", "error", "-show_entries", "format=duration:stream=duration", "-of", "json", "pipe:"],
|
||||
input=data,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
timeout=60,
|
||||
)
|
||||
info = json.loads(result.stdout or b"{}")
|
||||
candidates = [info.get("format", {}).get("duration")]
|
||||
candidates += [s.get("duration") for s in info.get("streams", [])]
|
||||
for value in candidates:
|
||||
if value:
|
||||
return float(value)
|
||||
log.debug(f"ffprobe found no duration (rc={result.returncode}): {result.stderr.decode(errors='replace')[:160]}")
|
||||
return None
|
||||
except (subprocess.SubprocessError, ValueError, json.JSONDecodeError) as e:
|
||||
log.debug(f"ffprobe duration error: {e}")
|
||||
return None
|
||||
+123
-105
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -470,6 +470,18 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/e8/35/4a113189f7138035a21bd255d30dc7bffc77c942c93b7948d2eac2e22429/ECPy-1.2.5-py3-none-any.whl", hash = "sha256:559c92e42406d9d1a6b2b8fc26e6ad7bc985f33903b72f426a56cb1073a25ce3", size = 43075, upload-time = "2020-10-26T11:56:13.613Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "exceptiongroup"
|
||||
version = "1.3.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/8a/0e/97c33bf5009bdbac74fd2beace167cab3f978feb69cc36f1ef79360d6c4e/exceptiongroup-1.3.1-py3-none-any.whl", hash = "sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598", size = 16740, upload-time = "2025-11-21T23:01:53.443Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastjsonschema"
|
||||
version = "2.19.1"
|
||||
@@ -608,6 +620,15 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/0e/61/66938bbb5fc52dbdf84594873d5b51fb1f7c7794e9c0f5bd885f30bc507b/idna-3.11-py3-none-any.whl", hash = "sha256:771a87f49d9defaf64091e6e6fe9c18d4833f140bd19464795bc32d966ca37ea", size = 71008, upload-time = "2025-10-12T14:55:18.883Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iniconfig"
|
||||
version = "2.3.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "iso8601"
|
||||
version = "2.1.0"
|
||||
@@ -965,6 +986,15 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/88/b2/d0896bdcdc8d28a7fc5717c305f1a861c26e18c05047949fb371034d98bd/nodeenv-1.10.0-py2.py3-none-any.whl", hash = "sha256:5bb13e3eed2923615535339b3c620e76779af4cb4c6a90deccc9e36b274d3827", size = 23438, upload-time = "2025-12-20T14:08:52.782Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "packaging"
|
||||
version = "26.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/d7/f1/e7a6dd94a8d4a5626c03e4e99c87f241ba9e350cd9e6d75123f992427270/packaging-26.2.tar.gz", hash = "sha256:ff452ff5a3e828ce110190feff1178bb1f2ea2281fa2075aadb987c2fb221661", size = 228134, upload-time = "2026-04-24T20:15:23.917Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/df/b2/87e62e8c3e2f4b32e5fe99e0b86d576da1312593b39f47d8ceef365e95ed/packaging-26.2-py3-none-any.whl", hash = "sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e", size = 100195, upload-time = "2026-04-24T20:15:22.081Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pathspec"
|
||||
version = "1.0.4"
|
||||
@@ -983,6 +1013,15 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/63/d7/97f7e3a6abb67d8080dd406fd4df842c2be0efaf712d1c899c32a075027c/platformdirs-4.9.4-py3-none-any.whl", hash = "sha256:68a9a4619a666ea6439f2ff250c12a853cd1cbd5158d258bd824a7df6be2f868", size = 21216, upload-time = "2026-03-05T18:34:12.172Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pluggy"
|
||||
version = "1.6.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pre-commit"
|
||||
version = "4.5.1"
|
||||
@@ -1250,6 +1289,50 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/0b/bb/0dc8b9a38609701ca3f107dc516300b317641bed9b2ef1c964a9ad37ae9e/pysubs2-1.8.1-py3-none-any.whl", hash = "sha256:eb5d8872b7f87208070dd6f0d85fc110b7ad6cc2a7ec422f5b12363e9194e4e4", size = 44269, upload-time = "2026-03-19T17:24:59.953Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pytest"
|
||||
version = "8.4.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "colorama", marker = "sys_platform == 'win32'" },
|
||||
{ name = "exceptiongroup", marker = "python_full_version < '3.11'" },
|
||||
{ name = "iniconfig" },
|
||||
{ name = "packaging" },
|
||||
{ name = "pluggy" },
|
||||
{ name = "pygments" },
|
||||
{ name = "tomli", marker = "python_full_version < '3.11'" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/a3/5c/00a0e072241553e1a7496d638deababa67c5058571567b92a7eaa258397c/pytest-8.4.2.tar.gz", hash = "sha256:86c0d0b93306b961d58d62a4db4879f27fe25513d4b969df351abdddb3c30e01", size = 1519618, upload-time = "2025-09-04T14:34:22.711Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/a8/a4/20da314d277121d6534b3a980b29035dcd51e6744bd79075a6ce8fa4eb8d/pytest-8.4.2-py3-none-any.whl", hash = "sha256:872f880de3fc3a5bdc88a11b39c9710c3497a547cfa9320bc3c5e62fbf272e79", size = 365750, upload-time = "2025-09-04T14:34:20.226Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pytest-aiohttp"
|
||||
version = "1.1.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "aiohttp" },
|
||||
{ name = "pytest" },
|
||||
{ name = "pytest-asyncio" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/72/4b/d326890c153f2c4ce1bf45d07683c08c10a1766058a22934620bc6ac6592/pytest_aiohttp-1.1.0.tar.gz", hash = "sha256:147de8cb164f3fc9d7196967f109ab3c0b93ea3463ab50631e56438eab7b5adc", size = 12842, upload-time = "2025-01-23T12:44:04.465Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/ba/0f/e6af71c02e0f1098eaf7d2dbf3ffdf0a69fc1e0ef174f96af05cef161f1b/pytest_aiohttp-1.1.0-py3-none-any.whl", hash = "sha256:f39a11693a0dce08dd6c542d241e199dd8047a6e6596b2bcfa60d373f143456d", size = 8932, upload-time = "2025-01-23T12:44:03.27Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pytest-asyncio"
|
||||
version = "0.26.0"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "pytest" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/8e/c4/453c52c659521066969523e87d85d54139bbd17b78f09532fb8eb8cdb58e/pytest_asyncio-0.26.0.tar.gz", hash = "sha256:c4df2a697648241ff39e7f0e4a73050b03f123f760673956cf0d72a4990e312f", size = 54156, upload-time = "2025-03-25T06:22:28.883Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/20/7f/338843f449ace853647ace35870874f69a764d251872ed1b4de9f234822c/pytest_asyncio-0.26.0-py3-none-any.whl", hash = "sha256:7b51ed894f4fbea1340262bdae5135797ebbe21d8638978e35d31c6d19f72fb0", size = 19694, upload-time = "2025-03-25T06:22:27.807Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "python-discovery"
|
||||
version = "1.2.0"
|
||||
@@ -1342,6 +1425,20 @@ socks = [
|
||||
{ name = "pysocks" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "responses"
|
||||
version = "0.26.1"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "pyyaml" },
|
||||
{ name = "requests" },
|
||||
{ name = "urllib3" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/c2/58/1fb6de3503428196df78638f991ec8095274f1ee9723e272ee4d9ff0092b/responses-0.26.1.tar.gz", hash = "sha256:2eb3218553cc8f79b57d257bac23af5e1bf381f5b9390b1767816f0843e01dc2", size = 83088, upload-time = "2026-05-21T19:56:39.747Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/3a/31/6a620b4427d546b9e7cca8b3b8c5f0559d9cef2bb9eedcda7f73c1473c19/responses-0.26.1-py3-none-any.whl", hash = "sha256:8aacc4586eb08fb2208ef64a9eb4258d9b0c6e6f4260845f2f018ab847495345", size = 35502, upload-time = "2026-05-21T19:56:38.046Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rfc3339-validator"
|
||||
version = "0.1.4"
|
||||
@@ -1651,7 +1748,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "unshackle"
|
||||
version = "5.0.0"
|
||||
version = "5.1.0"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "aiohttp" },
|
||||
@@ -1709,6 +1806,13 @@ dev = [
|
||||
{ name = "types-requests" },
|
||||
{ name = "virtualenv" },
|
||||
]
|
||||
test = [
|
||||
{ name = "pytest" },
|
||||
{ name = "pytest-aiohttp" },
|
||||
{ name = "pytest-asyncio" },
|
||||
{ name = "pyyaml" },
|
||||
{ name = "responses" },
|
||||
]
|
||||
|
||||
[package.metadata]
|
||||
requires-dist = [
|
||||
@@ -1767,6 +1871,13 @@ dev = [
|
||||
{ name = "types-requests", specifier = ">=2.31.0.20240406,<3" },
|
||||
{ name = "virtualenv", specifier = ">=20.36.1,<22" },
|
||||
]
|
||||
test = [
|
||||
{ name = "pytest", specifier = ">=8.3.0,<9" },
|
||||
{ name = "pytest-aiohttp", specifier = ">=1.0.5,<2" },
|
||||
{ name = "pytest-asyncio", specifier = ">=0.24.0,<1" },
|
||||
{ name = "pyyaml", specifier = ">=6.0.1,<7" },
|
||||
{ name = "responses", specifier = ">=0.25.0,<1" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "urllib3"
|
||||
|
||||
Reference in New Issue
Block a user