mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-05 23:45:07 +00:00
Compare commits
18
Commits
65ceb4ae51
...
4.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
79e8184474 | ||
|
|
178eed9236 | ||
|
|
63d2ba60c4 | ||
|
|
f46aa9d8c8 | ||
|
|
b1447eb14b | ||
|
|
e02aa66843 | ||
|
|
c82bb5fe34 | ||
|
|
ec2ecfe7b4 | ||
|
|
15acaea208 | ||
|
|
def18a4c44 | ||
|
|
7dd6323be5 | ||
|
|
d68bb28a66 | ||
|
|
d1e6d0812c | ||
|
|
2f7a3d6d1d | ||
|
|
572a894620 | ||
|
|
5bd03c67cf | ||
|
|
d8a362c853 | ||
|
|
08269bef60 |
@@ -0,0 +1,91 @@
|
|||||||
|
name: Release
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
paths:
|
||||||
|
- "pyproject.toml"
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
check-version:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
outputs:
|
||||||
|
should_release: ${{ steps.version_check.outputs.should_release }}
|
||||||
|
new_version: ${{ steps.version_check.outputs.new_version }}
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Check for major/minor version bump
|
||||||
|
id: version_check
|
||||||
|
run: |
|
||||||
|
NEW_VERSION=$(grep -m1 '^version' pyproject.toml | sed 's/version = "\(.*\)"/\1/')
|
||||||
|
echo "Detected version in pyproject.toml: $NEW_VERSION"
|
||||||
|
|
||||||
|
LATEST_TAG=$(git tag --list | grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -1)
|
||||||
|
echo "Latest git tag: $LATEST_TAG"
|
||||||
|
|
||||||
|
if [ -z "$LATEST_TAG" ]; then
|
||||||
|
echo "No previous tag found, treating as new release"
|
||||||
|
echo "should_release=true" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "new_version=$NEW_VERSION" >> "$GITHUB_OUTPUT"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
OLD_MAJOR=$(echo "$LATEST_TAG" | cut -d. -f1)
|
||||||
|
OLD_MINOR=$(echo "$LATEST_TAG" | cut -d. -f2)
|
||||||
|
NEW_MAJOR=$(echo "$NEW_VERSION" | cut -d. -f1)
|
||||||
|
NEW_MINOR=$(echo "$NEW_VERSION" | cut -d. -f2)
|
||||||
|
|
||||||
|
if [ "$NEW_MAJOR" -gt "$OLD_MAJOR" ] || [ "$NEW_MINOR" -gt "$OLD_MINOR" ]; then
|
||||||
|
echo "Major or minor version bump detected: $LATEST_TAG -> $NEW_VERSION"
|
||||||
|
echo "should_release=true" >> "$GITHUB_OUTPUT"
|
||||||
|
else
|
||||||
|
echo "Patch-only change ($LATEST_TAG -> $NEW_VERSION), skipping release"
|
||||||
|
echo "should_release=false" >> "$GITHUB_OUTPUT"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "new_version=$NEW_VERSION" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
release:
|
||||||
|
needs: check-version
|
||||||
|
if: needs.check-version.outputs.should_release == 'true'
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Install uv
|
||||||
|
uses: astral-sh/setup-uv@v4
|
||||||
|
|
||||||
|
- name: Set up Python
|
||||||
|
run: uv python install 3.12
|
||||||
|
|
||||||
|
- name: Install dependencies and build
|
||||||
|
run: |
|
||||||
|
uv sync
|
||||||
|
uv build
|
||||||
|
|
||||||
|
- name: Extract changelog for release
|
||||||
|
id: changelog
|
||||||
|
run: |
|
||||||
|
VERSION=${{ needs.check-version.outputs.new_version }}
|
||||||
|
# Extract the section for this version from CHANGELOG.md
|
||||||
|
awk "/^## \[$VERSION\]/{found=1; next} /^## \[/{if(found) exit} found{print}" CHANGELOG.md > release_notes.md
|
||||||
|
echo "Extracted release notes:"
|
||||||
|
cat release_notes.md
|
||||||
|
|
||||||
|
- name: Create GitHub Release
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
run: |
|
||||||
|
VERSION=${{ needs.check-version.outputs.new_version }}
|
||||||
|
gh release create "$VERSION" \
|
||||||
|
--title "$VERSION" \
|
||||||
|
--notes-file release_notes.md \
|
||||||
|
dist/unshackle-${VERSION}-py3-none-any.whl \
|
||||||
|
dist/unshackle-${VERSION}.tar.gz
|
||||||
+13
-5
@@ -6,7 +6,7 @@ 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).
|
This changelog is automatically generated using [git-cliff](https://git-cliff.org).
|
||||||
|
|
||||||
## [Unreleased]
|
## [4.0.0] - 2026-03-17
|
||||||
|
|
||||||
### Features
|
### Features
|
||||||
|
|
||||||
@@ -19,6 +19,11 @@ This changelog is automatically generated using [git-cliff](https://git-cliff.or
|
|||||||
- *tracks*: Add edition tags to output filenames
|
- *tracks*: Add edition tags to output filenames
|
||||||
- *templates*: [**breaking**] Add customizable output filename templates
|
- *templates*: [**breaking**] Add customizable output filename templates
|
||||||
- *templates*: Add configurable language tagging rule engine
|
- *templates*: Add configurable language tagging rule engine
|
||||||
|
- Update unshackle version to 4.0.0
|
||||||
|
- *dl*: Add --animeapi and --enrich options for anime metadata and tagging
|
||||||
|
- *dl*: Add skip messages for --no-audio and --no-chapters flags
|
||||||
|
- *dl*: Extract closed captions from HLS manifests and improve CC extraction
|
||||||
|
- *dl*: Add --worst flag and SHIELD OkHttp fingerprint preset
|
||||||
|
|
||||||
### Bug Fixes
|
### Bug Fixes
|
||||||
|
|
||||||
@@ -33,6 +38,13 @@ This changelog is automatically generated using [git-cliff](https://git-cliff.or
|
|||||||
- *n_m3u8dl_re*: Disable segment count validation for duration-based DASH
|
- *n_m3u8dl_re*: Disable segment count validation for duration-based DASH
|
||||||
- Correct formatting and add missing newlines in selector and EXAMPLE service
|
- Correct formatting and add missing newlines in selector and EXAMPLE service
|
||||||
- *dependencies*: Update pyplayready version to 0.8.3 and adjust dependencies
|
- *dependencies*: Update pyplayready version to 0.8.3 and adjust dependencies
|
||||||
|
- *drm*: Update PlayReady KID extraction for pyplayready 0.8.3 compatibility
|
||||||
|
- *api*: Resolve Sentinel serialization, missing params, and add search endpoint
|
||||||
|
- *dash*: Pass period_filter to n_m3u8dl_re via filtered MPD file
|
||||||
|
- *title*: Add HDR Vivid Format HDR Tag
|
||||||
|
- *ism*: Prevent duplicate track IDs for audio tracks with same lang/codec/bitrate
|
||||||
|
- *aria2c*: Correct progress bar tracking for HLS downloads
|
||||||
|
- *dl*: Filter CC subtitle languages with --s-lang and extract all manifest CCs
|
||||||
|
|
||||||
### Documentation
|
### Documentation
|
||||||
|
|
||||||
@@ -45,10 +57,6 @@ This changelog is automatically generated using [git-cliff](https://git-cliff.or
|
|||||||
- *example*: Migrate EXAMPLE service to track_request pattern
|
- *example*: Migrate EXAMPLE service to track_request pattern
|
||||||
- *providers*: Extract metadata providers into modular system
|
- *providers*: Extract metadata providers into modular system
|
||||||
|
|
||||||
### Maintenance
|
|
||||||
|
|
||||||
- *changelog*: Update changelog for upcoming release and reorganize sections
|
|
||||||
|
|
||||||
## [3.0.0] - 2026-02-15
|
## [3.0.0] - 2026-02-15
|
||||||
|
|
||||||
### Features
|
### Features
|
||||||
|
|||||||
+35
-4
@@ -4,11 +4,34 @@ This document covers advanced features, debugging, and system-level configuratio
|
|||||||
|
|
||||||
## serve (dict)
|
## serve (dict)
|
||||||
|
|
||||||
Configuration data for pywidevine's serve functionality run through unshackle.
|
Configuration for the integrated server that provides CDM endpoints (Widevine/PlayReady) and a REST API for remote downloading.
|
||||||
This effectively allows you to run `unshackle serve` to start serving pywidevine Serve-compliant CDMs right from your
|
|
||||||
local widevine device files.
|
|
||||||
|
|
||||||
- `api_secret` - Secret key for REST API authentication. When set, enables the REST API server alongside the CDM serve functionality. This key is required for authenticating API requests.
|
Start the server with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
unshackle serve # Default: localhost:8786
|
||||||
|
unshackle serve -h 0.0.0.0 -p 8888 # Listen on all interfaces
|
||||||
|
unshackle serve --no-key # Disable authentication
|
||||||
|
unshackle serve --api-only # REST API only, no CDM endpoints
|
||||||
|
```
|
||||||
|
|
||||||
|
### CLI Options
|
||||||
|
|
||||||
|
| Option | Default | Description |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `-h, --host` | `127.0.0.1` | Host to serve from |
|
||||||
|
| `-p, --port` | `8786` | Port to serve from |
|
||||||
|
| `--caddy` | `false` | Also serve with Caddy reverse-proxy for HTTPS |
|
||||||
|
| `--api-only` | `false` | Serve only the REST API, disable CDM endpoints |
|
||||||
|
| `--no-widevine` | `false` | Disable Widevine CDM endpoints |
|
||||||
|
| `--no-playready` | `false` | Disable PlayReady CDM endpoints |
|
||||||
|
| `--no-key` | `false` | Disable API key authentication (allows all requests) |
|
||||||
|
| `--debug-api` | `false` | Include tracebacks and stderr in API error responses |
|
||||||
|
| `--debug` | `false` | Enable debug logging for API operations |
|
||||||
|
|
||||||
|
### Configuration
|
||||||
|
|
||||||
|
- `api_secret` - Secret key for REST API authentication. Required unless `--no-key` is used. All API requests must include this key via the `X-API-Key` header or `api_key` query parameter.
|
||||||
- `devices` - List of Widevine device files (.wvd). If not specified, auto-populated from the WVDs directory.
|
- `devices` - List of Widevine device files (.wvd). If not specified, auto-populated from the WVDs directory.
|
||||||
- `playready_devices` - List of PlayReady device files (.prd). If not specified, auto-populated from the PRDs directory.
|
- `playready_devices` - List of PlayReady device files (.prd). If not specified, auto-populated from the PRDs directory.
|
||||||
- `users` - Dictionary mapping user secret keys to their access configuration:
|
- `users` - Dictionary mapping user secret keys to their access configuration:
|
||||||
@@ -42,6 +65,14 @@ serve:
|
|||||||
# - 'C:\Users\john\Devices\test_devices_001.wvd'
|
# - 'C:\Users\john\Devices\test_devices_001.wvd'
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### REST API
|
||||||
|
|
||||||
|
When the server is running, interactive API documentation is available at:
|
||||||
|
|
||||||
|
- **Swagger UI**: `http://localhost:8786/api/docs/`
|
||||||
|
|
||||||
|
See [API.md](API.md) for full REST API documentation with endpoints, parameters, and examples.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## debug (bool)
|
## debug (bool)
|
||||||
|
|||||||
+387
@@ -0,0 +1,387 @@
|
|||||||
|
# REST API Documentation
|
||||||
|
|
||||||
|
The unshackle REST API allows you to control downloads, search services, and manage jobs remotely. Start the server with `unshackle serve` and access the interactive Swagger UI at `http://localhost:8786/api/docs/`.
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Start the server (no authentication)
|
||||||
|
unshackle serve --no-key
|
||||||
|
|
||||||
|
# Start with authentication
|
||||||
|
unshackle serve # Requires api_secret in unshackle.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
## Authentication
|
||||||
|
|
||||||
|
When `api_secret` is set in `unshackle.yaml`, all API requests require authentication via:
|
||||||
|
|
||||||
|
- **Header**: `X-API-Key: your-secret-key-here`
|
||||||
|
- **Query parameter**: `?api_key=your-secret-key-here`
|
||||||
|
|
||||||
|
Use `--no-key` to disable authentication entirely (not recommended for public-facing servers).
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# unshackle.yaml
|
||||||
|
serve:
|
||||||
|
api_secret: "your-secret-key-here"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Endpoints
|
||||||
|
|
||||||
|
### GET /api/health
|
||||||
|
|
||||||
|
Health check with version and update information.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl http://localhost:8786/api/health
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "ok",
|
||||||
|
"version": "4.0.0",
|
||||||
|
"update_check": {
|
||||||
|
"update_available": false,
|
||||||
|
"current_version": "4.0.0",
|
||||||
|
"latest_version": null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### GET /api/services
|
||||||
|
|
||||||
|
List all available streaming services.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl http://localhost:8786/api/services
|
||||||
|
```
|
||||||
|
|
||||||
|
Returns an array of services with `tag`, `aliases`, `geofence`, `title_regex`, `url`, and `help` text.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### POST /api/search
|
||||||
|
|
||||||
|
Search for titles from a streaming service.
|
||||||
|
|
||||||
|
**Required parameters:**
|
||||||
|
| Parameter | Type | Description |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `service` | string | Service tag (e.g., `NF`, `AMZN`, `ATV`) |
|
||||||
|
| `query` | string | Search query |
|
||||||
|
|
||||||
|
**Optional parameters:**
|
||||||
|
| Parameter | Type | Default | Description |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `profile` | string | `null` | Profile for credentials/cookies |
|
||||||
|
| `proxy` | string | `null` | Proxy URI or country code |
|
||||||
|
| `no_proxy` | boolean | `false` | Disable all proxy use |
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST http://localhost:8786/api/search \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"service": "ATV", "query": "hijack"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"results": [
|
||||||
|
{
|
||||||
|
"id": "umc.cmc.1dg08zn0g3zx52hs8npoj5qe3",
|
||||||
|
"title": "Hijack",
|
||||||
|
"description": null,
|
||||||
|
"label": "TV Show",
|
||||||
|
"url": "https://tv.apple.com/us/show/hijack/umc.cmc.1dg08zn0g3zx52hs8npoj5qe3"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"count": 1
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### POST /api/list-titles
|
||||||
|
|
||||||
|
Get available titles (seasons/episodes/movies) for a service and title ID.
|
||||||
|
|
||||||
|
**Required parameters:**
|
||||||
|
| Parameter | Type | Description |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `service` | string | Service tag |
|
||||||
|
| `title_id` | string | Title ID or URL |
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST http://localhost:8786/api/list-titles \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"service": "ATV", "title_id": "umc.cmc.1dg08zn0g3zx52hs8npoj5qe3"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"titles": [
|
||||||
|
{
|
||||||
|
"type": "episode",
|
||||||
|
"name": "Final Call",
|
||||||
|
"series_title": "Hijack",
|
||||||
|
"season": 1,
|
||||||
|
"number": 1,
|
||||||
|
"year": 2023,
|
||||||
|
"id": "umc.cmc.4levibvvz01hl4zsm0jdk5v2p"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### POST /api/list-tracks
|
||||||
|
|
||||||
|
Get video, audio, and subtitle tracks for a title.
|
||||||
|
|
||||||
|
**Required parameters:**
|
||||||
|
| Parameter | Type | Description |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `service` | string | Service tag |
|
||||||
|
| `title_id` | string | Title ID or URL |
|
||||||
|
|
||||||
|
**Optional parameters:**
|
||||||
|
| Parameter | Type | Default | Description |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `wanted` | array | all | Episode filter (e.g., `["S01E01"]`) |
|
||||||
|
| `profile` | string | `null` | Profile for credentials/cookies |
|
||||||
|
| `proxy` | string | `null` | Proxy URI or country code |
|
||||||
|
| `no_proxy` | boolean | `false` | Disable all proxy use |
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST http://localhost:8786/api/list-tracks \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{
|
||||||
|
"service": "ATV",
|
||||||
|
"title_id": "umc.cmc.1dg08zn0g3zx52hs8npoj5qe3",
|
||||||
|
"wanted": ["S01E01"]
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
Returns video, audio, and subtitle tracks with codec, bitrate, resolution, language, and DRM information.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### POST /api/download
|
||||||
|
|
||||||
|
Start a download job. Returns immediately with a job ID (HTTP 202).
|
||||||
|
|
||||||
|
**Required parameters:**
|
||||||
|
| Parameter | Type | Description |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `service` | string | Service tag |
|
||||||
|
| `title_id` | string | Title ID or URL |
|
||||||
|
|
||||||
|
**Quality and codec parameters:**
|
||||||
|
| Parameter | Type | Default | Description |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `quality` | array[int] | best | Resolution(s) (e.g., `[1080, 2160]`) |
|
||||||
|
| `vcodec` | string or array | any | Video codec(s): `H264`, `H265`/`HEVC`, `VP9`, `AV1`, `VC1` |
|
||||||
|
| `acodec` | string or array | any | Audio codec(s): `AAC`, `AC3`, `EC3`, `AC4`, `OPUS`, `FLAC`, `ALAC`, `DTS` |
|
||||||
|
| `vbitrate` | int | highest | Video bitrate in kbps |
|
||||||
|
| `abitrate` | int | highest | Audio bitrate in kbps |
|
||||||
|
| `range` | array[string] | `["SDR"]` | Color range(s): `SDR`, `HDR10`, `HDR10+`, `HLG`, `DV`, `HYBRID` |
|
||||||
|
| `channels` | float | any | Audio channels (e.g., `5.1`, `7.1`) |
|
||||||
|
| `no_atmos` | boolean | `false` | Exclude Dolby Atmos tracks |
|
||||||
|
| `split_audio` | boolean | `null` | Create separate output per audio codec |
|
||||||
|
| `sub_format` | string | `null` | Output subtitle format: `SRT`, `VTT`, `ASS`, `SSA`, `TTML` |
|
||||||
|
|
||||||
|
**Episode selection:**
|
||||||
|
| Parameter | Type | Default | Description |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `wanted` | array[string] | all | Episodes (e.g., `["S01E01", "S01E02-S01E05"]`) |
|
||||||
|
| `latest_episode` | boolean | `false` | Download only the most recent episode |
|
||||||
|
|
||||||
|
**Language parameters:**
|
||||||
|
| Parameter | Type | Default | Description |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `lang` | array[string] | `["orig"]` | Language for video and audio (`orig` = original) |
|
||||||
|
| `v_lang` | array[string] | `[]` | Language override for video tracks only |
|
||||||
|
| `a_lang` | array[string] | `[]` | Language override for audio tracks only |
|
||||||
|
| `s_lang` | array[string] | `["all"]` | Language for subtitles |
|
||||||
|
| `require_subs` | array[string] | `[]` | Required subtitle languages (skip if missing) |
|
||||||
|
| `forced_subs` | boolean | `false` | Include forced subtitle tracks |
|
||||||
|
| `exact_lang` | boolean | `false` | Exact language matching (no variants) |
|
||||||
|
|
||||||
|
**Track selection:**
|
||||||
|
| Parameter | Type | Default | Description |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `video_only` | boolean | `false` | Only download video tracks |
|
||||||
|
| `audio_only` | boolean | `false` | Only download audio tracks |
|
||||||
|
| `subs_only` | boolean | `false` | Only download subtitle tracks |
|
||||||
|
| `chapters_only` | boolean | `false` | Only download chapters |
|
||||||
|
| `no_video` | boolean | `false` | Skip video tracks |
|
||||||
|
| `no_audio` | boolean | `false` | Skip audio tracks |
|
||||||
|
| `no_subs` | boolean | `false` | Skip subtitle tracks |
|
||||||
|
| `no_chapters` | boolean | `false` | Skip chapters |
|
||||||
|
| `audio_description` | boolean | `false` | Include audio description tracks |
|
||||||
|
|
||||||
|
**Output and tagging:**
|
||||||
|
| Parameter | Type | Default | Description |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `tag` | string | `null` | Override group tag |
|
||||||
|
| `repack` | boolean | `false` | Add REPACK tag to filename |
|
||||||
|
| `tmdb_id` | int | `null` | Use specific TMDB ID for tagging |
|
||||||
|
| `imdb_id` | string | `null` | Use specific IMDB ID (e.g., `tt1375666`) |
|
||||||
|
| `animeapi_id` | string | `null` | Anime database ID via AnimeAPI (e.g., `mal:12345`) |
|
||||||
|
| `enrich` | boolean | `false` | Override show title and year from external source |
|
||||||
|
| `no_folder` | boolean | `false` | Disable folder creation for TV shows |
|
||||||
|
| `no_source` | boolean | `false` | Remove source tag from filename |
|
||||||
|
| `no_mux` | boolean | `false` | Do not mux tracks into container |
|
||||||
|
| `output_dir` | string | `null` | Override output directory |
|
||||||
|
|
||||||
|
**Download behavior:**
|
||||||
|
| Parameter | Type | Default | Description |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `profile` | string | `null` | Profile for credentials/cookies |
|
||||||
|
| `proxy` | string | `null` | Proxy URI or country code |
|
||||||
|
| `no_proxy` | boolean | `false` | Disable all proxy use |
|
||||||
|
| `workers` | int | `null` | Max threads per track download |
|
||||||
|
| `downloads` | int | `1` | Concurrent track downloads |
|
||||||
|
| `slow` | boolean | `false` | Add 60-120s delay between titles |
|
||||||
|
| `best_available` | boolean | `false` | Continue if requested quality unavailable |
|
||||||
|
| `skip_dl` | boolean | `false` | Skip download, only get decryption keys |
|
||||||
|
| `export` | string | `null` | Export keys to JSON file path |
|
||||||
|
| `cdm_only` | boolean | `null` | Only use CDM (`true`) or only vaults (`false`) |
|
||||||
|
| `no_cache` | boolean | `false` | Bypass title cache |
|
||||||
|
| `reset_cache` | boolean | `false` | Clear title cache before fetching |
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X POST http://localhost:8786/api/download \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{
|
||||||
|
"service": "ATV",
|
||||||
|
"title_id": "umc.cmc.1dg08zn0g3zx52hs8npoj5qe3",
|
||||||
|
"wanted": ["S01E01"],
|
||||||
|
"quality": [1080, 2160],
|
||||||
|
"vcodec": ["H265"],
|
||||||
|
"acodec": ["AAC", "EC3"],
|
||||||
|
"range": ["HDR10", "SDR"],
|
||||||
|
"split_audio": true,
|
||||||
|
"lang": ["en"]
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"job_id": "504db959-80b0-446c-a764-7924b761d613",
|
||||||
|
"status": "queued",
|
||||||
|
"created_time": "2026-02-27T18:00:00.000000"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### GET /api/download/jobs
|
||||||
|
|
||||||
|
List all download jobs with optional filtering and sorting.
|
||||||
|
|
||||||
|
**Query parameters:**
|
||||||
|
| Parameter | Type | Default | Description |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `status` | string | all | Filter by status: `queued`, `downloading`, `completed`, `failed`, `cancelled` |
|
||||||
|
| `service` | string | all | Filter by service tag |
|
||||||
|
| `sort_by` | string | `created_time` | Sort field: `created_time`, `status`, `service` |
|
||||||
|
| `sort_order` | string | `desc` | Sort order: `asc`, `desc` |
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# List all jobs
|
||||||
|
curl http://localhost:8786/api/download/jobs
|
||||||
|
|
||||||
|
# Filter by status
|
||||||
|
curl "http://localhost:8786/api/download/jobs?status=completed"
|
||||||
|
|
||||||
|
# Filter by service
|
||||||
|
curl "http://localhost:8786/api/download/jobs?service=ATV"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### GET /api/download/jobs/{job_id}
|
||||||
|
|
||||||
|
Get detailed information about a specific download job including progress, parameters, and error details.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl http://localhost:8786/api/download/jobs/504db959-80b0-446c-a764-7924b761d613
|
||||||
|
```
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"job_id": "504db959-80b0-446c-a764-7924b761d613",
|
||||||
|
"status": "completed",
|
||||||
|
"created_time": "2026-02-27T18:00:00.000000",
|
||||||
|
"service": "ATV",
|
||||||
|
"title_id": "umc.cmc.1dg08zn0g3zx52hs8npoj5qe3",
|
||||||
|
"progress": 100.0,
|
||||||
|
"parameters": { ... },
|
||||||
|
"started_time": "2026-02-27T18:00:01.000000",
|
||||||
|
"completed_time": "2026-02-27T18:00:15.000000",
|
||||||
|
"output_files": [],
|
||||||
|
"error_message": null,
|
||||||
|
"error_details": null
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### DELETE /api/download/jobs/{job_id}
|
||||||
|
|
||||||
|
Cancel a queued or running download job.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -X DELETE http://localhost:8786/api/download/jobs/504db959-80b0-446c-a764-7924b761d613
|
||||||
|
```
|
||||||
|
|
||||||
|
Returns confirmation on success, or an error if the job has already completed or been cancelled.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Error Responses
|
||||||
|
|
||||||
|
All endpoints return consistent error responses:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"status": "error",
|
||||||
|
"error_code": "INVALID_PARAMETERS",
|
||||||
|
"message": "Invalid vcodec: XYZ. Must be one of: H264, H265, VP9, AV1, VC1, VP8",
|
||||||
|
"timestamp": "2026-02-27T18:00:00.000000+00:00",
|
||||||
|
"details": { ... }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Common error codes:
|
||||||
|
- `INVALID_INPUT` - Malformed request body
|
||||||
|
- `INVALID_PARAMETERS` - Invalid parameter values
|
||||||
|
- `MISSING_SERVICE` - Service tag not provided
|
||||||
|
- `INVALID_SERVICE` - Service not found
|
||||||
|
- `SERVICE_ERROR` - Service initialization or runtime error
|
||||||
|
- `AUTH_FAILED` - Authentication failure
|
||||||
|
- `NOT_FOUND` - Job or resource not found
|
||||||
|
- `INTERNAL_ERROR` - Unexpected server error
|
||||||
|
|
||||||
|
When `--debug-api` is enabled, error responses include additional `debug_info` with tracebacks and stderr output.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Download Job Lifecycle
|
||||||
|
|
||||||
|
```
|
||||||
|
queued -> downloading -> completed
|
||||||
|
\-> failed
|
||||||
|
queued -> cancelled
|
||||||
|
downloading -> cancelled
|
||||||
|
```
|
||||||
|
|
||||||
|
Jobs are retained for 24 hours after completion. The server supports up to 2 concurrent downloads by default.
|
||||||
@@ -67,6 +67,7 @@ dependencies = [
|
|||||||
"pycountry>=24.6.1",
|
"pycountry>=24.6.1",
|
||||||
"language-data>=1.4.0",
|
"language-data>=1.4.0",
|
||||||
"wasmtime>=41.0.0",
|
"wasmtime>=41.0.0",
|
||||||
|
"animeapi-py>=0.6.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[project.urls]
|
[project.urls]
|
||||||
|
|||||||
+194
-119
@@ -25,6 +25,7 @@ import click
|
|||||||
import jsonpickle
|
import jsonpickle
|
||||||
import yaml
|
import yaml
|
||||||
from construct import ConstError
|
from construct import ConstError
|
||||||
|
from langcodes import Language
|
||||||
from pymediainfo import MediaInfo
|
from pymediainfo import MediaInfo
|
||||||
from pyplayready.cdm import Cdm as PlayReadyCdm
|
from pyplayready.cdm import Cdm as PlayReadyCdm
|
||||||
from pyplayready.device import Device as PlayReadyDevice
|
from pyplayready.device import Device as PlayReadyDevice
|
||||||
@@ -61,7 +62,7 @@ from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
|
|||||||
from unshackle.core.tracks.attachment import Attachment
|
from unshackle.core.tracks.attachment import Attachment
|
||||||
from unshackle.core.tracks.hybrid import Hybrid
|
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,
|
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)
|
is_close_match, is_exact_match, suggest_font_packages, time_elapsed_since)
|
||||||
from unshackle.core.utils import tags
|
from unshackle.core.utils import tags
|
||||||
from unshackle.core.utils.click_types import (AUDIO_CODEC_LIST, LANGUAGE_RANGE, QUALITY_LIST, SEASON_RANGE,
|
from unshackle.core.utils.click_types import (AUDIO_CODEC_LIST, LANGUAGE_RANGE, QUALITY_LIST, SEASON_RANGE,
|
||||||
ContextData, MultipleChoice, MultipleVideoCodecChoice,
|
ContextData, MultipleChoice, MultipleVideoCodecChoice,
|
||||||
@@ -416,18 +417,17 @@ class dl:
|
|||||||
help="Use this TMDB ID for tagging instead of automatic lookup.",
|
help="Use this TMDB ID for tagging instead of automatic lookup.",
|
||||||
)
|
)
|
||||||
@click.option(
|
@click.option(
|
||||||
"--tmdb-name",
|
"--animeapi",
|
||||||
"tmdb_name",
|
"animeapi_id",
|
||||||
is_flag=True,
|
type=str,
|
||||||
default=False,
|
default=None,
|
||||||
help="Rename titles using the name returned from TMDB lookup.",
|
help="Anime database ID via AnimeAPI (e.g. mal:12345, anilist:98765). Defaults to MAL if no prefix.",
|
||||||
)
|
)
|
||||||
@click.option(
|
@click.option(
|
||||||
"--tmdb-year",
|
"--enrich",
|
||||||
"tmdb_year",
|
|
||||||
is_flag=True,
|
is_flag=True,
|
||||||
default=False,
|
default=False,
|
||||||
help="Use the release year from TMDB for naming and tagging.",
|
help="Override show title and year from external source. Requires --tmdb, --imdb, or --animeapi.",
|
||||||
)
|
)
|
||||||
@click.option(
|
@click.option(
|
||||||
"--imdb",
|
"--imdb",
|
||||||
@@ -506,6 +506,12 @@ class dl:
|
|||||||
@click.option(
|
@click.option(
|
||||||
"--reset-cache", "reset_cache", is_flag=True, default=False, help="Clear title cache before fetching."
|
"--reset-cache", "reset_cache", is_flag=True, default=False, help="Clear title cache before fetching."
|
||||||
)
|
)
|
||||||
|
@click.option(
|
||||||
|
"--worst",
|
||||||
|
is_flag=True,
|
||||||
|
default=False,
|
||||||
|
help="Select the lowest bitrate track within the specified quality. Requires -q/--quality.",
|
||||||
|
)
|
||||||
@click.option(
|
@click.option(
|
||||||
"--best-available",
|
"--best-available",
|
||||||
"best_available",
|
"best_available",
|
||||||
@@ -528,9 +534,9 @@ class dl:
|
|||||||
repack: bool = False,
|
repack: bool = False,
|
||||||
tag: Optional[str] = None,
|
tag: Optional[str] = None,
|
||||||
tmdb_id: Optional[int] = None,
|
tmdb_id: Optional[int] = None,
|
||||||
tmdb_name: bool = False,
|
|
||||||
tmdb_year: bool = False,
|
|
||||||
imdb_id: Optional[str] = None,
|
imdb_id: Optional[str] = None,
|
||||||
|
animeapi_id: Optional[str] = None,
|
||||||
|
enrich: bool = False,
|
||||||
output_dir: Optional[Path] = None,
|
output_dir: Optional[Path] = None,
|
||||||
*_: Any,
|
*_: Any,
|
||||||
**__: Any,
|
**__: Any,
|
||||||
@@ -575,11 +581,24 @@ class dl:
|
|||||||
|
|
||||||
self.profile = profile
|
self.profile = profile
|
||||||
self.tmdb_id = tmdb_id
|
self.tmdb_id = tmdb_id
|
||||||
self.tmdb_name = tmdb_name
|
|
||||||
self.tmdb_year = tmdb_year
|
|
||||||
self.imdb_id = imdb_id
|
self.imdb_id = imdb_id
|
||||||
|
self.enrich = enrich
|
||||||
|
self.animeapi_title: Optional[str] = None
|
||||||
self.output_dir = output_dir
|
self.output_dir = output_dir
|
||||||
|
|
||||||
|
if animeapi_id:
|
||||||
|
from unshackle.core.utils.animeapi import resolve_animeapi
|
||||||
|
|
||||||
|
anime_title, anime_ids = resolve_animeapi(animeapi_id)
|
||||||
|
self.animeapi_title = anime_title
|
||||||
|
if not self.tmdb_id and anime_ids.tmdb_id:
|
||||||
|
self.tmdb_id = anime_ids.tmdb_id
|
||||||
|
if not self.imdb_id and anime_ids.imdb_id:
|
||||||
|
self.imdb_id = anime_ids.imdb_id
|
||||||
|
|
||||||
|
if self.enrich and not (self.tmdb_id or self.imdb_id or self.animeapi_title):
|
||||||
|
raise click.UsageError("--enrich requires --tmdb, --imdb, or --animeapi to provide a metadata source.")
|
||||||
|
|
||||||
# Initialize debug logger with service name if debug logging is enabled
|
# Initialize debug logger with service name if debug logging is enabled
|
||||||
if config.debug or logging.root.level == logging.DEBUG:
|
if config.debug or logging.root.level == logging.DEBUG:
|
||||||
from collections import defaultdict
|
from collections import defaultdict
|
||||||
@@ -601,14 +620,23 @@ class dl:
|
|||||||
"profile": profile,
|
"profile": profile,
|
||||||
"proxy": proxy,
|
"proxy": proxy,
|
||||||
"tag": tag,
|
"tag": tag,
|
||||||
"tmdb_id": tmdb_id,
|
"tmdb_id": self.tmdb_id,
|
||||||
"tmdb_name": tmdb_name,
|
"imdb_id": self.imdb_id,
|
||||||
"tmdb_year": tmdb_year,
|
"animeapi_id": animeapi_id,
|
||||||
"imdb_id": imdb_id,
|
"enrich": enrich,
|
||||||
"cli_params": {
|
"cli_params": {
|
||||||
k: v
|
k: v
|
||||||
for k, v in ctx.params.items()
|
for k, v in ctx.params.items()
|
||||||
if k not in ["profile", "proxy", "tag", "tmdb_id", "tmdb_name", "tmdb_year", "imdb_id"]
|
if k
|
||||||
|
not in [
|
||||||
|
"profile",
|
||||||
|
"proxy",
|
||||||
|
"tag",
|
||||||
|
"tmdb_id",
|
||||||
|
"imdb_id",
|
||||||
|
"animeapi_id",
|
||||||
|
"enrich",
|
||||||
|
]
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -969,6 +997,7 @@ class dl:
|
|||||||
no_mux: bool,
|
no_mux: bool,
|
||||||
workers: Optional[int],
|
workers: Optional[int],
|
||||||
downloads: int,
|
downloads: int,
|
||||||
|
worst: bool,
|
||||||
best_available: bool,
|
best_available: bool,
|
||||||
split_audio: Optional[bool] = None,
|
split_audio: Optional[bool] = None,
|
||||||
*_: Any,
|
*_: Any,
|
||||||
@@ -994,6 +1023,10 @@ class dl:
|
|||||||
self.log.error("--require-subs and --s-lang cannot be used together")
|
self.log.error("--require-subs and --s-lang cannot be used together")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
|
if worst and not quality:
|
||||||
|
self.log.error("--worst requires -q/--quality to be specified")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
if select_titles and wanted:
|
if select_titles and wanted:
|
||||||
self.log.error("--select-titles and -w/--wanted cannot be used together")
|
self.log.error("--select-titles and -w/--wanted cannot be used together")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
@@ -1089,40 +1122,51 @@ class dl:
|
|||||||
cache_region = service.current_region if hasattr(service, "current_region") else None
|
cache_region = service.current_region if hasattr(service, "current_region") else None
|
||||||
cache_account_hash = get_account_hash(service.credential) if hasattr(service, "credential") else None
|
cache_account_hash = get_account_hash(service.credential) if hasattr(service, "credential") else None
|
||||||
|
|
||||||
if (self.tmdb_year or self.tmdb_name) and self.tmdb_id:
|
if self.enrich:
|
||||||
sample_title = titles[0] if hasattr(titles, "__getitem__") else titles
|
sample_title = titles[0] if hasattr(titles, "__getitem__") else titles
|
||||||
kind = "tv" if isinstance(sample_title, Episode) else "movie"
|
kind = "tv" if isinstance(sample_title, Episode) else "movie"
|
||||||
|
|
||||||
tmdb_year_val = None
|
enrich_title: Optional[str] = None
|
||||||
tmdb_name_val = None
|
enrich_year: Optional[int] = None
|
||||||
|
|
||||||
if self.tmdb_year:
|
if self.animeapi_title:
|
||||||
tmdb_year_val = providers.get_year_by_id(
|
enrich_title = self.animeapi_title
|
||||||
|
|
||||||
|
if self.tmdb_id:
|
||||||
|
if not enrich_title:
|
||||||
|
enrich_title = providers.get_title_by_id(
|
||||||
|
self.tmdb_id, kind, title_cacher, cache_title_id, cache_region, cache_account_hash
|
||||||
|
)
|
||||||
|
enrich_year = providers.get_year_by_id(
|
||||||
self.tmdb_id, kind, title_cacher, cache_title_id, cache_region, cache_account_hash
|
self.tmdb_id, kind, title_cacher, cache_title_id, cache_region, cache_account_hash
|
||||||
)
|
)
|
||||||
|
elif self.imdb_id:
|
||||||
|
imdbapi = providers.get_provider("imdbapi")
|
||||||
|
if imdbapi:
|
||||||
|
imdb_result = imdbapi.get_by_id(self.imdb_id, kind)
|
||||||
|
if imdb_result:
|
||||||
|
if not enrich_title:
|
||||||
|
enrich_title = imdb_result.title
|
||||||
|
enrich_year = imdb_result.year
|
||||||
|
|
||||||
if self.tmdb_name:
|
if enrich_title or enrich_year:
|
||||||
tmdb_name_val = providers.get_title_by_id(
|
if isinstance(titles, (Series, Movies)):
|
||||||
self.tmdb_id, kind, title_cacher, cache_title_id, cache_region, cache_account_hash
|
for t in titles:
|
||||||
)
|
if enrich_title:
|
||||||
|
if isinstance(t, Episode):
|
||||||
if isinstance(titles, (Series, Movies)):
|
t.title = enrich_title
|
||||||
for t in titles:
|
else:
|
||||||
if tmdb_year_val:
|
t.name = enrich_title
|
||||||
t.year = tmdb_year_val
|
if enrich_year and not t.year:
|
||||||
if tmdb_name_val:
|
t.year = enrich_year
|
||||||
if isinstance(t, Episode):
|
else:
|
||||||
t.title = tmdb_name_val
|
if enrich_title:
|
||||||
|
if isinstance(titles, Episode):
|
||||||
|
titles.title = enrich_title
|
||||||
else:
|
else:
|
||||||
t.name = tmdb_name_val
|
titles.name = enrich_title
|
||||||
else:
|
if enrich_year and not titles.year:
|
||||||
if tmdb_year_val:
|
titles.year = enrich_year
|
||||||
titles.year = tmdb_year_val
|
|
||||||
if tmdb_name_val:
|
|
||||||
if isinstance(titles, Episode):
|
|
||||||
titles.title = tmdb_name_val
|
|
||||||
else:
|
|
||||||
titles.name = tmdb_name_val
|
|
||||||
|
|
||||||
console.print(Padding(Rule(f"[rule.text]{titles.__class__.__name__}: {titles}"), (1, 2)))
|
console.print(Padding(Rule(f"[rule.text]{titles.__class__.__name__}: {titles}"), (1, 2)))
|
||||||
|
|
||||||
@@ -1181,7 +1225,7 @@ class dl:
|
|||||||
page_size=8,
|
page_size=8,
|
||||||
return_indices=True,
|
return_indices=True,
|
||||||
dependencies=dependencies,
|
dependencies=dependencies,
|
||||||
collapse_on_start=multiple_seasons
|
collapse_on_start=multiple_seasons,
|
||||||
)
|
)
|
||||||
|
|
||||||
if not selected_ui_idx:
|
if not selected_ui_idx:
|
||||||
@@ -1309,6 +1353,15 @@ class dl:
|
|||||||
v_lang = None
|
v_lang = None
|
||||||
title.tracks.videos = []
|
title.tracks.videos = []
|
||||||
|
|
||||||
|
if no_audio:
|
||||||
|
console.log("Skipped audio as --no-audio was used...")
|
||||||
|
a_lang = None
|
||||||
|
title.tracks.audio = []
|
||||||
|
|
||||||
|
if no_chapters:
|
||||||
|
console.log("Skipped chapters as --no-chapters was used...")
|
||||||
|
title.tracks.chapters = []
|
||||||
|
|
||||||
with console.status("Getting tracks...", spinner="dots"):
|
with console.status("Getting tracks...", spinner="dots"):
|
||||||
try:
|
try:
|
||||||
title.tracks.add(service.get_tracks(title), warn_only=True)
|
title.tracks.add(service.get_tracks(title), warn_only=True)
|
||||||
@@ -1567,20 +1620,18 @@ class dl:
|
|||||||
for resolution, color_range, codec in product(
|
for resolution, color_range, codec in product(
|
||||||
quality or [None], non_hybrid_ranges, vcodec or [None]
|
quality or [None], non_hybrid_ranges, vcodec or [None]
|
||||||
):
|
):
|
||||||
match = next(
|
candidates = [
|
||||||
(
|
t
|
||||||
t
|
for t in non_hybrid_tracks
|
||||||
for t in non_hybrid_tracks
|
if (
|
||||||
if (
|
not resolution
|
||||||
not resolution
|
or t.height == resolution
|
||||||
or t.height == resolution
|
or int(t.width * (9 / 16)) == resolution
|
||||||
or int(t.width * (9 / 16)) == resolution
|
)
|
||||||
)
|
and (not color_range or t.range == color_range)
|
||||||
and (not color_range or t.range == color_range)
|
and (not codec or t.codec == codec)
|
||||||
and (not codec or t.codec == codec)
|
]
|
||||||
),
|
match = candidates[-1] if worst and candidates else next(iter(candidates), None)
|
||||||
None,
|
|
||||||
)
|
|
||||||
if match and match not in non_hybrid_selected:
|
if match and match not in non_hybrid_selected:
|
||||||
non_hybrid_selected.append(match)
|
non_hybrid_selected.append(match)
|
||||||
|
|
||||||
@@ -1590,20 +1641,18 @@ class dl:
|
|||||||
for resolution, color_range, codec in product(
|
for resolution, color_range, codec in product(
|
||||||
quality or [None], range_ or [None], vcodec or [None]
|
quality or [None], range_ or [None], vcodec or [None]
|
||||||
):
|
):
|
||||||
match = next(
|
candidates = [
|
||||||
(
|
t
|
||||||
t
|
for t in title.tracks.videos
|
||||||
for t in title.tracks.videos
|
if (
|
||||||
if (
|
not resolution
|
||||||
not resolution
|
or t.height == resolution
|
||||||
or t.height == resolution
|
or int(t.width * (9 / 16)) == resolution
|
||||||
or int(t.width * (9 / 16)) == resolution
|
)
|
||||||
)
|
and (not color_range or t.range == color_range)
|
||||||
and (not color_range or t.range == color_range)
|
and (not codec or t.codec == codec)
|
||||||
and (not codec or t.codec == codec)
|
]
|
||||||
),
|
match = candidates[-1] if worst and candidates else next(iter(candidates), None)
|
||||||
None,
|
|
||||||
)
|
|
||||||
if match and match not in selected_videos:
|
if match and match not in selected_videos:
|
||||||
selected_videos.append(match)
|
selected_videos.append(match)
|
||||||
title.tracks.videos = selected_videos
|
title.tracks.videos = selected_videos
|
||||||
@@ -1663,8 +1712,6 @@ class dl:
|
|||||||
f"Required languages found ({', '.join(require_subs)}), downloading all available subtitles"
|
f"Required languages found ({', '.join(require_subs)}), downloading all available subtitles"
|
||||||
)
|
)
|
||||||
elif s_lang and "all" not in s_lang:
|
elif s_lang and "all" not in s_lang:
|
||||||
from unshackle.core.utilities import is_exact_match
|
|
||||||
|
|
||||||
match_func = is_exact_match if exact_lang else is_close_match
|
match_func = is_exact_match if exact_lang else is_close_match
|
||||||
|
|
||||||
missing_langs = [
|
missing_langs = [
|
||||||
@@ -1984,49 +2031,6 @@ class dl:
|
|||||||
dl_time = time_elapsed_since(dl_start_time)
|
dl_time = time_elapsed_since(dl_start_time)
|
||||||
console.print(Padding(f"Track downloads finished in [progress.elapsed]{dl_time}[/]", (0, 5)))
|
console.print(Padding(f"Track downloads finished in [progress.elapsed]{dl_time}[/]", (0, 5)))
|
||||||
|
|
||||||
video_track_n = 0
|
|
||||||
|
|
||||||
while (
|
|
||||||
not title.tracks.subtitles
|
|
||||||
and not no_subs
|
|
||||||
and not (hasattr(service, "NO_SUBTITLES") and service.NO_SUBTITLES)
|
|
||||||
and not video_only
|
|
||||||
and not no_video
|
|
||||||
and len(title.tracks.videos) > video_track_n
|
|
||||||
and any(
|
|
||||||
x.get("codec_name", "").startswith("eia_")
|
|
||||||
for x in ffprobe(title.tracks.videos[video_track_n].path).get("streams", [])
|
|
||||||
)
|
|
||||||
):
|
|
||||||
with console.status(f"Checking Video track {video_track_n + 1} for Closed Captions..."):
|
|
||||||
try:
|
|
||||||
# TODO: Figure out the real language, it might be different
|
|
||||||
# EIA-CC tracks sadly don't carry language information :(
|
|
||||||
# TODO: Figure out if the CC language is original lang or not.
|
|
||||||
# Will need to figure out above first to do so.
|
|
||||||
video_track = title.tracks.videos[video_track_n]
|
|
||||||
track_id = f"ccextractor-{video_track.id}"
|
|
||||||
cc_lang = title.language or video_track.language
|
|
||||||
cc = video_track.ccextractor(
|
|
||||||
track_id=track_id,
|
|
||||||
out_path=config.directories.temp
|
|
||||||
/ config.filenames.subtitle.format(id=track_id, language=cc_lang),
|
|
||||||
language=cc_lang,
|
|
||||||
original=False,
|
|
||||||
)
|
|
||||||
if cc:
|
|
||||||
# will not appear in track listings as it's added after all times it lists
|
|
||||||
title.tracks.add(cc)
|
|
||||||
self.log.info(f"Extracted a Closed Caption from Video track {video_track_n + 1}")
|
|
||||||
else:
|
|
||||||
self.log.info(f"No Closed Captions were found in Video track {video_track_n + 1}")
|
|
||||||
except EnvironmentError:
|
|
||||||
self.log.error(
|
|
||||||
"Cannot extract Closed Captions as the ccextractor executable was not found..."
|
|
||||||
)
|
|
||||||
break
|
|
||||||
video_track_n += 1
|
|
||||||
|
|
||||||
# Subtitle output mode configuration (for sidecar originals)
|
# Subtitle output mode configuration (for sidecar originals)
|
||||||
subtitle_output_mode = config.subtitle.get("output_mode", "mux")
|
subtitle_output_mode = config.subtitle.get("output_mode", "mux")
|
||||||
sidecar_format = config.subtitle.get("sidecar_format", "srt")
|
sidecar_format = config.subtitle.get("sidecar_format", "srt")
|
||||||
@@ -2092,6 +2096,75 @@ class dl:
|
|||||||
if has_decrypted:
|
if has_decrypted:
|
||||||
self.log.info(f"Decrypted tracks with {decrypt_tool}")
|
self.log.info(f"Decrypted tracks with {decrypt_tool}")
|
||||||
|
|
||||||
|
# Extract Closed Captions from decrypted video tracks
|
||||||
|
if (
|
||||||
|
not no_subs
|
||||||
|
and not (hasattr(service, "NO_SUBTITLES") and service.NO_SUBTITLES)
|
||||||
|
and not video_only
|
||||||
|
and not no_video
|
||||||
|
):
|
||||||
|
match_func = is_exact_match if exact_lang else is_close_match
|
||||||
|
for video_track_n, video_track in enumerate(title.tracks.videos):
|
||||||
|
has_manifest_cc = bool(getattr(video_track, "closed_captions", None))
|
||||||
|
has_eia_cc = (
|
||||||
|
not has_manifest_cc
|
||||||
|
and not title.tracks.subtitles
|
||||||
|
and any(
|
||||||
|
x.get("codec_name", "").startswith("eia_")
|
||||||
|
for x in ffprobe(video_track.path).get("streams", [])
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if not has_manifest_cc and not has_eia_cc:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Build list of CC entries to extract
|
||||||
|
if has_manifest_cc:
|
||||||
|
cc_entries = video_track.closed_captions
|
||||||
|
# Filter CC languages against --s-lang if specified
|
||||||
|
if s_lang and "all" not in s_lang:
|
||||||
|
cc_entries = [
|
||||||
|
entry for entry in cc_entries
|
||||||
|
if entry.get("language")
|
||||||
|
and match_func(Language.get(entry["language"]), s_lang)
|
||||||
|
]
|
||||||
|
if not cc_entries:
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
# EIA fallback: single entry with unknown language
|
||||||
|
cc_entries = [{}]
|
||||||
|
|
||||||
|
with console.status(f"Checking Video track {video_track_n + 1} for Closed Captions..."):
|
||||||
|
try:
|
||||||
|
for cc_idx, cc_entry in enumerate(cc_entries):
|
||||||
|
cc_lang = (
|
||||||
|
Language.get(cc_entry["language"])
|
||||||
|
if cc_entry.get("language")
|
||||||
|
else title.language or video_track.language
|
||||||
|
)
|
||||||
|
track_id = f"ccextractor-{video_track.id}-{cc_idx}"
|
||||||
|
cc = video_track.ccextractor(
|
||||||
|
track_id=track_id,
|
||||||
|
out_path=config.directories.temp
|
||||||
|
/ config.filenames.subtitle.format(id=track_id, language=cc_lang),
|
||||||
|
language=cc_lang,
|
||||||
|
original=False,
|
||||||
|
)
|
||||||
|
if cc:
|
||||||
|
cc.cc = True
|
||||||
|
title.tracks.add(cc)
|
||||||
|
self.log.info(
|
||||||
|
f"Extracted a Closed Caption ({cc_lang}) from Video track {video_track_n + 1}"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.log.info(
|
||||||
|
f"No Closed Captions were found in Video track {video_track_n + 1}"
|
||||||
|
)
|
||||||
|
except EnvironmentError:
|
||||||
|
self.log.error(
|
||||||
|
"Cannot extract Closed Captions as the ccextractor executable was not found..."
|
||||||
|
)
|
||||||
|
break
|
||||||
|
|
||||||
# Now repack the decrypted tracks
|
# Now repack the decrypted tracks
|
||||||
with console.status("Repackaging tracks with FFMPEG..."):
|
with console.status("Repackaging tracks with FFMPEG..."):
|
||||||
has_repacked = False
|
has_repacked = False
|
||||||
@@ -2399,7 +2472,9 @@ class dl:
|
|||||||
|
|
||||||
final_dir.mkdir(parents=True, exist_ok=True)
|
final_dir.mkdir(parents=True, exist_ok=True)
|
||||||
final_path = final_dir / f"{final_filename}{muxed_path.suffix}"
|
final_path = final_dir / f"{final_filename}{muxed_path.suffix}"
|
||||||
template_type = "series" if isinstance(title, Episode) else "songs" if isinstance(title, Song) else "movies"
|
template_type = (
|
||||||
|
"series" if isinstance(title, Episode) else "songs" if isinstance(title, Song) else "movies"
|
||||||
|
)
|
||||||
sep = config.get_template_separator(template_type)
|
sep = config.get_template_separator(template_type)
|
||||||
|
|
||||||
if final_path.exists() and audio_codec_suffix and append_audio_codec_suffix:
|
if final_path.exists() and audio_codec_suffix and append_audio_codec_suffix:
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ from contextlib import suppress
|
|||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
from pathlib import Path
|
||||||
from typing import Any, Callable, Dict, List, Optional
|
from typing import Any, Callable, Dict, List, Optional
|
||||||
|
|
||||||
log = logging.getLogger("download_manager")
|
log = logging.getLogger("download_manager")
|
||||||
@@ -105,11 +106,44 @@ def _perform_download(
|
|||||||
from unshackle.commands.dl import dl
|
from unshackle.commands.dl import dl
|
||||||
from unshackle.core.config import config
|
from unshackle.core.config import config
|
||||||
from unshackle.core.services import Services
|
from unshackle.core.services import Services
|
||||||
|
from unshackle.core.tracks import Subtitle, Video
|
||||||
from unshackle.core.utils.click_types import ContextData
|
from unshackle.core.utils.click_types import ContextData
|
||||||
from unshackle.core.utils.collections import merge_dict
|
from unshackle.core.utils.collections import merge_dict
|
||||||
|
|
||||||
log.info(f"Starting sync download for job {job_id}")
|
log.info(f"Starting sync download for job {job_id}")
|
||||||
|
|
||||||
|
# Convert string parameters to enums (API receives strings, dl.result() expects enums)
|
||||||
|
vcodec_raw = params.get("vcodec")
|
||||||
|
if vcodec_raw:
|
||||||
|
if isinstance(vcodec_raw, str):
|
||||||
|
vcodec_raw = [vcodec_raw]
|
||||||
|
if isinstance(vcodec_raw, list) and vcodec_raw and not isinstance(vcodec_raw[0], Video.Codec):
|
||||||
|
codec_map = {c.name.upper(): c for c in Video.Codec}
|
||||||
|
codec_map.update({c.value.upper(): c for c in Video.Codec})
|
||||||
|
params["vcodec"] = [codec_map[v.upper()] for v in vcodec_raw if v.upper() in codec_map]
|
||||||
|
else:
|
||||||
|
params["vcodec"] = []
|
||||||
|
|
||||||
|
range_raw = params.get("range")
|
||||||
|
if range_raw:
|
||||||
|
if isinstance(range_raw, str):
|
||||||
|
range_raw = [range_raw]
|
||||||
|
if isinstance(range_raw, list) and range_raw and not isinstance(range_raw[0], Video.Range):
|
||||||
|
range_map = {r.name.upper(): r for r in Video.Range}
|
||||||
|
range_map.update({r.value.upper(): r for r in Video.Range})
|
||||||
|
params["range"] = [range_map[r.upper()] for r in range_raw if r.upper() in range_map]
|
||||||
|
else:
|
||||||
|
params["range"] = [Video.Range.SDR]
|
||||||
|
|
||||||
|
sub_format_raw = params.get("sub_format")
|
||||||
|
if sub_format_raw and isinstance(sub_format_raw, str):
|
||||||
|
sub_map = {c.name.upper(): c for c in Subtitle.Codec}
|
||||||
|
sub_map.update({c.value.upper(): c for c in Subtitle.Codec})
|
||||||
|
params["sub_format"] = sub_map.get(sub_format_raw.upper())
|
||||||
|
|
||||||
|
if params.get("export") and isinstance(params["export"], str):
|
||||||
|
params["export"] = Path(params["export"])
|
||||||
|
|
||||||
# Load service configuration
|
# Load service configuration
|
||||||
service_config_path = Services.get_path(service) / config.filenames.config
|
service_config_path = Services.get_path(service) / config.filenames.config
|
||||||
if service_config_path.exists():
|
if service_config_path.exists():
|
||||||
@@ -127,10 +161,15 @@ def _perform_download(
|
|||||||
"proxy": params.get("proxy"),
|
"proxy": params.get("proxy"),
|
||||||
"no_proxy": params.get("no_proxy", False),
|
"no_proxy": params.get("no_proxy", False),
|
||||||
"profile": params.get("profile"),
|
"profile": params.get("profile"),
|
||||||
|
"repack": params.get("repack", False),
|
||||||
"tag": params.get("tag"),
|
"tag": params.get("tag"),
|
||||||
"tmdb_id": params.get("tmdb_id"),
|
"tmdb_id": params.get("tmdb_id"),
|
||||||
"tmdb_name": params.get("tmdb_name", False),
|
"imdb_id": params.get("imdb_id"),
|
||||||
"tmdb_year": params.get("tmdb_year", False),
|
"animeapi_id": params.get("animeapi_id"),
|
||||||
|
"enrich": params.get("enrich", False),
|
||||||
|
"output_dir": Path(params["output_dir"]) if params.get("output_dir") else None,
|
||||||
|
"no_cache": params.get("no_cache", False),
|
||||||
|
"reset_cache": params.get("reset_cache", False),
|
||||||
}
|
}
|
||||||
|
|
||||||
dl_instance = dl(
|
dl_instance = dl(
|
||||||
@@ -138,10 +177,13 @@ def _perform_download(
|
|||||||
no_proxy=params.get("no_proxy", False),
|
no_proxy=params.get("no_proxy", False),
|
||||||
profile=params.get("profile"),
|
profile=params.get("profile"),
|
||||||
proxy=params.get("proxy"),
|
proxy=params.get("proxy"),
|
||||||
|
repack=params.get("repack", False),
|
||||||
tag=params.get("tag"),
|
tag=params.get("tag"),
|
||||||
tmdb_id=params.get("tmdb_id"),
|
tmdb_id=params.get("tmdb_id"),
|
||||||
tmdb_name=params.get("tmdb_name", False),
|
imdb_id=params.get("imdb_id"),
|
||||||
tmdb_year=params.get("tmdb_year", False),
|
animeapi_id=params.get("animeapi_id"),
|
||||||
|
enrich=params.get("enrich", False),
|
||||||
|
output_dir=Path(params["output_dir"]) if params.get("output_dir") else None,
|
||||||
)
|
)
|
||||||
|
|
||||||
service_module = Services.load(service)
|
service_module = Services.load(service)
|
||||||
@@ -220,14 +262,14 @@ def _perform_download(
|
|||||||
dl_instance.result(
|
dl_instance.result(
|
||||||
service=service_instance,
|
service=service_instance,
|
||||||
quality=params.get("quality", []),
|
quality=params.get("quality", []),
|
||||||
vcodec=params.get("vcodec"),
|
vcodec=params.get("vcodec", []),
|
||||||
acodec=params.get("acodec"),
|
acodec=params.get("acodec"),
|
||||||
vbitrate=params.get("vbitrate"),
|
vbitrate=params.get("vbitrate"),
|
||||||
abitrate=params.get("abitrate"),
|
abitrate=params.get("abitrate"),
|
||||||
range_=params.get("range", ["SDR"]),
|
range_=params.get("range", ["SDR"]),
|
||||||
channels=params.get("channels"),
|
channels=params.get("channels"),
|
||||||
no_atmos=params.get("no_atmos", False),
|
no_atmos=params.get("no_atmos", False),
|
||||||
split_audio=params.get("split_audio"),
|
select_titles=False,
|
||||||
wanted=params.get("wanted", []),
|
wanted=params.get("wanted", []),
|
||||||
latest_episode=params.get("latest_episode", False),
|
latest_episode=params.get("latest_episode", False),
|
||||||
lang=params.get("lang", ["orig"]),
|
lang=params.get("lang", ["orig"]),
|
||||||
@@ -245,6 +287,7 @@ def _perform_download(
|
|||||||
no_subs=params.get("no_subs", False),
|
no_subs=params.get("no_subs", False),
|
||||||
no_audio=params.get("no_audio", False),
|
no_audio=params.get("no_audio", False),
|
||||||
no_chapters=params.get("no_chapters", False),
|
no_chapters=params.get("no_chapters", False),
|
||||||
|
no_video=params.get("no_video", False),
|
||||||
audio_description=params.get("audio_description", False),
|
audio_description=params.get("audio_description", False),
|
||||||
slow=params.get("slow", False),
|
slow=params.get("slow", False),
|
||||||
list_=False,
|
list_=False,
|
||||||
@@ -259,6 +302,7 @@ def _perform_download(
|
|||||||
workers=params.get("workers"),
|
workers=params.get("workers"),
|
||||||
downloads=params.get("downloads", 1),
|
downloads=params.get("downloads", 1),
|
||||||
best_available=params.get("best_available", False),
|
best_available=params.get("best_available", False),
|
||||||
|
split_audio=params.get("split_audio"),
|
||||||
)
|
)
|
||||||
|
|
||||||
except SystemExit as exc:
|
except SystemExit as exc:
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import enum
|
||||||
import logging
|
import logging
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
@@ -42,8 +43,10 @@ DEFAULT_DOWNLOAD_PARAMS = {
|
|||||||
"no_subs": False,
|
"no_subs": False,
|
||||||
"no_audio": False,
|
"no_audio": False,
|
||||||
"no_chapters": False,
|
"no_chapters": False,
|
||||||
|
"no_video": False,
|
||||||
"audio_description": False,
|
"audio_description": False,
|
||||||
"slow": False,
|
"slow": False,
|
||||||
|
"split_audio": None,
|
||||||
"skip_dl": False,
|
"skip_dl": False,
|
||||||
"export": None,
|
"export": None,
|
||||||
"cdm_only": None,
|
"cdm_only": None,
|
||||||
@@ -54,6 +57,11 @@ DEFAULT_DOWNLOAD_PARAMS = {
|
|||||||
"workers": None,
|
"workers": None,
|
||||||
"downloads": 1,
|
"downloads": 1,
|
||||||
"best_available": False,
|
"best_available": False,
|
||||||
|
"repack": False,
|
||||||
|
"imdb_id": None,
|
||||||
|
"output_dir": None,
|
||||||
|
"no_cache": False,
|
||||||
|
"reset_cache": False,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -341,6 +349,137 @@ def serialize_subtitle_track(track: Subtitle, include_url: bool = False) -> Dict
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
async def search_handler(data: Dict[str, Any], request: Optional[web.Request] = None) -> web.Response:
|
||||||
|
"""Handle search request."""
|
||||||
|
import inspect
|
||||||
|
|
||||||
|
import click
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
from unshackle.commands.dl import dl
|
||||||
|
from unshackle.core.config import config
|
||||||
|
from unshackle.core.services import Services
|
||||||
|
from unshackle.core.utils.click_types import ContextData
|
||||||
|
from unshackle.core.utils.collections import merge_dict
|
||||||
|
|
||||||
|
service_tag = data.get("service")
|
||||||
|
query = data.get("query")
|
||||||
|
|
||||||
|
if not service_tag:
|
||||||
|
raise APIError(APIErrorCode.MISSING_SERVICE, "Missing required 'service' field")
|
||||||
|
if not query:
|
||||||
|
raise APIError(APIErrorCode.INVALID_PARAMETERS, "Missing required 'query' field")
|
||||||
|
|
||||||
|
normalized_service = Services.get_tag(service_tag)
|
||||||
|
if not normalized_service:
|
||||||
|
raise APIError(
|
||||||
|
APIErrorCode.INVALID_SERVICE,
|
||||||
|
f"Service '{service_tag}' not found",
|
||||||
|
details={"service": service_tag},
|
||||||
|
)
|
||||||
|
|
||||||
|
profile = data.get("profile")
|
||||||
|
proxy_param = data.get("proxy")
|
||||||
|
no_proxy = data.get("no_proxy", False)
|
||||||
|
|
||||||
|
service_config_path = Services.get_path(normalized_service) / config.filenames.config
|
||||||
|
if service_config_path.exists():
|
||||||
|
service_config = yaml.safe_load(service_config_path.read_text(encoding="utf8"))
|
||||||
|
else:
|
||||||
|
service_config = {}
|
||||||
|
merge_dict(config.services.get(normalized_service), service_config)
|
||||||
|
|
||||||
|
proxy_providers = []
|
||||||
|
if not no_proxy:
|
||||||
|
proxy_providers = initialize_proxy_providers()
|
||||||
|
|
||||||
|
if proxy_param and not no_proxy:
|
||||||
|
try:
|
||||||
|
resolved_proxy = resolve_proxy(proxy_param, proxy_providers)
|
||||||
|
proxy_param = resolved_proxy
|
||||||
|
except ValueError as e:
|
||||||
|
raise APIError(
|
||||||
|
APIErrorCode.INVALID_PROXY,
|
||||||
|
f"Proxy error: {e}",
|
||||||
|
details={"proxy": proxy_param, "service": normalized_service},
|
||||||
|
)
|
||||||
|
|
||||||
|
@click.command()
|
||||||
|
@click.pass_context
|
||||||
|
def dummy_service(ctx: click.Context) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
ctx = click.Context(dummy_service)
|
||||||
|
ctx.obj = ContextData(config=service_config, cdm=None, proxy_providers=proxy_providers, profile=profile)
|
||||||
|
ctx.params = {"proxy": proxy_param, "no_proxy": no_proxy}
|
||||||
|
|
||||||
|
service_module = Services.load(normalized_service)
|
||||||
|
|
||||||
|
dummy_service.name = normalized_service
|
||||||
|
ctx.invoked_subcommand = normalized_service
|
||||||
|
|
||||||
|
service_ctx = click.Context(dummy_service, parent=ctx)
|
||||||
|
service_ctx.obj = ctx.obj
|
||||||
|
|
||||||
|
service_init_params = inspect.signature(service_module.__init__).parameters
|
||||||
|
service_kwargs = {"title": query}
|
||||||
|
|
||||||
|
# Extract default values from the click command
|
||||||
|
if hasattr(service_module, "cli") and hasattr(service_module.cli, "params"):
|
||||||
|
for param in service_module.cli.params:
|
||||||
|
if hasattr(param, "name") and param.name not in service_kwargs:
|
||||||
|
if hasattr(param, "default") and param.default is not None and not isinstance(param.default, enum.Enum):
|
||||||
|
service_kwargs[param.name] = param.default
|
||||||
|
|
||||||
|
for param_name, param_info in service_init_params.items():
|
||||||
|
if param_name not in service_kwargs and param_name not in ["self", "ctx"]:
|
||||||
|
if param_info.default is inspect.Parameter.empty:
|
||||||
|
if param_name == "meta_lang":
|
||||||
|
service_kwargs[param_name] = None
|
||||||
|
elif param_name == "movie":
|
||||||
|
service_kwargs[param_name] = False
|
||||||
|
else:
|
||||||
|
service_kwargs[param_name] = None
|
||||||
|
|
||||||
|
# Filter to only accepted params
|
||||||
|
accepted_params = set(service_init_params.keys()) - {"self", "ctx"}
|
||||||
|
service_kwargs = {k: v for k, v in service_kwargs.items() if k in accepted_params}
|
||||||
|
|
||||||
|
try:
|
||||||
|
service_instance = service_module(service_ctx, **service_kwargs)
|
||||||
|
except Exception as exc:
|
||||||
|
raise APIError(
|
||||||
|
APIErrorCode.SERVICE_ERROR,
|
||||||
|
f"Failed to initialize service: {exc}",
|
||||||
|
details={"service": normalized_service},
|
||||||
|
)
|
||||||
|
|
||||||
|
# Authenticate
|
||||||
|
cookies = dl.get_cookie_jar(normalized_service, profile)
|
||||||
|
credential = dl.get_credentials(normalized_service, profile)
|
||||||
|
service_instance.authenticate(cookies, credential)
|
||||||
|
|
||||||
|
# Search
|
||||||
|
results = []
|
||||||
|
try:
|
||||||
|
for result in service_instance.search():
|
||||||
|
results.append({
|
||||||
|
"id": result.id,
|
||||||
|
"title": result.title,
|
||||||
|
"description": result.description,
|
||||||
|
"label": result.label,
|
||||||
|
"url": result.url,
|
||||||
|
})
|
||||||
|
except NotImplementedError:
|
||||||
|
raise APIError(
|
||||||
|
APIErrorCode.SERVICE_ERROR,
|
||||||
|
f"Search is not supported by {normalized_service}",
|
||||||
|
details={"service": normalized_service},
|
||||||
|
)
|
||||||
|
|
||||||
|
return web.json_response({"results": results, "count": len(results)})
|
||||||
|
|
||||||
|
|
||||||
async def list_titles_handler(data: Dict[str, Any], request: Optional[web.Request] = None) -> web.Response:
|
async def list_titles_handler(data: Dict[str, Any], request: Optional[web.Request] = None) -> web.Response:
|
||||||
"""Handle list-titles request."""
|
"""Handle list-titles request."""
|
||||||
service_tag = data.get("service")
|
service_tag = data.get("service")
|
||||||
@@ -439,7 +578,7 @@ async def list_titles_handler(data: Dict[str, Any], request: Optional[web.Reques
|
|||||||
for param in service_module.cli.params:
|
for param in service_module.cli.params:
|
||||||
if hasattr(param, "name") and param.name not in service_kwargs:
|
if hasattr(param, "name") and param.name not in service_kwargs:
|
||||||
# Add default value if parameter is not already provided
|
# Add default value if parameter is not already provided
|
||||||
if hasattr(param, "default") and param.default is not None:
|
if hasattr(param, "default") and param.default is not None and not isinstance(param.default, enum.Enum):
|
||||||
service_kwargs[param.name] = param.default
|
service_kwargs[param.name] = param.default
|
||||||
|
|
||||||
# Handle required parameters that don't have click defaults
|
# Handle required parameters that don't have click defaults
|
||||||
@@ -587,7 +726,7 @@ async def list_tracks_handler(data: Dict[str, Any], request: Optional[web.Reques
|
|||||||
for param in service_module.cli.params:
|
for param in service_module.cli.params:
|
||||||
if hasattr(param, "name") and param.name not in service_kwargs:
|
if hasattr(param, "name") and param.name not in service_kwargs:
|
||||||
# Add default value if parameter is not already provided
|
# Add default value if parameter is not already provided
|
||||||
if hasattr(param, "default") and param.default is not None:
|
if hasattr(param, "default") and param.default is not None and not isinstance(param.default, enum.Enum):
|
||||||
service_kwargs[param.name] = param.default
|
service_kwargs[param.name] = param.default
|
||||||
|
|
||||||
# Handle required parameters that don't have click defaults
|
# Handle required parameters that don't have click defaults
|
||||||
@@ -631,7 +770,10 @@ async def list_tracks_handler(data: Dict[str, Any], request: Optional[web.Reques
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
season_range = SeasonRange()
|
season_range = SeasonRange()
|
||||||
wanted = season_range.parse_tokens(wanted_param)
|
if isinstance(wanted_param, list):
|
||||||
|
wanted = season_range.parse_tokens(*wanted_param)
|
||||||
|
else:
|
||||||
|
wanted = season_range.parse_tokens(wanted_param)
|
||||||
log.debug(f"Parsed wanted '{wanted_param}' into {len(wanted)} episodes: {wanted[:10]}...")
|
log.debug(f"Parsed wanted '{wanted_param}' into {len(wanted)} episodes: {wanted[:10]}...")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise APIError(
|
raise APIError(
|
||||||
@@ -760,9 +902,17 @@ def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]:
|
|||||||
None if valid, error message string if invalid
|
None if valid, error message string if invalid
|
||||||
"""
|
"""
|
||||||
if "vcodec" in data and data["vcodec"]:
|
if "vcodec" in data and data["vcodec"]:
|
||||||
valid_vcodecs = ["H264", "H265", "VP9", "AV1"]
|
valid_vcodecs = ["H264", "H265", "H.264", "H.265", "AVC", "HEVC", "VC1", "VC-1", "VP8", "VP9", "AV1"]
|
||||||
if data["vcodec"].upper() not in valid_vcodecs:
|
if isinstance(data["vcodec"], str):
|
||||||
return f"Invalid vcodec: {data['vcodec']}. Must be one of: {', '.join(valid_vcodecs)}"
|
vcodec_values = [v.strip() for v in data["vcodec"].split(",") if v.strip()]
|
||||||
|
elif isinstance(data["vcodec"], list):
|
||||||
|
vcodec_values = [str(v).strip() for v in data["vcodec"] if str(v).strip()]
|
||||||
|
else:
|
||||||
|
return "vcodec must be a string or list"
|
||||||
|
|
||||||
|
invalid = [value for value in vcodec_values if value.upper() not in valid_vcodecs]
|
||||||
|
if invalid:
|
||||||
|
return f"Invalid vcodec: {', '.join(invalid)}. Must be one of: {', '.join(valid_vcodecs)}"
|
||||||
|
|
||||||
if "acodec" in data and data["acodec"]:
|
if "acodec" in data and data["acodec"]:
|
||||||
valid_acodecs = ["AAC", "AC3", "EC3", "EAC3", "DD", "DD+", "AC4", "OPUS", "FLAC", "ALAC", "VORBIS", "OGG", "DTS"]
|
valid_acodecs = ["AAC", "AC3", "EC3", "EAC3", "DD", "DD+", "AC4", "OPUS", "FLAC", "ALAC", "VORBIS", "OGG", "DTS"]
|
||||||
@@ -778,7 +928,7 @@ def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]:
|
|||||||
return f"Invalid acodec: {', '.join(invalid)}. Must be one of: {', '.join(valid_acodecs)}"
|
return f"Invalid acodec: {', '.join(invalid)}. Must be one of: {', '.join(valid_acodecs)}"
|
||||||
|
|
||||||
if "sub_format" in data and data["sub_format"]:
|
if "sub_format" in data and data["sub_format"]:
|
||||||
valid_sub_formats = ["SRT", "VTT", "ASS", "SSA"]
|
valid_sub_formats = ["SRT", "VTT", "ASS", "SSA", "TTML", "STPP", "WVTT", "SMI", "SUB", "MPL2", "TMP"]
|
||||||
if data["sub_format"].upper() not in valid_sub_formats:
|
if data["sub_format"].upper() not in valid_sub_formats:
|
||||||
return f"Invalid sub_format: {data['sub_format']}. Must be one of: {', '.join(valid_sub_formats)}"
|
return f"Invalid sub_format: {data['sub_format']}. Must be one of: {', '.join(valid_sub_formats)}"
|
||||||
|
|
||||||
@@ -880,7 +1030,7 @@ async def download_handler(data: Dict[str, Any], request: Optional[web.Request]
|
|||||||
# Extract default values from the service's click command
|
# Extract default values from the service's click command
|
||||||
if hasattr(service_module, "cli") and hasattr(service_module.cli, "params"):
|
if hasattr(service_module, "cli") and hasattr(service_module.cli, "params"):
|
||||||
for param in service_module.cli.params:
|
for param in service_module.cli.params:
|
||||||
if hasattr(param, "name") and hasattr(param, "default") and param.default is not None:
|
if hasattr(param, "name") and hasattr(param, "default") and param.default is not None and not isinstance(param.default, enum.Enum):
|
||||||
# Store service-specific defaults (e.g., drm_system, hydrate_track, profile for NF)
|
# Store service-specific defaults (e.g., drm_system, hydrate_track, profile for NF)
|
||||||
service_specific_defaults[param.name] = param.default
|
service_specific_defaults[param.name] = param.default
|
||||||
|
|
||||||
|
|||||||
+130
-11
@@ -7,7 +7,8 @@ from aiohttp_swagger3 import SwaggerDocs, SwaggerInfo, SwaggerUiSettings
|
|||||||
from unshackle.core import __version__
|
from unshackle.core import __version__
|
||||||
from unshackle.core.api.errors import APIError, APIErrorCode, build_error_response, handle_api_exception
|
from unshackle.core.api.errors import APIError, APIErrorCode, build_error_response, handle_api_exception
|
||||||
from unshackle.core.api.handlers import (cancel_download_job_handler, download_handler, get_download_job_handler,
|
from unshackle.core.api.handlers import (cancel_download_job_handler, download_handler, get_download_job_handler,
|
||||||
list_download_jobs_handler, list_titles_handler, list_tracks_handler)
|
list_download_jobs_handler, list_titles_handler, list_tracks_handler,
|
||||||
|
search_handler)
|
||||||
from unshackle.core.services import Services
|
from unshackle.core.services import Services
|
||||||
from unshackle.core.update_checker import UpdateChecker
|
from unshackle.core.update_checker import UpdateChecker
|
||||||
|
|
||||||
@@ -199,6 +200,93 @@ async def services(request: web.Request) -> web.Response:
|
|||||||
return handle_api_exception(e, context={"operation": "list_services"}, debug_mode=debug_mode)
|
return handle_api_exception(e, context={"operation": "list_services"}, debug_mode=debug_mode)
|
||||||
|
|
||||||
|
|
||||||
|
async def search(request: web.Request) -> web.Response:
|
||||||
|
"""
|
||||||
|
Search for titles from a service.
|
||||||
|
---
|
||||||
|
summary: Search for titles
|
||||||
|
description: Search for titles by query string from a service
|
||||||
|
requestBody:
|
||||||
|
required: true
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
required:
|
||||||
|
- service
|
||||||
|
- query
|
||||||
|
properties:
|
||||||
|
service:
|
||||||
|
type: string
|
||||||
|
description: Service tag (e.g., NF, AMZN, ATV)
|
||||||
|
query:
|
||||||
|
type: string
|
||||||
|
description: Search query string
|
||||||
|
profile:
|
||||||
|
type: string
|
||||||
|
description: Profile to use for credentials and cookies (default - None)
|
||||||
|
proxy:
|
||||||
|
type: string
|
||||||
|
description: Proxy URI or country code (default - None)
|
||||||
|
no_proxy:
|
||||||
|
type: boolean
|
||||||
|
description: Force disable all proxy use (default - false)
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: Search results
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
results:
|
||||||
|
type: array
|
||||||
|
items:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
id:
|
||||||
|
type: string
|
||||||
|
description: Title ID for use with other endpoints
|
||||||
|
title:
|
||||||
|
type: string
|
||||||
|
description: Title name
|
||||||
|
description:
|
||||||
|
type: string
|
||||||
|
description: Title description
|
||||||
|
label:
|
||||||
|
type: string
|
||||||
|
description: Informative label (e.g., availability, region)
|
||||||
|
url:
|
||||||
|
type: string
|
||||||
|
description: URL to the title page
|
||||||
|
count:
|
||||||
|
type: integer
|
||||||
|
description: Number of results returned
|
||||||
|
'400':
|
||||||
|
description: Invalid request
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
data = await request.json()
|
||||||
|
except Exception as e:
|
||||||
|
return build_error_response(
|
||||||
|
APIError(
|
||||||
|
APIErrorCode.INVALID_INPUT,
|
||||||
|
"Invalid JSON request body",
|
||||||
|
details={"error": str(e)},
|
||||||
|
),
|
||||||
|
request.app.get("debug_api", False),
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
return await search_handler(data, request)
|
||||||
|
except APIError as e:
|
||||||
|
return build_error_response(e, request.app.get("debug_api", False))
|
||||||
|
except Exception as e:
|
||||||
|
log.exception("Error in search")
|
||||||
|
debug_mode = request.app.get("debug_api", False)
|
||||||
|
return handle_api_exception(e, context={"operation": "search"}, debug_mode=debug_mode)
|
||||||
|
|
||||||
|
|
||||||
async def list_titles(request: web.Request) -> web.Response:
|
async def list_titles(request: web.Request) -> web.Response:
|
||||||
"""
|
"""
|
||||||
List titles for a service and title ID.
|
List titles for a service and title ID.
|
||||||
@@ -409,11 +497,19 @@ async def download(request: web.Request) -> web.Response:
|
|||||||
type: integer
|
type: integer
|
||||||
description: Download resolution(s) (default - best available)
|
description: Download resolution(s) (default - best available)
|
||||||
vcodec:
|
vcodec:
|
||||||
type: string
|
oneOf:
|
||||||
description: Video codec to download (e.g., H264, H265, VP9, AV1) (default - None)
|
- type: string
|
||||||
|
- type: array
|
||||||
|
items:
|
||||||
|
type: string
|
||||||
|
description: Video codec(s) to download (e.g., "H265" or ["H264", "H265"]) - accepts H264, H265, AVC, HEVC, VP8, VP9, AV1, VC1 (default - None)
|
||||||
acodec:
|
acodec:
|
||||||
type: string
|
oneOf:
|
||||||
description: Audio codec(s) to download (e.g., AAC or AAC,EC3) (default - None)
|
- type: string
|
||||||
|
- type: array
|
||||||
|
items:
|
||||||
|
type: string
|
||||||
|
description: Audio codec(s) to download (e.g., "AAC" or ["AAC", "EC3"]) - accepts AAC, AC3, EC3, AC4, OPUS, FLAC, ALAC, DTS, OGG (default - None)
|
||||||
vbitrate:
|
vbitrate:
|
||||||
type: integer
|
type: integer
|
||||||
description: Video bitrate in kbps (default - None)
|
description: Video bitrate in kbps (default - None)
|
||||||
@@ -424,7 +520,7 @@ async def download(request: web.Request) -> web.Response:
|
|||||||
type: array
|
type: array
|
||||||
items:
|
items:
|
||||||
type: string
|
type: string
|
||||||
description: Video color range (SDR, HDR10, DV) (default - ["SDR"])
|
description: Video color range (SDR, HDR10, HDR10+, HLG, DV, HYBRID) (default - ["SDR"])
|
||||||
channels:
|
channels:
|
||||||
type: number
|
type: number
|
||||||
description: Audio channels (e.g., 2.0, 5.1, 7.1) (default - None)
|
description: Audio channels (e.g., 2.0, 5.1, 7.1) (default - None)
|
||||||
@@ -494,12 +590,18 @@ async def download(request: web.Request) -> web.Response:
|
|||||||
no_chapters:
|
no_chapters:
|
||||||
type: boolean
|
type: boolean
|
||||||
description: Do not download chapters (default - false)
|
description: Do not download chapters (default - false)
|
||||||
|
no_video:
|
||||||
|
type: boolean
|
||||||
|
description: Do not download video tracks (default - false)
|
||||||
audio_description:
|
audio_description:
|
||||||
type: boolean
|
type: boolean
|
||||||
description: Download audio description tracks (default - false)
|
description: Download audio description tracks (default - false)
|
||||||
slow:
|
slow:
|
||||||
type: boolean
|
type: boolean
|
||||||
description: Add 60-120s delay between downloads (default - false)
|
description: Add 60-120s delay between downloads (default - false)
|
||||||
|
split_audio:
|
||||||
|
type: boolean
|
||||||
|
description: Create separate output files per audio codec instead of merging all audio (default - null)
|
||||||
skip_dl:
|
skip_dl:
|
||||||
type: boolean
|
type: boolean
|
||||||
description: Skip downloading, only retrieve decryption keys (default - false)
|
description: Skip downloading, only retrieve decryption keys (default - false)
|
||||||
@@ -521,12 +623,12 @@ async def download(request: web.Request) -> web.Response:
|
|||||||
tmdb_id:
|
tmdb_id:
|
||||||
type: integer
|
type: integer
|
||||||
description: Use this TMDB ID for tagging (default - None)
|
description: Use this TMDB ID for tagging (default - None)
|
||||||
tmdb_name:
|
animeapi_id:
|
||||||
|
type: string
|
||||||
|
description: Anime database ID via AnimeAPI, e.g. mal:12345 (default - None)
|
||||||
|
enrich:
|
||||||
type: boolean
|
type: boolean
|
||||||
description: Rename titles using TMDB name (default - false)
|
description: Override show title and year from external source (default - false)
|
||||||
tmdb_year:
|
|
||||||
type: boolean
|
|
||||||
description: Use release year from TMDB (default - false)
|
|
||||||
no_folder:
|
no_folder:
|
||||||
type: boolean
|
type: boolean
|
||||||
description: Disable folder creation for TV shows (default - false)
|
description: Disable folder creation for TV shows (default - false)
|
||||||
@@ -545,6 +647,21 @@ async def download(request: web.Request) -> web.Response:
|
|||||||
best_available:
|
best_available:
|
||||||
type: boolean
|
type: boolean
|
||||||
description: Continue with best available if requested quality unavailable (default - false)
|
description: Continue with best available if requested quality unavailable (default - false)
|
||||||
|
repack:
|
||||||
|
type: boolean
|
||||||
|
description: Add REPACK tag to the output filename (default - false)
|
||||||
|
imdb_id:
|
||||||
|
type: string
|
||||||
|
description: Use this IMDB ID (e.g. tt1375666) for tagging (default - None)
|
||||||
|
output_dir:
|
||||||
|
type: string
|
||||||
|
description: Override the output directory for this download (default - None)
|
||||||
|
no_cache:
|
||||||
|
type: boolean
|
||||||
|
description: Bypass title cache for this download (default - false)
|
||||||
|
reset_cache:
|
||||||
|
type: boolean
|
||||||
|
description: Clear title cache before fetching (default - false)
|
||||||
responses:
|
responses:
|
||||||
'202':
|
'202':
|
||||||
description: Download job created
|
description: Download job created
|
||||||
@@ -723,6 +840,7 @@ def setup_routes(app: web.Application) -> None:
|
|||||||
"""Setup all API routes."""
|
"""Setup all API routes."""
|
||||||
app.router.add_get("/api/health", health)
|
app.router.add_get("/api/health", health)
|
||||||
app.router.add_get("/api/services", services)
|
app.router.add_get("/api/services", services)
|
||||||
|
app.router.add_post("/api/search", search)
|
||||||
app.router.add_post("/api/list-titles", list_titles)
|
app.router.add_post("/api/list-titles", list_titles)
|
||||||
app.router.add_post("/api/list-tracks", list_tracks)
|
app.router.add_post("/api/list-tracks", list_tracks)
|
||||||
app.router.add_post("/api/download", download)
|
app.router.add_post("/api/download", download)
|
||||||
@@ -748,6 +866,7 @@ def setup_swagger(app: web.Application) -> None:
|
|||||||
[
|
[
|
||||||
web.get("/api/health", health),
|
web.get("/api/health", health),
|
||||||
web.get("/api/services", services),
|
web.get("/api/services", services),
|
||||||
|
web.post("/api/search", search),
|
||||||
web.post("/api/list-titles", list_titles),
|
web.post("/api/list-titles", list_titles),
|
||||||
web.post("/api/list-tracks", list_tracks),
|
web.post("/api/list-tracks", list_tracks),
|
||||||
web.post("/api/download", download),
|
web.post("/api/download", download),
|
||||||
|
|||||||
@@ -431,14 +431,24 @@ def download(
|
|||||||
raise ValueError(error)
|
raise ValueError(error)
|
||||||
|
|
||||||
# Yield aggregate progress for this call's downloads
|
# Yield aggregate progress for this call's downloads
|
||||||
if total_size > 0:
|
progress_data = {"advance": 0}
|
||||||
# Yield both advance (bytes downloaded this iteration) and total for rich progress
|
|
||||||
if dl_speed != -1:
|
if len(gids) > 1:
|
||||||
yield dict(downloaded=f"{filesize.decimal(dl_speed)}/s", advance=0, completed=total_completed, total=total_size)
|
# Multi-file mode (e.g., HLS): Return the count of completed segments
|
||||||
|
progress_data["completed"] = len(completed)
|
||||||
|
progress_data["total"] = len(gids)
|
||||||
|
else:
|
||||||
|
# Single-file mode: Return the total bytes downloaded
|
||||||
|
progress_data["completed"] = total_completed
|
||||||
|
if total_size > 0:
|
||||||
|
progress_data["total"] = total_size
|
||||||
else:
|
else:
|
||||||
yield dict(advance=0, completed=total_completed, total=total_size)
|
progress_data["total"] = None
|
||||||
elif dl_speed != -1:
|
|
||||||
yield dict(downloaded=f"{filesize.decimal(dl_speed)}/s")
|
if dl_speed != -1:
|
||||||
|
progress_data["downloaded"] = f"{filesize.decimal(dl_speed)}/s"
|
||||||
|
|
||||||
|
yield progress_data
|
||||||
|
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
|
|||||||
@@ -44,16 +44,15 @@ class PlayReady:
|
|||||||
else:
|
else:
|
||||||
kids = []
|
kids = []
|
||||||
|
|
||||||
# Extract KIDs using pyplayready's method (may miss some KIDs)
|
# Extract KIDs using pyplayready's WrmHeader key_ids
|
||||||
if not kids:
|
if not kids:
|
||||||
for header in pssh.wrm_headers:
|
for header in pssh.wrm_headers:
|
||||||
try:
|
for signed_key_id in getattr(header, "key_ids", []):
|
||||||
signed_ids, _, _, _ = header.read_attributes()
|
|
||||||
except Exception:
|
|
||||||
continue
|
|
||||||
for signed_id in signed_ids:
|
|
||||||
try:
|
try:
|
||||||
kids.append(UUID(bytes_le=base64.b64decode(signed_id.value)))
|
if isinstance(signed_key_id.value, UUID):
|
||||||
|
kids.append(signed_key_id.value)
|
||||||
|
else:
|
||||||
|
kids.append(UUID(bytes_le=base64.b64decode(signed_key_id.value)))
|
||||||
except Exception:
|
except Exception:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@@ -119,7 +118,33 @@ class PlayReady:
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
# Also get individual KID
|
# v4.2/v4.3: DATA/PROTECTINFO/KIDS/KID
|
||||||
|
protectinfo_kids = root.findall(".//pr:DATA/pr:PROTECTINFO/pr:KIDS/pr:KID", ns)
|
||||||
|
for kid_elem in protectinfo_kids:
|
||||||
|
value = kid_elem.get("VALUE")
|
||||||
|
if value:
|
||||||
|
try:
|
||||||
|
kid_bytes = base64.b64decode(value + "==")
|
||||||
|
kid_uuid = UUID(bytes_le=kid_bytes)
|
||||||
|
if kid_uuid not in kids:
|
||||||
|
kids.append(kid_uuid)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# v4.1: DATA/PROTECTINFO/KID
|
||||||
|
protectinfo_kid = root.findall(".//pr:DATA/pr:PROTECTINFO/pr:KID", ns)
|
||||||
|
for kid_elem in protectinfo_kid:
|
||||||
|
value = kid_elem.get("VALUE")
|
||||||
|
if value:
|
||||||
|
try:
|
||||||
|
kid_bytes = base64.b64decode(value + "==")
|
||||||
|
kid_uuid = UUID(bytes_le=kid_bytes)
|
||||||
|
if kid_uuid not in kids:
|
||||||
|
kids.append(kid_uuid)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# v4.0: DATA/KID
|
||||||
individual_kids = root.findall(".//pr:DATA/pr:KID", ns)
|
individual_kids = root.findall(".//pr:DATA/pr:KID", ns)
|
||||||
for kid_elem in individual_kids:
|
for kid_elem in individual_kids:
|
||||||
if kid_elem.text:
|
if kid_elem.text:
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import math
|
|||||||
import re
|
import re
|
||||||
import shutil
|
import shutil
|
||||||
import sys
|
import sys
|
||||||
from copy import copy
|
from copy import copy, deepcopy
|
||||||
from functools import partial
|
from functools import partial
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Callable, Optional, Union
|
from typing import Any, Callable, Optional, Union
|
||||||
@@ -18,6 +18,7 @@ from zlib import crc32
|
|||||||
import requests
|
import requests
|
||||||
from curl_cffi.requests import Session as CurlSession
|
from curl_cffi.requests import Session as CurlSession
|
||||||
from langcodes import Language, tag_is_valid
|
from langcodes import Language, tag_is_valid
|
||||||
|
from lxml import etree
|
||||||
from lxml.etree import Element, ElementTree
|
from lxml.etree import Element, ElementTree
|
||||||
from pyplayready.system.pssh import PSSH as PR_PSSH
|
from pyplayready.system.pssh import PSSH as PR_PSSH
|
||||||
from pywidevine.cdm import Cdm as WidevineCdm
|
from pywidevine.cdm import Cdm as WidevineCdm
|
||||||
@@ -101,14 +102,22 @@ class DASH:
|
|||||||
"""
|
"""
|
||||||
tracks = Tracks()
|
tracks = Tracks()
|
||||||
|
|
||||||
|
filtered_period_ids: list[str] = []
|
||||||
|
|
||||||
for period in self.manifest.findall("Period"):
|
for period in self.manifest.findall("Period"):
|
||||||
if callable(period_filter) and period_filter(period):
|
if callable(period_filter) and period_filter(period):
|
||||||
|
if period_id := period.get("id"):
|
||||||
|
filtered_period_ids.append(period_id)
|
||||||
continue
|
continue
|
||||||
if next(iter(period.xpath("SegmentType/@value")), "content") != "content":
|
if next(iter(period.xpath("SegmentType/@value")), "content") != "content":
|
||||||
|
if period_id := period.get("id"):
|
||||||
|
filtered_period_ids.append(period_id)
|
||||||
continue
|
continue
|
||||||
if "urn:amazon:primevideo:cachingBreadth" in [
|
if "urn:amazon:primevideo:cachingBreadth" in [
|
||||||
x.get("schemeIdUri") for x in period.findall("SupplementalProperty")
|
x.get("schemeIdUri") for x in period.findall("SupplementalProperty")
|
||||||
]:
|
]:
|
||||||
|
if period_id := period.get("id"):
|
||||||
|
filtered_period_ids.append(period_id)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
for adaptation_set in period.findall("AdaptationSet"):
|
for adaptation_set in period.findall("AdaptationSet"):
|
||||||
@@ -235,6 +244,7 @@ class DASH:
|
|||||||
"period": period,
|
"period": period,
|
||||||
"adaptation_set": adaptation_set,
|
"adaptation_set": adaptation_set,
|
||||||
"representation": rep,
|
"representation": rep,
|
||||||
|
"filtered_period_ids": filtered_period_ids,
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
**track_args,
|
**track_args,
|
||||||
@@ -541,6 +551,26 @@ class DASH:
|
|||||||
skip_merge = False
|
skip_merge = False
|
||||||
if downloader.__name__ == "n_m3u8dl_re":
|
if downloader.__name__ == "n_m3u8dl_re":
|
||||||
skip_merge = True
|
skip_merge = True
|
||||||
|
|
||||||
|
# When periods were filtered out during to_tracks(), n_m3u8dl_re will re-parse
|
||||||
|
# the raw MPD and download ALL periods (including ads/pre-rolls). Write a filtered
|
||||||
|
# MPD with the rejected periods removed so n_m3u8dl_re downloads the correct content.
|
||||||
|
filtered_period_ids = track.data.get("dash", {}).get("filtered_period_ids", [])
|
||||||
|
if filtered_period_ids:
|
||||||
|
filtered_manifest = deepcopy(manifest)
|
||||||
|
for child in list(filtered_manifest):
|
||||||
|
if not hasattr(child.tag, "find"):
|
||||||
|
continue
|
||||||
|
if child.tag == "Period" and child.get("id") in filtered_period_ids:
|
||||||
|
filtered_manifest.remove(child)
|
||||||
|
|
||||||
|
filtered_mpd_path = save_dir / f".{track.id}_filtered.mpd"
|
||||||
|
filtered_mpd_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
etree.ElementTree(filtered_manifest).write(
|
||||||
|
str(filtered_mpd_path), xml_declaration=True, encoding="utf-8"
|
||||||
|
)
|
||||||
|
track.from_file = filtered_mpd_path
|
||||||
|
|
||||||
downloader_args.update(
|
downloader_args.update(
|
||||||
{
|
{
|
||||||
"filename": track.id,
|
"filename": track.id,
|
||||||
@@ -578,6 +608,11 @@ class DASH:
|
|||||||
status_update["downloaded"] = f"DASH {downloaded}"
|
status_update["downloaded"] = f"DASH {downloaded}"
|
||||||
progress(**status_update)
|
progress(**status_update)
|
||||||
|
|
||||||
|
# Clean up filtered MPD temp file before enumerating segments
|
||||||
|
filtered_mpd_path = save_dir / f".{track.id}_filtered.mpd"
|
||||||
|
if filtered_mpd_path.exists():
|
||||||
|
filtered_mpd_path.unlink()
|
||||||
|
|
||||||
# see https://github.com/devine-dl/devine/issues/71
|
# see https://github.com/devine-dl/devine/issues/71
|
||||||
for control_file in save_dir.glob("*.aria2__temp"):
|
for control_file in save_dir.glob("*.aria2__temp"):
|
||||||
control_file.unlink()
|
control_file.unlink()
|
||||||
|
|||||||
@@ -112,6 +112,15 @@ class HLS:
|
|||||||
session_drm = HLS.get_all_drm(session_keys)
|
session_drm = HLS.get_all_drm(session_keys)
|
||||||
|
|
||||||
audio_codecs_by_group_id: dict[str, Audio.Codec] = {}
|
audio_codecs_by_group_id: dict[str, Audio.Codec] = {}
|
||||||
|
cc_by_group_id: dict[str, list[dict[str, Any]]] = {}
|
||||||
|
for media in self.manifest.media:
|
||||||
|
if media.type == "CLOSED-CAPTIONS":
|
||||||
|
cc_by_group_id.setdefault(media.group_id, []).append({
|
||||||
|
"language": media.language,
|
||||||
|
"name": media.name,
|
||||||
|
"instream_id": media.instream_id,
|
||||||
|
"characteristics": media.characteristics,
|
||||||
|
})
|
||||||
tracks = Tracks()
|
tracks = Tracks()
|
||||||
|
|
||||||
for playlist in self.manifest.playlists:
|
for playlist in self.manifest.playlists:
|
||||||
@@ -161,6 +170,9 @@ class HLS:
|
|||||||
width=playlist.stream_info.resolution[0] if playlist.stream_info.resolution else None,
|
width=playlist.stream_info.resolution[0] if playlist.stream_info.resolution else None,
|
||||||
height=playlist.stream_info.resolution[1] if playlist.stream_info.resolution else None,
|
height=playlist.stream_info.resolution[1] if playlist.stream_info.resolution else None,
|
||||||
fps=playlist.stream_info.frame_rate,
|
fps=playlist.stream_info.frame_rate,
|
||||||
|
closed_captions=cc_by_group_id.get(
|
||||||
|
(playlist.stream_info.closed_captions or "").strip('"'), []
|
||||||
|
),
|
||||||
)
|
)
|
||||||
if primary_track_type is Video
|
if primary_track_type is Video
|
||||||
else {}
|
else {}
|
||||||
|
|||||||
@@ -145,7 +145,14 @@ class ISM:
|
|||||||
fragment_time += duration_frag
|
fragment_time += duration_frag
|
||||||
|
|
||||||
track_id = hashlib.md5(
|
track_id = hashlib.md5(
|
||||||
f"{codec}-{track_lang}-{ql.get('Bitrate') or 0}-{ql.get('Index') or 0}".encode()
|
"{codec}-{lang}-{bitrate}-{index}-{name}-{url}".format(
|
||||||
|
codec=codec,
|
||||||
|
lang=track_lang,
|
||||||
|
bitrate=ql.get("Bitrate") or 0,
|
||||||
|
index=ql.get("Index") or 0,
|
||||||
|
name=stream_index.get("Name") or "",
|
||||||
|
url=stream_index.get("Url") or "",
|
||||||
|
).encode()
|
||||||
).hexdigest()
|
).hexdigest()
|
||||||
|
|
||||||
data = {
|
data = {
|
||||||
|
|||||||
@@ -44,6 +44,17 @@ FINGERPRINT_PRESETS = {
|
|||||||
"akamai": "4:16777216|16711681|0|m,p,a,s",
|
"akamai": "4:16777216|16711681|0|m,p,a,s",
|
||||||
"description": "OkHttp 5.x (BoringSSL TLS stack)",
|
"description": "OkHttp 5.x (BoringSSL TLS stack)",
|
||||||
},
|
},
|
||||||
|
"shield_okhttp": {
|
||||||
|
"ja3": (
|
||||||
|
"771," # TLS 1.2
|
||||||
|
"4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53," # Ciphers (OkHttp 4.11)
|
||||||
|
"0-23-65281-10-11-35-16-5-13-51-45-43-21," # Extensions (incl padding ext 21)
|
||||||
|
"29-23-24," # Named groups (x25519, secp256r1, secp384r1)
|
||||||
|
"0" # EC point formats
|
||||||
|
),
|
||||||
|
"akamai": "4:16777216|16711681|0|m,p,a,s",
|
||||||
|
"description": "NVIDIA SHIELD Android TV OkHttp 4.11 (captured JA3)",
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -121,6 +121,8 @@ class Title:
|
|||||||
base_layer = DYNAMIC_RANGE_MAP.get(hdr_format)
|
base_layer = DYNAMIC_RANGE_MAP.get(hdr_format)
|
||||||
if base_layer and base_layer != "DV":
|
if base_layer and base_layer != "DV":
|
||||||
context["hdr"] += f".{base_layer}"
|
context["hdr"] += f".{base_layer}"
|
||||||
|
elif (primary_video_track.hdr_format or "").startswith("HDR Vivid"):
|
||||||
|
context["hdr"] = "HDR"
|
||||||
else:
|
else:
|
||||||
context["hdr"] = DYNAMIC_RANGE_MAP.get(hdr_format, "")
|
context["hdr"] = DYNAMIC_RANGE_MAP.get(hdr_format, "")
|
||||||
elif trc and "HLG" in trc:
|
elif trc and "HLG" in trc:
|
||||||
|
|||||||
@@ -103,53 +103,78 @@ class Tracks:
|
|||||||
tree = Tree("", hide_root=True)
|
tree = Tree("", hide_root=True)
|
||||||
for track_type in self.TRACK_ORDER_MAP:
|
for track_type in self.TRACK_ORDER_MAP:
|
||||||
tracks = list(x for x in all_tracks if isinstance(x, track_type))
|
tracks = list(x for x in all_tracks if isinstance(x, track_type))
|
||||||
if not tracks:
|
if tracks:
|
||||||
continue
|
num_tracks = len(tracks)
|
||||||
num_tracks = len(tracks)
|
track_type_plural = track_type.__name__ + ("s" if track_type != Audio and num_tracks != 1 else "")
|
||||||
track_type_plural = track_type.__name__ + ("s" if track_type != Audio and num_tracks != 1 else "")
|
tracks_tree = tree.add(f"[repr.number]{num_tracks}[/] {track_type_plural}")
|
||||||
tracks_tree = tree.add(f"[repr.number]{num_tracks}[/] {track_type_plural}")
|
for track in tracks:
|
||||||
for track in tracks:
|
if add_progress and track_type not in (Chapter, Attachment):
|
||||||
if add_progress and track_type not in (Chapter, Attachment):
|
progress = Progress(
|
||||||
progress = Progress(
|
SpinnerColumn(finished_text=""),
|
||||||
SpinnerColumn(finished_text=""),
|
BarColumn(),
|
||||||
BarColumn(),
|
"•",
|
||||||
"•",
|
TimeRemainingColumn(compact=True, elapsed_when_finished=True),
|
||||||
TimeRemainingColumn(compact=True, elapsed_when_finished=True),
|
"•",
|
||||||
"•",
|
TextColumn("[progress.data.speed]{task.fields[downloaded]}"),
|
||||||
TextColumn("[progress.data.speed]{task.fields[downloaded]}"),
|
console=console,
|
||||||
console=console,
|
speed_estimate_period=10,
|
||||||
speed_estimate_period=10,
|
)
|
||||||
|
task = progress.add_task("", downloaded="-")
|
||||||
|
state = {"total": 100.0}
|
||||||
|
|
||||||
|
def update_track_progress(
|
||||||
|
task_id: int = task,
|
||||||
|
_state: dict[str, float] = state,
|
||||||
|
_progress: Progress = progress,
|
||||||
|
**kwargs,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
Ensure terminal status states render as a fully completed bar.
|
||||||
|
|
||||||
|
Some downloaders can report completed slightly below total
|
||||||
|
before emitting the final "Downloaded" state.
|
||||||
|
"""
|
||||||
|
if "total" in kwargs and kwargs["total"] is not None:
|
||||||
|
_state["total"] = kwargs["total"]
|
||||||
|
|
||||||
|
downloaded_state = kwargs.get("downloaded")
|
||||||
|
if downloaded_state in {"Downloaded", "Decrypted", "[yellow]SKIPPED"}:
|
||||||
|
kwargs["completed"] = _state["total"]
|
||||||
|
_progress.update(task_id=task_id, **kwargs)
|
||||||
|
|
||||||
|
progress_callables.append(update_track_progress)
|
||||||
|
track_table = Table.grid()
|
||||||
|
track_table.add_row(str(track)[6:], style="text2")
|
||||||
|
track_table.add_row(progress)
|
||||||
|
tracks_tree.add(track_table)
|
||||||
|
else:
|
||||||
|
tracks_tree.add(str(track)[6:], style="text2")
|
||||||
|
|
||||||
|
# Show Closed Captions right after Subtitles (even if no subtitle tracks exist)
|
||||||
|
if track_type is Subtitle:
|
||||||
|
seen_cc: set[str] = set()
|
||||||
|
unique_cc: list[str] = []
|
||||||
|
for video in (x for x in all_tracks if isinstance(x, Video)):
|
||||||
|
for cc in getattr(video, "closed_captions", []):
|
||||||
|
lang = cc.get("language", "und")
|
||||||
|
name = cc.get("name", "")
|
||||||
|
instream_id = cc.get("instream_id", "")
|
||||||
|
key = f"{lang}|{instream_id}"
|
||||||
|
if key in seen_cc:
|
||||||
|
continue
|
||||||
|
seen_cc.add(key)
|
||||||
|
parts = [f"[CC] | {lang}"]
|
||||||
|
if name:
|
||||||
|
parts.append(name)
|
||||||
|
if instream_id:
|
||||||
|
parts.append(instream_id)
|
||||||
|
unique_cc.append(" | ".join(parts))
|
||||||
|
if unique_cc:
|
||||||
|
cc_tree = tree.add(
|
||||||
|
f"[repr.number]{len(unique_cc)}[/] Closed Caption{'s' if len(unique_cc) != 1 else ''}"
|
||||||
)
|
)
|
||||||
task = progress.add_task("", downloaded="-")
|
for cc_str in unique_cc:
|
||||||
state = {"total": 100.0}
|
cc_tree.add(cc_str, style="text2")
|
||||||
|
|
||||||
def update_track_progress(
|
|
||||||
task_id: int = task,
|
|
||||||
_state: dict[str, float] = state,
|
|
||||||
_progress: Progress = progress,
|
|
||||||
**kwargs,
|
|
||||||
) -> None:
|
|
||||||
"""
|
|
||||||
Ensure terminal status states render as a fully completed bar.
|
|
||||||
|
|
||||||
Some downloaders can report completed slightly below total
|
|
||||||
before emitting the final "Downloaded" state.
|
|
||||||
"""
|
|
||||||
if "total" in kwargs and kwargs["total"] is not None:
|
|
||||||
_state["total"] = kwargs["total"]
|
|
||||||
|
|
||||||
downloaded_state = kwargs.get("downloaded")
|
|
||||||
if downloaded_state in {"Downloaded", "Decrypted", "[yellow]SKIPPED"}:
|
|
||||||
kwargs["completed"] = _state["total"]
|
|
||||||
_progress.update(task_id=task_id, **kwargs)
|
|
||||||
|
|
||||||
progress_callables.append(update_track_progress)
|
|
||||||
track_table = Table.grid()
|
|
||||||
track_table.add_row(str(track)[6:], style="text2")
|
|
||||||
track_table.add_row(progress)
|
|
||||||
tracks_tree.add(track_table)
|
|
||||||
else:
|
|
||||||
tracks_tree.add(str(track)[6:], style="text2")
|
|
||||||
|
|
||||||
return tree, progress_callables
|
return tree, progress_callables
|
||||||
|
|
||||||
|
|||||||
@@ -200,6 +200,7 @@ class Video(Track):
|
|||||||
height: Optional[int] = None,
|
height: Optional[int] = None,
|
||||||
fps: Optional[Union[str, int, float]] = None,
|
fps: Optional[Union[str, int, float]] = None,
|
||||||
scan_type: Optional[Video.ScanType] = None,
|
scan_type: Optional[Video.ScanType] = None,
|
||||||
|
closed_captions: Optional[list[dict[str, Any]]] = None,
|
||||||
**kwargs: Any,
|
**kwargs: Any,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""
|
"""
|
||||||
@@ -264,6 +265,7 @@ class Video(Track):
|
|||||||
raise ValueError("Expected fps to be a number, float, or a string as numerator/denominator form, " + str(e))
|
raise ValueError("Expected fps to be a number, float, or a string as numerator/denominator form, " + str(e))
|
||||||
|
|
||||||
self.scan_type = scan_type
|
self.scan_type = scan_type
|
||||||
|
self.closed_captions: list[dict[str, Any]] = closed_captions or []
|
||||||
self.needs_duration_fix = False
|
self.needs_duration_fix = False
|
||||||
|
|
||||||
def __str__(self) -> str:
|
def __str__(self) -> str:
|
||||||
@@ -346,22 +348,27 @@ class Video(Track):
|
|||||||
if not binaries.CCExtractor:
|
if not binaries.CCExtractor:
|
||||||
raise EnvironmentError("ccextractor executable was not found.")
|
raise EnvironmentError("ccextractor executable was not found.")
|
||||||
|
|
||||||
# ccextractor often fails in weird ways unless we repack
|
|
||||||
self.repackage()
|
|
||||||
|
|
||||||
out_path = Path(out_path)
|
out_path = Path(out_path)
|
||||||
|
|
||||||
try:
|
def _run_ccextractor() -> bool:
|
||||||
subprocess.run(
|
try:
|
||||||
[binaries.CCExtractor, "-trim", "-nobom", "-noru", "-ru1", "-o", out_path, self.path],
|
subprocess.run(
|
||||||
check=True,
|
[binaries.CCExtractor, "-trim", "-nobom", "-noru", "-ru1", "-o", out_path, self.path],
|
||||||
stdout=subprocess.PIPE,
|
check=True,
|
||||||
stderr=subprocess.PIPE,
|
stdout=subprocess.PIPE,
|
||||||
)
|
stderr=subprocess.PIPE,
|
||||||
except subprocess.CalledProcessError as e:
|
)
|
||||||
out_path.unlink(missing_ok=True)
|
except subprocess.CalledProcessError as e:
|
||||||
if not e.returncode == 10: # No captions found
|
out_path.unlink(missing_ok=True)
|
||||||
raise
|
if e.returncode != 10: # 10 = No captions found
|
||||||
|
raise
|
||||||
|
return out_path.exists()
|
||||||
|
|
||||||
|
# Try on the original file first (preserves container-level CC data like c608 boxes),
|
||||||
|
# then fall back to repacked file (ccextractor can fail on some container formats).
|
||||||
|
if not _run_ccextractor():
|
||||||
|
self.repackage()
|
||||||
|
_run_ccextractor()
|
||||||
|
|
||||||
if out_path.exists():
|
if out_path.exists():
|
||||||
cc_track = Subtitle(
|
cc_track = Subtitle(
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from unshackle.core.providers._base import ExternalIds
|
||||||
|
|
||||||
|
log = logging.getLogger("ANIMEAPI")
|
||||||
|
|
||||||
|
PLATFORM_MAP: dict[str, str] = {
|
||||||
|
"mal": "myanimelist",
|
||||||
|
"anilist": "anilist",
|
||||||
|
"kitsu": "kitsu",
|
||||||
|
"tmdb": "themoviedb",
|
||||||
|
"trakt": "trakt",
|
||||||
|
"tvdb": "thetvdb",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_animeapi(value: str) -> tuple[Optional[str], ExternalIds]:
|
||||||
|
"""Resolve an anime database ID via AnimeAPI to a title and external IDs.
|
||||||
|
|
||||||
|
Accepts formats like 'mal:12345', 'anilist:98765', or just '12345' (defaults to MAL).
|
||||||
|
Returns (anime_title, ExternalIds) with any TMDB/IMDB/TVDB IDs found.
|
||||||
|
"""
|
||||||
|
import animeapi
|
||||||
|
|
||||||
|
platform_str, id_str = _parse_animeapi_value(value)
|
||||||
|
|
||||||
|
platform_enum = _get_platform(platform_str)
|
||||||
|
if platform_enum is None:
|
||||||
|
log.warning("Unknown AnimeAPI platform: %s (supported: %s)", platform_str, ", ".join(PLATFORM_MAP))
|
||||||
|
return None, ExternalIds()
|
||||||
|
|
||||||
|
log.info("Resolving AnimeAPI %s:%s", platform_str, id_str)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with animeapi.AnimeAPI() as api:
|
||||||
|
relation = api.get_anime_relations(id_str, platform_enum)
|
||||||
|
except Exception as exc:
|
||||||
|
log.warning("AnimeAPI lookup failed for %s:%s: %s", platform_str, id_str, exc)
|
||||||
|
return None, ExternalIds()
|
||||||
|
|
||||||
|
title = getattr(relation, "title", None)
|
||||||
|
|
||||||
|
tmdb_id = getattr(relation, "themoviedb", None)
|
||||||
|
tmdb_type = getattr(relation, "themoviedb_type", None)
|
||||||
|
imdb_id = getattr(relation, "imdb", None)
|
||||||
|
tvdb_id = getattr(relation, "thetvdb", None)
|
||||||
|
|
||||||
|
tmdb_kind: Optional[str] = None
|
||||||
|
if tmdb_type is not None:
|
||||||
|
tmdb_kind = tmdb_type.value if hasattr(tmdb_type, "value") else str(tmdb_type).lower()
|
||||||
|
if tmdb_kind not in ("movie", "tv"):
|
||||||
|
tmdb_kind = "tv"
|
||||||
|
|
||||||
|
external_ids = ExternalIds(
|
||||||
|
tmdb_id=int(tmdb_id) if tmdb_id is not None else None,
|
||||||
|
tmdb_kind=tmdb_kind,
|
||||||
|
imdb_id=str(imdb_id) if imdb_id is not None else None,
|
||||||
|
tvdb_id=int(tvdb_id) if tvdb_id is not None else None,
|
||||||
|
)
|
||||||
|
|
||||||
|
log.info(
|
||||||
|
"AnimeAPI resolved: title=%r, tmdb=%s, imdb=%s, tvdb=%s",
|
||||||
|
title,
|
||||||
|
external_ids.tmdb_id,
|
||||||
|
external_ids.imdb_id,
|
||||||
|
external_ids.tvdb_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
return title, external_ids
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_animeapi_value(value: str) -> tuple[str, str]:
|
||||||
|
"""Parse 'platform:id' format. Defaults to 'mal' if no prefix."""
|
||||||
|
if ":" in value:
|
||||||
|
platform, _, id_str = value.partition(":")
|
||||||
|
return platform.lower().strip(), id_str.strip()
|
||||||
|
return "mal", value.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def _get_platform(platform_str: str) -> object | None:
|
||||||
|
"""Map a platform string to an animeapi.Platform enum value."""
|
||||||
|
import animeapi
|
||||||
|
|
||||||
|
canonical = PLATFORM_MAP.get(platform_str)
|
||||||
|
if canonical is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
platform_name = canonical.upper()
|
||||||
|
return getattr(animeapi.Platform, platform_name, None)
|
||||||
@@ -109,6 +109,20 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/fb/76/641ae371508676492379f16e2fa48f4e2c11741bd63c48be4b12a6b09cba/aiosignal-1.4.0-py3-none-any.whl", hash = "sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e", size = 7490, upload-time = "2025-07-03T22:54:42.156Z" },
|
{ url = "https://files.pythonhosted.org/packages/fb/76/641ae371508676492379f16e2fa48f4e2c11741bd63c48be4b12a6b09cba/aiosignal-1.4.0-py3-none-any.whl", hash = "sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e", size = 7490, upload-time = "2025-07-03T22:54:42.156Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "animeapi-py"
|
||||||
|
version = "3.8.1"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
dependencies = [
|
||||||
|
{ name = "aiohttp" },
|
||||||
|
{ name = "dacite" },
|
||||||
|
{ name = "requests" },
|
||||||
|
]
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/28/a2/f868bba3b6399e2c953f8796fa90c8de91f797ad0fe19c7e2c536cd0092f/animeapi_py-3.8.1.tar.gz", hash = "sha256:9ed10f8207f1ccd7949ee3728285f4aced9a5ec57f71d211594ca5dc356fdea5", size = 25663, upload-time = "2026-02-25T15:29:17.879Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/ba/98/6775d71cf7d88d554e8394f5ce5cda90041c99fdf1b2b60af02001e8c790/animeapi_py-3.8.1-py3-none-any.whl", hash = "sha256:c29f6e633d17bb613f459aa6514c0baab7ae325881f8a109eb6e4b3be5c22827", size = 26983, upload-time = "2026-02-25T15:29:16.685Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "anyio"
|
name = "anyio"
|
||||||
version = "4.12.1"
|
version = "4.12.1"
|
||||||
@@ -449,6 +463,15 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/f9/0f/9c5275f17ad6ff5be70edb8e0120fdc184a658c9577ca426d4230f654beb/curl_cffi-0.13.0-cp39-abi3-win_arm64.whl", hash = "sha256:d438a3b45244e874794bc4081dc1e356d2bb926dcc7021e5a8fef2e2105ef1d8", size = 1365753, upload-time = "2025-08-06T13:05:41.879Z" },
|
{ url = "https://files.pythonhosted.org/packages/f9/0f/9c5275f17ad6ff5be70edb8e0120fdc184a658c9577ca426d4230f654beb/curl_cffi-0.13.0-cp39-abi3-win_arm64.whl", hash = "sha256:d438a3b45244e874794bc4081dc1e356d2bb926dcc7021e5a8fef2e2105ef1d8", size = 1365753, upload-time = "2025-08-06T13:05:41.879Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "dacite"
|
||||||
|
version = "1.9.2"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/55/a0/7ca79796e799a3e782045d29bf052b5cde7439a2bbb17f15ff44f7aacc63/dacite-1.9.2.tar.gz", hash = "sha256:6ccc3b299727c7aa17582f0021f6ae14d5de47c7227932c47fec4cdfefd26f09", size = 22420, upload-time = "2025-02-05T09:27:29.757Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/94/35/386550fd60316d1e37eccdda609b074113298f23cef5bddb2049823fe666/dacite-1.9.2-py3-none-any.whl", hash = "sha256:053f7c3f5128ca2e9aceb66892b1a3c8936d02c686e707bee96e19deef4bc4a0", size = 16600, upload-time = "2025-02-05T09:27:24.345Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "distlib"
|
name = "distlib"
|
||||||
version = "0.4.0"
|
version = "0.4.0"
|
||||||
@@ -1627,11 +1650,12 @@ wheels = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "unshackle"
|
name = "unshackle"
|
||||||
version = "3.1.0"
|
version = "4.0.0"
|
||||||
source = { editable = "." }
|
source = { editable = "." }
|
||||||
dependencies = [
|
dependencies = [
|
||||||
{ name = "aiohttp" },
|
{ name = "aiohttp" },
|
||||||
{ name = "aiohttp-swagger3" },
|
{ name = "aiohttp-swagger3" },
|
||||||
|
{ name = "animeapi-py" },
|
||||||
{ name = "appdirs" },
|
{ name = "appdirs" },
|
||||||
{ name = "brotli" },
|
{ name = "brotli" },
|
||||||
{ name = "chardet" },
|
{ name = "chardet" },
|
||||||
@@ -1690,6 +1714,7 @@ dev = [
|
|||||||
requires-dist = [
|
requires-dist = [
|
||||||
{ name = "aiohttp", specifier = ">=3.13.3,<4" },
|
{ name = "aiohttp", specifier = ">=3.13.3,<4" },
|
||||||
{ name = "aiohttp-swagger3", specifier = ">=0.9.0,<1" },
|
{ name = "aiohttp-swagger3", specifier = ">=0.9.0,<1" },
|
||||||
|
{ name = "animeapi-py", specifier = ">=0.6.0" },
|
||||||
{ name = "appdirs", specifier = ">=1.4.4,<2" },
|
{ name = "appdirs", specifier = ">=1.4.4,<2" },
|
||||||
{ name = "brotli", specifier = ">=1.1.0,<2" },
|
{ name = "brotli", specifier = ">=1.1.0,<2" },
|
||||||
{ name = "chardet", specifier = ">=5.2.0,<6" },
|
{ name = "chardet", specifier = ">=5.2.0,<6" },
|
||||||
|
|||||||
Reference in New Issue
Block a user