mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-06 07:55:10 +00:00
Compare commits
23
Commits
eeec4e1f1b
..
4.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
79e8184474 | ||
|
|
178eed9236 | ||
|
|
63d2ba60c4 | ||
|
|
f46aa9d8c8 | ||
|
|
b1447eb14b | ||
|
|
e02aa66843 | ||
|
|
c82bb5fe34 | ||
|
|
ec2ecfe7b4 | ||
|
|
15acaea208 | ||
|
|
def18a4c44 | ||
|
|
7dd6323be5 | ||
|
|
d68bb28a66 | ||
|
|
d1e6d0812c | ||
|
|
2f7a3d6d1d | ||
|
|
572a894620 | ||
|
|
5bd03c67cf | ||
|
|
d8a362c853 | ||
|
|
08269bef60 | ||
|
|
65ceb4ae51 | ||
|
|
c8883a5404 | ||
|
|
13d7636d86 | ||
|
|
6ce7b6c4d3 | ||
|
|
798ce95042 |
@@ -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
|
||||
+28
-2
@@ -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).
|
||||
|
||||
## [3.1.0] - 2026-02-23
|
||||
## [4.0.0] - 2026-03-17
|
||||
|
||||
### Features
|
||||
|
||||
@@ -15,6 +15,15 @@ This changelog is automatically generated using [git-cliff](https://git-cliff.or
|
||||
- *debug*: Log binary tool versions at session start
|
||||
- *dl*: Add --repack flag to insert REPACK tag in output filenames
|
||||
- *core*: Add TrackRequest system for multi-codec/multi-range support
|
||||
- *dl*: Add --output option to override download directory
|
||||
- *tracks*: Add edition tags to output filenames
|
||||
- *templates*: [**breaking**] Add customizable output filename templates
|
||||
- *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
|
||||
|
||||
@@ -25,11 +34,28 @@ This changelog is automatically generated using [git-cliff](https://git-cliff.or
|
||||
- *dl*: Allow selection of audio tracks for 'all' languages in addition to 'best'
|
||||
- *dl*: Overwrite existing files on re-download and use atomic replace
|
||||
- *dl*: Handle cross-device moves when temp and downloads differ
|
||||
- *track*: Fallback to requests downloader from n_m3u8dl_re for unsupported track types
|
||||
- *n_m3u8dl_re*: Disable segment count validation for duration-based DASH
|
||||
- Correct formatting and add missing newlines in selector and EXAMPLE service
|
||||
- *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
|
||||
|
||||
- Update and correct configuration documentation
|
||||
|
||||
### Changes
|
||||
|
||||
- *hybrid*: Replace log.info with console status and add JSONL debug logging
|
||||
- *dl*: Remove legacy multi-fetch loop for unmigrated services
|
||||
- *example*: Migrate EXAMPLE service to track_request pattern
|
||||
- *providers*: Extract metadata providers into modular system
|
||||
|
||||
## [3.0.0] - 2026-02-15
|
||||
|
||||
@@ -511,7 +537,7 @@ This changelog is automatically generated using [git-cliff](https://git-cliff.or
|
||||
- Reorganize Planned Features section in README for clarity
|
||||
- Improve track selection logic in dl.py
|
||||
|
||||
[3.1.0]: https://github.com/unshackle-dl/unshackle/compare/3.0.0..3.1.0
|
||||
[unreleased]: https://github.com/unshackle-dl/unshackle/compare/3.0.0..HEAD
|
||||
[3.0.0]: https://github.com/unshackle-dl/unshackle/compare/2.3.0..3.0.0
|
||||
[2.3.0]: https://github.com/unshackle-dl/unshackle/compare/2.2.0..2.3.0
|
||||
[2.2.0]: https://github.com/unshackle-dl/unshackle/compare/2.1.0..2.2.0
|
||||
|
||||
+35
-4
@@ -4,11 +4,34 @@ This document covers advanced features, debugging, and system-level configuratio
|
||||
|
||||
## serve (dict)
|
||||
|
||||
Configuration data for pywidevine's serve functionality run through unshackle.
|
||||
This effectively allows you to run `unshackle serve` to start serving pywidevine Serve-compliant CDMs right from your
|
||||
local widevine device files.
|
||||
Configuration for the integrated server that provides CDM endpoints (Widevine/PlayReady) and a REST API for remote downloading.
|
||||
|
||||
- `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.
|
||||
- `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:
|
||||
@@ -42,6 +65,14 @@ serve:
|
||||
# - '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)
|
||||
|
||||
+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.
|
||||
+92
-12
@@ -30,16 +30,102 @@ filenames:
|
||||
|
||||
---
|
||||
|
||||
## scene_naming (bool)
|
||||
## output_template (dict)
|
||||
|
||||
Set scene-style naming for titles. When `true` uses scene naming patterns (e.g., `Prime.Suspect.S07E01...`), when
|
||||
`false` uses a more human-readable style (e.g., `Prime Suspect S07E01 ...`). Default: `true`.
|
||||
Configure custom output filename templates for movies, series, and songs.
|
||||
This is **required** in your `unshackle.yaml` — a warning is shown if not configured.
|
||||
|
||||
Available variables: `{title}`, `{year}`, `{season}`, `{episode}`, `{season_episode}`, `{episode_name}`,
|
||||
`{quality}`, `{resolution}`, `{source}`, `{audio}`, `{audio_channels}`, `{audio_full}`,
|
||||
`{video}`, `{hdr}`, `{hfr}`, `{atmos}`, `{dual}`, `{multi}`, `{tag}`, `{edition}`, `{repack}`,
|
||||
`{lang_tag}`
|
||||
|
||||
Add `?` suffix to make a variable conditional (omitted when empty): `{year?}`, `{hdr?}`, `{repack?}`
|
||||
|
||||
```yaml
|
||||
output_template:
|
||||
# Scene-style (dot-separated)
|
||||
movies: '{title}.{year}.{repack?}.{edition?}.{quality}.{source}.WEB-DL.{dual?}.{multi?}.{audio_full}.{atmos?}.{hdr?}.{hfr?}.{video}-{tag}'
|
||||
series: '{title}.{year?}.{season_episode}.{episode_name?}.{repack?}.{edition?}.{quality}.{source}.WEB-DL.{dual?}.{multi?}.{audio_full}.{atmos?}.{hdr?}.{hfr?}.{video}-{tag}'
|
||||
songs: '{track_number}.{title}.{repack?}.{edition?}.{source?}.WEB-DL.{audio_full}.{atmos?}-{tag}'
|
||||
|
||||
# Plex-friendly (space-separated)
|
||||
# movies: '{title} ({year}) {quality}'
|
||||
# series: '{title} {season_episode} {episode_name?}'
|
||||
# songs: '{track_number}. {title}'
|
||||
```
|
||||
|
||||
Example outputs:
|
||||
- Scene movies: `The.Matrix.1999.1080p.NF.WEB-DL.DDP5.1.H.264-EXAMPLE`
|
||||
- Scene movies (REPACK): `Dune.2021.REPACK.2160p.HBO.WEB-DL.DDP5.1.H.265-EXAMPLE`
|
||||
- Scene series: `Breaking.Bad.2008.S01E01.Pilot.1080p.NF.WEB-DL.DDP5.1.H.264-EXAMPLE`
|
||||
- Plex movies: `The Matrix (1999) 1080p`
|
||||
|
||||
---
|
||||
|
||||
## dash_naming (bool)
|
||||
---
|
||||
|
||||
Use dash-separated naming convention for output files. Default: `false`.
|
||||
## language_tags (dict)
|
||||
|
||||
Automatically adds language-based identifiers (e.g., `DANiSH`, `NORDiC`, `DKsubs`) to output filenames
|
||||
based on audio and subtitle track languages. Use `{lang_tag?}` in your `output_template` to place the tag.
|
||||
|
||||
Rules are evaluated in order; the first matching rule wins. All conditions within a single rule
|
||||
must match (AND logic). If no rules match, `{lang_tag?}` is cleanly removed from the filename.
|
||||
|
||||
### Conditions
|
||||
|
||||
| Condition | Type | Description |
|
||||
|-----------|------|-------------|
|
||||
| `audio` | string | Matches if any selected audio track has this language |
|
||||
| `subs_contain` | string | Matches if any selected subtitle has this language |
|
||||
| `subs_contain_all` | list | Matches if subtitles include ALL listed languages |
|
||||
|
||||
Language matching uses fuzzy matching (e.g., `en` matches `en-US`, `en-GB`).
|
||||
|
||||
### Example: Nordic tagging
|
||||
|
||||
```yaml
|
||||
language_tags:
|
||||
rules:
|
||||
- audio: da
|
||||
tag: DANiSH
|
||||
- audio: sv
|
||||
tag: SWEDiSH
|
||||
- audio: nb
|
||||
tag: NORWEGiAN
|
||||
- audio: en
|
||||
subs_contain_all: [da, sv, nb]
|
||||
tag: NORDiC
|
||||
- audio: en
|
||||
subs_contain: da
|
||||
tag: DKsubs
|
||||
|
||||
output_template:
|
||||
movies: '{title}.{year?}.{lang_tag?}.{quality}.{source}.WEB-DL.{audio_full}.{video}-{tag}'
|
||||
```
|
||||
|
||||
Example outputs:
|
||||
- Danish audio: `Show.S01E01.DANiSH.1080p.NF.WEB-DL.DDP5.1.H.264-TAG`
|
||||
- English audio + multiple Nordic subs: `Show.S01E01.NORDiC.1080p.NF.WEB-DL.DDP5.1.H.264-TAG`
|
||||
- English audio + Danish subs only: `Show.S01E01.DKsubs.1080p.NF.WEB-DL.DDP5.1.H.264-TAG`
|
||||
- No matching languages: `Show.S01E01.1080p.NF.WEB-DL.DDP5.1.H.264-TAG`
|
||||
|
||||
### Example: Other regional tags
|
||||
|
||||
```yaml
|
||||
language_tags:
|
||||
rules:
|
||||
- audio: nl
|
||||
tag: DUTCH
|
||||
- audio: de
|
||||
tag: GERMAN
|
||||
- audio: fr
|
||||
subs_contain: en
|
||||
tag: ENGFR
|
||||
- audio: fr
|
||||
tag: FRENCH
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -50,16 +136,10 @@ to ASCII equivalents. Default: `false`.
|
||||
|
||||
---
|
||||
|
||||
## series_year (bool)
|
||||
|
||||
Whether to include the series year in series names for episodes and folders. Default: `true`.
|
||||
|
||||
---
|
||||
|
||||
## tag (str)
|
||||
|
||||
Group or Username to postfix to the end of download filenames following a dash.
|
||||
Only applies when `scene_naming` is enabled.
|
||||
Use `{tag}` in your output template to include it.
|
||||
For example, `tag: "J0HN"` will have `-J0HN` at the end of all download filenames.
|
||||
|
||||
---
|
||||
|
||||
+3
-2
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "unshackle"
|
||||
version = "3.1.0"
|
||||
version = "4.0.0"
|
||||
description = "Modular Movie, TV, and Music Archival Software."
|
||||
authors = [{ name = "unshackle team" }]
|
||||
requires-python = ">=3.10,<3.13"
|
||||
@@ -56,7 +56,7 @@ dependencies = [
|
||||
"urllib3>=2.6.3,<3",
|
||||
"chardet>=5.2.0,<6",
|
||||
"curl-cffi>=0.7.0b4,<0.14",
|
||||
"pyplayready>=0.6.3,<0.7",
|
||||
"pyplayready>=0.8.3,<0.9",
|
||||
"httpx>=0.28.1,<0.29",
|
||||
"cryptography>=45.0.0,<47",
|
||||
"subby",
|
||||
@@ -67,6 +67,7 @@ dependencies = [
|
||||
"pycountry>=24.6.1",
|
||||
"language-data>=1.4.0",
|
||||
"wasmtime>=41.0.0",
|
||||
"animeapi-py>=0.6.0",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
|
||||
+196
-120
@@ -25,6 +25,7 @@ import click
|
||||
import jsonpickle
|
||||
import yaml
|
||||
from construct import ConstError
|
||||
from langcodes import Language
|
||||
from pymediainfo import MediaInfo
|
||||
from pyplayready.cdm import Cdm as PlayReadyCdm
|
||||
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.hybrid import Hybrid
|
||||
from unshackle.core.utilities import (find_font_with_fallbacks, get_debug_logger, get_system_fonts, init_debug_logger,
|
||||
is_close_match, suggest_font_packages, time_elapsed_since)
|
||||
is_close_match, is_exact_match, suggest_font_packages, time_elapsed_since)
|
||||
from unshackle.core.utils import tags
|
||||
from unshackle.core.utils.click_types import (AUDIO_CODEC_LIST, LANGUAGE_RANGE, QUALITY_LIST, SEASON_RANGE,
|
||||
ContextData, MultipleChoice, MultipleVideoCodecChoice,
|
||||
@@ -416,18 +417,17 @@ class dl:
|
||||
help="Use this TMDB ID for tagging instead of automatic lookup.",
|
||||
)
|
||||
@click.option(
|
||||
"--tmdb-name",
|
||||
"tmdb_name",
|
||||
is_flag=True,
|
||||
default=False,
|
||||
help="Rename titles using the name returned from TMDB lookup.",
|
||||
"--animeapi",
|
||||
"animeapi_id",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Anime database ID via AnimeAPI (e.g. mal:12345, anilist:98765). Defaults to MAL if no prefix.",
|
||||
)
|
||||
@click.option(
|
||||
"--tmdb-year",
|
||||
"tmdb_year",
|
||||
"--enrich",
|
||||
is_flag=True,
|
||||
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(
|
||||
"--imdb",
|
||||
@@ -506,6 +506,12 @@ class dl:
|
||||
@click.option(
|
||||
"--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(
|
||||
"--best-available",
|
||||
"best_available",
|
||||
@@ -528,9 +534,9 @@ class dl:
|
||||
repack: bool = False,
|
||||
tag: Optional[str] = None,
|
||||
tmdb_id: Optional[int] = None,
|
||||
tmdb_name: bool = False,
|
||||
tmdb_year: bool = False,
|
||||
imdb_id: Optional[str] = None,
|
||||
animeapi_id: Optional[str] = None,
|
||||
enrich: bool = False,
|
||||
output_dir: Optional[Path] = None,
|
||||
*_: Any,
|
||||
**__: Any,
|
||||
@@ -575,11 +581,24 @@ class dl:
|
||||
|
||||
self.profile = profile
|
||||
self.tmdb_id = tmdb_id
|
||||
self.tmdb_name = tmdb_name
|
||||
self.tmdb_year = tmdb_year
|
||||
self.imdb_id = imdb_id
|
||||
self.enrich = enrich
|
||||
self.animeapi_title: Optional[str] = None
|
||||
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
|
||||
if config.debug or logging.root.level == logging.DEBUG:
|
||||
from collections import defaultdict
|
||||
@@ -601,14 +620,23 @@ class dl:
|
||||
"profile": profile,
|
||||
"proxy": proxy,
|
||||
"tag": tag,
|
||||
"tmdb_id": tmdb_id,
|
||||
"tmdb_name": tmdb_name,
|
||||
"tmdb_year": tmdb_year,
|
||||
"imdb_id": imdb_id,
|
||||
"tmdb_id": self.tmdb_id,
|
||||
"imdb_id": self.imdb_id,
|
||||
"animeapi_id": animeapi_id,
|
||||
"enrich": enrich,
|
||||
"cli_params": {
|
||||
k: v
|
||||
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,
|
||||
workers: Optional[int],
|
||||
downloads: int,
|
||||
worst: bool,
|
||||
best_available: bool,
|
||||
split_audio: Optional[bool] = None,
|
||||
*_: Any,
|
||||
@@ -994,6 +1023,10 @@ class dl:
|
||||
self.log.error("--require-subs and --s-lang cannot be used together")
|
||||
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:
|
||||
self.log.error("--select-titles and -w/--wanted cannot be used together")
|
||||
sys.exit(1)
|
||||
@@ -1089,40 +1122,51 @@ class dl:
|
||||
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
|
||||
|
||||
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
|
||||
kind = "tv" if isinstance(sample_title, Episode) else "movie"
|
||||
|
||||
tmdb_year_val = None
|
||||
tmdb_name_val = None
|
||||
enrich_title: Optional[str] = None
|
||||
enrich_year: Optional[int] = None
|
||||
|
||||
if self.tmdb_year:
|
||||
tmdb_year_val = providers.get_year_by_id(
|
||||
if self.animeapi_title:
|
||||
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
|
||||
)
|
||||
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:
|
||||
tmdb_name_val = providers.get_title_by_id(
|
||||
self.tmdb_id, kind, title_cacher, cache_title_id, cache_region, cache_account_hash
|
||||
)
|
||||
|
||||
if isinstance(titles, (Series, Movies)):
|
||||
for t in titles:
|
||||
if tmdb_year_val:
|
||||
t.year = tmdb_year_val
|
||||
if tmdb_name_val:
|
||||
if isinstance(t, Episode):
|
||||
t.title = tmdb_name_val
|
||||
if enrich_title or enrich_year:
|
||||
if isinstance(titles, (Series, Movies)):
|
||||
for t in titles:
|
||||
if enrich_title:
|
||||
if isinstance(t, Episode):
|
||||
t.title = enrich_title
|
||||
else:
|
||||
t.name = enrich_title
|
||||
if enrich_year and not t.year:
|
||||
t.year = enrich_year
|
||||
else:
|
||||
if enrich_title:
|
||||
if isinstance(titles, Episode):
|
||||
titles.title = enrich_title
|
||||
else:
|
||||
t.name = tmdb_name_val
|
||||
else:
|
||||
if tmdb_year_val:
|
||||
titles.year = tmdb_year_val
|
||||
if tmdb_name_val:
|
||||
if isinstance(titles, Episode):
|
||||
titles.title = tmdb_name_val
|
||||
else:
|
||||
titles.name = tmdb_name_val
|
||||
titles.name = enrich_title
|
||||
if enrich_year and not titles.year:
|
||||
titles.year = enrich_year
|
||||
|
||||
console.print(Padding(Rule(f"[rule.text]{titles.__class__.__name__}: {titles}"), (1, 2)))
|
||||
|
||||
@@ -1181,7 +1225,7 @@ class dl:
|
||||
page_size=8,
|
||||
return_indices=True,
|
||||
dependencies=dependencies,
|
||||
collapse_on_start=multiple_seasons
|
||||
collapse_on_start=multiple_seasons,
|
||||
)
|
||||
|
||||
if not selected_ui_idx:
|
||||
@@ -1309,6 +1353,15 @@ class dl:
|
||||
v_lang = None
|
||||
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"):
|
||||
try:
|
||||
title.tracks.add(service.get_tracks(title), warn_only=True)
|
||||
@@ -1567,20 +1620,18 @@ class dl:
|
||||
for resolution, color_range, codec in product(
|
||||
quality or [None], non_hybrid_ranges, vcodec or [None]
|
||||
):
|
||||
match = next(
|
||||
(
|
||||
t
|
||||
for t in non_hybrid_tracks
|
||||
if (
|
||||
not resolution
|
||||
or t.height == resolution
|
||||
or int(t.width * (9 / 16)) == resolution
|
||||
)
|
||||
and (not color_range or t.range == color_range)
|
||||
and (not codec or t.codec == codec)
|
||||
),
|
||||
None,
|
||||
)
|
||||
candidates = [
|
||||
t
|
||||
for t in non_hybrid_tracks
|
||||
if (
|
||||
not resolution
|
||||
or t.height == resolution
|
||||
or int(t.width * (9 / 16)) == resolution
|
||||
)
|
||||
and (not color_range or t.range == color_range)
|
||||
and (not codec or t.codec == codec)
|
||||
]
|
||||
match = candidates[-1] if worst and candidates else next(iter(candidates), None)
|
||||
if match and match not in non_hybrid_selected:
|
||||
non_hybrid_selected.append(match)
|
||||
|
||||
@@ -1590,20 +1641,18 @@ class dl:
|
||||
for resolution, color_range, codec in product(
|
||||
quality or [None], range_ or [None], vcodec or [None]
|
||||
):
|
||||
match = next(
|
||||
(
|
||||
t
|
||||
for t in title.tracks.videos
|
||||
if (
|
||||
not resolution
|
||||
or t.height == resolution
|
||||
or int(t.width * (9 / 16)) == resolution
|
||||
)
|
||||
and (not color_range or t.range == color_range)
|
||||
and (not codec or t.codec == codec)
|
||||
),
|
||||
None,
|
||||
)
|
||||
candidates = [
|
||||
t
|
||||
for t in title.tracks.videos
|
||||
if (
|
||||
not resolution
|
||||
or t.height == resolution
|
||||
or int(t.width * (9 / 16)) == resolution
|
||||
)
|
||||
and (not color_range or t.range == color_range)
|
||||
and (not codec or t.codec == codec)
|
||||
]
|
||||
match = candidates[-1] if worst and candidates else next(iter(candidates), None)
|
||||
if match and match not in selected_videos:
|
||||
selected_videos.append(match)
|
||||
title.tracks.videos = selected_videos
|
||||
@@ -1663,8 +1712,6 @@ class dl:
|
||||
f"Required languages found ({', '.join(require_subs)}), downloading all available subtitles"
|
||||
)
|
||||
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
|
||||
|
||||
missing_langs = [
|
||||
@@ -1984,49 +2031,6 @@ class dl:
|
||||
dl_time = time_elapsed_since(dl_start_time)
|
||||
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 = config.subtitle.get("output_mode", "mux")
|
||||
sidecar_format = config.subtitle.get("sidecar_format", "srt")
|
||||
@@ -2092,6 +2096,75 @@ class dl:
|
||||
if has_decrypted:
|
||||
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
|
||||
with console.status("Repackaging tracks with FFMPEG..."):
|
||||
has_repacked = False
|
||||
@@ -2399,13 +2472,16 @@ class dl:
|
||||
|
||||
final_dir.mkdir(parents=True, exist_ok=True)
|
||||
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"
|
||||
)
|
||||
sep = config.get_template_separator(template_type)
|
||||
|
||||
if final_path.exists() and audio_codec_suffix and append_audio_codec_suffix:
|
||||
sep = "." if config.scene_naming else " "
|
||||
final_filename = f"{final_filename.rstrip()}{sep}{audio_codec_suffix.name}"
|
||||
final_path = final_dir / f"{final_filename}{muxed_path.suffix}"
|
||||
|
||||
if final_path in used_final_paths:
|
||||
sep = "." if config.scene_naming else " "
|
||||
i = 2
|
||||
while final_path in used_final_paths:
|
||||
final_path = final_dir / f"{final_filename.rstrip()}{sep}{i}{muxed_path.suffix}"
|
||||
|
||||
@@ -1 +1 @@
|
||||
__version__ = "3.1.0"
|
||||
__version__ = "4.0.0"
|
||||
|
||||
@@ -10,6 +10,7 @@ from contextlib import suppress
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta
|
||||
from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
|
||||
log = logging.getLogger("download_manager")
|
||||
@@ -105,11 +106,44 @@ def _perform_download(
|
||||
from unshackle.commands.dl import dl
|
||||
from unshackle.core.config import config
|
||||
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.collections import merge_dict
|
||||
|
||||
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
|
||||
service_config_path = Services.get_path(service) / config.filenames.config
|
||||
if service_config_path.exists():
|
||||
@@ -127,10 +161,15 @@ def _perform_download(
|
||||
"proxy": params.get("proxy"),
|
||||
"no_proxy": params.get("no_proxy", False),
|
||||
"profile": params.get("profile"),
|
||||
"repack": params.get("repack", False),
|
||||
"tag": params.get("tag"),
|
||||
"tmdb_id": params.get("tmdb_id"),
|
||||
"tmdb_name": params.get("tmdb_name", False),
|
||||
"tmdb_year": params.get("tmdb_year", False),
|
||||
"imdb_id": params.get("imdb_id"),
|
||||
"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(
|
||||
@@ -138,10 +177,13 @@ def _perform_download(
|
||||
no_proxy=params.get("no_proxy", False),
|
||||
profile=params.get("profile"),
|
||||
proxy=params.get("proxy"),
|
||||
repack=params.get("repack", False),
|
||||
tag=params.get("tag"),
|
||||
tmdb_id=params.get("tmdb_id"),
|
||||
tmdb_name=params.get("tmdb_name", False),
|
||||
tmdb_year=params.get("tmdb_year", False),
|
||||
imdb_id=params.get("imdb_id"),
|
||||
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)
|
||||
@@ -220,14 +262,14 @@ def _perform_download(
|
||||
dl_instance.result(
|
||||
service=service_instance,
|
||||
quality=params.get("quality", []),
|
||||
vcodec=params.get("vcodec"),
|
||||
vcodec=params.get("vcodec", []),
|
||||
acodec=params.get("acodec"),
|
||||
vbitrate=params.get("vbitrate"),
|
||||
abitrate=params.get("abitrate"),
|
||||
range_=params.get("range", ["SDR"]),
|
||||
channels=params.get("channels"),
|
||||
no_atmos=params.get("no_atmos", False),
|
||||
split_audio=params.get("split_audio"),
|
||||
select_titles=False,
|
||||
wanted=params.get("wanted", []),
|
||||
latest_episode=params.get("latest_episode", False),
|
||||
lang=params.get("lang", ["orig"]),
|
||||
@@ -245,6 +287,7 @@ def _perform_download(
|
||||
no_subs=params.get("no_subs", False),
|
||||
no_audio=params.get("no_audio", False),
|
||||
no_chapters=params.get("no_chapters", False),
|
||||
no_video=params.get("no_video", False),
|
||||
audio_description=params.get("audio_description", False),
|
||||
slow=params.get("slow", False),
|
||||
list_=False,
|
||||
@@ -259,6 +302,7 @@ def _perform_download(
|
||||
workers=params.get("workers"),
|
||||
downloads=params.get("downloads", 1),
|
||||
best_available=params.get("best_available", False),
|
||||
split_audio=params.get("split_audio"),
|
||||
)
|
||||
|
||||
except SystemExit as exc:
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import enum
|
||||
import logging
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
@@ -42,8 +43,10 @@ DEFAULT_DOWNLOAD_PARAMS = {
|
||||
"no_subs": False,
|
||||
"no_audio": False,
|
||||
"no_chapters": False,
|
||||
"no_video": False,
|
||||
"audio_description": False,
|
||||
"slow": False,
|
||||
"split_audio": None,
|
||||
"skip_dl": False,
|
||||
"export": None,
|
||||
"cdm_only": None,
|
||||
@@ -54,6 +57,11 @@ DEFAULT_DOWNLOAD_PARAMS = {
|
||||
"workers": None,
|
||||
"downloads": 1,
|
||||
"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
|
||||
|
||||
|
||||
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:
|
||||
"""Handle list-titles request."""
|
||||
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:
|
||||
if hasattr(param, "name") and param.name not in service_kwargs:
|
||||
# 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
|
||||
|
||||
# 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:
|
||||
if hasattr(param, "name") and param.name not in service_kwargs:
|
||||
# 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
|
||||
|
||||
# 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:
|
||||
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]}...")
|
||||
except Exception as e:
|
||||
raise APIError(
|
||||
@@ -760,9 +902,17 @@ def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]:
|
||||
None if valid, error message string if invalid
|
||||
"""
|
||||
if "vcodec" in data and data["vcodec"]:
|
||||
valid_vcodecs = ["H264", "H265", "VP9", "AV1"]
|
||||
if data["vcodec"].upper() not in valid_vcodecs:
|
||||
return f"Invalid vcodec: {data['vcodec']}. Must be one of: {', '.join(valid_vcodecs)}"
|
||||
valid_vcodecs = ["H264", "H265", "H.264", "H.265", "AVC", "HEVC", "VC1", "VC-1", "VP8", "VP9", "AV1"]
|
||||
if isinstance(data["vcodec"], str):
|
||||
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"]:
|
||||
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)}"
|
||||
|
||||
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:
|
||||
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
|
||||
if hasattr(service_module, "cli") and hasattr(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)
|
||||
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.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,
|
||||
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.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)
|
||||
|
||||
|
||||
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:
|
||||
"""
|
||||
List titles for a service and title ID.
|
||||
@@ -409,11 +497,19 @@ async def download(request: web.Request) -> web.Response:
|
||||
type: integer
|
||||
description: Download resolution(s) (default - best available)
|
||||
vcodec:
|
||||
type: string
|
||||
description: Video codec to download (e.g., H264, H265, VP9, AV1) (default - None)
|
||||
oneOf:
|
||||
- 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:
|
||||
type: string
|
||||
description: Audio codec(s) to download (e.g., AAC or AAC,EC3) (default - None)
|
||||
oneOf:
|
||||
- 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:
|
||||
type: integer
|
||||
description: Video bitrate in kbps (default - None)
|
||||
@@ -424,7 +520,7 @@ async def download(request: web.Request) -> web.Response:
|
||||
type: array
|
||||
items:
|
||||
type: string
|
||||
description: Video color range (SDR, HDR10, DV) (default - ["SDR"])
|
||||
description: Video color range (SDR, HDR10, HDR10+, HLG, DV, HYBRID) (default - ["SDR"])
|
||||
channels:
|
||||
type: number
|
||||
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:
|
||||
type: boolean
|
||||
description: Do not download chapters (default - false)
|
||||
no_video:
|
||||
type: boolean
|
||||
description: Do not download video tracks (default - false)
|
||||
audio_description:
|
||||
type: boolean
|
||||
description: Download audio description tracks (default - false)
|
||||
slow:
|
||||
type: boolean
|
||||
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:
|
||||
type: boolean
|
||||
description: Skip downloading, only retrieve decryption keys (default - false)
|
||||
@@ -521,12 +623,12 @@ async def download(request: web.Request) -> web.Response:
|
||||
tmdb_id:
|
||||
type: integer
|
||||
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
|
||||
description: Rename titles using TMDB name (default - false)
|
||||
tmdb_year:
|
||||
type: boolean
|
||||
description: Use release year from TMDB (default - false)
|
||||
description: Override show title and year from external source (default - false)
|
||||
no_folder:
|
||||
type: boolean
|
||||
description: Disable folder creation for TV shows (default - false)
|
||||
@@ -545,6 +647,21 @@ async def download(request: web.Request) -> web.Response:
|
||||
best_available:
|
||||
type: boolean
|
||||
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:
|
||||
'202':
|
||||
description: Download job created
|
||||
@@ -723,6 +840,7 @@ def setup_routes(app: web.Application) -> None:
|
||||
"""Setup all API routes."""
|
||||
app.router.add_get("/api/health", health)
|
||||
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-tracks", list_tracks)
|
||||
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/services", services),
|
||||
web.post("/api/search", search),
|
||||
web.post("/api/list-titles", list_titles),
|
||||
web.post("/api/list-tracks", list_tracks),
|
||||
web.post("/api/download", download),
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
@@ -93,11 +95,27 @@ class Config:
|
||||
self.decrypt_labs_api_key: str = kwargs.get("decrypt_labs_api_key") or ""
|
||||
self.update_checks: bool = kwargs.get("update_checks", True)
|
||||
self.update_check_interval: int = kwargs.get("update_check_interval", 24)
|
||||
self.scene_naming: bool = kwargs.get("scene_naming", True)
|
||||
self.dash_naming: bool = kwargs.get("dash_naming", False)
|
||||
self.series_year: bool = kwargs.get("series_year", True)
|
||||
|
||||
self.language_tags: dict = kwargs.get("language_tags") or {}
|
||||
self.output_template: dict = kwargs.get("output_template") or {}
|
||||
|
||||
if kwargs.get("scene_naming") is not None:
|
||||
raise SystemExit(
|
||||
"ERROR: The 'scene_naming' option has been removed.\n"
|
||||
"Please configure 'output_template' in your unshackle.yaml instead.\n"
|
||||
"See unshackle-example.yaml for examples."
|
||||
)
|
||||
|
||||
if not self.output_template:
|
||||
raise SystemExit(
|
||||
"ERROR: No 'output_template' configured in your unshackle.yaml.\n"
|
||||
"Please add an 'output_template' section with movies, series, and songs templates.\n"
|
||||
"See unshackle-example.yaml for examples."
|
||||
)
|
||||
|
||||
self._validate_output_templates()
|
||||
|
||||
self.unicode_filenames: bool = kwargs.get("unicode_filenames", False)
|
||||
self.insert_episodename_into_filenames: bool = kwargs.get("insert_episodename_into_filenames", True)
|
||||
|
||||
self.title_cache_time: int = kwargs.get("title_cache_time", 1800) # 30 minutes default
|
||||
self.title_cache_max_retention: int = kwargs.get("title_cache_max_retention", 86400) # 24 hours default
|
||||
@@ -106,6 +124,78 @@ class Config:
|
||||
self.debug: bool = kwargs.get("debug", False)
|
||||
self.debug_keys: bool = kwargs.get("debug_keys", False)
|
||||
|
||||
def _validate_output_templates(self) -> None:
|
||||
"""Validate output template configurations and warn about potential issues."""
|
||||
if not self.output_template:
|
||||
return
|
||||
|
||||
valid_variables = {
|
||||
"title",
|
||||
"year",
|
||||
"season",
|
||||
"episode",
|
||||
"season_episode",
|
||||
"episode_name",
|
||||
"quality",
|
||||
"resolution",
|
||||
"source",
|
||||
"tag",
|
||||
"track_number",
|
||||
"artist",
|
||||
"album",
|
||||
"disc",
|
||||
"audio",
|
||||
"audio_channels",
|
||||
"audio_full",
|
||||
"atmos",
|
||||
"dual",
|
||||
"multi",
|
||||
"video",
|
||||
"hdr",
|
||||
"hfr",
|
||||
"edition",
|
||||
"repack",
|
||||
"lang_tag",
|
||||
}
|
||||
|
||||
unsafe_chars = r'[<>:"/\\|?*]'
|
||||
|
||||
for template_type, template_str in self.output_template.items():
|
||||
if not isinstance(template_str, str):
|
||||
warnings.warn(f"Template '{template_type}' must be a string, got {type(template_str).__name__}")
|
||||
continue
|
||||
|
||||
variables = re.findall(r"\{([^}]+)\}", template_str)
|
||||
|
||||
for var in variables:
|
||||
var_clean = var.rstrip("?")
|
||||
if var_clean not in valid_variables:
|
||||
warnings.warn(f"Unknown template variable '{var}' in {template_type} template")
|
||||
|
||||
test_template = re.sub(r"\{[^}]+\}", "TEST", template_str)
|
||||
if re.search(unsafe_chars, test_template):
|
||||
warnings.warn(f"Template '{template_type}' may contain filesystem-unsafe characters")
|
||||
|
||||
if not template_str.strip():
|
||||
warnings.warn(f"Template '{template_type}' is empty")
|
||||
|
||||
def get_template_separator(self, template_type: str = "movies") -> str:
|
||||
"""Get the filename separator for the given template type.
|
||||
|
||||
Analyzes the active template to determine whether it uses dots or spaces
|
||||
between variables. Falls back to dot separator (scene-style) by default.
|
||||
|
||||
Args:
|
||||
template_type: One of "movies", "series", or "songs".
|
||||
"""
|
||||
template = self.output_template[template_type]
|
||||
between_vars = re.findall(r"\}([^{]*)\{", template)
|
||||
separator_text = "".join(between_vars)
|
||||
dot_count = separator_text.count(".")
|
||||
space_count = separator_text.count(" ")
|
||||
|
||||
return " " if space_count > dot_count else "."
|
||||
|
||||
@classmethod
|
||||
def from_yaml(cls, path: Path) -> Config:
|
||||
if not path.exists():
|
||||
|
||||
@@ -431,14 +431,24 @@ def download(
|
||||
raise ValueError(error)
|
||||
|
||||
# Yield aggregate progress for this call's downloads
|
||||
if total_size > 0:
|
||||
# Yield both advance (bytes downloaded this iteration) and total for rich progress
|
||||
if dl_speed != -1:
|
||||
yield dict(downloaded=f"{filesize.decimal(dl_speed)}/s", advance=0, completed=total_completed, total=total_size)
|
||||
progress_data = {"advance": 0}
|
||||
|
||||
if len(gids) > 1:
|
||||
# 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:
|
||||
yield dict(advance=0, completed=total_completed, total=total_size)
|
||||
elif dl_speed != -1:
|
||||
yield dict(downloaded=f"{filesize.decimal(dl_speed)}/s")
|
||||
progress_data["total"] = None
|
||||
|
||||
if dl_speed != -1:
|
||||
progress_data["downloaded"] = f"{filesize.decimal(dl_speed)}/s"
|
||||
|
||||
yield progress_data
|
||||
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
|
||||
@@ -44,16 +44,15 @@ class PlayReady:
|
||||
else:
|
||||
kids = []
|
||||
|
||||
# Extract KIDs using pyplayready's method (may miss some KIDs)
|
||||
# Extract KIDs using pyplayready's WrmHeader key_ids
|
||||
if not kids:
|
||||
for header in pssh.wrm_headers:
|
||||
try:
|
||||
signed_ids, _, _, _ = header.read_attributes()
|
||||
except Exception:
|
||||
continue
|
||||
for signed_id in signed_ids:
|
||||
for signed_key_id in getattr(header, "key_ids", []):
|
||||
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:
|
||||
continue
|
||||
|
||||
@@ -119,7 +118,33 @@ class PlayReady:
|
||||
except Exception:
|
||||
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)
|
||||
for kid_elem in individual_kids:
|
||||
if kid_elem.text:
|
||||
|
||||
@@ -7,7 +7,7 @@ import math
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
from copy import copy
|
||||
from copy import copy, deepcopy
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Optional, Union
|
||||
@@ -18,6 +18,7 @@ from zlib import crc32
|
||||
import requests
|
||||
from curl_cffi.requests import Session as CurlSession
|
||||
from langcodes import Language, tag_is_valid
|
||||
from lxml import etree
|
||||
from lxml.etree import Element, ElementTree
|
||||
from pyplayready.system.pssh import PSSH as PR_PSSH
|
||||
from pywidevine.cdm import Cdm as WidevineCdm
|
||||
@@ -101,14 +102,22 @@ class DASH:
|
||||
"""
|
||||
tracks = Tracks()
|
||||
|
||||
filtered_period_ids: list[str] = []
|
||||
|
||||
for period in self.manifest.findall("Period"):
|
||||
if callable(period_filter) and period_filter(period):
|
||||
if period_id := period.get("id"):
|
||||
filtered_period_ids.append(period_id)
|
||||
continue
|
||||
if next(iter(period.xpath("SegmentType/@value")), "content") != "content":
|
||||
if period_id := period.get("id"):
|
||||
filtered_period_ids.append(period_id)
|
||||
continue
|
||||
if "urn:amazon:primevideo:cachingBreadth" in [
|
||||
x.get("schemeIdUri") for x in period.findall("SupplementalProperty")
|
||||
]:
|
||||
if period_id := period.get("id"):
|
||||
filtered_period_ids.append(period_id)
|
||||
continue
|
||||
|
||||
for adaptation_set in period.findall("AdaptationSet"):
|
||||
@@ -235,6 +244,7 @@ class DASH:
|
||||
"period": period,
|
||||
"adaptation_set": adaptation_set,
|
||||
"representation": rep,
|
||||
"filtered_period_ids": filtered_period_ids,
|
||||
}
|
||||
},
|
||||
**track_args,
|
||||
@@ -541,6 +551,26 @@ class DASH:
|
||||
skip_merge = False
|
||||
if downloader.__name__ == "n_m3u8dl_re":
|
||||
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(
|
||||
{
|
||||
"filename": track.id,
|
||||
@@ -578,6 +608,11 @@ class DASH:
|
||||
status_update["downloaded"] = f"DASH {downloaded}"
|
||||
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
|
||||
for control_file in save_dir.glob("*.aria2__temp"):
|
||||
control_file.unlink()
|
||||
|
||||
@@ -112,6 +112,15 @@ class HLS:
|
||||
session_drm = HLS.get_all_drm(session_keys)
|
||||
|
||||
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()
|
||||
|
||||
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,
|
||||
height=playlist.stream_info.resolution[1] if playlist.stream_info.resolution else None,
|
||||
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
|
||||
else {}
|
||||
|
||||
@@ -145,7 +145,14 @@ class ISM:
|
||||
fragment_time += duration_frag
|
||||
|
||||
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()
|
||||
|
||||
data = {
|
||||
|
||||
@@ -44,6 +44,17 @@ FINGERPRINT_PRESETS = {
|
||||
"akamai": "4:16777216|16711681|0|m,p,a,s",
|
||||
"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)",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -9,9 +9,9 @@ from rich.tree import Tree
|
||||
from sortedcontainers import SortedKeyList
|
||||
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import AUDIO_CODEC_MAP, DYNAMIC_RANGE_MAP, VIDEO_CODEC_MAP
|
||||
from unshackle.core.titles.title import Title
|
||||
from unshackle.core.utilities import sanitize_filename
|
||||
from unshackle.core.utils.template_formatter import TemplateFormatter
|
||||
|
||||
|
||||
class Episode(Title):
|
||||
@@ -78,180 +78,60 @@ class Episode(Title):
|
||||
self.year = year
|
||||
self.description = description
|
||||
|
||||
def _build_template_context(self, media_info: MediaInfo, show_service: bool = True) -> dict:
|
||||
"""Build template context dictionary from MediaInfo."""
|
||||
context = self._build_base_template_context(media_info, show_service)
|
||||
context["title"] = self.title.replace("$", "S")
|
||||
context["year"] = self.year or ""
|
||||
context["season"] = f"S{self.season:02}"
|
||||
context["episode"] = f"E{self.number:02}"
|
||||
context["season_episode"] = f"S{self.season:02}E{self.number:02}"
|
||||
context["episode_name"] = self.name or ""
|
||||
return context
|
||||
|
||||
def __str__(self) -> str:
|
||||
return "{title}{year} S{season:02}E{number:02} {name}".format(
|
||||
title=self.title,
|
||||
year=f" {self.year}" if self.year and config.series_year else "",
|
||||
year=f" {self.year}" if self.year else "",
|
||||
season=self.season,
|
||||
number=self.number,
|
||||
name=self.name or "",
|
||||
).strip()
|
||||
|
||||
def get_filename(self, media_info: MediaInfo, folder: bool = False, show_service: bool = True) -> str:
|
||||
primary_video_track = next(iter(media_info.video_tracks), None)
|
||||
primary_audio_track = None
|
||||
if media_info.audio_tracks:
|
||||
sorted_audio = sorted(
|
||||
media_info.audio_tracks,
|
||||
key=lambda x: (
|
||||
float(x.bit_rate) if x.bit_rate else 0,
|
||||
bool(x.format_additionalfeatures and "JOC" in x.format_additionalfeatures),
|
||||
),
|
||||
reverse=True,
|
||||
)
|
||||
primary_audio_track = sorted_audio[0]
|
||||
unique_audio_languages = len({x.language.split("-")[0] for x in media_info.audio_tracks if x.language})
|
||||
|
||||
def _get_resolution_token(track: Any) -> str:
|
||||
if not track or not getattr(track, "height", None):
|
||||
return ""
|
||||
width = getattr(track, "width", track.height)
|
||||
resolution = min(width, track.height)
|
||||
try:
|
||||
dar = getattr(track, "other_display_aspect_ratio", None) or []
|
||||
if dar and dar[0]:
|
||||
aspect_ratio = [int(float(plane)) for plane in str(dar[0]).split(":")]
|
||||
if len(aspect_ratio) == 1:
|
||||
aspect_ratio.append(1)
|
||||
ratio = aspect_ratio[0] / aspect_ratio[1]
|
||||
if ratio not in (16 / 9, 4 / 3, 9 / 16, 3 / 4):
|
||||
resolution = int(max(width, track.height) * (9 / 16))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
scan_suffix = "i" if str(getattr(track, "scan_type", "")).lower() == "interlaced" else "p"
|
||||
return f"{resolution}{scan_suffix}"
|
||||
|
||||
# Title [Year] SXXEXX Name (or Title [Year] SXX if folder)
|
||||
if folder:
|
||||
name = f"{self.title}"
|
||||
if self.year and config.series_year:
|
||||
name += f" {self.year}"
|
||||
name += f" S{self.season:02}"
|
||||
else:
|
||||
if config.dash_naming:
|
||||
# Format: Title - SXXEXX - Episode Name
|
||||
name = self.title.replace("$", "S") # e.g., Arli$$
|
||||
series_template = config.output_template.get("series")
|
||||
if series_template:
|
||||
folder_template = series_template
|
||||
folder_template = re.sub(r'\{episode\}', '', folder_template)
|
||||
folder_template = re.sub(r'\{episode_name\?\}', '', folder_template)
|
||||
folder_template = re.sub(r'\{episode_name\}', '', folder_template)
|
||||
folder_template = re.sub(r'\{season_episode\}', '{season}', folder_template)
|
||||
|
||||
# Add year if configured
|
||||
if self.year and config.series_year:
|
||||
name += f" {self.year}"
|
||||
folder_template = re.sub(r'\.{2,}', '.', folder_template)
|
||||
folder_template = re.sub(r'\s{2,}', ' ', folder_template)
|
||||
folder_template = re.sub(r'^[\.\s]+|[\.\s]+$', '', folder_template)
|
||||
|
||||
# Add season and episode
|
||||
name += f" - S{self.season:02}E{self.number:02}"
|
||||
formatter = TemplateFormatter(folder_template)
|
||||
context = self._build_template_context(media_info, show_service)
|
||||
context['season'] = f"S{self.season:02}"
|
||||
|
||||
# Add episode name with dash separator
|
||||
if self.name and config.insert_episodename_into_filenames:
|
||||
name += f" - {self.name}"
|
||||
folder_name = formatter.format(context)
|
||||
|
||||
name = name.strip()
|
||||
else:
|
||||
# Standard format without extra dashes
|
||||
name = "{title}{year} S{season:02}E{number:02} {name}".format(
|
||||
title=self.title.replace("$", "S"), # e.g., Arli$$
|
||||
year=f" {self.year}" if self.year and config.series_year else "",
|
||||
season=self.season,
|
||||
number=self.number,
|
||||
name=self.name if self.name and config.insert_episodename_into_filenames else "",
|
||||
).strip()
|
||||
|
||||
if getattr(config, "repack", False):
|
||||
name += " REPACK"
|
||||
|
||||
if self.tracks:
|
||||
first_track = next(iter(self.tracks), None)
|
||||
if first_track and first_track.edition:
|
||||
name += " " + " ".join(first_track.edition)
|
||||
|
||||
if primary_video_track:
|
||||
resolution_token = _get_resolution_token(primary_video_track)
|
||||
if resolution_token:
|
||||
name += f" {resolution_token}"
|
||||
|
||||
# Service (use track source if available)
|
||||
if show_service:
|
||||
source_name = None
|
||||
if self.tracks:
|
||||
first_track = next(iter(self.tracks), None)
|
||||
if first_track and hasattr(first_track, "source") and first_track.source:
|
||||
source_name = first_track.source
|
||||
name += f" {source_name or self.service.__name__}"
|
||||
|
||||
# 'WEB-DL'
|
||||
name += " WEB-DL"
|
||||
|
||||
# DUAL
|
||||
if unique_audio_languages == 2:
|
||||
name += " DUAL"
|
||||
|
||||
# MULTi
|
||||
if unique_audio_languages > 2:
|
||||
name += " MULTi"
|
||||
|
||||
# Audio Codec + Channels (+ feature)
|
||||
if primary_audio_track:
|
||||
codec = primary_audio_track.format
|
||||
channel_layout = primary_audio_track.channel_layout or primary_audio_track.channellayout_original
|
||||
if channel_layout:
|
||||
channels = float(
|
||||
sum({"LFE": 0.1}.get(position.upper(), 1) for position in channel_layout.split(" "))
|
||||
)
|
||||
else:
|
||||
channel_count = primary_audio_track.channel_s or primary_audio_track.channels or 0
|
||||
channels = float(channel_count)
|
||||
|
||||
features = primary_audio_track.format_additionalfeatures or ""
|
||||
name += f" {AUDIO_CODEC_MAP.get(codec, codec)}{channels:.1f}"
|
||||
if "JOC" in features or primary_audio_track.joc:
|
||||
name += " Atmos"
|
||||
|
||||
# Video (dynamic range + hfr +) Codec
|
||||
if primary_video_track:
|
||||
codec = primary_video_track.format
|
||||
hdr_format = primary_video_track.hdr_format_commercial
|
||||
hdr_format_full = primary_video_track.hdr_format or ""
|
||||
trc = (
|
||||
primary_video_track.transfer_characteristics
|
||||
or primary_video_track.transfer_characteristics_original
|
||||
or ""
|
||||
)
|
||||
frame_rate = float(primary_video_track.frame_rate)
|
||||
|
||||
def _append_token(current: str, token: Optional[str]) -> str:
|
||||
token = (token or "").strip()
|
||||
current = current.rstrip()
|
||||
if not token:
|
||||
return current
|
||||
if current.endswith(f" {token}"):
|
||||
return current
|
||||
return f"{current} {token}"
|
||||
|
||||
# Primary HDR format detection
|
||||
if hdr_format:
|
||||
if hdr_format_full.startswith("Dolby Vision"):
|
||||
name = _append_token(name, "DV")
|
||||
if any(
|
||||
indicator in (hdr_format_full + " " + hdr_format)
|
||||
for indicator in ["HDR10", "SMPTE ST 2086"]
|
||||
):
|
||||
name = _append_token(name, "HDR")
|
||||
elif "HDR Vivid" in hdr_format:
|
||||
name = _append_token(name, "HDR")
|
||||
if '.' in series_template and ' ' not in series_template:
|
||||
return sanitize_filename(folder_name, ".")
|
||||
else:
|
||||
dynamic_range = DYNAMIC_RANGE_MAP.get(hdr_format) or hdr_format or ""
|
||||
name = _append_token(name, dynamic_range)
|
||||
elif "HLG" in trc or "Hybrid Log-Gamma" in trc or "ARIB STD-B67" in trc or "arib-std-b67" in trc.lower():
|
||||
name += " HLG"
|
||||
elif any(indicator in trc for indicator in ["PQ", "SMPTE ST 2084", "BT.2100"]) or "smpte2084" in trc.lower() or "bt.2020-10" in trc.lower():
|
||||
name += " HDR"
|
||||
if frame_rate > 30:
|
||||
name += " HFR"
|
||||
name += f" {VIDEO_CODEC_MAP.get(codec, codec)}"
|
||||
return sanitize_filename(folder_name, " ")
|
||||
else:
|
||||
name = f"{self.title}"
|
||||
if self.year:
|
||||
name += f" {self.year}"
|
||||
name += f" S{self.season:02}"
|
||||
return sanitize_filename(name, " ")
|
||||
|
||||
if config.tag:
|
||||
name += f"-{config.tag}"
|
||||
|
||||
return sanitize_filename(name, "." if config.scene_naming else " ")
|
||||
formatter = TemplateFormatter(config.output_template["series"])
|
||||
context = self._build_template_context(media_info, show_service)
|
||||
return formatter.format(context)
|
||||
|
||||
|
||||
class Series(SortedKeyList, ABC):
|
||||
@@ -261,7 +141,7 @@ class Series(SortedKeyList, ABC):
|
||||
def __str__(self) -> str:
|
||||
if not self:
|
||||
return super().__str__()
|
||||
return self[0].title + (f" ({self[0].year})" if self[0].year and config.series_year else "")
|
||||
return self[0].title + (f" ({self[0].year})" if self[0].year else "")
|
||||
|
||||
def tree(self, verbose: bool = False) -> Tree:
|
||||
seasons = Counter(x.season for x in self)
|
||||
|
||||
+16
-136
@@ -7,9 +7,9 @@ from rich.tree import Tree
|
||||
from sortedcontainers import SortedKeyList
|
||||
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import AUDIO_CODEC_MAP, DYNAMIC_RANGE_MAP, VIDEO_CODEC_MAP
|
||||
from unshackle.core.titles.title import Title
|
||||
from unshackle.core.utilities import sanitize_filename
|
||||
from unshackle.core.utils.template_formatter import TemplateFormatter
|
||||
|
||||
|
||||
class Movie(Title):
|
||||
@@ -45,148 +45,28 @@ class Movie(Title):
|
||||
self.year = year
|
||||
self.description = description
|
||||
|
||||
def _build_template_context(self, media_info: MediaInfo, show_service: bool = True) -> dict:
|
||||
"""Build template context dictionary from MediaInfo."""
|
||||
context = self._build_base_template_context(media_info, show_service)
|
||||
context["title"] = self.name.replace("$", "S")
|
||||
context["year"] = self.year or ""
|
||||
return context
|
||||
|
||||
def __str__(self) -> str:
|
||||
if self.year:
|
||||
if config.dash_naming:
|
||||
return f"{self.name} - {self.year}"
|
||||
return f"{self.name} ({self.year})"
|
||||
return self.name
|
||||
|
||||
def get_filename(self, media_info: MediaInfo, folder: bool = False, show_service: bool = True) -> str:
|
||||
primary_video_track = next(iter(media_info.video_tracks), None)
|
||||
primary_audio_track = None
|
||||
if media_info.audio_tracks:
|
||||
sorted_audio = sorted(
|
||||
media_info.audio_tracks,
|
||||
key=lambda x: (
|
||||
float(x.bit_rate) if x.bit_rate else 0,
|
||||
bool(x.format_additionalfeatures and "JOC" in x.format_additionalfeatures),
|
||||
),
|
||||
reverse=True,
|
||||
)
|
||||
primary_audio_track = sorted_audio[0]
|
||||
unique_audio_languages = len({x.language.split("-")[0] for x in media_info.audio_tracks if x.language})
|
||||
if folder:
|
||||
name = f"{self.name}"
|
||||
if self.year:
|
||||
name += f" ({self.year})"
|
||||
return sanitize_filename(name, " ")
|
||||
|
||||
def _get_resolution_token(track: Any) -> str:
|
||||
if not track or not getattr(track, "height", None):
|
||||
return ""
|
||||
width = getattr(track, "width", track.height)
|
||||
resolution = min(width, track.height)
|
||||
try:
|
||||
dar = getattr(track, "other_display_aspect_ratio", None) or []
|
||||
if dar and dar[0]:
|
||||
aspect_ratio = [int(float(plane)) for plane in str(dar[0]).split(":")]
|
||||
if len(aspect_ratio) == 1:
|
||||
aspect_ratio.append(1)
|
||||
ratio = aspect_ratio[0] / aspect_ratio[1]
|
||||
if ratio not in (16 / 9, 4 / 3, 9 / 16, 3 / 4):
|
||||
resolution = int(max(width, track.height) * (9 / 16))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
scan_suffix = "i" if str(getattr(track, "scan_type", "")).lower() == "interlaced" else "p"
|
||||
return f"{resolution}{scan_suffix}"
|
||||
|
||||
# Name (Year)
|
||||
name = str(self).replace("$", "S") # e.g., Arli$$
|
||||
|
||||
if getattr(config, "repack", False):
|
||||
name += " REPACK"
|
||||
|
||||
if self.tracks:
|
||||
first_track = next(iter(self.tracks), None)
|
||||
if first_track and first_track.edition:
|
||||
name += " " + " ".join(first_track.edition)
|
||||
|
||||
if primary_video_track:
|
||||
resolution_token = _get_resolution_token(primary_video_track)
|
||||
if resolution_token:
|
||||
name += f" {resolution_token}"
|
||||
|
||||
# Service (use track source if available)
|
||||
if show_service:
|
||||
source_name = None
|
||||
if self.tracks:
|
||||
first_track = next(iter(self.tracks), None)
|
||||
if first_track and hasattr(first_track, "source") and first_track.source:
|
||||
source_name = first_track.source
|
||||
name += f" {source_name or self.service.__name__}"
|
||||
|
||||
# 'WEB-DL'
|
||||
name += " WEB-DL"
|
||||
|
||||
# DUAL
|
||||
if unique_audio_languages == 2:
|
||||
name += " DUAL"
|
||||
|
||||
# MULTi
|
||||
if unique_audio_languages > 2:
|
||||
name += " MULTi"
|
||||
|
||||
# Audio Codec + Channels (+ feature)
|
||||
if primary_audio_track:
|
||||
codec = primary_audio_track.format
|
||||
channel_layout = primary_audio_track.channel_layout or primary_audio_track.channellayout_original
|
||||
if channel_layout:
|
||||
channels = float(
|
||||
sum({"LFE": 0.1}.get(position.upper(), 1) for position in channel_layout.split(" "))
|
||||
)
|
||||
else:
|
||||
channel_count = primary_audio_track.channel_s or primary_audio_track.channels or 0
|
||||
channels = float(channel_count)
|
||||
|
||||
features = primary_audio_track.format_additionalfeatures or ""
|
||||
name += f" {AUDIO_CODEC_MAP.get(codec, codec)}{channels:.1f}"
|
||||
if "JOC" in features or primary_audio_track.joc:
|
||||
name += " Atmos"
|
||||
|
||||
# Video (dynamic range + hfr +) Codec
|
||||
if primary_video_track:
|
||||
codec = primary_video_track.format
|
||||
hdr_format = primary_video_track.hdr_format_commercial
|
||||
hdr_format_full = primary_video_track.hdr_format or ""
|
||||
trc = (
|
||||
primary_video_track.transfer_characteristics
|
||||
or primary_video_track.transfer_characteristics_original
|
||||
or ""
|
||||
)
|
||||
frame_rate = float(primary_video_track.frame_rate)
|
||||
|
||||
def _append_token(current: str, token: Optional[str]) -> str:
|
||||
token = (token or "").strip()
|
||||
current = current.rstrip()
|
||||
if not token:
|
||||
return current
|
||||
if current.endswith(f" {token}"):
|
||||
return current
|
||||
return f"{current} {token}"
|
||||
|
||||
# Primary HDR format detection
|
||||
if hdr_format:
|
||||
if hdr_format_full.startswith("Dolby Vision"):
|
||||
name = _append_token(name, "DV")
|
||||
if any(
|
||||
indicator in (hdr_format_full + " " + hdr_format)
|
||||
for indicator in ["HDR10", "SMPTE ST 2086"]
|
||||
):
|
||||
name = _append_token(name, "HDR")
|
||||
elif "HDR Vivid" in hdr_format:
|
||||
name = _append_token(name, "HDR")
|
||||
else:
|
||||
dynamic_range = DYNAMIC_RANGE_MAP.get(hdr_format) or hdr_format or ""
|
||||
name = _append_token(name, dynamic_range)
|
||||
elif "HLG" in trc or "Hybrid Log-Gamma" in trc or "ARIB STD-B67" in trc or "arib-std-b67" in trc.lower():
|
||||
name += " HLG"
|
||||
elif any(indicator in trc for indicator in ["PQ", "SMPTE ST 2084", "BT.2100"]) or "smpte2084" in trc.lower() or "bt.2020-10" in trc.lower():
|
||||
name += " HDR"
|
||||
if frame_rate > 30:
|
||||
name += " HFR"
|
||||
name += f" {VIDEO_CODEC_MAP.get(codec, codec)}"
|
||||
|
||||
if config.tag:
|
||||
name += f"-{config.tag}"
|
||||
|
||||
return sanitize_filename(name, "." if config.scene_naming else " ")
|
||||
formatter = TemplateFormatter(config.output_template["movies"])
|
||||
context = self._build_template_context(media_info, show_service)
|
||||
return formatter.format(context)
|
||||
|
||||
|
||||
class Movies(SortedKeyList, ABC):
|
||||
|
||||
@@ -7,9 +7,9 @@ from rich.tree import Tree
|
||||
from sortedcontainers import SortedKeyList
|
||||
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import AUDIO_CODEC_MAP
|
||||
from unshackle.core.titles.title import Title
|
||||
from unshackle.core.utilities import sanitize_filename
|
||||
from unshackle.core.utils.template_formatter import TemplateFormatter
|
||||
|
||||
|
||||
class Song(Title):
|
||||
@@ -41,7 +41,7 @@ class Song(Title):
|
||||
if not album:
|
||||
raise ValueError("Song album must be provided")
|
||||
if not isinstance(album, str):
|
||||
raise TypeError(f"Expected album to be a str, not {name!r}")
|
||||
raise TypeError(f"Expected album to be a str, not {album!r}")
|
||||
|
||||
if not track:
|
||||
raise ValueError("Song track must be provided")
|
||||
@@ -81,54 +81,27 @@ class Song(Title):
|
||||
artist=self.artist, album=self.album, year=self.year, track=self.track, name=self.name
|
||||
).strip()
|
||||
|
||||
def _build_template_context(self, media_info: MediaInfo, show_service: bool = True) -> dict:
|
||||
"""Build template context dictionary from MediaInfo."""
|
||||
context = self._build_base_template_context(media_info, show_service)
|
||||
context["title"] = self.name.replace("$", "S")
|
||||
context["year"] = self.year or ""
|
||||
context["track_number"] = f"{self.track:02}"
|
||||
context["artist"] = self.artist.replace("$", "S")
|
||||
context["album"] = self.album.replace("$", "S")
|
||||
context["disc"] = f"{self.disc:02}" if self.disc > 1 else ""
|
||||
return context
|
||||
|
||||
def get_filename(self, media_info: MediaInfo, folder: bool = False, show_service: bool = True) -> str:
|
||||
audio_track = next(iter(media_info.audio_tracks), None)
|
||||
codec = audio_track.format
|
||||
channel_layout = audio_track.channel_layout or audio_track.channellayout_original
|
||||
if channel_layout:
|
||||
channels = float(sum({"LFE": 0.1}.get(position.upper(), 1) for position in channel_layout.split(" ")))
|
||||
else:
|
||||
channel_count = audio_track.channel_s or audio_track.channels or 0
|
||||
channels = float(channel_count)
|
||||
|
||||
features = audio_track.format_additionalfeatures or ""
|
||||
|
||||
if folder:
|
||||
# Artist - Album (Year)
|
||||
name = str(self).split(" / ")[0]
|
||||
else:
|
||||
# NN. Song Name
|
||||
name = str(self).split(" / ")[1]
|
||||
name = f"{self.artist} - {self.album}"
|
||||
if self.year:
|
||||
name += f" ({self.year})"
|
||||
return sanitize_filename(name, " ")
|
||||
|
||||
if getattr(config, "repack", False):
|
||||
name += " REPACK"
|
||||
|
||||
if self.tracks:
|
||||
first_track = next(iter(self.tracks), None)
|
||||
if first_track and first_track.edition:
|
||||
name += " " + " ".join(first_track.edition)
|
||||
|
||||
# Service (use track source if available)
|
||||
if show_service:
|
||||
source_name = None
|
||||
if self.tracks:
|
||||
first_track = next(iter(self.tracks), None)
|
||||
if first_track and hasattr(first_track, "source") and first_track.source:
|
||||
source_name = first_track.source
|
||||
name += f" {source_name or self.service.__name__}"
|
||||
|
||||
# 'WEB-DL'
|
||||
name += " WEB-DL"
|
||||
|
||||
# Audio Codec + Channels (+ feature)
|
||||
name += f" {AUDIO_CODEC_MAP.get(codec, codec)}{channels:.1f}"
|
||||
if "JOC" in features or audio_track.joc:
|
||||
name += " Atmos"
|
||||
|
||||
if config.tag:
|
||||
name += f"-{config.tag}"
|
||||
|
||||
return sanitize_filename(name, " ")
|
||||
formatter = TemplateFormatter(config.output_template["songs"])
|
||||
context = self._build_template_context(media_info, show_service)
|
||||
return formatter.format(context)
|
||||
|
||||
|
||||
class Album(SortedKeyList, ABC):
|
||||
|
||||
@@ -6,6 +6,8 @@ from typing import Any, Optional, Union
|
||||
from langcodes import Language
|
||||
from pymediainfo import MediaInfo
|
||||
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import AUDIO_CODEC_MAP, DYNAMIC_RANGE_MAP, VIDEO_CODEC_MAP
|
||||
from unshackle.core.tracks import Tracks
|
||||
|
||||
|
||||
@@ -51,6 +53,127 @@ class Title:
|
||||
def __eq__(self, other: Title) -> bool:
|
||||
return self.id == other.id
|
||||
|
||||
def _build_base_template_context(self, media_info: MediaInfo, show_service: bool = True) -> dict:
|
||||
"""Build base template context dictionary from MediaInfo.
|
||||
|
||||
Extracts video, audio, HDR, HFR, and multi-language information shared
|
||||
across all title types. Subclasses should call this and extend the
|
||||
returned dict with their specific fields (e.g., season/episode).
|
||||
"""
|
||||
primary_video_track = next(iter(media_info.video_tracks), None)
|
||||
primary_audio_track = next(iter(media_info.audio_tracks), None)
|
||||
unique_audio_languages = len({x.language.split("-")[0] for x in media_info.audio_tracks if x.language})
|
||||
|
||||
context: dict[str, Any] = {
|
||||
"source": self.service.__name__ if show_service else "",
|
||||
"tag": config.tag or "",
|
||||
"repack": "REPACK" if getattr(config, "repack", False) else "",
|
||||
"quality": "",
|
||||
"resolution": "",
|
||||
"audio": "",
|
||||
"audio_channels": "",
|
||||
"audio_full": "",
|
||||
"atmos": "",
|
||||
"dual": "",
|
||||
"multi": "",
|
||||
"video": "",
|
||||
"hdr": "",
|
||||
"hfr": "",
|
||||
"edition": "",
|
||||
"lang_tag": "",
|
||||
}
|
||||
|
||||
if self.tracks:
|
||||
first_track = next(iter(self.tracks), None)
|
||||
if first_track and first_track.edition:
|
||||
context["edition"] = " ".join(first_track.edition)
|
||||
|
||||
if primary_video_track:
|
||||
width = getattr(primary_video_track, "width", primary_video_track.height)
|
||||
resolution = min(width, primary_video_track.height)
|
||||
try:
|
||||
dar = getattr(primary_video_track, "other_display_aspect_ratio", None) or []
|
||||
if dar and dar[0]:
|
||||
aspect_ratio = [int(float(plane)) for plane in str(dar[0]).split(":")]
|
||||
if len(aspect_ratio) == 1:
|
||||
aspect_ratio.append(1)
|
||||
ratio = aspect_ratio[0] / aspect_ratio[1]
|
||||
if ratio not in (16 / 9, 4 / 3, 9 / 16, 3 / 4):
|
||||
resolution = int(max(width, primary_video_track.height) * (9 / 16))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
scan_suffix = "i" if str(getattr(primary_video_track, "scan_type", "")).lower() == "interlaced" else "p"
|
||||
|
||||
context.update(
|
||||
{
|
||||
"quality": f"{resolution}{scan_suffix}",
|
||||
"resolution": str(resolution),
|
||||
"video": VIDEO_CODEC_MAP.get(primary_video_track.format, primary_video_track.format),
|
||||
}
|
||||
)
|
||||
|
||||
hdr_format = primary_video_track.hdr_format_commercial
|
||||
trc = primary_video_track.transfer_characteristics or primary_video_track.transfer_characteristics_original
|
||||
if hdr_format:
|
||||
if (primary_video_track.hdr_format or "").startswith("Dolby Vision"):
|
||||
context["hdr"] = "DV"
|
||||
base_layer = DYNAMIC_RANGE_MAP.get(hdr_format)
|
||||
if base_layer and base_layer != "DV":
|
||||
context["hdr"] += f".{base_layer}"
|
||||
elif (primary_video_track.hdr_format or "").startswith("HDR Vivid"):
|
||||
context["hdr"] = "HDR"
|
||||
else:
|
||||
context["hdr"] = DYNAMIC_RANGE_MAP.get(hdr_format, "")
|
||||
elif trc and "HLG" in trc:
|
||||
context["hdr"] = "HLG"
|
||||
else:
|
||||
context["hdr"] = ""
|
||||
|
||||
frame_rate = float(primary_video_track.frame_rate) if primary_video_track.frame_rate else 0.0
|
||||
context["hfr"] = "HFR" if frame_rate > 30 else ""
|
||||
|
||||
if primary_audio_track:
|
||||
codec = primary_audio_track.format
|
||||
channel_layout = primary_audio_track.channel_layout or primary_audio_track.channellayout_original
|
||||
|
||||
if channel_layout:
|
||||
channels = float(sum({"LFE": 0.1}.get(position.upper(), 1) for position in channel_layout.split(" ")))
|
||||
else:
|
||||
channel_count = primary_audio_track.channel_s or primary_audio_track.channels or 0
|
||||
channels = float(channel_count)
|
||||
|
||||
features = primary_audio_track.format_additionalfeatures or ""
|
||||
|
||||
context.update(
|
||||
{
|
||||
"audio": AUDIO_CODEC_MAP.get(codec, codec),
|
||||
"audio_channels": f"{channels:.1f}",
|
||||
"audio_full": f"{AUDIO_CODEC_MAP.get(codec, codec)}{channels:.1f}",
|
||||
"atmos": "Atmos" if ("JOC" in features or primary_audio_track.joc) else "",
|
||||
}
|
||||
)
|
||||
|
||||
if unique_audio_languages == 2:
|
||||
context["dual"] = "DUAL"
|
||||
context["multi"] = ""
|
||||
elif unique_audio_languages > 2:
|
||||
context["dual"] = ""
|
||||
context["multi"] = "MULTi"
|
||||
else:
|
||||
context["dual"] = ""
|
||||
context["multi"] = ""
|
||||
|
||||
lang_tag_rules = config.language_tags.get("rules") if config.language_tags else None
|
||||
if lang_tag_rules and self.tracks:
|
||||
from unshackle.core.utils.language_tags import evaluate_language_tag
|
||||
|
||||
audio_langs = [a.language for a in self.tracks.audio]
|
||||
sub_langs = [s.language for s in self.tracks.subtitles]
|
||||
context["lang_tag"] = evaluate_language_tag(lang_tag_rules, audio_langs, sub_langs)
|
||||
|
||||
return context
|
||||
|
||||
@abstractmethod
|
||||
def get_filename(self, media_info: MediaInfo, folder: bool = False, show_service: bool = True) -> str:
|
||||
"""
|
||||
|
||||
@@ -103,53 +103,78 @@ class Tracks:
|
||||
tree = Tree("", hide_root=True)
|
||||
for track_type in self.TRACK_ORDER_MAP:
|
||||
tracks = list(x for x in all_tracks if isinstance(x, track_type))
|
||||
if not tracks:
|
||||
continue
|
||||
num_tracks = len(tracks)
|
||||
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}")
|
||||
for track in tracks:
|
||||
if add_progress and track_type not in (Chapter, Attachment):
|
||||
progress = Progress(
|
||||
SpinnerColumn(finished_text=""),
|
||||
BarColumn(),
|
||||
"•",
|
||||
TimeRemainingColumn(compact=True, elapsed_when_finished=True),
|
||||
"•",
|
||||
TextColumn("[progress.data.speed]{task.fields[downloaded]}"),
|
||||
console=console,
|
||||
speed_estimate_period=10,
|
||||
if tracks:
|
||||
num_tracks = len(tracks)
|
||||
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}")
|
||||
for track in tracks:
|
||||
if add_progress and track_type not in (Chapter, Attachment):
|
||||
progress = Progress(
|
||||
SpinnerColumn(finished_text=""),
|
||||
BarColumn(),
|
||||
"•",
|
||||
TimeRemainingColumn(compact=True, elapsed_when_finished=True),
|
||||
"•",
|
||||
TextColumn("[progress.data.speed]{task.fields[downloaded]}"),
|
||||
console=console,
|
||||
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="-")
|
||||
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")
|
||||
for cc_str in unique_cc:
|
||||
cc_tree.add(cc_str, style="text2")
|
||||
|
||||
return tree, progress_callables
|
||||
|
||||
|
||||
@@ -200,6 +200,7 @@ class Video(Track):
|
||||
height: Optional[int] = None,
|
||||
fps: Optional[Union[str, int, float]] = None,
|
||||
scan_type: Optional[Video.ScanType] = None,
|
||||
closed_captions: Optional[list[dict[str, Any]]] = None,
|
||||
**kwargs: Any,
|
||||
) -> 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))
|
||||
|
||||
self.scan_type = scan_type
|
||||
self.closed_captions: list[dict[str, Any]] = closed_captions or []
|
||||
self.needs_duration_fix = False
|
||||
|
||||
def __str__(self) -> str:
|
||||
@@ -346,22 +348,27 @@ class Video(Track):
|
||||
if not binaries.CCExtractor:
|
||||
raise EnvironmentError("ccextractor executable was not found.")
|
||||
|
||||
# ccextractor often fails in weird ways unless we repack
|
||||
self.repackage()
|
||||
|
||||
out_path = Path(out_path)
|
||||
|
||||
try:
|
||||
subprocess.run(
|
||||
[binaries.CCExtractor, "-trim", "-nobom", "-noru", "-ru1", "-o", out_path, self.path],
|
||||
check=True,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
except subprocess.CalledProcessError as e:
|
||||
out_path.unlink(missing_ok=True)
|
||||
if not e.returncode == 10: # No captions found
|
||||
raise
|
||||
def _run_ccextractor() -> bool:
|
||||
try:
|
||||
subprocess.run(
|
||||
[binaries.CCExtractor, "-trim", "-nobom", "-noru", "-ru1", "-o", out_path, self.path],
|
||||
check=True,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
except subprocess.CalledProcessError as e:
|
||||
out_path.unlink(missing_ok=True)
|
||||
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():
|
||||
cc_track = Subtitle(
|
||||
|
||||
@@ -136,7 +136,7 @@ def sanitize_filename(filename: str, spacer: str = ".") -> str:
|
||||
if spacer == ".":
|
||||
filename = re.sub(r" - ", spacer, filename) # title separators to spacer (avoids .-. pattern)
|
||||
filename = re.sub(r"[:; ]", spacer, filename) # structural chars to (spacer)
|
||||
filename = re.sub(r"[\\*!?¿,'\"" "()<>|$#~]", "", filename) # not filename safe chars
|
||||
filename = re.sub(r"[\\*!?¿,'\"" "<>|$#~]", "", filename) # not filename safe chars
|
||||
filename = re.sub(rf"[{spacer}]{{2,}}", spacer, filename) # remove extra neighbouring (spacer)s
|
||||
|
||||
return filename
|
||||
|
||||
@@ -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)
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Language tag rule engine for output filename templates."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, Sequence
|
||||
|
||||
from langcodes import Language
|
||||
|
||||
from unshackle.core.utilities import is_close_match
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def evaluate_language_tag(
|
||||
rules: list[dict[str, Any]],
|
||||
audio_languages: Sequence[Language],
|
||||
subtitle_languages: Sequence[Language],
|
||||
) -> str:
|
||||
"""Evaluate language tag rules against selected tracks.
|
||||
|
||||
Rules are evaluated in order; the first matching rule's tag is returned.
|
||||
Returns empty string if no rules match.
|
||||
|
||||
Args:
|
||||
rules: List of rule dicts from config, each with conditions and a ``tag``.
|
||||
audio_languages: Languages of the selected audio tracks.
|
||||
subtitle_languages: Languages of the selected subtitle tracks.
|
||||
|
||||
Returns:
|
||||
The tag string from the first matching rule, or ``""`` if none match.
|
||||
"""
|
||||
for rule in rules:
|
||||
tag = rule.get("tag")
|
||||
if not tag:
|
||||
log.warning("Language tag rule missing 'tag' field, skipping: %s", rule)
|
||||
continue
|
||||
|
||||
if _rule_matches(rule, audio_languages, subtitle_languages):
|
||||
log.debug("Language tag rule matched: %s -> %s", rule, tag)
|
||||
return str(tag)
|
||||
|
||||
return ""
|
||||
|
||||
|
||||
def _rule_matches(
|
||||
rule: dict[str, Any],
|
||||
audio_languages: Sequence[Language],
|
||||
subtitle_languages: Sequence[Language],
|
||||
) -> bool:
|
||||
"""Check if all conditions in a rule are satisfied."""
|
||||
has_condition = False
|
||||
|
||||
audio_lang = rule.get("audio")
|
||||
if audio_lang is not None:
|
||||
has_condition = True
|
||||
if not is_close_match(audio_lang, list(audio_languages)):
|
||||
return False
|
||||
|
||||
subs_contain = rule.get("subs_contain")
|
||||
if subs_contain is not None:
|
||||
has_condition = True
|
||||
if not is_close_match(subs_contain, list(subtitle_languages)):
|
||||
return False
|
||||
|
||||
subs_contain_all = rule.get("subs_contain_all")
|
||||
if subs_contain_all is not None:
|
||||
has_condition = True
|
||||
if not isinstance(subs_contain_all, list):
|
||||
subs_contain_all = [subs_contain_all]
|
||||
for lang in subs_contain_all:
|
||||
if not is_close_match(lang, list(subtitle_languages)):
|
||||
return False
|
||||
|
||||
if not has_condition:
|
||||
log.warning("Language tag rule has no conditions, skipping: %s", rule)
|
||||
return False
|
||||
|
||||
return True
|
||||
@@ -0,0 +1,162 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from unshackle.core.utilities import sanitize_filename
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TemplateFormatter:
|
||||
"""
|
||||
Template formatter for custom filename patterns.
|
||||
|
||||
Supports variable substitution and conditional variables.
|
||||
Example: '{title}.{year}.{quality?}.{source}-{tag}'
|
||||
"""
|
||||
|
||||
def __init__(self, template: str):
|
||||
"""Initialize the template formatter.
|
||||
|
||||
Args:
|
||||
template: Template string with variables in {variable} format
|
||||
"""
|
||||
self.template = template
|
||||
self.variables = self._extract_variables()
|
||||
|
||||
def _extract_variables(self) -> list[str]:
|
||||
"""Extract all variables from the template."""
|
||||
pattern = r"\{([^}]+)\}"
|
||||
matches = re.findall(pattern, self.template)
|
||||
return [match.strip() for match in matches]
|
||||
|
||||
def format(self, context: dict[str, Any]) -> str:
|
||||
"""Format the template with the provided context.
|
||||
|
||||
Args:
|
||||
context: Dictionary containing variable values
|
||||
|
||||
Returns:
|
||||
Formatted filename string
|
||||
|
||||
Raises:
|
||||
ValueError: If required template variables are missing from context
|
||||
"""
|
||||
is_valid, missing_vars = self.validate(context)
|
||||
if not is_valid:
|
||||
error_msg = f"Missing required template variables: {', '.join(missing_vars)}"
|
||||
log.error(error_msg)
|
||||
raise ValueError(error_msg)
|
||||
|
||||
try:
|
||||
result = self.template
|
||||
|
||||
for variable in self.variables:
|
||||
placeholder = "{" + variable + "}"
|
||||
is_conditional = variable.endswith("?")
|
||||
|
||||
if is_conditional:
|
||||
var_name = variable[:-1]
|
||||
value = context.get(var_name, "")
|
||||
|
||||
if value:
|
||||
safe_value = str(value).strip()
|
||||
result = result.replace(placeholder, safe_value)
|
||||
else:
|
||||
# Remove the placeholder and consume the adjacent separator on one side
|
||||
# e.g. "{disc?}-{track}" → "{track}" when disc is empty
|
||||
# e.g. "{title}.{edition?}.{quality}" → "{title}.{quality}" when edition is empty
|
||||
def _remove_conditional(m: re.Match) -> str:
|
||||
s = m.group(0)
|
||||
has_left = s[0] in ".- "
|
||||
has_right = s[-1] in ".- "
|
||||
if has_left and has_right:
|
||||
return s[0] # keep left separator
|
||||
return ""
|
||||
|
||||
result = re.sub(
|
||||
rf"[\.\s\-]?{re.escape(placeholder)}[\.\s\-]?",
|
||||
_remove_conditional,
|
||||
result,
|
||||
count=1,
|
||||
)
|
||||
else:
|
||||
value = context.get(variable, "")
|
||||
if value is None:
|
||||
log.warning(f"Template variable '{variable}' is None, using empty string")
|
||||
value = ""
|
||||
|
||||
safe_value = str(value).strip()
|
||||
result = result.replace(placeholder, safe_value)
|
||||
|
||||
# Clean up multiple consecutive dots/separators and other artifacts
|
||||
result = re.sub(r"\.{2,}", ".", result) # Multiple dots -> single dot
|
||||
result = re.sub(r"\s{2,}", " ", result) # Multiple spaces -> single space
|
||||
result = re.sub(r"-{2,}", "-", result) # Multiple dashes -> single dash
|
||||
result = re.sub(r"^[\.\s\-]+|[\.\s\-]+$", "", result) # Remove leading/trailing dots, spaces, dashes
|
||||
result = re.sub(r"\.-", "-", result) # Remove dots before dashes (for dot-based templates)
|
||||
result = re.sub(r"[\.\s]+\)", ")", result) # Remove dots/spaces before closing parentheses
|
||||
result = re.sub(r"\(\s*\)", "", result) # Remove empty parentheses (empty conditional)
|
||||
|
||||
# Determine the appropriate separator based on template style
|
||||
# Count separator characters between variables (between } and {)
|
||||
between_vars = re.findall(r"\}([^{]*)\{", self.template)
|
||||
separator_text = "".join(between_vars)
|
||||
dot_count = separator_text.count(".")
|
||||
space_count = separator_text.count(" ")
|
||||
|
||||
if space_count > dot_count:
|
||||
result = sanitize_filename(result, spacer=" ")
|
||||
else:
|
||||
result = sanitize_filename(result, spacer=".")
|
||||
|
||||
if not result or result.isspace():
|
||||
log.warning("Template formatting resulted in empty filename, using fallback")
|
||||
return "untitled"
|
||||
|
||||
log.debug(f"Template formatted successfully: '{self.template}' -> '{result}'")
|
||||
return result
|
||||
|
||||
except (KeyError, ValueError, re.error) as e:
|
||||
log.error(f"Error formatting template '{self.template}': {e}")
|
||||
fallback = f"error_formatting_{hash(self.template) % 10000}"
|
||||
log.warning(f"Using fallback filename: {fallback}")
|
||||
return fallback
|
||||
|
||||
def validate(self, context: dict[str, Any]) -> tuple[bool, list[str]]:
|
||||
"""Validate that all required variables are present in context.
|
||||
|
||||
Args:
|
||||
context: Dictionary containing variable values
|
||||
|
||||
Returns:
|
||||
Tuple of (is_valid, missing_variables)
|
||||
"""
|
||||
missing = []
|
||||
|
||||
for variable in self.variables:
|
||||
is_conditional = variable.endswith("?")
|
||||
var_name = variable[:-1] if is_conditional else variable
|
||||
|
||||
if not is_conditional and var_name not in context:
|
||||
missing.append(var_name)
|
||||
|
||||
return len(missing) == 0, missing
|
||||
|
||||
def get_required_variables(self) -> list[str]:
|
||||
"""Get list of required (non-conditional) variables."""
|
||||
required = []
|
||||
for variable in self.variables:
|
||||
if not variable.endswith("?"):
|
||||
required.append(variable)
|
||||
return required
|
||||
|
||||
def get_optional_variables(self) -> list[str]:
|
||||
"""Get list of optional (conditional) variables."""
|
||||
optional = []
|
||||
for variable in self.variables:
|
||||
if variable.endswith("?"):
|
||||
optional.append(variable[:-1]) # Remove the ?
|
||||
return optional
|
||||
@@ -17,15 +17,66 @@ tag_imdb_tmdb: true
|
||||
# Set terminal background color (custom option not in CONFIG.md)
|
||||
set_terminal_bg: false
|
||||
|
||||
# Set file naming convention
|
||||
# true for style - Prime.Suspect.S07E01.The.Final.Act.Part.One.1080p.ITV.WEB-DL.AAC2.0.H.264
|
||||
# false for style - Prime Suspect S07E01 The Final Act - Part One
|
||||
scene_naming: true
|
||||
# Custom output templates for filenames
|
||||
# Configure output_template in your unshackle.yaml to control filename format.
|
||||
# If not configured, default scene-style templates are used and a warning is shown.
|
||||
# Available variables: {title}, {year}, {season}, {episode}, {season_episode}, {episode_name},
|
||||
# {quality}, {resolution}, {source}, {audio}, {audio_channels}, {audio_full},
|
||||
# {video}, {hdr}, {hfr}, {atmos}, {dual}, {multi}, {tag}, {edition}, {repack},
|
||||
# {lang_tag}
|
||||
# Conditional variables (included only if present): Add ? suffix like {year?}, {episode_name?}, {hdr?}
|
||||
# Customize the templates below:
|
||||
#
|
||||
# Example outputs:
|
||||
# Scene movies: 'The.Matrix.1999.1080p.SERVICE.WEB-DL.DDP5.1.H.264-EXAMPLE'
|
||||
# Scene movies (HDR): 'Dune.2021.2160p.SERVICE.WEB-DL.DDP5.1.HDR10.H.265-EXAMPLE'
|
||||
# Scene movies (REPACK): 'Dune.2021.REPACK.2160p.SERVICE.WEB-DL.DDP5.1.H.265-EXAMPLE'
|
||||
# Scene series: 'Breaking.Bad.2008.S01E01.Pilot.1080p.SERVICE.WEB-DL.DDP5.1.H.264-EXAMPLE'
|
||||
# Plex movies: 'The Matrix (1999) 1080p'
|
||||
# Plex series: 'Breaking Bad S01E01 Pilot'
|
||||
output_template:
|
||||
# Scene-style naming (dot-separated)
|
||||
movies: '{title}.{year}.{repack?}.{edition?}.{quality}.{source}.WEB-DL.{dual?}.{multi?}.{audio_full}.{atmos?}.{hdr?}.{hfr?}.{video}-{tag}'
|
||||
series: '{title}.{year?}.{season_episode}.{episode_name?}.{repack?}.{edition?}.{quality}.{source}.WEB-DL.{dual?}.{multi?}.{audio_full}.{atmos?}.{hdr?}.{hfr?}.{video}-{tag}'
|
||||
songs: '{track_number}.{title}.{repack?}.{edition?}.{source?}.WEB-DL.{audio_full}.{atmos?}-{tag}'
|
||||
#
|
||||
# Plex-friendly naming (space-separated, clean format)
|
||||
# movies: '{title} ({year}) {quality}'
|
||||
# series: '{title} {season_episode} {episode_name?}'
|
||||
# songs: '{track_number}. {title}'
|
||||
#
|
||||
# Minimal naming (basic info only)
|
||||
# movies: '{title}.{year}.{quality}'
|
||||
# series: '{title}.{season_episode}.{episode_name?}'
|
||||
#
|
||||
# Custom scene-style with specific elements
|
||||
# movies: '{title}.{year}.{quality}.{hdr?}.{source}.WEB-DL.{audio_full}.{video}-{tag}'
|
||||
# series: '{title}.{year?}.{season_episode}.{episode_name?}.{quality}.{hdr?}.{source}.WEB-DL.{audio_full}.{atmos?}.{video}-{tag}'
|
||||
|
||||
# Whether to include the year in series names for episodes and folders (default: true)
|
||||
# true for style - Show Name (2023) S01E01 Episode Name
|
||||
# false for style - Show Name S01E01 Episode Name
|
||||
series_year: true
|
||||
# Language-based tagging for output filenames
|
||||
# Automatically adds language identifiers (e.g., DANiSH, NORDiC, DKsubs) based on
|
||||
# audio and subtitle track languages. Rules are evaluated in order; first match wins.
|
||||
# Use {lang_tag?} in your output_template to place the tag in the filename.
|
||||
#
|
||||
# Conditions (all conditions in a rule must match):
|
||||
# audio: <lang> - any audio track matches this language
|
||||
# subs_contain: <lang> - any subtitle matches this language
|
||||
# subs_contain_all: [lang, ...] - subtitles include ALL listed languages
|
||||
#
|
||||
# language_tags:
|
||||
# rules:
|
||||
# - audio: da
|
||||
# tag: DANiSH
|
||||
# - audio: sv
|
||||
# tag: SWEDiSH
|
||||
# - audio: nb
|
||||
# tag: NORWEGiAN
|
||||
# - audio: en
|
||||
# subs_contain_all: [da, sv, nb]
|
||||
# tag: NORDiC
|
||||
# - audio: en
|
||||
# subs_contain: da
|
||||
# tag: DKsubs
|
||||
|
||||
# Check for updates from GitHub repository on startup (default: true)
|
||||
update_checks: true
|
||||
@@ -41,7 +92,6 @@ title_cache_max_retention: 86400 # Maximum cache retention for fallback when API
|
||||
|
||||
# Filename Configuration
|
||||
unicode_filenames: false # optionally replace non-ASCII characters with ASCII equivalents
|
||||
insert_episodename_into_filenames: true # optionally determines whether the specific name of an episode is automatically included within the filename for series content.
|
||||
|
||||
# Debug logging configuration
|
||||
# Comprehensive JSON-based debug logging for troubleshooting and service development
|
||||
|
||||
@@ -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" },
|
||||
]
|
||||
|
||||
[[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]]
|
||||
name = "anyio"
|
||||
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" },
|
||||
]
|
||||
|
||||
[[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]]
|
||||
name = "distlib"
|
||||
version = "0.4.0"
|
||||
@@ -1259,22 +1282,22 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "pyplayready"
|
||||
version = "0.6.3"
|
||||
version = "0.8.3"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "aiohttp" },
|
||||
{ name = "click" },
|
||||
{ name = "construct" },
|
||||
{ name = "cryptography" },
|
||||
{ name = "ecpy" },
|
||||
{ name = "lxml" },
|
||||
{ name = "platformdirs" },
|
||||
{ name = "pycryptodome" },
|
||||
{ name = "pyyaml" },
|
||||
{ name = "requests" },
|
||||
{ name = "xmltodict" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/53/f2/6d75b6d10a8361b53a2acbe959d51aa586418e9af497381a9f5c436ca488/pyplayready-0.6.3.tar.gz", hash = "sha256:b9b82a32c2cced9c43f910eb1fb891545f1491dc063c1eb9c20634e2417eda76", size = 58019, upload-time = "2025-08-20T19:32:43.642Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/99/7a/5c83dd76a3e1cf5158f7cc7a62193a5a329acce3e2a8237cd921ac5c6b31/pyplayready-0.8.3.tar.gz", hash = "sha256:a86b6cee37fa502e49e5b6956a0086de677afff82507ed34a4507eac8fa563af", size = 67517, upload-time = "2026-02-26T21:06:33.213Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/5b/7f/64d5ff5d765f9f2138ee7cc196fd9401f9eae0fb514c66660ad4e56584fa/pyplayready-0.6.3-py3-none-any.whl", hash = "sha256:82f35434e790a7da21df57ec053a2924ceb63622c5a6c5ff9f0fa03db0531c57", size = 66162, upload-time = "2025-08-20T19:32:42.62Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/26/f0/8dc65e90a21ec65b52278d1017d7abbff763f536ca168a687a1a60d2deb8/pyplayready-0.8.3-py3-none-any.whl", hash = "sha256:995ea335998cc63890f24959e9ab88cd5ef962a507396f1097badc843bc7be9e", size = 78016, upload-time = "2026-02-26T21:06:32.008Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1627,11 +1650,12 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "unshackle"
|
||||
version = "3.1.0"
|
||||
version = "4.0.0"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "aiohttp" },
|
||||
{ name = "aiohttp-swagger3" },
|
||||
{ name = "animeapi-py" },
|
||||
{ name = "appdirs" },
|
||||
{ name = "brotli" },
|
||||
{ name = "chardet" },
|
||||
@@ -1690,6 +1714,7 @@ dev = [
|
||||
requires-dist = [
|
||||
{ name = "aiohttp", specifier = ">=3.13.3,<4" },
|
||||
{ name = "aiohttp-swagger3", specifier = ">=0.9.0,<1" },
|
||||
{ name = "animeapi-py", specifier = ">=0.6.0" },
|
||||
{ name = "appdirs", specifier = ">=1.4.4,<2" },
|
||||
{ name = "brotli", specifier = ">=1.1.0,<2" },
|
||||
{ name = "chardet", specifier = ">=5.2.0,<6" },
|
||||
@@ -1715,7 +1740,7 @@ requires-dist = [
|
||||
{ name = "pymediainfo", specifier = ">=6.1.0,<8" },
|
||||
{ name = "pymp4", specifier = ">=1.4.0,<2" },
|
||||
{ name = "pymysql", specifier = ">=1.1.0,<2" },
|
||||
{ name = "pyplayready", specifier = ">=0.6.3,<0.7" },
|
||||
{ name = "pyplayready", specifier = ">=0.8.3,<0.9" },
|
||||
{ name = "pysubs2", specifier = ">=1.7.0,<2" },
|
||||
{ name = "pywidevine", extras = ["serve"], specifier = ">=1.8.0,<2" },
|
||||
{ name = "pyyaml", specifier = ">=6.0.1,<7" },
|
||||
@@ -1796,15 +1821,6 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/4f/bc/ab575ebf0254577034d23908299b0d13ea5d7ceb35f43a5c08acf2252826/wcwidth-0.3.3-py3-none-any.whl", hash = "sha256:8e9056c446f21c7393514946d143a748c56aad72476844d3f215f7915276508f", size = 86509, upload-time = "2026-01-24T16:23:56.966Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xmltodict"
|
||||
version = "0.14.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/50/05/51dcca9a9bf5e1bce52582683ce50980bcadbc4fa5143b9f2b19ab99958f/xmltodict-0.14.2.tar.gz", hash = "sha256:201e7c28bb210e374999d1dde6382923ab0ed1a8a5faeece48ab525b7810a553", size = 51942, upload-time = "2024-10-16T06:10:29.683Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/d6/45/fc303eb433e8a2a271739c98e953728422fa61a3c1f36077a49e395c972e/xmltodict-0.14.2-py2.py3-none-any.whl", hash = "sha256:20cc7d723ed729276e808f26fb6b3599f786cbc37e06c65e192ba77c40f20aac", size = 9981, upload-time = "2024-10-16T06:10:27.649Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "yarl"
|
||||
version = "1.22.0"
|
||||
|
||||
Reference in New Issue
Block a user