diff --git a/pyproject.toml b/pyproject.toml
index 4097d975..fa73638e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -142,12 +142,17 @@ force-exclude = true
line-length = 120
[tool.ruff.lint]
-select = ["E4", "E7", "E9", "F", "W"]
+select = ["E4", "E7", "E9", "F", "W", "UP", "B"]
+# StrEnum makes str() and format() of a member give its value, not "Codec.AVC"; callers and services read that text.
+ignore = ["UP042"]
[tool.ruff.lint.per-file-ignores]
# binaries are resolved lazily via module-level __getattr__ (PEP 562), so the
# names in __all__ are intentionally not defined statically.
"unshackle/core/binaries.py" = ["F822"]
+# Optional hooks with a no-op default: a service or vault overrides only the ones it needs.
+"unshackle/core/service.py" = ["B027"]
+"unshackle/core/vault.py" = ["B027"]
[tool.isort]
profile = "black"
diff --git a/scripts/bench_downloader.py b/scripts/bench_downloader.py
index 8d4aae44..972c5bf7 100644
--- a/scripts/bench_downloader.py
+++ b/scripts/bench_downloader.py
@@ -40,7 +40,7 @@ import threading
import time
from pathlib import Path
from shutil import rmtree
-from typing import Any, Optional
+from typing import Any
import click
import fault_server # local sibling (scripts/): fault-injection server + payload verifier
@@ -105,7 +105,7 @@ class SegmentHandler(http.server.BaseHTTPRequestHandler):
server.connections += 1
self.slow_conn = server.connections <= server.faults["slow_conn"]
- def _parse_range(self, total: int) -> Optional[tuple[int, int]]:
+ def _parse_range(self, total: int) -> tuple[int, int] | None:
header = self.headers.get("Range")
if not header or not header.startswith("bytes="):
return None
@@ -214,8 +214,8 @@ class SegmentHandler(http.server.BaseHTTPRequestHandler):
def run_batch(
- urls: list[str], out_dir: Path, workers: int, session: Optional[Any], adaptive: bool = False, procs: int = 1
-) -> tuple[float, list[float], Optional[BaseException]]:
+ urls: list[str], out_dir: Path, workers: int, session: Any | None, adaptive: bool = False, procs: int = 1
+) -> tuple[float, list[float], BaseException | None]:
"""Download one batch through the real code path.
Returns (wall seconds, completion timestamps relative to start, error-or-None).
@@ -223,7 +223,7 @@ def run_batch(
"""
DOWNLOAD_CANCELLED.clear()
completions: list[float] = []
- err: Optional[BaseException] = None
+ err: BaseException | None = None
start = time.perf_counter()
try:
for event in download_batch(
@@ -258,7 +258,7 @@ def run_batch(
return wall, completions, err, strays, locked, pool_threads
-def incomplete_segments(out_dir: Path, expected: int, expected_bytes: Optional[bytes]) -> list[int]:
+def incomplete_segments(out_dir: Path, expected: int, expected_bytes: bytes | None) -> list[int]:
"""Segment indexes that are missing, empty, or (synthetic mode) not byte-identical.
Content compare (not just size) is required: on a mid-body interruption the downloader
@@ -331,9 +331,9 @@ def sweep(
urls: list[str],
workers: list[int],
runs: int,
- session: Optional[Any],
- server: Optional[SegmentServer],
- expected_bytes: Optional[bytes],
+ session: Any | None,
+ server: SegmentServer | None,
+ expected_bytes: bytes | None,
adaptive: bool = False,
procs: int = 1,
) -> list[Row]:
@@ -468,7 +468,7 @@ def print_fault_report(rows: list[FaultRow], runs: int, segments: int, profile:
)
-def _procs_notice(procs: int, n_urls: int, session: Optional[Any]) -> None:
+def _procs_notice(procs: int, n_urls: int, session: Any | None) -> None:
"""Warn loudly when --procs cannot engage, so a run is never mistaken for a multiprocess test."""
if procs <= 1:
return
@@ -490,7 +490,7 @@ def run_fault_mode(
seg_size: int,
worker_counts: list[int],
runs: int,
- session: Optional[Any],
+ session: Any | None,
adaptive: bool,
procs: int,
seed: int,
@@ -650,12 +650,12 @@ def main(
fault_slow_conn: int,
part_size_mib: int,
fast_timeouts: bool,
- urls_file: Optional[str],
- impersonate: Optional[str],
+ urls_file: str | None,
+ impersonate: str | None,
adaptive: bool,
procs: int,
no_read1: bool,
- fault_profile: Optional[str],
+ fault_profile: str | None,
seed: int,
) -> None:
"""Benchmark downloader throughput vs worker count, with optional fault injection."""
@@ -668,12 +668,12 @@ def main(
"tail_slow_once": fault_tail_slow_once,
"slow_conn": fault_slow_conn,
}
- server: Optional[SegmentServer] = None
- session: Optional[Any] = None
+ server: SegmentServer | None = None
+ session: Any | None = None
saved: dict[str, Any] = {}
- saved_network: Optional[dict] = None
+ saved_network: dict | None = None
total = segments
- expected_bytes: Optional[bytes] = None # synthetic reference buffer; None in real-URL mode
+ expected_bytes: bytes | None = None # synthetic reference buffer; None in real-URL mode
if fast_timeouts: # bench-only: patched globals are read at call time inside download()
fast = {"READ_TIMEOUT": 2, "RETRY_WAIT": 1, "HEDGE_MIN_WAIT": 1.0}
diff --git a/scripts/fault_server.py b/scripts/fault_server.py
index 40863439..276c65c9 100644
--- a/scripts/fault_server.py
+++ b/scripts/fault_server.py
@@ -45,7 +45,7 @@ import threading
import time
from dataclasses import asdict, dataclass
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
-from typing import Any, Optional
+from typing import Any
MIB = 1024 * 1024
DEFAULT_SEED = 1729
@@ -186,7 +186,7 @@ class FaultServer(ThreadingHTTPServer):
"""Deterministic per-(path, attempt) fault gate: fires for ``pct`` percent of them."""
if pct <= 0:
return False
- digest = hashlib.sha256(f"{self.seed}:{kind}:{path}:{attempt}".encode("utf-8")).digest()
+ digest = hashlib.sha256(f"{self.seed}:{kind}:{path}:{attempt}".encode()).digest()
return (int.from_bytes(digest[:4], "big") / 0xFFFFFFFF) * 100.0 < pct
def reset_counters(self) -> None:
@@ -212,7 +212,7 @@ class FaultHandler(BaseHTTPRequestHandler):
def log_message(self, *_: Any) -> None: # silence per-request logging
pass
- def _parse_range(self, total: int) -> Optional[tuple[int, int]]:
+ def _parse_range(self, total: int) -> tuple[int, int] | None:
header = self.headers.get("Range")
if not header or not header.startswith("bytes="):
return None
@@ -372,7 +372,7 @@ class FaultHandler(BaseHTTPRequestHandler):
time.sleep(per_chunk)
-def resolve_profile(name: str, overrides: Optional[dict[str, Any]] = None) -> FaultProfile:
+def resolve_profile(name: str, overrides: dict[str, Any] | None = None) -> FaultProfile:
"""Return a copy of the named preset with any non-None ``overrides`` applied."""
if name not in PROFILES:
raise KeyError(f"unknown profile {name!r}; choices: {', '.join(sorted(PROFILES))}")
diff --git a/scripts/fetch_manifest_corpus.py b/scripts/fetch_manifest_corpus.py
index bdcae56d..8454ec2e 100644
--- a/scripts/fetch_manifest_corpus.py
+++ b/scripts/fetch_manifest_corpus.py
@@ -18,7 +18,7 @@ import re
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
-from typing import Any, Optional
+from typing import Any
from urllib.parse import urlparse
import requests
@@ -56,7 +56,7 @@ EXCLUDED: dict[str, str] = {
"https://storage.googleapis.com/shaka-demo-assets/heliocentrism-xlink/heliocentrism.mpd": "xlink:href remote Periods are not resolved",
}
-Stream = tuple[str, str, str, Optional[dict[str, Any]]]
+Stream = tuple[str, str, str, dict[str, Any] | None]
def dashif_streams() -> list[Stream]:
@@ -128,7 +128,7 @@ def shaka_packager_streams() -> list[Stream]:
]
-def kind_of(head: bytes) -> Optional[str]:
+def kind_of(head: bytes) -> str | None:
"""Tell the manifest type from the first bytes, since many manifest URLs have no telling extension."""
text = head.lstrip(b"\xef\xbb\xbf").lstrip()
if text.startswith(b"#EXTM3U"):
@@ -145,7 +145,7 @@ def file_name(source: str, name: str, url: str, kind: str) -> str:
return f"{kind}/{source}-{slug}-{hashlib.sha1(url.encode()).hexdigest()[:8]}.{EXTENSIONS[kind]}"
-def fetch(stream: Stream) -> Optional[dict[str, Any]]:
+def fetch(stream: Stream) -> dict[str, Any] | None:
"""Download one manifest into OUT and return its index entry, or None when it is not a manifest."""
source, name, url, expect = stream
try:
diff --git a/scripts/live_manifest_test.py b/scripts/live_manifest_test.py
index e4a6cd29..c4a36460 100644
--- a/scripts/live_manifest_test.py
+++ b/scripts/live_manifest_test.py
@@ -22,7 +22,7 @@ import sys
import time
from pathlib import Path
from tempfile import mkdtemp
-from typing import Any, Optional
+from typing import Any
import click
from requests import Session
@@ -94,7 +94,7 @@ class Counter:
self.files += 1
-def pick_track(tracks: object, which: str) -> Optional[Any]:
+def pick_track(tracks: object, which: str) -> Any | None:
vids = list(getattr(tracks, "videos", []))
if not vids:
auds = list(getattr(tracks, "audio", []))
diff --git a/scripts/live_segmentbase_ab.py b/scripts/live_segmentbase_ab.py
index 04082fc6..cb5283ba 100644
--- a/scripts/live_segmentbase_ab.py
+++ b/scripts/live_segmentbase_ab.py
@@ -19,7 +19,7 @@ import subprocess
import time
from pathlib import Path
from tempfile import mkdtemp
-from typing import Any, Optional
+from typing import Any
import click
from requests import Session
@@ -34,7 +34,7 @@ STREAMS: list[tuple[str, str]] = [
("sony-1a", "https://dash.akamaized.net/dash264/TestCases/1a/sony/SNE_DASH_SD_CASE1A_REVISED.mpd"),
]
-guard_results: list[Optional[tuple[int, int]]] = []
+guard_results: list[tuple[int, int] | None] = []
def install_guard_spy() -> bool:
@@ -43,7 +43,7 @@ def install_guard_spy() -> bool:
if orig is None:
return False
- def spy(is_subtitle: bool, segments: Any, init_len: int) -> Optional[tuple[int, int]]:
+ def spy(is_subtitle: bool, segments: Any, init_len: int) -> tuple[int, int] | None:
result = orig(is_subtitle, segments, init_len)
guard_results.append(result)
return result
diff --git a/tests/commands/test_cdm_cache.py b/tests/commands/test_cdm_cache.py
index fb957d98..78820b21 100644
--- a/tests/commands/test_cdm_cache.py
+++ b/tests/commands/test_cdm_cache.py
@@ -9,7 +9,7 @@ key pair and a blocking request to its host.
from __future__ import annotations
import logging
-from typing import Any, Optional
+from typing import Any
import pytest
@@ -32,7 +32,7 @@ def builds(monkeypatch) -> list[tuple[str, str]]:
"""Record every ``load_cdm`` call and hand back a fresh stub for each one."""
calls: list[tuple[str, str]] = []
- def fake_load_cdm(cdm_name: str, *, service_name: str = "", vaults: Optional[Any] = None) -> StubCdm:
+ def fake_load_cdm(cdm_name: str, *, service_name: str = "", vaults: Any | None = None) -> StubCdm:
calls.append((cdm_name, service_name))
return StubCdm(cdm_name, service_name)
diff --git a/tests/conftest.py b/tests/conftest.py
index 8a4f2d34..af6f7a1d 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -5,8 +5,9 @@ from __future__ import annotations
import importlib
import socket
import socketserver
+from collections.abc import Callable
from pathlib import Path
-from typing import Any, Callable, Optional
+from typing import Any
import pytest
@@ -87,7 +88,7 @@ def mux_args(monkeypatch: pytest.MonkeyPatch) -> Callable[..., list[str]]:
class Stop(Exception):
pass
- def run(tracks: Any, ids: Optional[dict[str, int]] = None, **kwargs: Any) -> list[str]:
+ def run(tracks: Any, ids: dict[str, int] | None = None, **kwargs: Any) -> list[str]:
captured: list[list[str]] = []
def fake_popen(args: list[str], **_: object) -> None:
diff --git a/tests/core/key_resolver.py b/tests/core/key_resolver.py
index 3081876d..23d85891 100644
--- a/tests/core/key_resolver.py
+++ b/tests/core/key_resolver.py
@@ -2,8 +2,9 @@
from __future__ import annotations
+from collections.abc import Callable
from types import SimpleNamespace
-from typing import Any, Callable, Optional
+from typing import Any
from uuid import UUID
from rich.table import Table
@@ -45,7 +46,7 @@ WIDEVINE = cdm_type_stub("widevine")
def resolver(
vaults: Any = None,
cdm: Any = WIDEVINE,
- cdm_for: Optional[Callable[..., Any]] = None,
+ cdm_for: Callable[..., Any] | None = None,
tag: str = "TEST",
**flags: Any,
) -> ContentKeyResolver:
diff --git a/tests/core/test_adaptive_workers.py b/tests/core/test_adaptive_workers.py
index d39fd47b..6c0210e6 100644
--- a/tests/core/test_adaptive_workers.py
+++ b/tests/core/test_adaptive_workers.py
@@ -6,6 +6,7 @@ from __future__ import annotations
import inspect
from functools import partial
+from itertools import pairwise
from pathlib import Path
import pytest
@@ -252,7 +253,7 @@ def test_plan_tail_parts_full_coverage_no_gaps() -> None:
assert parts, "expected a split for a large segment with spare capacity"
assert parts[0][0] == 0
assert parts[-1][1] == size - 1
- for (_, prev_end), (start, _) in zip(parts, parts[1:]):
+ for (_, prev_end), (start, _) in pairwise(parts):
assert start == prev_end + 1 # each part begins exactly where the previous one ended
covered = sum(end - start + 1 for start, end in parts)
assert covered == size
@@ -282,7 +283,7 @@ def test_split_ranges_covers_exactly_no_gaps_no_overlaps() -> None:
for size in (1, 100, 4 * 1024 * 1024, 16 * 1024 * 1024 + 7, 64 * 1024 * 1024):
parts = split_ranges(size, max_parts=8, part_target=4 * 1024 * 1024)
assert parts[0][0] == 0 and parts[-1][1] == size - 1
- for (_, prev_end), (start, _) in zip(parts, parts[1:]):
+ for (_, prev_end), (start, _) in pairwise(parts):
assert start == prev_end + 1
assert all(start <= end for start, end in parts)
assert sum(end - start + 1 for start, end in parts) == size
diff --git a/tests/core/test_all_drm.py b/tests/core/test_all_drm.py
index 5a824194..980f60c4 100644
--- a/tests/core/test_all_drm.py
+++ b/tests/core/test_all_drm.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import base64
import logging
from types import SimpleNamespace
-from typing import Any, Optional
+from typing import Any
from uuid import UUID
import m3u8
@@ -53,20 +53,20 @@ def playready(kid: UUID = KID) -> PlayReady:
class Run:
"""A ContentKeyResolver whose DRM objects license with fixed content keys, for one track in an --all-drm run."""
- def __init__(self, vault: Optional[dict[UUID, str]] = None, **flags: Any) -> None:
+ def __init__(self, vault: dict[UUID, str] | None = None, **flags: Any) -> None:
self.requests: list[str] = []
self.held: list[dict[UUID, str]] = []
self.vault_queries: list[UUID] = []
self.keys = resolver(Vault(self.get_key(vault or {})), tag="EXAMPLE", **flags)
def get_key(self, vault: dict[UUID, str]) -> Any:
- def get_key(kid: UUID) -> tuple[Optional[str], Optional[str]]:
+ def get_key(kid: UUID) -> tuple[str | None, str | None]:
self.vault_queries.append(kid)
return vault.get(kid), "vault" if kid in vault else None
return get_key
- def drm(self, drm: Any, keys: Optional[dict[UUID, str]] = None, fail: bool = False) -> Any:
+ def drm(self, drm: Any, keys: dict[UUID, str] | None = None, fail: bool = False) -> Any:
"""Give ``drm`` a licence that returns ``keys`` (KID:KEY by default), or that is refused."""
def get_content_keys(cdm: Any, certificate: Any = None, licence: Any = None) -> None:
@@ -79,7 +79,7 @@ class Run:
drm.get_content_keys = get_content_keys
return drm
- def run(self, drm: Any, *others: Any, track_kid: Optional[UUID] = KID) -> None:
+ def run(self, drm: Any, *others: Any, track_kid: UUID | None = KID) -> None:
track = SimpleNamespace(drm=[drm, *others], id="track", height=None)
self.keys.licence_for(track, None, key_table(), all_drm=True)(drm, track_kid=track_kid)
diff --git a/tests/core/test_anilist_provider.py b/tests/core/test_anilist_provider.py
index 9d3ef743..59d2cf97 100644
--- a/tests/core/test_anilist_provider.py
+++ b/tests/core/test_anilist_provider.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from typing import Any, Optional
+from typing import Any
import pytest
@@ -41,7 +41,7 @@ def _provider(monkeypatch: pytest.MonkeyPatch, body: dict) -> tuple[AniListProvi
provider = AniListProvider()
sent: list[dict] = []
- def fake_post(url: str, json: Optional[dict] = None, **kwargs: Any) -> FakeResponse:
+ def fake_post(url: str, json: dict | None = None, **kwargs: Any) -> FakeResponse:
sent.append(json or {})
return FakeResponse(body)
@@ -75,7 +75,7 @@ def default_title_language(monkeypatch: pytest.MonkeyPatch) -> None:
("²", None), # superscript two passes isdigit() but crashes int()
],
)
-def test_parse_anilist_ref(value: Any, expected: Optional[tuple[str, int]]) -> None:
+def test_parse_anilist_ref(value: Any, expected: tuple[str, int] | None) -> None:
assert parse_anilist_ref(value) == expected
@@ -215,7 +215,7 @@ def test_a_title_with_no_variant_at_all_is_a_miss(monkeypatch: pytest.MonkeyPatc
[("JP", "ja"), ("KR", "ko"), ("CN", "zh"), ("TW", "zh"), ("US", None), (None, None)],
)
def test_country_of_origin_maps_to_a_language(
- monkeypatch: pytest.MonkeyPatch, country: Optional[str], language: Optional[str]
+ monkeypatch: pytest.MonkeyPatch, country: str | None, language: str | None
) -> None:
provider, _ = _provider(monkeypatch, {"data": {"Media": {**ONE_PIECE, "countryOfOrigin": country}}})
@@ -228,7 +228,7 @@ def test_country_of_origin_maps_to_a_language(
@pytest.mark.parametrize(
("format_", "kind"), [("MOVIE", "movie"), ("TV", "tv"), ("ONA", "tv"), ("SPECIAL", "tv"), (None, "tv")]
)
-def test_format_maps_to_kind(monkeypatch: pytest.MonkeyPatch, format_: Optional[str], kind: str) -> None:
+def test_format_maps_to_kind(monkeypatch: pytest.MonkeyPatch, format_: str | None, kind: str) -> None:
provider, _ = _provider(monkeypatch, {"data": {"Media": {**ONE_PIECE, "format": format_}}})
result = provider.get_by_id(21, "tv")
diff --git a/tests/core/test_binary_version.py b/tests/core/test_binary_version.py
index 96d30d5d..95cd8026 100644
--- a/tests/core/test_binary_version.py
+++ b/tests/core/test_binary_version.py
@@ -1,7 +1,7 @@
import sys
import time
+from collections.abc import Callable
from pathlib import Path
-from typing import Callable, Optional
import pytest
@@ -35,8 +35,8 @@ def test_parse_version(text: str, expected: str | None) -> None:
assert parse_version(text) == expected
-def fake_probe(outputs: dict[str, Optional[str]], calls: list[list[str]]) -> Callable[[Path, list[str]], Optional[str]]:
- def probe(path: Path, args: list[str]) -> Optional[str]:
+def fake_probe(outputs: dict[str, str | None], calls: list[list[str]]) -> Callable[[Path, list[str]], str | None]:
+ def probe(path: Path, args: list[str]) -> str | None:
calls.append(args)
return outputs.get(" ".join(args), "")
diff --git a/tests/core/test_cacher.py b/tests/core/test_cacher.py
index 0b9ebdfa..3f2284d0 100644
--- a/tests/core/test_cacher.py
+++ b/tests/core/test_cacher.py
@@ -1,5 +1,5 @@
import time
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from pathlib import Path
import jsonpickle
@@ -53,7 +53,7 @@ def test_unix_timestamp_is_absolute_also_when_it_is_in_the_past(offset: int) ->
def test_iso_string_with_utc_offset_becomes_naive_local_time() -> None:
- moment = datetime.now(timezone.utc).replace(microsecond=0) + timedelta(hours=1)
+ moment = datetime.now(UTC).replace(microsecond=0) + timedelta(hours=1)
expected = datetime.fromtimestamp(moment.timestamp())
assert Cacher.resolve_datetime(moment.isoformat()) == expected
assert Cacher.resolve_datetime(moment.strftime("%Y-%m-%dT%H:%M:%SZ")) == expected
diff --git a/tests/core/test_cdm_choice.py b/tests/core/test_cdm_choice.py
index c9673fc7..7f807117 100644
--- a/tests/core/test_cdm_choice.py
+++ b/tests/core/test_cdm_choice.py
@@ -4,8 +4,10 @@ Device names start with the system they are for: ``wv_`` is Widevine, ``pr_`` is
``stub:pr``. Each answer tuple runs over the named systems of its column.
"""
+from collections.abc import Callable
+from functools import partial
from types import SimpleNamespace
-from typing import Any, Callable, Optional
+from typing import Any
import pytest
@@ -22,7 +24,7 @@ SERVER = ("widevine", "playready", "wv")
TIER = {"devices": ["wv_tier"], "playready_devices": ["pr_tier"]}
DUAL = {"widevine": "wv_dev", "playready": "pr_dev"}
-ROWS: dict[str, tuple[dict, Optional[str], Optional[dict]]] = {
+ROWS: dict[str, tuple[dict, str | None, dict | None]] = {
"string widevine": ({"EXAMPLE": "wv_dev"}, None, None),
"string playready": ({"EXAMPLE": "pr_dev"}, None, None),
"profile mapping, no profile": ({"EXAMPLE": {"alice": "pr_alice", "default": "wv_dev"}}, None, None),
@@ -89,10 +91,10 @@ def attempt(answer: Callable[[], Any]) -> Any:
def each(systems: tuple, answer: Callable[[Any], Any]) -> tuple:
"""``answer`` for each named system."""
- return tuple(attempt(lambda: answer(system)) for system in systems)
+ return tuple(attempt(partial(answer, system)) for system in systems)
-def answers(monkeypatch: pytest.MonkeyPatch, cdm: dict, profile: Optional[str], key_cdm: Optional[dict]) -> dict:
+def answers(monkeypatch: pytest.MonkeyPatch, cdm: dict, profile: str | None, key_cdm: dict | None) -> dict:
"""What every ladder answers for one config row."""
monkeypatch.setattr(handlers.config, "cdm", cdm, raising=False)
user = {**TIER, **({"cdm": key_cdm} if key_cdm else {})}
@@ -336,7 +338,7 @@ def test_each_ladder_gives_the_pinned_choice(monkeypatch: pytest.MonkeyPatch, de
("name", "system"),
[("wv", "widevine"), ("PlayReady", "playready"), ("PR", "playready"), ("clearkey", None), (5, None), (None, None)],
)
-def test_drm_system_reads_each_name_of_a_system(name: Any, system: Optional[str]) -> None:
+def test_drm_system_reads_each_name_of_a_system(name: Any, system: str | None) -> None:
assert drm_system(name) == system
@@ -344,5 +346,5 @@ def test_drm_system_reads_each_name_of_a_system(name: Any, system: Optional[str]
("entry", "system"),
[({"widevine": "wv_dev"}, "widevine"), (DUAL, None), ({"default": "pr_dev"}, None), ("pr_dev", None)],
)
-def test_the_entry_settles_a_system_only_when_it_names_one(entry: Any, system: Optional[str]) -> None:
+def test_the_entry_settles_a_system_only_when_it_names_one(entry: Any, system: str | None) -> None:
assert choose_cdm({"EXAMPLE": entry}, "EXAMPLE").system == system
diff --git a/tests/core/test_clearkey_cenc.py b/tests/core/test_clearkey_cenc.py
index 75778f76..4be366dd 100644
--- a/tests/core/test_clearkey_cenc.py
+++ b/tests/core/test_clearkey_cenc.py
@@ -12,7 +12,7 @@ from __future__ import annotations
import base64
import json
-from typing import Any, Optional
+from typing import Any
from uuid import UUID
import pytest
@@ -52,7 +52,7 @@ class StubLicence:
def __init__(self, response: Any) -> None:
self.response = response
- self.challenge: Optional[bytes] = None
+ self.challenge: bytes | None = None
def __call__(self, *, challenge: bytes) -> Any:
self.challenge = challenge
@@ -72,8 +72,8 @@ class StubSession:
def __init__(self, content: bytes) -> None:
self.content = content
- self.url: Optional[str] = None
- self.data: Optional[bytes] = None
+ self.url: str | None = None
+ self.data: bytes | None = None
def post(self, url: str, data: Any = None, **_: Any) -> StubResponse:
self.url = url
diff --git a/tests/core/test_controld_proxy.py b/tests/core/test_controld_proxy.py
index 411c4464..dca0ee0a 100644
--- a/tests/core/test_controld_proxy.py
+++ b/tests/core/test_controld_proxy.py
@@ -12,8 +12,8 @@ import socket
import socketserver
import threading
import time
+from collections.abc import Iterator
from types import SimpleNamespace
-from typing import Iterator
from unittest.mock import Mock
import click
diff --git a/tests/core/test_dash_audio_channels.py b/tests/core/test_dash_audio_channels.py
index 432be42b..248cbfe9 100644
--- a/tests/core/test_dash_audio_channels.py
+++ b/tests/core/test_dash_audio_channels.py
@@ -1,5 +1,4 @@
import xml.etree.ElementTree as ET
-from typing import Optional
import pytest
@@ -66,5 +65,5 @@ def test_the_first_decodable_descriptor_wins() -> None:
@pytest.mark.parametrize(
("representation", "expected"), [(config((COUNT, "6"), tag="Representation"), 5.1), (None, 2.0)]
)
-def test_the_representation_overrides_the_adaptation_set(representation: Optional[ET.Element], expected: float) -> None:
+def test_the_representation_overrides_the_adaptation_set(representation: ET.Element | None, expected: float) -> None:
assert DASH.get_audio_channels(config((COUNT, "2")), representation) == expected
diff --git a/tests/core/test_dash_period_rebase.py b/tests/core/test_dash_period_rebase.py
index 4acb93d1..b4955edf 100644
--- a/tests/core/test_dash_period_rebase.py
+++ b/tests/core/test_dash_period_rebase.py
@@ -1,12 +1,13 @@
import re
import struct
import threading
+from collections.abc import Iterator
from functools import partial
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from io import BytesIO
from pathlib import Path
from types import SimpleNamespace
-from typing import Any, Iterator
+from typing import Any
import pytest
import requests
diff --git a/tests/core/test_disable_metadata.py b/tests/core/test_disable_metadata.py
index 90ada3fc..39843519 100644
--- a/tests/core/test_disable_metadata.py
+++ b/tests/core/test_disable_metadata.py
@@ -2,8 +2,6 @@
from __future__ import annotations
-from typing import Optional, Union
-
import pytest
from unshackle.core import providers
@@ -14,23 +12,23 @@ from unshackle.core.providers._base import ExternalIds, MetadataProvider, Metada
class FakeProvider(MetadataProvider):
"""Stands in for a real provider; fails the test if it is searched."""
- def __init__(self, name: str, result: Optional[MetadataResult] = None) -> None:
+ def __init__(self, name: str, result: MetadataResult | None = None) -> None:
self.NAME = name
self._result = result
- self.asked: list[Union[int, str]] = []
+ self.asked: list[int | str] = []
super().__init__()
def is_available(self) -> bool:
return True
- def search(self, title: str, year: Optional[int], kind: str) -> Optional[MetadataResult]:
+ def search(self, title: str, year: int | None, kind: str) -> MetadataResult | None:
raise AssertionError("no provider may be searched while disable_metadata is set")
- def get_by_id(self, provider_id: Union[int, str], kind: str) -> Optional[MetadataResult]:
+ def get_by_id(self, provider_id: int | str, kind: str) -> MetadataResult | None:
self.asked.append(provider_id)
return self._result
- def get_external_ids(self, provider_id: Union[int, str], kind: str) -> ExternalIds:
+ def get_external_ids(self, provider_id: int | str, kind: str) -> ExternalIds:
return ExternalIds()
diff --git a/tests/core/test_downloader_resume.py b/tests/core/test_downloader_resume.py
index 24333277..9f374f3e 100644
--- a/tests/core/test_downloader_resume.py
+++ b/tests/core/test_downloader_resume.py
@@ -20,9 +20,9 @@ import importlib
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
-from typing import Optional
import pytest
+import urllib3
from requests import Session
# the downloaders package re-exports a `requests` function that shadows this submodule
@@ -40,7 +40,7 @@ class _FaultServer:
def __init__(self, body: bytes) -> None:
self.body = body
self.attempts = 0 # GETs seen for the single resource
- self.ranges: list[Optional[str]] = [] # Range header per GET, in order
+ self.ranges: list[str | None] = [] # Range header per GET, in order
self.truncate_first = 0 # send only half the body + close, for the first N attempts
self._lock = threading.Lock()
server = self
@@ -85,7 +85,7 @@ class _FaultServer:
self._httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
self._thread = threading.Thread(target=self._httpd.serve_forever, daemon=True)
- def __enter__(self) -> "_FaultServer":
+ def __enter__(self) -> _FaultServer:
self._thread.start()
return self
@@ -111,7 +111,7 @@ def test_truncated_segment_is_not_finalized(tmp_path: Path, monkeypatch: pytest.
save = tmp_path / "seg.bin"
with _FaultServer(body) as srv:
srv.truncate_first = 99 # every attempt under-delivers
- with pytest.raises(Exception):
+ with pytest.raises((OSError, urllib3.exceptions.HTTPError)):
consume(dl.download(url=srv.url, save_path=save, session=Session(), segmented=True))
assert not save.exists(), "truncated segment must not be finalized as complete"
diff --git a/tests/core/test_drm_lock.py b/tests/core/test_drm_lock.py
index 9459f04e..b3dd3077 100644
--- a/tests/core/test_drm_lock.py
+++ b/tests/core/test_drm_lock.py
@@ -4,7 +4,7 @@ take turns so the second one reads the content keys out of the cache."""
from __future__ import annotations
from threading import Lock
-from typing import Any, Optional
+from typing import Any
from uuid import UUID
import pytest
@@ -18,7 +18,7 @@ KID_B = UUID("22222222222222222222222222222222")
class FakeDRM:
- def __init__(self, kids: Optional[list[Any]] = None, content_id: Optional[str] = None) -> None:
+ def __init__(self, kids: list[Any] | None = None, content_id: str | None = None) -> None:
self.kids = kids or []
self.content_id = content_id
diff --git a/tests/core/test_error_codes.py b/tests/core/test_error_codes.py
index 65bdfd0c..17dc445b 100644
--- a/tests/core/test_error_codes.py
+++ b/tests/core/test_error_codes.py
@@ -2,9 +2,10 @@
from __future__ import annotations
+from collections.abc import Callable
from pathlib import Path
from types import SimpleNamespace
-from typing import Any, Callable, Optional
+from typing import Any
import click
import pytest
@@ -25,7 +26,7 @@ from unshackle.core.service import Service
from unshackle.core.utils import ip_info, run_proxy
-def code_of(call: Callable[[], Any]) -> Optional[APIErrorCode]:
+def code_of(call: Callable[[], Any]) -> APIErrorCode | None:
"""The code the raised exception names itself, not the one its message would give."""
with pytest.raises(BaseException) as caught:
call()
@@ -77,7 +78,7 @@ class Blocked(Service):
@pytest.mark.parametrize("proxy", [None, "https://u:p@chosen.example:89"], ids=["own-region", "proxy-region"])
-def test_a_blocked_region_is_a_geofence_error(monkeypatch: pytest.MonkeyPatch, proxy: Optional[str]) -> None:
+def test_a_blocked_region_is_a_geofence_error(monkeypatch: pytest.MonkeyPatch, proxy: str | None) -> None:
monkeypatch.setattr(service_mod, "get_ip_info", lambda *args, **kwargs: {"country": "gb"})
monkeypatch.setattr(service_mod, "verify_proxy_exit", lambda session: {"country": "gb"})
monkeypatch.setattr(run_proxy, "watched", {})
@@ -140,7 +141,7 @@ def http_failure(status: Any) -> requests.ConnectionError:
ids=["404", "410", "429", "503", "403", "not-a-status", "no-answer"],
)
def test_a_manifest_fetch_failure_is_coded_from_an_unambiguous_status(
- failure: Exception, code: Optional[APIErrorCode]
+ failure: Exception, code: APIErrorCode | None
) -> None:
error = manifest_fetch_error("DASH", "Example Movie", failure)
assert isinstance(error, click.ClickException) and "may have expired" in error.message
diff --git a/tests/core/test_export.py b/tests/core/test_export.py
index 0acaf80a..9e1d4884 100644
--- a/tests/core/test_export.py
+++ b/tests/core/test_export.py
@@ -12,7 +12,7 @@ import json
import logging
from pathlib import Path
from types import SimpleNamespace
-from typing import Any, Optional, cast
+from typing import Any, cast
from uuid import UUID
import click
@@ -396,7 +396,7 @@ def ad_mpd(ad_id: str) -> str:
{period(ad_id, "PRE_ROLL")}{period("main", "")}"""
-def export_service_filtered_title(tmp_path: Path, manifest_url: Optional[str]) -> Path:
+def export_service_filtered_title(tmp_path: Path, manifest_url: str | None) -> Path:
"""Export a DASH title as a service would, its own period_filter dropping the pre-roll, with no manifest snapshot.
Without a snapshot the import re-fetches the manifest, the path ``content_periods`` serves.
@@ -423,7 +423,7 @@ def export_service_filtered_title(tmp_path: Path, manifest_url: Optional[str]) -
@pytest.mark.parametrize("manifest_url", [AD_MPD_URL, None])
@pytest.mark.parametrize("ad_id_on_refetch", ["ad-1", "ad-9"])
def test_import_keeps_out_the_periods_the_service_filtered(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch, manifest_url: Optional[str], ad_id_on_refetch: str
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, manifest_url: str | None, ad_id_on_refetch: str
) -> None:
"""The import re-fetches the MPD without the service, so its filter must travel in the export.
diff --git a/tests/core/test_fps.py b/tests/core/test_fps.py
index 1f074b12..5d6d02c5 100644
--- a/tests/core/test_fps.py
+++ b/tests/core/test_fps.py
@@ -1,6 +1,6 @@
import warnings
+from collections.abc import Callable
from pathlib import Path
-from typing import Callable
import pytest
diff --git a/tests/core/test_hdr10plus_probe.py b/tests/core/test_hdr10plus_probe.py
index 07f28b6e..2e3acea3 100644
--- a/tests/core/test_hdr10plus_probe.py
+++ b/tests/core/test_hdr10plus_probe.py
@@ -67,7 +67,9 @@ def ladder(
) -> tuple[list[Any], list[str]]:
"""HEVC HDR10 tracks, highest bitrate first; '+' marks the ones whose fragment carries HDR10+."""
heights = heights or [2160 - 100 * i for i in range(len(pattern))]
- videos = [hevc(f"v{i}{mark}", height, 100 - i) for i, (mark, height) in enumerate(zip(pattern, heights))]
+ videos = [
+ hevc(f"v{i}{mark}", height, 100 - i) for i, (mark, height) in enumerate(zip(pattern, heights, strict=False))
+ ]
return videos, probe(monkeypatch, videos)
diff --git a/tests/core/test_hls_segment_io.py b/tests/core/test_hls_segment_io.py
index 53a0d018..0b4d075e 100644
--- a/tests/core/test_hls_segment_io.py
+++ b/tests/core/test_hls_segment_io.py
@@ -43,7 +43,7 @@ def test_concat_list_is_written_as_utf8(tmp_path: Path, monkeypatch: pytest.Monk
def spy_write_text(self, data, encoding=None, *args, **kwargs):
encodings.append(encoding)
- return real_write_text(self, data, encoding=encoding, *args, **kwargs)
+ return real_write_text(self, data, *args, encoding=encoding, **kwargs)
seen: list[bytes] = []
diff --git a/tests/core/test_hls_session_keys.py b/tests/core/test_hls_session_keys.py
index 9c5c9083..c9ff059b 100644
--- a/tests/core/test_hls_session_keys.py
+++ b/tests/core/test_hls_session_keys.py
@@ -4,7 +4,6 @@ from __future__ import annotations
import base64
import json
-from typing import Optional
import m3u8
import pytest
@@ -34,14 +33,14 @@ def _b64(items: list[dict]) -> str:
return base64.b64encode(json.dumps(items).encode()).decode()
-def _item(method: str, keyformat: Optional[str] = None) -> dict:
+def _item(method: str, keyformat: str | None = None) -> dict:
item = {"method": method, "uri": KEY_URI}
if keyformat:
item["keyformat"] = keyformat
return item
-def _key(method: str, keyformat: Optional[str] = None) -> m3u8.model.Key:
+def _key(method: str, keyformat: str | None = None) -> m3u8.model.Key:
return m3u8.model.Key(method=method, base_uri="", uri=KEY_URI, keyformat=keyformat)
@@ -60,7 +59,7 @@ def test_session_data_playready_urn_key_is_kept() -> None:
("ISO-23001-7", None),
],
)
-def test_session_data_supported_keys_are_kept(method: str, keyformat: Optional[str]) -> None:
+def test_session_data_supported_keys_are_kept(method: str, keyformat: str | None) -> None:
keys = HLS.parse_session_data_keys(_master(_b64([_item(method, keyformat)])))
assert [k.keyformat for k in keys] == [keyformat]
diff --git a/tests/core/test_hls_webvtt_discontinuity.py b/tests/core/test_hls_webvtt_discontinuity.py
index 8683fffe..7bc99e13 100644
--- a/tests/core/test_hls_webvtt_discontinuity.py
+++ b/tests/core/test_hls_webvtt_discontinuity.py
@@ -2,7 +2,6 @@ from functools import partial
from http.server import ThreadingHTTPServer
from pathlib import Path
from types import SimpleNamespace
-from typing import Optional
from tests.core.test_dash_period_rebase import fragment, init_segment, server, tfdts
from unshackle.core.manifests import HLS
@@ -23,7 +22,7 @@ def starts(text: str) -> list[str]:
def rebase(texts: list[str], bounds_ms: list[int]) -> list[str]:
- return [shift_webvtt(t, o) for t, o in zip(texts, webvtt_block_offsets(texts, bounds_ms))]
+ return [shift_webvtt(t, o) for t, o in zip(texts, webvtt_block_offsets(texts, bounds_ms), strict=False)]
def test_restarting_blocks_move_to_their_playlist_start() -> None:
@@ -84,7 +83,7 @@ def playlist(names: list[str], init: str = "") -> bytes:
return f"#EXTM3U\n#EXT-X-VERSION:6\n#EXT-X-TARGETDURATION:4\n{blocks}#EXT-X-ENDLIST\n".encode()
-def download(server: ThreadingHTTPServer, tmp_path: Path, codec: Optional[Subtitle.Codec] = None) -> Path:
+def download(server: ThreadingHTTPServer, tmp_path: Path, codec: Subtitle.Codec | None = None) -> Path:
url = f"http://127.0.0.1:{server.server_address[1]}/master.m3u8"
track = HLS.from_text(MASTER, url=url).to_tracks(language="en").subtitles[0]
if codec:
diff --git a/tests/core/test_http_cdm.py b/tests/core/test_http_cdm.py
index a3b7948c..222e2201 100644
--- a/tests/core/test_http_cdm.py
+++ b/tests/core/test_http_cdm.py
@@ -3,7 +3,7 @@
from __future__ import annotations
import base64
-from typing import Any, Dict, List, Optional
+from typing import Any
from uuid import UUID
import pytest
@@ -23,17 +23,17 @@ KEY_A, KEY_B, KEY_X = "01" * 16, "02" * 16, "0f" * 16
class FakeVaults:
- def __init__(self, keys: Dict[UUID, str]) -> None:
+ def __init__(self, keys: dict[UUID, str]) -> None:
self.keys = dict(keys)
- self.added: Dict[Any, str] = {}
+ self.added: dict[Any, str] = {}
def __len__(self) -> int:
return 1
- def get_key(self, kid: UUID) -> tuple[Optional[str], None]:
+ def get_key(self, kid: UUID) -> tuple[str | None, None]:
return self.keys.get(kid), None
- def add_keys(self, keys: Dict[Any, str]) -> None:
+ def add_keys(self, keys: dict[Any, str]) -> None:
self.added.update(keys)
@@ -42,21 +42,21 @@ class StubCdm(HttpCdm):
def __init__(
self,
- cached: Optional[List[Dict[str, Any]]] = None,
- licence: Optional[List[Dict[str, Any]]] = None,
+ cached: list[dict[str, Any]] | None = None,
+ licence: list[dict[str, Any]] | None = None,
vaults: Any = None,
) -> None:
super().__init__("https://cdm.test/", "L3", None, "EXAMPLE", vaults, {})
self.cached = cached
self.licence = licence or []
self.challenges = 0
- self.required: List[Optional[List[str]]] = []
- self.bodies: List[Dict[str, Any]] = []
+ self.required: list[list[str] | None] = []
+ self.bodies: list[dict[str, Any]] = []
def _request_challenge(
self,
- session: Dict[str, Any],
- body: Dict[str, Any],
+ session: dict[str, Any],
+ body: dict[str, Any],
license_type: str,
privacy_mode: bool,
) -> bytes:
@@ -66,16 +66,16 @@ class StubCdm(HttpCdm):
return b""
return self._keep_challenge(session, b"challenge", "remote-1")
- def _request_keys(self, session: Dict[str, Any], body: Dict[str, Any]) -> List[Dict[str, Any]]:
+ def _request_keys(self, session: dict[str, Any], body: dict[str, Any]) -> list[dict[str, Any]]:
self.bodies.append(body)
return self.licence
-def key(kid: UUID, value: str) -> Dict[str, str]:
+def key(kid: UUID, value: str) -> dict[str, str]:
return {"kid": kid.hex, "key": value, "type": "CONTENT"}
-def licensed(cdm: StubCdm, *kids: UUID) -> Dict[UUID, str]:
+def licensed(cdm: StubCdm, *kids: UUID) -> dict[UUID, str]:
"""Run one challenge and licence round and return the content keys of the session."""
session_id = cdm.open()
cdm.set_required_kids(list(kids), session_id=session_id)
@@ -149,9 +149,9 @@ class L1StubCdm(StubCdm):
def __init__(self) -> None:
super().__init__(licence=[key(KID_A, KEY_A)])
- self.sent: List[Dict[str, Any]] = []
+ self.sent: list[dict[str, Any]] = []
- def _request_challenge(self, session: Dict[str, Any], body: Dict[str, Any], *rest: Any) -> bytes:
+ def _request_challenge(self, session: dict[str, Any], body: dict[str, Any], *rest: Any) -> bytes:
self.sent.append(body)
return super()._request_challenge(session, body, *rest)
diff --git a/tests/core/test_http_cdm_loopback.py b/tests/core/test_http_cdm_loopback.py
index 937e33ef..b2628edb 100644
--- a/tests/core/test_http_cdm_loopback.py
+++ b/tests/core/test_http_cdm_loopback.py
@@ -9,8 +9,9 @@ from __future__ import annotations
import base64
import json
import threading
+from collections.abc import Callable, Iterator
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
-from typing import Any, Callable, Dict, Iterator, List
+from typing import Any
from uuid import UUID
import pytest
@@ -29,15 +30,15 @@ CHALLENGE = b"loopback challenge"
LICENCE = b"loopback licence"
PR_LICENCE = "loopback"
-Answer = Callable[[Dict[str, Any]], Dict[str, Any]]
+Answer = Callable[[dict[str, Any]], dict[str, Any]]
class Api:
"""A loopback HTTP API: one answer per path, every request recorded."""
def __init__(self) -> None:
- self.answers: Dict[str, Answer] = {}
- self.requests: List[tuple[str, Dict[str, str], Dict[str, Any]]] = []
+ self.answers: dict[str, Answer] = {}
+ self.requests: list[tuple[str, dict[str, str], dict[str, Any]]] = []
api = self
class Handler(BaseHTTPRequestHandler):
@@ -192,7 +193,7 @@ def test_decrypt_labs_partial_cache_asks_for_a_licence(api: Api, second_answer:
assert keys == {KID: KEY}
-CUSTOM_CONFIG: Dict[str, Any] = {
+CUSTOM_CONFIG: dict[str, Any] = {
"auth": {"type": "header", "header_name": "x-api-key", "key": "s3cret"},
"endpoints": {"get_request": "/challenge", "decrypt_response": {"path": "/keys"}},
"request_mapping": {"get_request": {"param_names": {"init_data": "pssh"}}},
@@ -221,7 +222,7 @@ def custom_answers(api: Api) -> None:
({"name": "SL3000", "type": "PLAYREADY"}, playready_drm, PR_LICENCE),
],
)
-def test_custom_api(api: Api, device: Dict[str, Any], drm_of: Callable[[], Any], licence: Any) -> None:
+def test_custom_api(api: Api, device: dict[str, Any], drm_of: Callable[[], Any], licence: Any) -> None:
custom_answers(api)
drm = drm_of()
cdm = CustomRemoteCDM(host=api.url, device=device, **CUSTOM_CONFIG)
diff --git a/tests/core/test_hybrid_hdr10plus.py b/tests/core/test_hybrid_hdr10plus.py
index 14d84bc8..31301a4b 100644
--- a/tests/core/test_hybrid_hdr10plus.py
+++ b/tests/core/test_hybrid_hdr10plus.py
@@ -10,9 +10,10 @@ import json
import logging
import re
import weakref
+from collections.abc import Iterator
from pathlib import Path
from types import SimpleNamespace
-from typing import Any, Iterator, Optional
+from typing import Any
import pytest
@@ -219,7 +220,7 @@ def make_hybrid() -> Hybrid:
return obj
-def stub_hybrid_steps(monkeypatch: pytest.MonkeyPatch, *steps: str, tool: Optional[str] = "hdr10plus_tool") -> None:
+def stub_hybrid_steps(monkeypatch: pytest.MonkeyPatch, *steps: str, tool: str | None = "hdr10plus_tool") -> None:
"""Make the stream, Level 5 and inject steps (and those named) do nothing, with a fixed active area."""
for name in ("extract_stream", "level_5", "injecting", *steps):
monkeypatch.setattr(Hybrid, name, lambda self, *a, **k: None)
@@ -240,7 +241,7 @@ def capture_generate(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]:
@pytest.mark.parametrize("top, expected", [(277, (2160 - 554) / 2160), (1000, None)])
-def test_active_area_share(top: int, expected: Optional[float], quiet: None, monkeypatch: pytest.MonkeyPatch) -> None:
+def test_active_area_share(top: int, expected: float | None, quiet: None, monkeypatch: pytest.MonkeyPatch) -> None:
"""A letterboxed picture gives its crop and share of the frame; an implausibly small one gives None.
cropdetect settles over its frames, so the last crop line counts.
@@ -451,7 +452,7 @@ def test_a_conversion_run_removes_its_rpus_so_the_next_base_makes_its_own(
@pytest.mark.parametrize("range_, tool", [(Video.Range.HDR10, "hdr10plus_tool"), (Video.Range.HDR10P, None)])
def test_a_base_without_usable_hdr10plus_is_measured_inside_its_crop(
- range_: Video.Range, tool: Optional[str], quiet: None, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ range_: Video.Range, tool: str | None, quiet: None, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
base = tmp_path / "base.mkv"
base.write_bytes(b"")
@@ -594,7 +595,7 @@ def test_an_hdr10plus_conversion_fills_light_levels_the_stream_does_not_state(
],
)
def test_a_sample_rpu_is_shifted_to_the_first_frame_of_the_base(
- dv_start: float, expected: Optional[dict[str, Any]], quiet: None, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ dv_start: float, expected: dict[str, Any] | None, quiet: None, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""--sample cuts each track on its own segment grid, so the RPU can start before or after the base."""
seen: dict[str, Any] = {}
@@ -850,7 +851,7 @@ def video(
id_: str,
range_: Video.Range,
height: int = 2160,
- codec: Optional[Video.Codec] = Video.Codec.HEVC,
+ codec: Video.Codec | None = Video.Codec.HEVC,
native_hybrid: bool = False,
) -> Any:
return SimpleNamespace(id=id_, height=height, range=range_, codec=codec, native_hybrid=native_hybrid, stereo=False)
diff --git a/tests/core/test_hybrid_l6.py b/tests/core/test_hybrid_l6.py
index 20048fca..5afd887d 100644
--- a/tests/core/test_hybrid_l6.py
+++ b/tests/core/test_hybrid_l6.py
@@ -9,8 +9,9 @@ import contextlib
import json
import logging
import subprocess
+from collections.abc import Iterator
from pathlib import Path
-from typing import Any, Iterator, Optional
+from typing import Any
import pytest
@@ -128,7 +129,7 @@ def rpu_info(max_cll: int, max_fall: int, max_mdl: int, min_mdl: int) -> dict:
def patch_level6(
monkeypatch: pytest.MonkeyPatch,
info: dict,
- probe: Optional[tuple[int, int, int, int]],
+ probe: tuple[int, int, int, int] | None,
) -> list[Path]:
"""Mock the RPU read, the HDR10 probe, and the editor. Returns the editor call log."""
edits: list[Path] = []
diff --git a/tests/core/test_imdb_provider.py b/tests/core/test_imdb_provider.py
index e8a06b3f..426adf6b 100644
--- a/tests/core/test_imdb_provider.py
+++ b/tests/core/test_imdb_provider.py
@@ -3,7 +3,7 @@
from __future__ import annotations
import json
-from typing import Any, Optional
+from typing import Any
import pytest
@@ -21,7 +21,7 @@ class _Response:
def node(
imdb_id: str = "tt3581920",
text: str = "The Last of Us",
- year: Optional[int] = 2023,
+ year: int | None = 2023,
title_type: str = "tvSeries",
languages: Any = ({"id": "en", "text": "English"}, {"id": "id", "text": "Indonesian"}),
) -> dict:
diff --git a/tests/core/test_import_foreign_hls.py b/tests/core/test_import_foreign_hls.py
index d07e2156..449b2795 100644
--- a/tests/core/test_import_foreign_hls.py
+++ b/tests/core/test_import_foreign_hls.py
@@ -12,7 +12,7 @@ import json
import struct
from pathlib import Path
from types import SimpleNamespace
-from typing import Any, Optional, cast
+from typing import Any, cast
from unittest.mock import patch
from uuid import UUID
@@ -42,7 +42,7 @@ def playready_object(kid: UUID) -> str:
return base64.b64encode(struct.pack(" str:
+def media_playlist(kid: UUID | None) -> str:
key = ""
if kid:
key = (
@@ -91,7 +91,7 @@ def write_export(tmp_path: Path, language: str = "", manifest_url: str = MASTER_
return path
-def import_title(export: Path, master_text: str, playlists: dict[str, Optional[UUID]]) -> tuple[ImportService, Any]:
+def import_title(export: Path, master_text: str, playlists: dict[str, UUID | None]) -> tuple[ImportService, Any]:
ctx = cast(click.Context, SimpleNamespace(parent=None, params={}))
svc = ImportService(ctx, "EXAMPLE", "ep-1", str(export))
@@ -99,7 +99,7 @@ def import_title(export: Path, master_text: str, playlists: dict[str, Optional[U
name = url.split("?")[0].rsplit("/", 1)[-1]
return SimpleNamespace(text=media_playlist(playlists.get(name)), raise_for_status=lambda: None)
- setattr(svc.session, "get", get)
+ svc.session.get = get
episode = next(iter(svc.get_titles()))
with patch.object(HLS, "from_url", side_effect=lambda url, session=None, **kw: HLS.from_text(master_text, url)):
episode.tracks = svc.get_tracks(episode)
diff --git a/tests/core/test_import_manifest_data.py b/tests/core/test_import_manifest_data.py
index b529218b..77374f04 100644
--- a/tests/core/test_import_manifest_data.py
+++ b/tests/core/test_import_manifest_data.py
@@ -12,7 +12,7 @@ from __future__ import annotations
import json
from functools import partial
from pathlib import Path
-from typing import Any, Optional
+from typing import Any
import click
import pytest
@@ -57,7 +57,7 @@ def exported_video(track_id: str, url: str, codec: str, width: int, height: int)
}
-def make_service(tmp_path: Path, manifest_url: Optional[str], tracks: dict[str, Any]) -> ImportService:
+def make_service(tmp_path: Path, manifest_url: str | None, tracks: dict[str, Any]) -> ImportService:
entry: dict[str, Any] = {
"meta": {"type": "movie", "id": "movie-1", "name": "Example Movie", "year": 2024, "language": "en"},
"manifest_type": "DASH",
diff --git a/tests/core/test_import_missing_key.py b/tests/core/test_import_missing_key.py
index b5342eb7..b925fcdf 100644
--- a/tests/core/test_import_missing_key.py
+++ b/tests/core/test_import_missing_key.py
@@ -9,7 +9,7 @@ from __future__ import annotations
from pathlib import Path
from types import SimpleNamespace
-from typing import Any, Optional
+from typing import Any
from uuid import UUID
import click
@@ -66,7 +66,7 @@ class CountedImport(ImportService):
self.calls = calls
self.server_cdm_type = "widevine"
- def license_track(self, track: Any, drm: Any, kid: Optional[UUID] = None) -> Optional[dict[UUID, str]]:
+ def license_track(self, track: Any, drm: Any, kid: UUID | None = None) -> dict[UUID, str] | None:
self.calls.append("licence")
return super().license_track(track, drm, kid)
diff --git a/tests/core/test_import_tracks.py b/tests/core/test_import_tracks.py
index 804531f3..418a9b97 100644
--- a/tests/core/test_import_tracks.py
+++ b/tests/core/test_import_tracks.py
@@ -11,7 +11,7 @@ from __future__ import annotations
import json
from pathlib import Path
-from typing import Any, Optional
+from typing import Any
from unittest.mock import patch
from uuid import UUID
@@ -56,9 +56,9 @@ URL_SUBTITLE = {
def make_service(
tmp_path: Path,
- language: Optional[str],
- tracks: Optional[dict[str, Any]] = None,
- manifest_url: Optional[str] = "https://example.invalid/m.mpd",
+ language: str | None,
+ tracks: dict[str, Any] | None = None,
+ manifest_url: str | None = "https://example.invalid/m.mpd",
) -> ImportService:
entry: dict[str, Any] = {
"meta": {"type": "movie", "id": "movie-1", "name": "Example Movie", "year": 2024, "language": language},
@@ -86,9 +86,7 @@ def test_manifest_supplies_language_without_title_language(tmp_path: Path, mpd:
@pytest.mark.parametrize("language", [None, "und"], ids=["missing", "und"])
-def test_unlabelled_manifest_without_usable_language_blames_the_service(
- tmp_path: Path, language: Optional[str]
-) -> None:
+def test_unlabelled_manifest_without_usable_language_blames_the_service(tmp_path: Path, language: str | None) -> None:
"""`und` is truthy and a valid tag, so it must be rejected as firmly as no language at all."""
with pytest.raises(click.ClickException) as error:
get_tracks(make_service(tmp_path, language=language), MPD_NO_LANG)
@@ -111,7 +109,7 @@ def exported_video(language: str = "ja") -> dict[str, Any]:
@pytest.mark.parametrize("manifest_url", ["https://example.invalid/m.mpd", None], ids=["manifest-url", "per-track-url"])
-def test_unlabelled_manifest_takes_the_exported_track_language(tmp_path: Path, manifest_url: Optional[str]) -> None:
+def test_unlabelled_manifest_takes_the_exported_track_language(tmp_path: Path, manifest_url: str | None) -> None:
"""A title with no language takes it from its exported tracks, for either import branch."""
service = make_service(tmp_path, language=None, tracks={"v1": exported_video()}, manifest_url=manifest_url)
tracks = get_tracks(service, MPD_NO_LANG)
diff --git a/tests/core/test_ism_init.py b/tests/core/test_ism_init.py
index 77a193c9..fa8006bc 100644
--- a/tests/core/test_ism_init.py
+++ b/tests/core/test_ism_init.py
@@ -470,7 +470,7 @@ def test_avcc_requires_sps_and_pps():
def test_read_track_id_from_fragment():
# Minimal moof/traf/tfhd carrying track_ID = 7.
- tfhd = full_box("tfhd".encode(), 0, 0, struct.pack(">I", 7) + b"\x00" * 4)
+ tfhd = full_box(b"tfhd", 0, 0, struct.pack(">I", 7) + b"\x00" * 4)
traf = box(b"traf", tfhd)
moof = box(b"moof", traf)
mdat = box(b"mdat", b"\x00\x00")
diff --git a/tests/core/test_kid_windows.py b/tests/core/test_kid_windows.py
index 0a94a1e9..d3e2c273 100644
--- a/tests/core/test_kid_windows.py
+++ b/tests/core/test_kid_windows.py
@@ -1,6 +1,5 @@
import struct
from pathlib import Path
-from typing import Optional
from uuid import UUID
import pytest
@@ -79,7 +78,7 @@ def moof(
time: int,
*groups: bytes,
samples: int = 48,
- duration: Optional[int] = None,
+ duration: int | None = None,
tfxd: bool = False,
) -> bytes:
flags = 0x02 | (0x08 if duration is not None else 0)
diff --git a/tests/core/test_kv_add_keys_batching.py b/tests/core/test_kv_add_keys_batching.py
index e5c0a2c0..424db1e3 100644
--- a/tests/core/test_kv_add_keys_batching.py
+++ b/tests/core/test_kv_add_keys_batching.py
@@ -3,8 +3,8 @@
from __future__ import annotations
import logging
+from collections.abc import Iterator
from pathlib import Path
-from typing import Iterator, Optional, Union
from uuid import UUID
import pytest
@@ -27,16 +27,16 @@ class RecordingVault(Vault):
super().__init__("net")
self.batches: list[int] = []
- def get_key(self, kid: Union[UUID, str], service: str) -> Optional[str]:
+ def get_key(self, kid: UUID | str, service: str) -> str | None:
return None
def get_keys(self, service: str) -> Iterator[tuple[str, str]]:
return iter(())
- def add_key(self, service: str, kid: Union[UUID, str], key: str) -> bool:
+ def add_key(self, service: str, kid: UUID | str, key: str) -> bool:
return False
- def add_keys(self, service: str, kid_keys: dict[Union[UUID, str], str]) -> int:
+ def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int:
self.batches.append(len(kid_keys))
return len(kid_keys)
@@ -49,7 +49,7 @@ def test_sql_vault_gets_one_call(tmp_path: Path, monkeypatch: pytest.MonkeyPatch
calls: list[int] = []
real = vault.add_keys
- def spy(service: str, kid_keys: dict[Union[UUID, str], str]) -> int:
+ def spy(service: str, kid_keys: dict[UUID | str, str]) -> int:
calls.append(len(kid_keys))
return real(service, kid_keys)
diff --git a/tests/core/test_latest_episodes.py b/tests/core/test_latest_episodes.py
index b32584b1..8388e751 100644
--- a/tests/core/test_latest_episodes.py
+++ b/tests/core/test_latest_episodes.py
@@ -2,8 +2,6 @@
from __future__ import annotations
-from typing import Optional
-
import pytest
from unshackle.commands.dl import latest_episode_keys
@@ -16,7 +14,7 @@ class Svc:
pass
-def episode(season: int, number: int, part: Optional[int] = None) -> Episode:
+def episode(season: int, number: int, part: int | None = None) -> Episode:
return Episode(id_=f"ep-{season}x{number}.{part}", service=Svc, title="T", season=season, number=number, part=part)
@@ -36,7 +34,7 @@ def series() -> Series:
],
)
def test_the_newest_episodes_are_picked_across_seasons(
- latest_episode: bool, latest_episodes: Optional[int], expected: list[tuple[int, int]]
+ latest_episode: bool, latest_episodes: int | None, expected: list[tuple[int, int]]
) -> None:
assert latest_episode_keys(series(), latest_episode, latest_episodes) == expected
diff --git a/tests/core/test_launch_context.py b/tests/core/test_launch_context.py
index 7c1a1509..6eac816b 100644
--- a/tests/core/test_launch_context.py
+++ b/tests/core/test_launch_context.py
@@ -2,9 +2,10 @@
from __future__ import annotations
+from collections.abc import Callable
from pathlib import Path
from types import SimpleNamespace
-from typing import Any, Callable
+from typing import Any
import click
import pytest
diff --git a/tests/core/test_licence_turns.py b/tests/core/test_licence_turns.py
index aef3bb9e..e4736127 100644
--- a/tests/core/test_licence_turns.py
+++ b/tests/core/test_licence_turns.py
@@ -3,8 +3,9 @@
from __future__ import annotations
import threading
+from collections.abc import Callable
from types import SimpleNamespace
-from typing import Any, Callable, Optional
+from typing import Any
from uuid import UUID
import click
@@ -68,7 +69,7 @@ def widevine(*kids: UUID) -> Widevine:
return Widevine(pssh=PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=list(kids)))
-def prepare(keys: ContentKeyResolver, drm: Any, track_kid: Optional[UUID], table: Table, all_drm: bool = False) -> None:
+def prepare(keys: ContentKeyResolver, drm: Any, track_kid: UUID | None, table: Table, all_drm: bool = False) -> None:
keys.licence_for(SimpleNamespace(drm=[drm]), None, table, all_drm)(drm, track_kid=track_kid)
@@ -150,7 +151,7 @@ def test_a_key_label_is_added_once_with_its_marker_and_source(licences: Licences
ids=["widevine", "playready", "clearkey"],
)
def test_an_all_zero_licence_key_is_dropped(
- monkeypatch: pytest.MonkeyPatch, drm_class: type, build: Callable[[], Any], cdm: Optional[str]
+ monkeypatch: pytest.MonkeyPatch, drm_class: type, build: Callable[[], Any], cdm: str | None
) -> None:
def get_content_keys(self: Any, **_: Any) -> None:
self.content_keys.update({KID_A: KEYS[KID_A], KID_C: "0" * 32})
diff --git a/tests/core/test_manifest_corpus.py b/tests/core/test_manifest_corpus.py
index 058fc2dc..793e02da 100644
--- a/tests/core/test_manifest_corpus.py
+++ b/tests/core/test_manifest_corpus.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import json
from collections import Counter
from pathlib import Path
-from typing import Any, Union
+from typing import Any
from unittest.mock import MagicMock
import pytest
@@ -33,7 +33,7 @@ def cases(entries: list[dict[str, Any]]) -> list[Any]:
def parse(entry: dict[str, Any]) -> Tracks:
"""Parse a fixture the way from_url does: XML from bytes, M3U8 decoded as UTF-8."""
data = (CORPUS / entry["file"]).read_bytes()
- parser: Union[DASH, HLS, ISM]
+ parser: DASH | HLS | ISM
if entry["kind"] == "hls":
parser = HLS.from_text(data.decode("utf-8"), entry["url"])
else:
diff --git a/tests/core/test_manifest_snapshot.py b/tests/core/test_manifest_snapshot.py
index e09ad7bc..2779b36d 100644
--- a/tests/core/test_manifest_snapshot.py
+++ b/tests/core/test_manifest_snapshot.py
@@ -7,7 +7,7 @@ import json
import logging
import zlib
from copy import deepcopy
-from typing import Any, Optional
+from typing import Any
import pytest
@@ -21,7 +21,7 @@ from unshackle.core.wire import track_from_dict, track_to_dict
URL = "https://cdn.example/title/manifest.mpd"
-def period(pid: Optional[str], kind: str) -> str:
+def period(pid: str | None, kind: str) -> str:
attr = f' id="{pid}"' if pid else ""
name = pid or "noid"
return f"""
@@ -67,7 +67,7 @@ def service_tracks(text: str = MPD) -> Tracks:
return DASH.from_text(text, URL).to_tracks(language="en", period_filter=is_ad)
-def detach_video(tracks: Tracks, track_id: Optional[str] = None) -> Track:
+def detach_video(tracks: Tracks, track_id: str | None = None) -> Track:
"""Give the video an AdaptationSet outside the tree, the way a service that builds its own does."""
video = tracks.videos[0]
data = video.data["dash"]
diff --git a/tests/core/test_mp4decrypt_track_key.py b/tests/core/test_mp4decrypt_track_key.py
index 0c9629de..5cde540f 100644
--- a/tests/core/test_mp4decrypt_track_key.py
+++ b/tests/core/test_mp4decrypt_track_key.py
@@ -3,8 +3,9 @@ from __future__ import annotations
import io
import subprocess
import sys
+from collections.abc import Callable
from pathlib import Path
-from typing import Any, Callable
+from typing import Any
from uuid import UUID
import pytest
diff --git a/tests/core/test_music_container.py b/tests/core/test_music_container.py
index d706948c..188d576c 100644
--- a/tests/core/test_music_container.py
+++ b/tests/core/test_music_container.py
@@ -13,7 +13,6 @@ from __future__ import annotations
import shutil
import subprocess
from pathlib import Path
-from typing import Optional
import mutagen
import pytest
@@ -148,7 +147,7 @@ def test_a_failed_remux_keeps_the_source_and_removes_its_partial_file(tmp_path:
assert not list(tmp_path.glob("track_music*")), "a failed remux must not leave a partial file"
-def make_track(path: Path, codec: Optional[Audio.Codec]) -> Audio:
+def make_track(path: Path, codec: Audio.Codec | None) -> Audio:
track = Audio(id_="a1", url="https://example.test/a1.mp4", language="en", codec=codec)
track.path = path
return track
@@ -167,7 +166,7 @@ def make_track(path: Path, codec: Optional[Audio.Codec]) -> Audio:
],
)
def test_the_file_codec_decides_the_container(
- tmp_path: Path, encoder: str, fmt: str, declared: Optional[Audio.Codec], extension: str, probed: Audio.Codec
+ tmp_path: Path, encoder: str, fmt: str, declared: Audio.Codec | None, extension: str, probed: Audio.Codec
) -> None:
"""Every track downloads under a .mp4 name, and a service can declare no codec or the wrong one."""
track = make_track(encode(tmp_path / "track.mp4", encoder, "-f", fmt), declared)
diff --git a/tests/core/test_music_extract.py b/tests/core/test_music_extract.py
index 0c5b3f3e..d89f01c3 100644
--- a/tests/core/test_music_extract.py
+++ b/tests/core/test_music_extract.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from typing import Any, Optional
+from typing import Any
import pytest
@@ -31,11 +31,11 @@ def make_song(
album: str = "Album",
artist: str = "Artist",
name: str = "Song",
- album_artist: Optional[str] = None,
- total_tracks: Optional[int] = None,
- total_discs: Optional[int] = None,
- artwork_url: Optional[str] = None,
- data: Optional[Any] = None,
+ album_artist: str | None = None,
+ total_tracks: int | None = None,
+ total_discs: int | None = None,
+ artwork_url: str | None = None,
+ data: Any | None = None,
) -> Song:
return Song(
id_=f"{album}-{disc}-{track}",
@@ -81,7 +81,7 @@ def test_first_text(values: tuple[Any, ...], default: str, expected: str) -> Non
((), None),
],
)
-def test_first_number(values: tuple[Any, ...], expected: Optional[float]) -> None:
+def test_first_number(values: tuple[Any, ...], expected: float | None) -> None:
assert first_number(*values) == expected
@@ -110,7 +110,7 @@ def test_year_from_value(value: Any, expected: int) -> None:
("nope", None),
],
)
-def test_duration_seconds(value: Any, expected: Optional[float]) -> None:
+def test_duration_seconds(value: Any, expected: float | None) -> None:
assert duration_seconds(value) == expected
@@ -165,7 +165,7 @@ def test_format_names(value: Any, sep: str, expected: str) -> None:
("", None, "album"),
],
)
-def test_classify_release_kind(raw_kind: str, count: Optional[float], expected: str) -> None:
+def test_classify_release_kind(raw_kind: str, count: float | None, expected: str) -> None:
assert classify_release_kind(raw_kind, count) == expected
diff --git a/tests/core/test_music_tagger_roundtrip.py b/tests/core/test_music_tagger_roundtrip.py
index f63497d0..eb2cc288 100644
--- a/tests/core/test_music_tagger_roundtrip.py
+++ b/tests/core/test_music_tagger_roundtrip.py
@@ -40,7 +40,7 @@ class FakeResponse:
def raise_for_status(self) -> None:
pass
- def __enter__(self) -> "FakeResponse":
+ def __enter__(self) -> FakeResponse:
return self
def __exit__(self, *exc_info: Any) -> None:
diff --git a/tests/core/test_placement.py b/tests/core/test_placement.py
index 0e341a49..5c70e128 100644
--- a/tests/core/test_placement.py
+++ b/tests/core/test_placement.py
@@ -2,8 +2,9 @@
from __future__ import annotations
+from collections.abc import Iterator
from pathlib import Path
-from typing import Any, Iterator
+from typing import Any
import pytest
from pymediainfo import MediaInfo
diff --git a/tests/core/test_playlist_encoding.py b/tests/core/test_playlist_encoding.py
index fe3548ed..757913cf 100644
--- a/tests/core/test_playlist_encoding.py
+++ b/tests/core/test_playlist_encoding.py
@@ -5,7 +5,7 @@ XML declaration gives the encoding."""
from __future__ import annotations
-from typing import Any, Optional
+from typing import Any
import pytest
import requests
@@ -21,7 +21,7 @@ MASTER = b'#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1000000,RESOLUTION=1280x720,CODE
MEDIA = b"#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXTINF:6.0,\nseg1.ts\n#EXT-X-ENDLIST\n"
-def make_response(body: bytes, url: str, encoding: Optional[str]) -> requests.Response:
+def make_response(body: bytes, url: str, encoding: str | None) -> requests.Response:
res = requests.Response()
res.status_code = 200
res._content = body
diff --git a/tests/core/test_playready_bare_header.py b/tests/core/test_playready_bare_header.py
index f7170169..c547bfbe 100644
--- a/tests/core/test_playready_bare_header.py
+++ b/tests/core/test_playready_bare_header.py
@@ -85,7 +85,7 @@ def test_dash_skips_an_unparseable_playready_entry_and_keeps_widevine(caplog: py
@pytest.mark.parametrize(
"data",
- [b"\x00\x00not a header", "".encode("utf-8")],
+ [b"\x00\x00not a header", b""],
ids=["garbage", "utf-8-header"],
)
def test_other_bad_data_keeps_the_original_error(data: bytes) -> None:
diff --git a/tests/core/test_proxy_dispatch.py b/tests/core/test_proxy_dispatch.py
index f262bb03..170e6fad 100644
--- a/tests/core/test_proxy_dispatch.py
+++ b/tests/core/test_proxy_dispatch.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import json
import logging
-from typing import Iterator, Optional
+from collections.abc import Iterator
import pytest
@@ -31,22 +31,22 @@ class Alpha(Proxy):
def __repr__(self) -> str:
return "Alpha"
- def get_proxy(self, query: str) -> Optional[str]:
+ def get_proxy(self, query: str) -> str | None:
return self.answers.get(query)
class Beta(Alpha):
- def last_connection_display(self) -> Optional[str]:
+ def last_connection_display(self) -> str | None:
return "via Dallas (server 12)"
class Tunnel(Alpha):
- def __init__(self, info: Optional[dict] = None, **answers: str) -> None:
+ def __init__(self, info: dict | None = None, **answers: str) -> None:
super().__init__(**answers)
self.info = info
self.asked: list[str] = []
- def get_connection_info(self, query: str) -> Optional[dict]:
+ def get_connection_info(self, query: str) -> dict | None:
self.asked.append(query)
return self.info
diff --git a/tests/core/test_proxy_network_selector.py b/tests/core/test_proxy_network_selector.py
index b1552f5c..00f6fdb8 100644
--- a/tests/core/test_proxy_network_selector.py
+++ b/tests/core/test_proxy_network_selector.py
@@ -7,8 +7,8 @@ import re
import socket
import ssl
import threading
+from collections.abc import Iterator
from pathlib import Path
-from typing import Iterator
from unittest.mock import MagicMock
import pytest
@@ -306,7 +306,7 @@ def tls_echo(tmp_path: Path) -> Iterator[tuple[int, ssl.SSLContext]]:
"""A TLS echo server for *.prod.surfshark.com on loopback, and a client context that trusts it."""
key = ec.generate_private_key(ec.SECP256R1())
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "*.prod.surfshark.com")])
- now = datetime.datetime.now(datetime.timezone.utc)
+ now = datetime.datetime.now(datetime.UTC)
cert = (
x509.CertificateBuilder()
.subject_name(name)
diff --git a/tests/core/test_remote_cdm_no_probe.py b/tests/core/test_remote_cdm_no_probe.py
index 7202f52d..530a0192 100644
--- a/tests/core/test_remote_cdm_no_probe.py
+++ b/tests/core/test_remote_cdm_no_probe.py
@@ -1,7 +1,8 @@
import json
import threading
+from collections.abc import Iterator
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
-from typing import Any, Iterator
+from typing import Any
import pytest
import requests
diff --git a/tests/core/test_remote_cdm_pssh_reuse.py b/tests/core/test_remote_cdm_pssh_reuse.py
index 9d559afc..6689e9ba 100644
--- a/tests/core/test_remote_cdm_pssh_reuse.py
+++ b/tests/core/test_remote_cdm_pssh_reuse.py
@@ -7,7 +7,8 @@ decrypt in parallel on it. Each CDM session keeps its own PSSH and required KIDs
from __future__ import annotations
import base64
-from typing import Any, Callable, List
+from collections.abc import Callable
+from typing import Any
import pytest
from pyplayready.system.wrmheader import WRMHeader
@@ -36,9 +37,9 @@ class FakePssh:
self.raw = raw
-def recording(cdm: Any) -> List[tuple[str, Any]]:
+def recording(cdm: Any) -> list[tuple[str, Any]]:
"""Make the adapter record the init data and required KIDs of each challenge instead of sending it."""
- sent: List[tuple[str, Any]] = []
+ sent: list[tuple[str, Any]] = []
def request_challenge(session: Any, body: Any, *_: Any) -> bytes:
sent.append((body["init_data"], session.get("required_kids")))
diff --git a/tests/core/test_resolution_naming.py b/tests/core/test_resolution_naming.py
index d4e99d53..8a057be7 100644
--- a/tests/core/test_resolution_naming.py
+++ b/tests/core/test_resolution_naming.py
@@ -3,7 +3,6 @@
from __future__ import annotations
import types
-from typing import Optional
import pytest
@@ -26,7 +25,7 @@ def clean_config(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "codec_names", {})
-def quality(width: Optional[int], height: Optional[int], scan_type: str = "Progressive") -> str:
+def quality(width: int | None, height: int | None, scan_type: str = "Progressive") -> str:
movie = Movie(id_="movie-0001", service=DummyService, name="The Film", year=2024, language="en")
video = types.SimpleNamespace(
width=width,
diff --git a/tests/core/test_resolve_by_ids.py b/tests/core/test_resolve_by_ids.py
index bffa03f5..24449d22 100644
--- a/tests/core/test_resolve_by_ids.py
+++ b/tests/core/test_resolve_by_ids.py
@@ -2,8 +2,6 @@
from __future__ import annotations
-from typing import Optional, Union
-
import pytest
from unshackle.core import providers
@@ -14,26 +12,26 @@ from unshackle.core.providers._base import ExternalIds, MetadataProvider, Metada
class FakeProvider(MetadataProvider):
"""Stands in for a real provider; records the ID it was asked for."""
- def __init__(self, name: str, result: Optional[MetadataResult] = None, raises: bool = False) -> None:
+ def __init__(self, name: str, result: MetadataResult | None = None, raises: bool = False) -> None:
self.NAME = name
self._result = result
self._raises = raises
- self.asked: list[Union[int, str]] = []
+ self.asked: list[int | str] = []
super().__init__()
def is_available(self) -> bool:
return True
- def search(self, title: str, year: Optional[int], kind: str) -> Optional[MetadataResult]:
+ def search(self, title: str, year: int | None, kind: str) -> MetadataResult | None:
raise AssertionError("resolve_by_ids must not search when an ID was supplied")
- def get_by_id(self, provider_id: Union[int, str], kind: str) -> Optional[MetadataResult]:
+ def get_by_id(self, provider_id: int | str, kind: str) -> MetadataResult | None:
self.asked.append(provider_id)
if self._raises:
raise ValueError("provider is down")
return self._result
- def get_external_ids(self, provider_id: Union[int, str], kind: str) -> ExternalIds:
+ def get_external_ids(self, provider_id: int | str, kind: str) -> ExternalIds:
return ExternalIds()
diff --git a/tests/core/test_resume_hls_integration.py b/tests/core/test_resume_hls_integration.py
index 0a2ae7b2..0effed6d 100644
--- a/tests/core/test_resume_hls_integration.py
+++ b/tests/core/test_resume_hls_integration.py
@@ -14,6 +14,7 @@ from functools import partial
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
+import requests
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_CANCELLED
@@ -109,7 +110,7 @@ def test_hls_second_run_reuses_completed_segments(server, tmp_path):
# part1.bin missing -> run 1 completes part0 then dies during the download phase
ctx = make_ctx(tmp_path)
- with pytest.raises(Exception):
+ with pytest.raises(requests.HTTPError):
HLS.download_track(make_track(server), ctx)
assert (ctx.save_dir / "segments" / "0.bin").read_bytes() == PART0
@@ -133,7 +134,7 @@ def test_hls_aes128_content_never_writes_sidecar(server, tmp_path):
# part1.bin missing -> crash mid-download, the state resume would normally preserve
ctx = make_ctx(tmp_path)
- with pytest.raises(Exception):
+ with pytest.raises(requests.HTTPError):
HLS.download_track(make_track(server), ctx)
assert not resume.sidecar_path(ctx.save_dir).exists()
diff --git a/tests/core/test_resume_integration.py b/tests/core/test_resume_integration.py
index dd52a1f4..4f2bcfa1 100644
--- a/tests/core/test_resume_integration.py
+++ b/tests/core/test_resume_integration.py
@@ -16,6 +16,7 @@ from functools import partial
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import pytest
+import requests
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_CANCELLED
@@ -116,7 +117,7 @@ def test_second_run_reuses_completed_segments(server, tmp_path):
# part1.bin is missing -> the first run completes part0 then dies on part1
ctx = make_ctx(tmp_path)
- with pytest.raises(Exception):
+ with pytest.raises(requests.HTTPError):
DASH.download_track(make_track(mpd(server), server), ctx)
assert (ctx.save_dir / "0.mp4").read_bytes() == PART0
@@ -138,7 +139,7 @@ def test_changed_segmentation_wipes_stale_segments(server, tmp_path):
server.routes["/part0.bin"] = PART0
ctx = make_ctx(tmp_path)
- with pytest.raises(Exception):
+ with pytest.raises(requests.HTTPError):
DASH.download_track(make_track(mpd(server), server), ctx)
assert (ctx.save_dir / "0.mp4").exists()
diff --git a/tests/core/test_retry_after.py b/tests/core/test_retry_after.py
index f21fdf80..d082f7f6 100644
--- a/tests/core/test_retry_after.py
+++ b/tests/core/test_retry_after.py
@@ -1,6 +1,6 @@
"""RnetSession.get_sleep_time must survive hostile or malformed Retry-After headers."""
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from email.utils import format_datetime
from types import SimpleNamespace
@@ -35,18 +35,18 @@ def test_huge_numeric_retry_after_respects_session_cap():
def test_http_date_retry_after_honoured(session):
- when = format_datetime(datetime.now(timezone.utc) + timedelta(seconds=10), usegmt=True)
+ when = format_datetime(datetime.now(UTC) + timedelta(seconds=10), usegmt=True)
assert 5 <= session.get_sleep_time(response(when), 1) <= 10
def test_naive_http_date_does_not_raise(session):
# "-0000" makes parsedate_to_datetime return a naive datetime
- when = format_datetime(datetime.now(timezone.utc) + timedelta(seconds=10)).replace("+0000", "-0000")
+ when = format_datetime(datetime.now(UTC) + timedelta(seconds=10)).replace("+0000", "-0000")
assert 5 <= session.get_sleep_time(response(when), 1) <= 10
def test_past_http_date_yields_no_sleep(session):
- when = format_datetime(datetime.now(timezone.utc) - timedelta(seconds=30), usegmt=True)
+ when = format_datetime(datetime.now(UTC) - timedelta(seconds=30), usegmt=True)
assert session.get_sleep_time(response(when), 1) <= 0
diff --git a/tests/core/test_segment_pipeline.py b/tests/core/test_segment_pipeline.py
index 40a60091..68dcd884 100644
--- a/tests/core/test_segment_pipeline.py
+++ b/tests/core/test_segment_pipeline.py
@@ -2,11 +2,12 @@
from __future__ import annotations
+from collections.abc import Iterator
from concurrent.futures import Future
from functools import partial
from pathlib import Path
from types import SimpleNamespace
-from typing import Any, Iterator
+from typing import Any
from uuid import UUID
import pytest
diff --git a/tests/core/test_service_config.py b/tests/core/test_service_config.py
index 4020e982..8a0a557a 100644
--- a/tests/core/test_service_config.py
+++ b/tests/core/test_service_config.py
@@ -2,8 +2,8 @@
from __future__ import annotations
+from collections.abc import Callable
from pathlib import Path
-from typing import Callable
import click
import pytest
diff --git a/tests/core/test_service_dl_overrides.py b/tests/core/test_service_dl_overrides.py
index c0054cd7..b397b616 100644
--- a/tests/core/test_service_dl_overrides.py
+++ b/tests/core/test_service_dl_overrides.py
@@ -3,7 +3,7 @@
from __future__ import annotations
import logging
-from typing import Any, Optional
+from typing import Any
import click
import pytest
@@ -16,7 +16,7 @@ from unshackle.core.utils.click_types import LANGUAGE_RANGE, MultipleChoice
log = logging.getLogger("test_service_dl_overrides")
-def make_ctx(args: Optional[list[str]] = None, default_map: Optional[dict[str, Any]] = None) -> click.Context:
+def make_ctx(args: list[str] | None = None, default_map: dict[str, Any] | None = None) -> click.Context:
"""Build a parsed context for a mirror of the dl group's option shapes."""
@click.group("dl", invoke_without_command=True)
diff --git a/tests/core/test_service_remote_config.py b/tests/core/test_service_remote_config.py
index 19b1c970..34d5d7a5 100644
--- a/tests/core/test_service_remote_config.py
+++ b/tests/core/test_service_remote_config.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from typing import Any, Optional, cast
+from typing import Any, cast
import click
import pytest
@@ -14,7 +14,7 @@ from unshackle.core.services import Services
def make_ctx(
- command: click.Command, args: Optional[list[str]] = None, default_map: Optional[dict[str, Any]] = None
+ command: click.Command, args: list[str] | None = None, default_map: dict[str, Any] | None = None
) -> click.Context:
"""Parse the group options of a real ``Services`` command, without running its callback."""
return command.make_context(
@@ -27,11 +27,11 @@ def group(ctx: click.Context) -> Services:
@pytest.fixture
-def routed(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, Optional[str]]]:
+def routed(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, str | None]]:
"""Record the path get_command takes and the server it passes, without loading a service or calling a server."""
- calls: list[tuple[str, Optional[str]]] = []
+ calls: list[tuple[str, str | None]] = []
- def remote(name: str, server_name: Optional[str]) -> click.Command:
+ def remote(name: str, server_name: str | None) -> click.Command:
calls.append(("remote", server_name))
return click.Command(name)
@@ -46,7 +46,7 @@ def routed(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, Optional[str]]]:
@pytest.mark.parametrize("command", [dl.cli, search])
def test_service_remote_routes_to_remote_command(
- monkeypatch: pytest.MonkeyPatch, routed: list[tuple[str, Optional[str]]], command: click.Command
+ monkeypatch: pytest.MonkeyPatch, routed: list[tuple[str, str | None]], command: click.Command
) -> None:
"""The typed name matches the config key in any case, as a service only the server has keeps the typed case."""
monkeypatch.setattr(config, "services", {"EXAMPLE": {"dl": {"remote": True, "server": "box"}}})
@@ -73,8 +73,8 @@ def test_routing_precedence(
routed: list,
services: dict,
args: list[str],
- default_map: Optional[dict[str, Any]],
- expected: tuple[str, Optional[str]],
+ default_map: dict[str, Any] | None,
+ expected: tuple[str, str | None],
) -> None:
monkeypatch.setattr(config, "services", services)
ctx = make_ctx(dl.cli, args, default_map)
diff --git a/tests/core/test_session_headers.py b/tests/core/test_session_headers.py
index c3bbf107..57554d53 100644
--- a/tests/core/test_session_headers.py
+++ b/tests/core/test_session_headers.py
@@ -8,9 +8,9 @@ server received, because the session dicts pass even with the leak in place.
from __future__ import annotations
import threading
+from collections.abc import Iterator
from http.cookiejar import Cookie, CookieJar
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
-from typing import Iterator
import pytest
import rnet
diff --git a/tests/core/test_tag_rules_integration.py b/tests/core/test_tag_rules_integration.py
index a8e09f86..d0405757 100644
--- a/tests/core/test_tag_rules_integration.py
+++ b/tests/core/test_tag_rules_integration.py
@@ -4,7 +4,8 @@ from __future__ import annotations
import inspect
import types
-from typing import Any, Iterator
+from collections.abc import Iterator
+from typing import Any
import pytest
from langcodes import Language
diff --git a/tests/core/test_vault_bad_keys.py b/tests/core/test_vault_bad_keys.py
index a3e8ad8f..7a3718a5 100644
--- a/tests/core/test_vault_bad_keys.py
+++ b/tests/core/test_vault_bad_keys.py
@@ -3,7 +3,6 @@ import threading
import time
from pathlib import Path
from types import SimpleNamespace
-from typing import Optional, Union
from uuid import UUID
import pytest
@@ -103,7 +102,7 @@ SERVER = SimpleNamespace(
)
-def batch_title(*batches: dict[UUID, str], kids: Optional[list[UUID]] = None) -> SimpleNamespace:
+def batch_title(*batches: dict[UUID, str], kids: list[UUID] | None = None) -> SimpleNamespace:
"""A title with one track per batch, whose DRM names ``kids`` (every KID of its batch by default)."""
return SimpleNamespace(
tracks=[
@@ -259,13 +258,13 @@ def test_retry_takes_the_next_parallel_answer_without_a_new_request(tmp_path: Pa
started, release = threading.Event(), threading.Event()
class Fast(FakeVault):
- def get_key(self, kid: Union[UUID, str], service: str) -> Optional[str]:
+ def get_key(self, kid: UUID | str, service: str) -> str | None:
# answer only once the slow query runs, or the pool shutdown cancels it before it starts
started.wait(5)
return super().get_key(kid, service)
class Slow(FakeVault):
- def get_key(self, kid: Union[UUID, str], service: str) -> Optional[str]:
+ def get_key(self, kid: UUID | str, service: str) -> str | None:
started.set()
release.wait(5)
return super().get_key(kid, service)
@@ -409,7 +408,7 @@ def test_stale_backup_from_a_killed_run_is_not_restored(tmp_path: Path, monkeypa
ids=["file-uses-it", "file-does-not", "unmapped"],
)
def test_an_unkeyed_kid_the_file_uses_is_licensed_before_the_decrypt(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch, windows: Optional[dict], licensed: list[UUID]
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, windows: dict | None, licensed: list[UUID]
) -> None:
keys = make_resolver(monkeypatch, Vaults("SVC"))
drm = FakeDRM({KID: GOOD})
diff --git a/tests/core/test_vault_table_case.py b/tests/core/test_vault_table_case.py
index acb79570..efb7b1fd 100644
--- a/tests/core/test_vault_table_case.py
+++ b/tests/core/test_vault_table_case.py
@@ -11,8 +11,8 @@ from __future__ import annotations
import logging
import sqlite3
import threading
+from collections.abc import Iterator
from pathlib import Path
-from typing import Iterator, Optional, Union
from uuid import UUID
import pytest
@@ -40,16 +40,16 @@ def tables(path: Path) -> list[str]:
class UnlistableVault(Vault):
"""Stands in for the API vault, which supports neither listing nor bulk dumps."""
- def get_key(self, kid: Union[UUID, str], service: str) -> Optional[str]:
+ def get_key(self, kid: UUID | str, service: str) -> str | None:
return None
def get_keys(self, service: str) -> Iterator[tuple[str, str]]:
raise ValueError("Bulk dump is not supported.")
- def add_key(self, service: str, kid: Union[UUID, str], key: str) -> bool:
+ def add_key(self, service: str, kid: UUID | str, key: str) -> bool:
return False
- def add_keys(self, service: str, kid_keys: dict[Union[UUID, str], str]) -> int:
+ def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int:
return 0
def get_services(self) -> Iterator[str]:
@@ -131,7 +131,7 @@ def test_synced_lowercase_table_survives_the_service_being_added_later(tmp_path:
("00112233445566778899AABBCCDDEEFF", False),
],
)
-def test_is_null_key(key: Optional[str], expected: bool) -> None:
+def test_is_null_key(key: str | None, expected: bool) -> None:
assert is_null_key(key) is expected
@@ -201,7 +201,7 @@ def test_copy_skips_a_vault_that_cannot_list_services() -> None:
def test_lookups_work_from_another_thread(vault: SQLite) -> None:
"""`kv search` probes services in a ThreadPoolExecutor; connections are thread-local."""
- found: list[Optional[str]] = []
+ found: list[str | None] = []
thread = threading.Thread(target=lambda: found.append(vault.get_key(KID, "SVCA")))
thread.start()
thread.join()
diff --git a/tests/core/test_vaults_lookup.py b/tests/core/test_vaults_lookup.py
index f7f441d3..638780d0 100644
--- a/tests/core/test_vaults_lookup.py
+++ b/tests/core/test_vaults_lookup.py
@@ -1,6 +1,6 @@
import threading
import time
-from typing import Iterator, Optional, Union
+from collections.abc import Iterator
from uuid import UUID
from unshackle.core.vault import Vault
@@ -8,13 +8,13 @@ from unshackle.core.vaults import Vaults
class FakeVault(Vault):
- def __init__(self, name: str, key: Optional[str], delay: float = 0.0, local: bool = False):
+ def __init__(self, name: str, key: str | None, delay: float = 0.0, local: bool = False):
super().__init__(name)
self.key, self.delay, self.local = key, delay, local
self.calls = 0
self.threads: set[int] = set()
- def get_key(self, kid: Union[UUID, str], service: str) -> Optional[str]:
+ def get_key(self, kid: UUID | str, service: str) -> str | None:
self.calls += 1
self.threads.add(threading.get_ident())
time.sleep(self.delay)
@@ -23,7 +23,7 @@ class FakeVault(Vault):
def get_keys(self, service: str) -> Iterator[tuple[str, str]]:
return iter(())
- def add_key(self, service: str, kid: Union[UUID, str], key: str) -> bool:
+ def add_key(self, service: str, kid: UUID | str, key: str) -> bool:
return False
def add_keys(self, service: str, kid_keys: dict) -> int:
diff --git a/tests/core/test_zero_kid_fallback.py b/tests/core/test_zero_kid_fallback.py
index 212e784e..f20815e7 100644
--- a/tests/core/test_zero_kid_fallback.py
+++ b/tests/core/test_zero_kid_fallback.py
@@ -1,7 +1,6 @@
from __future__ import annotations
import base64
-from typing import Union
from uuid import UUID
import pytest
@@ -17,7 +16,7 @@ AUDIO_KID = UUID("ffeeddcc-bbaa-9988-7766-554433221100")
VIDEO_KEY = "0000000000000000000000000000000a"
AUDIO_KEY = "0000000000000000000000000000000b"
-DRM = Union[Widevine, PlayReady]
+DRM = Widevine | PlayReady
def _playready_pssh(*kids: UUID) -> tuple[PlayReadyPSSH, str]:
diff --git a/tests/downloaders/test_download_hardening.py b/tests/downloaders/test_download_hardening.py
index 04ad331c..9779fcc1 100644
--- a/tests/downloaders/test_download_hardening.py
+++ b/tests/downloaders/test_download_hardening.py
@@ -9,12 +9,13 @@ media requests must ask for identity encoding.
import importlib
import threading
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
from email.utils import format_datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from types import SimpleNamespace
import pytest
+import requests
dl = importlib.import_module("unshackle.core.downloaders.requests")
@@ -109,7 +110,7 @@ def test_range_item_ignored_by_server_fails_not_corrupts(server, tmp_path, monke
server.honor_range = False
monkeypatch.setattr(dl, "RETRY_WAIT", 0.01)
urls = [{"url": url(server), "headers": {"Range": f"bytes={SLICE_START}-{SLICE_END}"}}]
- with pytest.raises(Exception):
+ with pytest.raises(OSError):
run(server, tmp_path, urls, max_workers=1)
# nothing finalized: a 200 full-parent body must never become the segment
assert not list(tmp_path.glob("seg_*.bin"))
@@ -154,7 +155,7 @@ def test_retry_sleep_honors_numeric_retry_after():
def test_retry_sleep_honors_http_date_retry_after():
- when = format_datetime(datetime.now(timezone.utc) + timedelta(seconds=10), usegmt=True)
+ when = format_datetime(datetime.now(UTC) + timedelta(seconds=10), usegmt=True)
assert 5 <= dl.retry_sleep(exc_with_headers({"Retry-After": when}), 1) <= 10
@@ -172,7 +173,7 @@ def test_retry_sleep_invalid_retry_after_falls_back():
def test_retry_sleep_naive_http_date_treated_as_utc():
# "-0000" makes parsedate_to_datetime return a naive datetime; must clamp, not raise
- when = format_datetime(datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(seconds=10))
+ when = format_datetime(datetime.now(UTC).replace(tzinfo=None) + timedelta(seconds=10))
assert when.endswith("-0000")
v = dl.retry_sleep(exc_with_headers({"Retry-After": when}), 1)
assert 5 <= v <= 10
@@ -219,7 +220,7 @@ def test_session_retry_does_not_nest_inside_an_attempt(server, tmp_path, monkeyp
session.mount("http://", adapter)
session.mount("https://", adapter)
- with pytest.raises(Exception):
+ with pytest.raises(requests.HTTPError):
run(server, tmp_path, [{"url": url(server)}], max_workers=1, session=session)
assert len(server.requests) == dl.MAX_ATTEMPTS
diff --git a/tests/downloaders/test_outage_budget.py b/tests/downloaders/test_outage_budget.py
index 79ad91db..91df1df5 100644
--- a/tests/downloaders/test_outage_budget.py
+++ b/tests/downloaders/test_outage_budget.py
@@ -121,7 +121,7 @@ def test_disk_full_is_not_retried(tmp_path, monkeypatch, serve):
def test_status_failure_keeps_the_normal_budget(tmp_path, serve):
server = serve(503)
- with pytest.raises(Exception):
+ with pytest.raises(rq.HTTPError):
list(dl.download(url=server.url, save_path=tmp_path / "a.bin", session=rq.Session()))
assert server.requests == dl.MAX_ATTEMPTS
diff --git a/tests/downloaders/test_ranged_parallel.py b/tests/downloaders/test_ranged_parallel.py
index b31d928b..04c0f414 100644
--- a/tests/downloaders/test_ranged_parallel.py
+++ b/tests/downloaders/test_ranged_parallel.py
@@ -211,7 +211,7 @@ def test_permanent_status_unwraps_causes():
assert dl.permanent_status(HTTPError(response=_Resp(403))) == 403
assert dl.permanent_status(HTTPError(response=_Resp(429))) is None
assert dl.permanent_status(HTTPError(response=_Resp(503))) is None
- assert dl.permanent_status(IOError("short read")) is None
+ assert dl.permanent_status(OSError("short read")) is None
# RnetSession wraps the HTTPError one level down as __cause__
wrapped = RuntimeError("max retries")
wrapped.__cause__ = HTTPError(response=_Resp(404))
diff --git a/tests/downloaders/test_tail_boost.py b/tests/downloaders/test_tail_boost.py
index 83fae148..e2b6970d 100644
--- a/tests/downloaders/test_tail_boost.py
+++ b/tests/downloaders/test_tail_boost.py
@@ -210,7 +210,7 @@ def test_tail_boost_permanent_part_failure_still_fails_the_batch(server, tmp_pat
server.deny_offset_ranges = True # every part window past the first is a 403
monkeypatch.setattr(dl, "RETRY_WAIT", 0.01)
- with pytest.raises(Exception):
+ with pytest.raises(dl.TailPartFailed):
run(server, tmp_path, seg_urls(server))
assert boost_engaged(server), "tail boost never engaged; the permanent-failure rule is untested"
diff --git a/tests/lang_selection/test_as_requested.py b/tests/lang_selection/test_as_requested.py
index 36b65abf..ae802ac8 100644
--- a/tests/lang_selection/test_as_requested.py
+++ b/tests/lang_selection/test_as_requested.py
@@ -1,7 +1,5 @@
from __future__ import annotations
-from typing import Optional
-
import pytest
from unshackle.core.utilities import as_requested
@@ -20,5 +18,5 @@ from unshackle.core.utilities import as_requested
([], "en", ""),
],
)
-def test_as_requested(tokens: list[str], orig_token: Optional[str], expected: str) -> None:
+def test_as_requested(tokens: list[str], orig_token: str | None, expected: str) -> None:
assert as_requested(tokens, orig_token) == expected
diff --git a/tests/lang_selection/test_kind_only_selection.py b/tests/lang_selection/test_kind_only_selection.py
index c4c58844..45765286 100644
--- a/tests/lang_selection/test_kind_only_selection.py
+++ b/tests/lang_selection/test_kind_only_selection.py
@@ -11,7 +11,7 @@ from __future__ import annotations
import inspect
import logging
from pathlib import Path
-from typing import Any, Optional, cast
+from typing import Any, cast
import pytest
import requests
@@ -97,7 +97,7 @@ def run(
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
episodes: dict,
- service: Optional[FakeService] = None,
+ service: FakeService | None = None,
to_end: bool = False,
**flags: Any,
) -> Any:
diff --git a/tests/lang_selection/test_matching_languages.py b/tests/lang_selection/test_matching_languages.py
index 8261d921..d664f72f 100644
--- a/tests/lang_selection/test_matching_languages.py
+++ b/tests/lang_selection/test_matching_languages.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import Sequence
+from collections.abc import Sequence
import pytest
diff --git a/tests/lang_selection/test_original_audio_ids.py b/tests/lang_selection/test_original_audio_ids.py
index c680617e..72bd072a 100644
--- a/tests/lang_selection/test_original_audio_ids.py
+++ b/tests/lang_selection/test_original_audio_ids.py
@@ -1,7 +1,5 @@
from __future__ import annotations
-from typing import Optional
-
import pytest
from unshackle.core.wire import original_audio_ids
@@ -14,7 +12,7 @@ class FakeTrack:
class FakeTitle:
- def __init__(self, language: Optional[str]) -> None:
+ def __init__(self, language: str | None) -> None:
self.language = language
diff --git a/tests/lang_selection/test_resolve_sort_langs.py b/tests/lang_selection/test_resolve_sort_langs.py
index b6139185..3035c9e6 100644
--- a/tests/lang_selection/test_resolve_sort_langs.py
+++ b/tests/lang_selection/test_resolve_sort_langs.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import Optional, Sequence
+from collections.abc import Sequence
import pytest
from langcodes import Language
@@ -22,7 +22,7 @@ from unshackle.core.utilities import ServiceTag, resolve_sort_langs
([], "ja", []),
],
)
-def test_resolve_sort_langs(tokens: Sequence[str], original: Optional[str], expected: list[str]) -> None:
+def test_resolve_sort_langs(tokens: Sequence[str], original: str | None, expected: list[str]) -> None:
assert resolve_sort_langs(tokens, original) == expected
diff --git a/tests/lang_selection/test_track_selection.py b/tests/lang_selection/test_track_selection.py
index f56521df..97cc834a 100644
--- a/tests/lang_selection/test_track_selection.py
+++ b/tests/lang_selection/test_track_selection.py
@@ -17,7 +17,7 @@ def selection(**flags: Any) -> TrackSelection:
"""A TrackSelection with every filter off but the given flags."""
off: dict[str, Any] = {}
for flag in fields(TrackSelection):
- off[flag.name] = [] if str(flag.type).startswith("list") else None if "Optional" in str(flag.type) else False
+ off[flag.name] = None if "None" in str(flag.type) else [] if str(flag.type).startswith("list") else False
return TrackSelection(**{**off, **flags})
diff --git a/tests/remote/e2e/test_live_quality.py b/tests/remote/e2e/test_live_quality.py
index d7031fd4..84ac8406 100644
--- a/tests/remote/e2e/test_live_quality.py
+++ b/tests/remote/e2e/test_live_quality.py
@@ -11,7 +11,7 @@ discovered and skips so you can copy values back into the fixture.
from __future__ import annotations
import time
-from typing import Any, Optional
+from typing import Any
import pytest
@@ -51,7 +51,7 @@ def wait_for_titles(http_session, server_url: str, sid: str, timeout: float = 12
return 408, {"message": "auth timeout"}
-def pick_target_title(titles: list[dict[str, Any]], season: int = 1, episode: int = 1) -> Optional[dict[str, Any]]:
+def pick_target_title(titles: list[dict[str, Any]], season: int = 1, episode: int = 1) -> dict[str, Any] | None:
"""Pick the configured target episode; fall back to the first title."""
for t in titles:
if t.get("type") == "episode" and t.get("season") == season and t.get("number") == episode:
@@ -76,7 +76,7 @@ def summarize(video_tracks: list[dict[str, Any]]) -> dict[str, Any]:
}
-def resolve_title_id(conf: dict) -> Optional[str]:
+def resolve_title_id(conf: dict) -> str | None:
"""Prefer series_url so S01E01 logic kicks in; fall back to movie title_url."""
return conf.get("series_url") or conf.get("title_url")
diff --git a/tests/remote/key_source.py b/tests/remote/key_source.py
index 4566a6d9..9aee983a 100644
--- a/tests/remote/key_source.py
+++ b/tests/remote/key_source.py
@@ -1,13 +1,14 @@
import logging
+from collections.abc import Iterable
from types import SimpleNamespace
-from typing import Any, Iterable, Optional
+from typing import Any
from uuid import UUID
from unshackle.core.remote_service import RemoteService, ServerVault
def remote_keys(
- server_cdm: Optional[bool] = True,
+ server_cdm: bool | None = True,
server_cdm_type: str = "widevine",
local_cdm: Any = None,
) -> RemoteService:
@@ -39,7 +40,7 @@ class MemoryKeySource:
self.local_cdm = local_cdm
self.client_licensed = set(client_licensed)
self.server_vault_keys: dict[UUID, str] = {}
- self.asked: list[tuple[Any, Optional[UUID]]] = []
+ self.asked: list[tuple[Any, UUID | None]] = []
def resolve_server_keys(self, title: Any) -> None:
pass
@@ -47,7 +48,7 @@ class MemoryKeySource:
def licenses_locally(self, track: Any) -> bool:
return str(track.id) in self.client_licensed
- def license_track(self, track: Any, drm: Any, kid: Optional[UUID] = None) -> Optional[dict[UUID, str]]:
+ def license_track(self, track: Any, drm: Any, kid: UUID | None = None) -> dict[UUID, str] | None:
self.asked.append((track.id, kid))
if self.licence is None:
self.client_licensed.add(str(track.id))
diff --git a/tests/remote/unit/test_api_episode_part.py b/tests/remote/unit/test_api_episode_part.py
index c808469f..8abf1dd5 100644
--- a/tests/remote/unit/test_api_episode_part.py
+++ b/tests/remote/unit/test_api_episode_part.py
@@ -10,7 +10,7 @@ from __future__ import annotations
import asyncio
import json
import re
-from typing import Any, Dict, List, Optional
+from typing import Any
import pytest
@@ -27,8 +27,8 @@ class _FakeSvc:
pass
-def ep(season: int = 1, number: int = 1, part: Optional[int] = None, **overrides: Any) -> Episode:
- base: Dict[str, Any] = dict(
+def ep(season: int = 1, number: int = 1, part: int | None = None, **overrides: Any) -> Episode:
+ base: dict[str, Any] = dict(
id_=f"ep-{season}-{number}-{part or 0}",
service=_FakeSvc,
title="My Show",
@@ -43,23 +43,23 @@ def ep(season: int = 1, number: int = 1, part: Optional[int] = None, **overrides
class _FakeTracks:
- videos: List[Any] = []
- audio: List[Any] = []
- subtitles: List[Any] = []
+ videos: list[Any] = []
+ audio: list[Any] = []
+ subtitles: list[Any] = []
class _FakeService:
- def __init__(self, titles: List[Episode]) -> None:
+ def __init__(self, titles: list[Episode]) -> None:
self._titles = titles
- def get_titles(self) -> List[Episode]:
+ def get_titles(self) -> list[Episode]:
return self._titles
def get_tracks(self, title: Episode) -> _FakeTracks:
return _FakeTracks()
-def run_list_tracks(monkeypatch: pytest.MonkeyPatch, titles: List[Episode], **data: Any) -> Dict[str, Any]:
+def run_list_tracks(monkeypatch: pytest.MonkeyPatch, titles: list[Episode], **data: Any) -> dict[str, Any]:
"""Drive list_tracks_handler end to end with the service layer stubbed out."""
monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: "FAKE")
monkeypatch.setattr(handlers, "setup_list_service", lambda *a, **kw: _FakeService(titles))
@@ -72,7 +72,7 @@ def run_list_tracks(monkeypatch: pytest.MonkeyPatch, titles: List[Episode], **da
return json.loads(response.body)
-def selected(result: Dict[str, Any]) -> List[str]:
+def selected(result: dict[str, Any]) -> list[str]:
"""Selection-syntax keys of whatever the handler returned, single or multi."""
entries = result["episodes"] if "episodes" in result else [{"title": result["title"]}]
keys = []
@@ -134,7 +134,7 @@ def test_movie_json_unaffected() -> None:
@pytest.fixture
-def split_titles() -> List[Episode]:
+def split_titles() -> list[Episode]:
"""E1 split into three parts, E2 unsplit."""
return [ep(1, 1, 1), ep(1, 1, 2), ep(1, 1, 3), ep(1, 2, None)]
@@ -214,7 +214,7 @@ def test_rest_multi_episode_order_is_stable_across_parts(monkeypatch) -> None:
(["1x01"], ["1x1"]),
],
)
-def test_parsed_keys_pass_unchanged(wanted: Any, parsed: List[str]) -> None:
+def test_parsed_keys_pass_unchanged(wanted: Any, parsed: list[str]) -> None:
"""A pre-parsed part or negative key never reaches parse_tokens, which cannot read it."""
assert SEASON_RANGE.convert(wanted) == parsed
diff --git a/tests/remote/unit/test_api_title_fields.py b/tests/remote/unit/test_api_title_fields.py
index e66ad890..f30a801e 100644
--- a/tests/remote/unit/test_api_title_fields.py
+++ b/tests/remote/unit/test_api_title_fields.py
@@ -9,7 +9,7 @@ from __future__ import annotations
import asyncio
import json
from datetime import date
-from typing import Any, Dict, List, Optional
+from typing import Any
import pytest
from langcodes import Language
@@ -30,7 +30,7 @@ class _FakeSvc:
def ep(**overrides: Any) -> Episode:
- base: Dict[str, Any] = dict(
+ base: dict[str, Any] = dict(
id_="ep-0001",
service=_FakeSvc,
title="My Show",
@@ -45,7 +45,7 @@ def ep(**overrides: Any) -> Episode:
def _movie(**overrides: Any) -> Movie:
- base: Dict[str, Any] = dict(id_="movie-0001", service=_FakeSvc, name="Film", year=2024, language=Language.get("en"))
+ base: dict[str, Any] = dict(id_="movie-0001", service=_FakeSvc, name="Film", year=2024, language=Language.get("en"))
base.update(overrides)
return Movie(**base)
@@ -129,10 +129,10 @@ class _FakeService:
ANIME = True
DAILY = True
- def __init__(self, titles: List[Episode]) -> None:
+ def __init__(self, titles: list[Episode]) -> None:
self._titles = titles
- def get_titles(self) -> List[Episode]:
+ def get_titles(self) -> list[Episode]:
return self._titles
@@ -144,7 +144,7 @@ def test_list_titles_stamps_the_service_flags(monkeypatch: pytest.MonkeyPatch) -
assert (title["anime"], title["daily"]) == (True, True)
-def round_trip(episode: Episode, stamp: Optional[Any] = None) -> Episode:
+def round_trip(episode: Episode, stamp: Any | None = None) -> Episode:
info = serialize_title(episode)
if stamp is not None:
info = stamp_service_flags(info, stamp)
diff --git a/tests/remote/unit/test_cache_payload_safety.py b/tests/remote/unit/test_cache_payload_safety.py
index 18bdd8c9..8a44b0d5 100644
--- a/tests/remote/unit/test_cache_payload_safety.py
+++ b/tests/remote/unit/test_cache_payload_safety.py
@@ -61,7 +61,7 @@ def test_writer_skips_unsafe_entry(tmp_path, monkeypatch, write) -> None:
@pytest.mark.parametrize(
"expiration",
- [None, dt.datetime(2030, 1, 1, 12, 0, 0), dt.datetime(2030, 1, 1, 12, 0, 0, tzinfo=dt.timezone.utc)],
+ [None, dt.datetime(2030, 1, 1, 12, 0, 0), dt.datetime(2030, 1, 1, 12, 0, 0, tzinfo=dt.UTC)],
ids=["none", "naive", "aware"],
)
def test_real_cacher_file_round_trips(tmp_path, monkeypatch, expiration) -> None:
diff --git a/tests/remote/unit/test_cdm_patch_leaves_no_shadow.py b/tests/remote/unit/test_cdm_patch_leaves_no_shadow.py
index 841dcd73..97ba7775 100644
--- a/tests/remote/unit/test_cdm_patch_leaves_no_shadow.py
+++ b/tests/remote/unit/test_cdm_patch_leaves_no_shadow.py
@@ -16,7 +16,6 @@ from __future__ import annotations
import re
from pathlib import Path
-from typing import List
import pytest
@@ -29,7 +28,7 @@ PACKAGE_SETATTR = re.compile(r"""setattr\(\s*(?!loader\b)[\w.]+\s*,\s*["']load_c
def test_no_test_patches_load_cdm_on_the_package() -> None:
- offenders: List[str] = []
+ offenders: list[str] = []
for path in sorted(TESTS_ROOT.rglob("test_*.py")):
if path == Path(__file__).resolve():
continue
diff --git a/tests/remote/unit/test_dashboard.py b/tests/remote/unit/test_dashboard.py
index e4d25d47..8353b3e4 100644
--- a/tests/remote/unit/test_dashboard.py
+++ b/tests/remote/unit/test_dashboard.py
@@ -7,7 +7,7 @@ import logging
import sys
import threading
from collections.abc import Callable
-from datetime import datetime, timedelta, timezone
+from datetime import UTC, datetime, timedelta
import pytest
from aiohttp import web
@@ -326,7 +326,7 @@ async def test_dashboard_log_read_does_not_touch_the_session() -> None:
store = SessionStore()
entry = await store.create("EXAMPLE", object())
- stale = datetime.now(timezone.utc) - timedelta(seconds=1)
+ stale = datetime.now(UTC) - timedelta(seconds=1)
entry.last_accessed = stale
assert store.peek(entry.session_id) is entry
assert entry.last_accessed == stale
diff --git a/tests/remote/unit/test_handler_event_loop.py b/tests/remote/unit/test_handler_event_loop.py
index 2bb9c5ab..8eb4723c 100644
--- a/tests/remote/unit/test_handler_event_loop.py
+++ b/tests/remote/unit/test_handler_event_loop.py
@@ -12,8 +12,9 @@ from __future__ import annotations
import asyncio
import json
import threading
+from collections.abc import Awaitable, Callable
from types import SimpleNamespace
-from typing import Any, Awaitable, Callable, List
+from typing import Any
import pytest
from aiohttp import web
@@ -56,7 +57,7 @@ class BlockingTitles:
def __init__(self, handshake: Handshake) -> None:
self.handshake = handshake
- def get_titles(self) -> List[Movie]:
+ def get_titles(self) -> list[Movie]:
self.handshake.block()
return [a_movie()]
@@ -65,7 +66,7 @@ class BlockingTracks:
def __init__(self, handshake: Handshake) -> None:
self.handshake = handshake
- def get_titles(self) -> List[Movie]:
+ def get_titles(self) -> list[Movie]:
return [a_movie()]
def get_tracks(self, title: Any) -> Any:
diff --git a/tests/remote/unit/test_handler_proxy_policy.py b/tests/remote/unit/test_handler_proxy_policy.py
index 62d3b222..022b64dd 100644
--- a/tests/remote/unit/test_handler_proxy_policy.py
+++ b/tests/remote/unit/test_handler_proxy_policy.py
@@ -1,5 +1,6 @@
"""The server spends its own proxy subscriptions only for a key that opts in."""
+from datetime import UTC
from types import SimpleNamespace
import pytest
@@ -266,7 +267,7 @@ class TestDownloadEnforcement:
def created_params(self, monkeypatch):
"""Drive download_handler with the job machinery faked out; capture create_job params."""
import asyncio
- from datetime import datetime, timezone
+ from datetime import datetime
from unshackle.core.api import download_manager as dm
@@ -279,7 +280,7 @@ class TestDownloadEnforcement:
def create_job(self, service, title_id, owner_key=None, **params):
created.update(params)
return SimpleNamespace(
- job_id="job1", status=SimpleNamespace(value="queued"), created_time=datetime.now(timezone.utc)
+ job_id="job1", status=SimpleNamespace(value="queued"), created_time=datetime.now(UTC)
)
monkeypatch.setattr(dm, "get_download_manager", lambda: FakeManager())
diff --git a/tests/remote/unit/test_licence_declared_kwargs.py b/tests/remote/unit/test_licence_declared_kwargs.py
index 1093b81f..6a2cf7db 100644
--- a/tests/remote/unit/test_licence_declared_kwargs.py
+++ b/tests/remote/unit/test_licence_declared_kwargs.py
@@ -11,7 +11,7 @@ from __future__ import annotations
import base64
from types import SimpleNamespace
-from typing import Any, Optional
+from typing import Any
from uuid import UUID
import pyplayready.system.pssh as pr_pssh_mod
@@ -59,13 +59,13 @@ class SessionService(_Recorder):
"""DEMO: a session-aware service, the shape that needs the open CDM session id."""
def get_widevine_license(
- self, *, challenge: bytes, title: Any, track: Any, session_id: Optional[bytes] = None
+ self, *, challenge: bytes, title: Any, track: Any, session_id: bytes | None = None
) -> bytes:
self.calls.append({"challenge": challenge, "title": title, "track": track, "session_id": session_id})
return b"LIC"
def get_playready_license(
- self, *, challenge: bytes, title: Any, track: Any, session_id: Optional[bytes] = None
+ self, *, challenge: bytes, title: Any, track: Any, session_id: bytes | None = None
) -> str:
self.calls.append({"challenge": challenge, "title": title, "track": track, "session_id": session_id})
return "ok"
@@ -104,7 +104,7 @@ class StubPlayReady(PlayReady):
pssh_b64: Any = None
kids: Any = None
- def __init__(self, pssh: Any = None, pssh_b64: Optional[str] = None, **kwargs: Any) -> None:
+ def __init__(self, pssh: Any = None, pssh_b64: str | None = None, **kwargs: Any) -> None:
self.pssh = SimpleNamespace(wrm_headers=[SimpleNamespace(dumps=lambda: "")])
self.pssh_b64 = pssh_b64
self.kids = [KID]
diff --git a/tests/remote/unit/test_remote_loopback.py b/tests/remote/unit/test_remote_loopback.py
index 19cbe882..9b7274e7 100644
--- a/tests/remote/unit/test_remote_loopback.py
+++ b/tests/remote/unit/test_remote_loopback.py
@@ -6,10 +6,11 @@ import asyncio
import json
import logging
import threading
-from datetime import datetime, timezone
+from collections.abc import Callable, Iterator
+from datetime import UTC, datetime
from threading import Event, Semaphore, Thread
from types import SimpleNamespace
-from typing import Any, Callable, Iterator, Optional
+from typing import Any
import aiohttp
import click
@@ -46,7 +47,7 @@ class StubService:
"""
logins = 0
- hooks: dict[str, Callable[["StubService"], None]] = {}
+ hooks: dict[str, Callable[[StubService], None]] = {}
def __init__(self, beats: Semaphore) -> None:
self.beats = beats
@@ -187,7 +188,7 @@ def on_loop(server: SimpleNamespace, coroutine: Any) -> Any:
return asyncio.run_coroutine_threadsafe(coroutine, server.loop).result(10)
-def count(server: SimpleNamespace, method: str, route: str, session_id: Optional[str] = None) -> int:
+def count(server: SimpleNamespace, method: str, route: str, session_id: str | None = None) -> int:
"""The requests the server saw for one route; without a session id, for any session."""
if session_id is None:
prefix, _, suffix = route.partition("{session_id}")
@@ -210,7 +211,7 @@ def example_messages(caplog: pytest.LogCaptureFixture) -> list[str]:
def idle_seconds(entry: Any) -> float:
- return (datetime.now(timezone.utc) - entry.last_accessed).total_seconds()
+ return (datetime.now(UTC) - entry.last_accessed).total_seconds()
@pytest.mark.parametrize(
diff --git a/tests/remote/unit/test_remote_probes.py b/tests/remote/unit/test_remote_probes.py
index afc14284..19490363 100644
--- a/tests/remote/unit/test_remote_probes.py
+++ b/tests/remote/unit/test_remote_probes.py
@@ -4,9 +4,10 @@ from __future__ import annotations
import asyncio
import json
+from collections.abc import Callable
from threading import Event, Thread
from types import SimpleNamespace
-from typing import Any, Callable
+from typing import Any
import pytest
import responses
diff --git a/tests/remote/unit/test_remote_protocol.py b/tests/remote/unit/test_remote_protocol.py
index 1c3d6b73..fd63c670 100644
--- a/tests/remote/unit/test_remote_protocol.py
+++ b/tests/remote/unit/test_remote_protocol.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import ast
import functools
from pathlib import Path
-from typing import Any, Optional
+from typing import Any
import pytest
import yaml
@@ -193,7 +193,7 @@ def keys(shape: Any) -> set[str]:
return set(shape.__required_keys__ | shape.__optional_keys__)
-def properties(schema: Optional[dict]) -> set[str]:
+def properties(schema: dict | None) -> set[str]:
return set(
((schema or {}).get("content", {}).get("application/json", {}).get("schema", {}) or {}).get("properties", {})
)
diff --git a/tests/remote/unit/test_route_error_replies.py b/tests/remote/unit/test_route_error_replies.py
index 04a452d5..ba6fd663 100644
--- a/tests/remote/unit/test_route_error_replies.py
+++ b/tests/remote/unit/test_route_error_replies.py
@@ -14,7 +14,7 @@ from collections import Counter, defaultdict
from dataclasses import dataclass, field
from pathlib import Path
from types import SimpleNamespace
-from typing import Any, NoReturn, Optional
+from typing import Any, NoReturn
import pytest
from aiohttp import web
@@ -58,7 +58,7 @@ RELEASE = threading.Event()
SEEN: list[dict[str, Any]] = []
-def raise_fault(kind: Optional[str]) -> NoReturn:
+def raise_fault(kind: str | None) -> NoReturn:
if kind == "api":
raise APIError(APIErrorCode.SERVICE_ERROR, "pinned refusal", details={"pinned": True})
if kind == "exit":
@@ -69,7 +69,7 @@ def raise_fault(kind: Optional[str]) -> NoReturn:
class Faulty:
"""A stand-in whose methods all raise the fault *kind*; a *late* one first waits for RELEASE."""
- def __init__(self, kind: Optional[str] = None, late: bool = False, **attrs: Any) -> None:
+ def __init__(self, kind: str | None = None, late: bool = False, **attrs: Any) -> None:
self.kind = kind
self.late = late
self.session = SimpleNamespace(headers={}, cookies=[], get=self.fail)
@@ -139,11 +139,11 @@ class Case:
method: str
path: str
body: Any = None
- session: Optional[Faulty] = None
+ session: Faulty | None = None
owner: str = KEY
status: AuthStatus = AuthStatus.AUTHENTICATED
patch: dict[str, Any] = field(default_factory=dict)
- key: Optional[str] = KEY
+ key: str | None = KEY
def generic_cases() -> dict[str, Case]:
@@ -291,7 +291,7 @@ async def open_session(stand_in: Faulty, owner: str, status: AuthStatus) -> None
session.served_keys["00" * 16] = ("11" * 16, "pinned-vault")
-def masked(value: Any, ref: Optional[str]) -> Any:
+def masked(value: Any, ref: str | None) -> Any:
"""*value* with the error ref and the timestamp replaced, at any depth.
The longer Python 3.14 text of an unhashable key error reads as the 3.11 text.
diff --git a/tests/remote/unit/test_server_cdm_max_height.py b/tests/remote/unit/test_server_cdm_max_height.py
index da486eb3..7373f014 100644
--- a/tests/remote/unit/test_server_cdm_max_height.py
+++ b/tests/remote/unit/test_server_cdm_max_height.py
@@ -653,9 +653,10 @@ class _SentCreate(Exception):
pass
-def sent_create(
- server_cdm, cdm_name=None, local_cdm=SimpleNamespace(is_playready=False), cdm_entry=False, cdm_map=None
-):
+WIDEVINE_CDM = SimpleNamespace(is_playready=False)
+
+
+def sent_create(server_cdm, cdm_name=None, local_cdm=WIDEVINE_CDM, cdm_entry=False, cdm_map=None):
def post(path, data):
raise _SentCreate(data)
diff --git a/tests/remote/unit/test_server_vault_push.py b/tests/remote/unit/test_server_vault_push.py
index c7ea2539..6d770c9f 100644
--- a/tests/remote/unit/test_server_vault_push.py
+++ b/tests/remote/unit/test_server_vault_push.py
@@ -9,7 +9,7 @@ import logging
import threading
from pathlib import Path
from types import SimpleNamespace
-from typing import Any, Optional
+from typing import Any
from uuid import UUID
import click
@@ -121,7 +121,7 @@ def decrypt(
ffmpeg: Any,
decodes: bool = True,
track: Any = "track",
- flagged: Optional[dict] = None,
+ flagged: dict | None = None,
licence: Any = None,
) -> list:
"""Decrypt a track that holds a licence key, a vault key and a null key; return what reached the server vault."""
diff --git a/tests/remote/unit/test_session_service_lock.py b/tests/remote/unit/test_session_service_lock.py
index 04d4112a..869af611 100644
--- a/tests/remote/unit/test_session_service_lock.py
+++ b/tests/remote/unit/test_session_service_lock.py
@@ -18,8 +18,9 @@ import asyncio
import contextlib
import json
import threading
+from collections.abc import Iterator
from types import SimpleNamespace
-from typing import Any, Iterator, List
+from typing import Any
import pytest
@@ -42,7 +43,7 @@ class Overlap:
def __init__(self, window: float = OVERLAP_WINDOW) -> None:
self.window = window
self.max_active = 0
- self.trace: List[str] = []
+ self.trace: list[str] = []
self._lock = threading.Lock()
self._active = 0
self._joined = threading.Event()
@@ -86,7 +87,7 @@ class ServiceProbe:
self.name = name
self.session = SimpleNamespace(headers={}, cookies=[])
- def get_titles(self) -> List[Movie]:
+ def get_titles(self) -> list[Movie]:
with self.overlap.call(f"{self.name}:titles"):
return [a_movie("movie-0001"), a_movie("movie-0002")]
@@ -94,7 +95,7 @@ class ServiceProbe:
with self.overlap.call(f"{self.name}:tracks:{title.id}"):
return empty_tracks()
- def get_chapters(self, title: Any) -> List[Any]:
+ def get_chapters(self, title: Any) -> list[Any]:
with self.overlap.call(f"{self.name}:chapters:{title.id}"):
return []
@@ -105,14 +106,14 @@ def seed_titles(session: SessionEntry) -> None:
session.title_map[title_id] = a_movie(title_id)
-def bodies(responses: List[Any]) -> List[dict]:
+def bodies(responses: list[Any]) -> list[dict]:
parsed = [json.loads(response.body) for response in responses]
for body in parsed:
assert "error" not in body, body
return parsed
-async def two_track_calls(session_id: str) -> List[Any]:
+async def two_track_calls(session_id: str) -> list[Any]:
return list(
await asyncio.gather(
handlers.session_tracks_handler({"title_id": "movie-0001"}, session_id),
@@ -151,7 +152,7 @@ async def test_the_track_lock_covers_the_chapters_call() -> None:
# Every call closes before the next one opens, so one title's chapters are read before the
# other title's tracks are fetched.
assert len(overlap.trace) == 8, overlap.trace
- for opened, closed in zip(overlap.trace[0::2], overlap.trace[1::2]):
+ for opened, closed in zip(overlap.trace[0::2], overlap.trace[1::2], strict=True):
assert closed == f"-{opened[1:]}", overlap.trace
@@ -211,7 +212,7 @@ class BlockingTracks:
self.loop_was_blocked = not self.resume.wait(timeout=HANDSHAKE_TIMEOUT)
return empty_tracks()
- def get_chapters(self, title: Any) -> List[Any]:
+ def get_chapters(self, title: Any) -> list[Any]:
return []
diff --git a/tests/remote/unit/test_session_store.py b/tests/remote/unit/test_session_store.py
index 89f86388..209d6136 100644
--- a/tests/remote/unit/test_session_store.py
+++ b/tests/remote/unit/test_session_store.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import asyncio
import threading
import time
+from datetime import UTC
from types import SimpleNamespace
import pytest
@@ -71,10 +72,10 @@ async def test_delete_returns_false_when_missing(store: SessionStore) -> None:
async def test_cleanup_expired_drops_old_authenticated(store: SessionStore, monkeypatch: pytest.MonkeyPatch) -> None:
- from datetime import datetime, timedelta, timezone
+ from datetime import datetime, timedelta
entry = await store.create("EXAMPLE", _FakeService())
- entry.last_accessed = datetime.now(timezone.utc) - timedelta(seconds=store.ttl + 100)
+ entry.last_accessed = datetime.now(UTC) - timedelta(seconds=store.ttl + 100)
removed = await store.cleanup_expired()
assert removed == 1
assert store.session_count == 0
@@ -82,10 +83,10 @@ async def test_cleanup_expired_drops_old_authenticated(store: SessionStore, monk
async def test_session_with_work_in_progress_does_not_expire(store: SessionStore) -> None:
"""A request that holds the lock for longer than the TTL keeps its session and cache directory."""
- from datetime import datetime, timedelta, timezone
+ from datetime import datetime, timedelta
entry = await store.create("EXAMPLE", _FakeService(), session_id="busy")
- entry.last_accessed = datetime.now(timezone.utc) - timedelta(seconds=store.ttl + 100)
+ entry.last_accessed = datetime.now(UTC) - timedelta(seconds=store.ttl + 100)
async with entry.lock:
assert await store.cleanup_expired() == 0
assert await store.get("busy") is entry
@@ -93,31 +94,31 @@ async def test_session_with_work_in_progress_does_not_expire(store: SessionStore
async def test_cleanup_expired_keeps_a_login_under_grace(store: SessionStore) -> None:
"""A session that still logs in, a prompt included, gets a longer grace period (10 min) than authenticated TTL."""
- from datetime import datetime, timedelta, timezone
+ from datetime import datetime, timedelta
entry = await store.create("EXAMPLE", _FakeService(), input_bridge=InputBridge())
- entry.last_accessed = datetime.now(timezone.utc) - timedelta(seconds=store.ttl + 1)
+ entry.last_accessed = datetime.now(UTC) - timedelta(seconds=store.ttl + 1)
removed = await store.cleanup_expired()
assert removed == 0
assert store.session_count == 1
async def test_get_keeps_a_login_past_the_ttl(store: SessionStore) -> None:
- from datetime import datetime, timedelta, timezone
+ from datetime import datetime, timedelta
entry = await store.create("EXAMPLE", _FakeService(), input_bridge=InputBridge())
- entry.last_accessed = datetime.now(timezone.utc) - timedelta(seconds=store.ttl + 1)
+ entry.last_accessed = datetime.now(UTC) - timedelta(seconds=store.ttl + 1)
assert await store.get(entry.session_id) is entry
async def test_cleanup_expired_drops_a_login_past_grace(store: SessionStore) -> None:
"""The auth-state grace is the single AUTH_INPUT_TIMEOUT rule, not a separate magic number."""
- from datetime import datetime, timedelta, timezone
+ from datetime import datetime, timedelta
from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT
entry = await store.create("EXAMPLE", _FakeService(), input_bridge=InputBridge())
- entry.last_accessed = datetime.now(timezone.utc) - timedelta(seconds=AUTH_INPUT_TIMEOUT + 1)
+ entry.last_accessed = datetime.now(UTC) - timedelta(seconds=AUTH_INPUT_TIMEOUT + 1)
removed = await store.cleanup_expired()
assert removed == 1
assert store.session_count == 0
@@ -167,13 +168,13 @@ async def test_max_sessions_evicts_the_oldest_session_of_the_key_that_holds_the_
async def test_get_expiry_removes_cache_dir(store: SessionStore, monkeypatch: pytest.MonkeyPatch) -> None:
- from datetime import datetime, timedelta, timezone
+ from datetime import datetime, timedelta
removed: list = []
monkeypatch.setattr(SessionStore, "cleanup_cache_dir", staticmethod(removed.append))
entry = await store.create("EXAMPLE", _FakeService())
entry.cache_tag = "_sessions/k/s/EXAMPLE"
- entry.last_accessed = datetime.now(timezone.utc) - timedelta(seconds=store.ttl + 100)
+ entry.last_accessed = datetime.now(UTC) - timedelta(seconds=store.ttl + 100)
assert await store.get(entry.session_id) is None
assert removed == ["_sessions/k/s/EXAMPLE"]
@@ -251,12 +252,12 @@ async def test_eviction_applies_staged_service_reload(store: SessionStore, monke
async def test_inline_expiry_applies_staged_service_reload(
store: SessionStore, monkeypatch: pytest.MonkeyPatch
) -> None:
- from datetime import datetime, timedelta, timezone
+ from datetime import datetime, timedelta
applied = _stage_reload(monkeypatch, {"EXAMPLE"})
entry = await store.create("EXAMPLE", _FakeService())
- entry.last_accessed = datetime.now(timezone.utc) - timedelta(seconds=store.ttl + 100)
+ entry.last_accessed = datetime.now(UTC) - timedelta(seconds=store.ttl + 100)
assert await store.get(entry.session_id) is None
await asyncio.sleep(0.05)
assert applied == [set()]
@@ -266,10 +267,10 @@ async def test_cleanup_expired_applies_staged_service_reload_once(
store: SessionStore, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A cleanup sweep that drops several sessions on one tag schedules one reload for that tag."""
- from datetime import datetime, timedelta, timezone
+ from datetime import datetime, timedelta
applied = _stage_reload(monkeypatch, {"EXAMPLE"})
- stale = datetime.now(timezone.utc) - timedelta(seconds=store.ttl + 100)
+ stale = datetime.now(UTC) - timedelta(seconds=store.ttl + 100)
for sid in ("a", "b"):
(await store.create("EXAMPLE", _FakeService(), session_id=sid)).last_accessed = stale
diff --git a/tests/remote/unit/test_tunnel.py b/tests/remote/unit/test_tunnel.py
index 4217ca3b..62ae830c 100644
--- a/tests/remote/unit/test_tunnel.py
+++ b/tests/remote/unit/test_tunnel.py
@@ -8,7 +8,7 @@ import socket
import socketserver
import threading
import time
-from typing import Callable, Iterator
+from collections.abc import Callable, Iterator
import aiohttp
import click
@@ -545,7 +545,7 @@ def spy_links(monkeypatch: pytest.MonkeyPatch) -> list:
return links
-def wait_until(check: "Callable[[], bool]", seconds: float = 3) -> bool:
+def wait_until(check: Callable[[], bool], seconds: float = 3) -> bool:
deadline = time.monotonic() + seconds
while not check() and time.monotonic() < deadline:
time.sleep(0.05)
diff --git a/tests/test_client_session_auth.py b/tests/test_client_session_auth.py
index ffe8cadc..a57049b4 100644
--- a/tests/test_client_session_auth.py
+++ b/tests/test_client_session_auth.py
@@ -191,8 +191,8 @@ def test_history_scoped_by_owner(tmp_path, monkeypatch):
monkeypatch.setattr(dm, "history_path", lambda: tmp_path / "h.jsonl")
(tmp_path / "h.jsonl").write_text(
- '{"job_id": "a", "owner": "%s", "service": "X"}\n{"job_id": "b", "owner": "%s", "service": "X"}\n'
- % (dm.owner_id("k1"), dm.owner_id("k2"))
+ f'{{"job_id": "a", "owner": "{dm.owner_id("k1")}", "service": "X"}}\n'
+ f'{{"job_id": "b", "owner": "{dm.owner_id("k2")}", "service": "X"}}\n'
)
assert [e["job_id"] for e in dm.read_job_history(owner=dm.owner_id("k1"))] == ["a"]
assert not dm.delete_job_history("b", owner=dm.owner_id("k1"))
diff --git a/tests/test_downloader_leaks.py b/tests/test_downloader_leaks.py
index 0a2cc267..b7e4f8e3 100644
--- a/tests/test_downloader_leaks.py
+++ b/tests/test_downloader_leaks.py
@@ -14,10 +14,12 @@ import importlib
import socketserver
import threading
import time
+from collections.abc import Iterator
from pathlib import Path
-from typing import Any, Iterator
+from typing import Any
import pytest
+import urllib3
from unshackle.core.constants import DOWNLOAD_CANCELLED, DownloadCancelled
from unshackle.core.downloaders.requests import requests as download_batch
@@ -111,7 +113,7 @@ def test_failed_batch_frees_handles_even_after_flag_clear(server: _Server, tmp_p
host, port = str(server.server_address[0]), int(server.server_address[1])
urls = [f"http://{host}:{port}/stall/0"] + [f"http://{host}:{port}/ok/{i}" for i in range(1, 4)]
- with pytest.raises(Exception):
+ with pytest.raises((OSError, urllib3.exceptions.HTTPError)):
for _ in download_batch(urls=urls, output_dir=tmp_path, filename="seg_{i}.bin", max_workers=4):
pass
diff --git a/tests/test_sample.py b/tests/test_sample.py
index ab49565c..4807700e 100644
--- a/tests/test_sample.py
+++ b/tests/test_sample.py
@@ -6,9 +6,9 @@ import functools
import http.server
import struct
import threading
+from collections.abc import Callable
from pathlib import Path
from types import SimpleNamespace
-from typing import Callable, Optional
from unittest.mock import MagicMock
import click
@@ -124,7 +124,7 @@ BASE_MPD = """
WINDOW = (62, 120)
-def dash_names(mpd: str, window: Optional[tuple[int, int]]) -> tuple[list[str], float]:
+def dash_names(mpd: str, window: tuple[int, int] | None) -> tuple[list[str], float]:
tree = load_xml(mpd.encode())
period = tree.find("Period")
aset = period.find("AdaptationSet")
diff --git a/tests/test_setup.py b/tests/test_setup.py
index 627f49a1..9a5ad080 100644
--- a/tests/test_setup.py
+++ b/tests/test_setup.py
@@ -8,9 +8,9 @@ import subprocess
import sys
import tarfile
import zipfile
+from collections.abc import Callable, Iterable, Iterator
from pathlib import Path
from types import SimpleNamespace
-from typing import Callable, Iterable, Iterator
import pytest
import yaml
diff --git a/tests/tracks/test_mux_default_language.py b/tests/tracks/test_mux_default_language.py
index 8e14d7b9..407022cd 100644
--- a/tests/tracks/test_mux_default_language.py
+++ b/tests/tracks/test_mux_default_language.py
@@ -1,8 +1,8 @@
from __future__ import annotations
import logging
+from collections.abc import Callable
from pathlib import Path
-from typing import Callable, Optional
import pytest
from langcodes import Language
@@ -22,7 +22,7 @@ from unshackle.core.tracks import Audio, Subtitle, Tracks
(["en-US"], None, None),
],
)
-def test_first_match_index(languages: list[str], preferred: Optional[str], expected: Optional[int]) -> None:
+def test_first_match_index(languages: list[str], preferred: str | None, expected: int | None) -> None:
tracks = [
Audio(id_=f"a{i}", url=f"https://x/{i}", language=lang, codec=Audio.Codec.AAC, bitrate=1)
for i, lang in enumerate(languages)
@@ -55,7 +55,7 @@ def subtitle(index: int, language: str, kind: str) -> Subtitle:
(None, [], None),
],
)
-def test_default_subtitle_index(language: Optional[str], types: list[str], expected: Optional[int]) -> None:
+def test_default_subtitle_index(language: str | None, types: list[str], expected: int | None) -> None:
kinds = [("pl", "forced"), ("pl", "normal"), ("en", "normal"), ("en", "sdh")]
subtitles = [subtitle(i, lang, kind) for i, (lang, kind) in enumerate(kinds)]
assert Tracks.default_subtitle_index(subtitles, language, types) == expected
@@ -65,7 +65,7 @@ def test_default_subtitle_index(language: Optional[str], types: list[str], expec
("audio", "expected"),
[("en", 1), ("ar", 0), ("fr", 2), (None, 2)],
)
-def test_a_forced_default_with_no_language_follows_the_audio(audio: Optional[str], expected: int) -> None:
+def test_a_forced_default_with_no_language_follows_the_audio(audio: str | None, expected: int) -> None:
kinds = [("ar", "forced"), ("en", "forced"), ("en", "normal")]
subtitles = [subtitle(i, lang, kind) for i, (lang, kind) in enumerate(kinds)]
audio_language = Language.get(audio) if audio else None
diff --git a/tests/tracks/test_track_language_names.py b/tests/tracks/test_track_language_names.py
index 5e2474c5..10ac3487 100644
--- a/tests/tracks/test_track_language_names.py
+++ b/tests/tracks/test_track_language_names.py
@@ -1,5 +1,5 @@
+from collections.abc import Callable
from pathlib import Path
-from typing import Callable, Optional
import pytest
from langcodes import Language
@@ -10,7 +10,7 @@ from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
from unshackle.core.utilities import language_name, multi_script_languages, with_script
-def sub(lang: str, name: Optional[str] = None, sdh: bool = False, original: bool = False) -> Subtitle:
+def sub(lang: str, name: str | None = None, sdh: bool = False, original: bool = False) -> Subtitle:
return Subtitle(
id_="s",
url="https://x/s",
@@ -77,7 +77,7 @@ def test_with_script(tag: str, expected: str) -> None:
("x-foo", None),
],
)
-def test_language_name(tag: str, expected: Optional[str]) -> None:
+def test_language_name(tag: str, expected: str | None) -> None:
assert language_name(Language.get(tag)) == expected
@@ -105,7 +105,7 @@ def test_language_name(tag: str, expected: Optional[str]) -> None:
("qaa", None),
],
)
-def test_native_language_name(tag: str, expected: Optional[str], monkeypatch: pytest.MonkeyPatch) -> None:
+def test_native_language_name(tag: str, expected: str | None, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(config, "muxing", {"track_names": "native"})
assert language_name(Language.get(tag)) == expected
diff --git a/tests/tracks/test_vp9_colour_args.py b/tests/tracks/test_vp9_colour_args.py
index a40fb2c6..1c3b0cb0 100644
--- a/tests/tracks/test_vp9_colour_args.py
+++ b/tests/tracks/test_vp9_colour_args.py
@@ -1,8 +1,9 @@
import json
import subprocess
+from collections.abc import Callable
from pathlib import Path
from types import SimpleNamespace
-from typing import Any, Callable, Optional
+from typing import Any
import pytest
@@ -39,7 +40,7 @@ def probe_returns(monkeypatch: pytest.MonkeyPatch, stream: dict[str, Any]) -> No
def pairs(args: list[str]) -> dict[str, str]:
- return dict(zip(args[::2], args[1::2]))
+ return dict(zip(args[::2], args[1::2], strict=False))
def test_hdr10_vp9_gets_cicp_and_mastering_display(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
@@ -78,7 +79,7 @@ def test_partial_mastering_display_keeps_the_cicp_args(tmp_path: Path, monkeypat
],
)
def test_the_file_transfer_wins_over_the_range(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch, transfer: str, range_: Video.Range, expected: Optional[str]
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, transfer: str, range_: Video.Range, expected: str | None
) -> None:
probe_returns(monkeypatch, {"color_transfer": transfer})
diff --git a/unshackle/commands/cfg.py b/unshackle/commands/cfg.py
index b2d9f506..df1321df 100644
--- a/unshackle/commands/cfg.py
+++ b/unshackle/commands/cfg.py
@@ -95,6 +95,6 @@ def cfg(ctx: click.Context, key: str, value: str, unset: bool, list_: bool) -> N
del parent_data[trailing_key]
log.info(f"Unset {key}")
except KeyError:
- raise click.ClickException(f"Key '{key}' does not exist in the config.")
+ raise click.ClickException(f"Key '{key}' does not exist in the config.") from None
config_path.parent.mkdir(parents=True, exist_ok=True)
yaml.dump(data, config_path)
diff --git a/unshackle/commands/dl.py b/unshackle/commands/dl.py
index d0a058c5..8820153a 100644
--- a/unshackle/commands/dl.py
+++ b/unshackle/commands/dl.py
@@ -9,7 +9,7 @@ import subprocess
import sys
import time
from collections import Counter
-from collections.abc import Iterable
+from collections.abc import Callable, Collection, Iterable, Sequence
from concurrent import futures
from concurrent.futures import ThreadPoolExecutor
from copy import deepcopy
@@ -19,7 +19,7 @@ from itertools import groupby
from operator import attrgetter
from pathlib import Path
from threading import Lock
-from typing import TYPE_CHECKING, Any, Callable, Collection, Optional, Sequence, TypedDict, Union
+from typing import TYPE_CHECKING, Any, TypedDict
import click
import mediaexport
@@ -153,7 +153,7 @@ class SkippedSubtitle(TypedDict):
title: str
-def parse_language(tag: Optional[str]) -> Optional[Language]:
+def parse_language(tag: str | None) -> Language | None:
"""A provider's original-language tag as a Language, or None if it is absent or not a real tag."""
tag = (tag or "").strip()
if not tag or not tag_is_valid(tag) or tag.startswith("und"):
@@ -166,7 +166,7 @@ def normalize_dl_config(dl_config: dict[str, Any]) -> dict[str, Any]:
return {DL_OPTION_ALIASES.get(key, key): value for key, value in dl_config.items()}
-def convert_scc(subtitle: Subtitle, sub_format: Optional[Union[Subtitle.Codec, str]]) -> Subtitle.Codec:
+def convert_scc(subtitle: Subtitle, sub_format: Subtitle.Codec | str | None) -> Subtitle.Codec:
"""
Convert an SCC subtitle to sub_format when pycaption can write it, else to SRT, and return the new codec.
Only pycaption reads SCC, and nothing later in the pipeline (styling, SDH strip, mux) can.
@@ -181,13 +181,13 @@ def convert_scc(subtitle: Subtitle, sub_format: Optional[Union[Subtitle.Codec, s
def subtitle_look(
- sub_format: Optional[Union[Subtitle.Codec, str]],
- sub_font: Optional[str],
+ sub_format: Subtitle.Codec | str | None,
+ sub_font: str | None,
style_fields: Any,
*,
typed_font: bool = True,
typed_format: bool = True,
-) -> tuple[Optional[Union[Subtitle.Codec, str]], Optional[pysubs2.SSAStyle]]:
+) -> tuple[Subtitle.Codec | str | None, pysubs2.SSAStyle | None]:
"""The subtitle format and ASS style for --sub-font and the subtitle.ass_style config.
A style makes ASS the format when none is set. Another format leaves the style unused. A typed --sub-font
@@ -205,9 +205,7 @@ def subtitle_look(
return sub_format or Subtitle.Codec.SubStationAlphav4, style
-def set_subtitle_look(
- subtitles: Iterable[Subtitle], style: Optional[pysubs2.SSAStyle], videos: Iterable[Video]
-) -> None:
+def set_subtitle_look(subtitles: Iterable[Subtitle], style: pysubs2.SSAStyle | None, videos: Iterable[Video]) -> None:
"""Give each subtitle that is not already SSA/ASS the style, and every subtitle the size of the first video."""
size = next(((v.width, v.height) for v in videos if v.width and v.height), None)
for subtitle in subtitles:
@@ -226,7 +224,7 @@ def title_wanted(candidate: Any, wanted: Collection[str]) -> bool:
return bool(candidate.matches_wanted(wanted))
-def latest_episode_keys(titles: Any, latest_episode: bool, latest_episodes: Optional[int]) -> list[tuple[int, int]]:
+def latest_episode_keys(titles: Any, latest_episode: bool, latest_episodes: int | None) -> list[tuple[int, int]]:
"""The (season, number) of each episode ``--latest-episode(s)`` keeps, oldest first.
Counts distinct episodes, not Series entries, so a split episode takes one slot and all its parts download.
@@ -238,7 +236,7 @@ def latest_episode_keys(titles: Any, latest_episode: bool, latest_episodes: Opti
return list(dict.fromkeys((ep.season, ep.number) for ep in titles))[-count:]
-def apply_enrich(title: Title_T, name: Optional[str], year: Optional[int], language: Optional[Language]) -> None:
+def apply_enrich(title: Title_T, name: str | None, year: int | None, language: Language | None) -> None:
"""Set the --enrich name, year and original language on a title. A song takes only the language.
A service can set the title again in get_tracks, so dl applies them after that call too.
@@ -257,11 +255,11 @@ def load_tracks(
service: Service,
title: Title_T,
*,
- name: Optional[str] = None,
- year: Optional[int] = None,
- language: Optional[Language] = None,
- workers: Optional[int] = None,
- on_probe: Optional[Callable[[], None]] = None,
+ name: str | None = None,
+ year: int | None = None,
+ language: Language | None = None,
+ workers: int | None = None,
+ on_probe: Callable[[], None] | None = None,
) -> None:
"""Load the tracks and chapters of a title, then apply the --enrich name, year and language again."""
title.tracks.add(probed_tracks(service, title, workers=workers, on_probe=on_probe), warn_only=True)
@@ -269,7 +267,7 @@ def load_tracks(
apply_enrich(title, name, year, language)
-def server_url(server_name: Optional[str]) -> str:
+def server_url(server_name: str | None) -> str:
"""The configured URL of a remote server, or an empty string when the config cannot be read."""
from unshackle.core.remote_service import resolve_server
@@ -289,7 +287,7 @@ def post_script_group(candidate: Any) -> Any:
return ("title", id(candidate))
-def remux_music_tracks(title: Any, log: logging.Logger, sample: Optional[tuple[int, int]] = None) -> None:
+def remux_music_tracks(title: Any, log: logging.Logger, sample: tuple[int, int] | None = None) -> None:
"""Remux each audio track of a Song into the container of its codec, cut to ``sample`` when given.
A Song never reaches the muxer, so each downloaded audio track is itself a delivered
@@ -404,7 +402,7 @@ def download_tracks_in_passes(
class dl:
- def find_custom_font(self, font_name: str) -> Optional[Path]:
+ def find_custom_font(self, font_name: str) -> Path | None:
"""
Find font in custom fonts directory.
@@ -499,8 +497,8 @@ class dl:
subtitle: Subtitle,
base_filename: str,
output_dir: Path,
- target_codec: Optional[Subtitle.Codec] = None,
- source_path: Optional[Path] = None,
+ target_codec: Subtitle.Codec | None = None,
+ source_path: Path | None = None,
) -> Path:
"""Make the sidecar path: {base}.{lang}[.forced][.sdh].{ext}"""
lang_suffix = str(subtitle.language) if subtitle.language else "und"
@@ -520,7 +518,7 @@ class dl:
base_filename: str,
output_dir: Path,
sidecar_format: str,
- original_paths: Optional[dict[str, Path]] = None,
+ original_paths: dict[str, Path] | None = None,
) -> list[Path]:
"""
Output subtitles as sidecar files, converting if needed.
@@ -1123,29 +1121,29 @@ class dl:
return dl(ctx, **kwargs)
EXPORT_LOCK = Lock()
- export_snapshots: dict[str, Optional[dict[str, Any]]]
+ export_snapshots: dict[str, dict[str, Any] | None]
keys: ContentKeyResolver
- _remote_service: Optional["ServerKeySource"] = None
+ _remote_service: ServerKeySource | None = None
typed_params: frozenset[str] = frozenset()
def __init__(
self,
ctx: click.Context,
no_proxy: bool,
- profile: Optional[str] = None,
- proxy: Optional[str] = None,
+ profile: str | None = None,
+ proxy: str | None = None,
repack: bool = False,
- tag: Optional[str] = None,
- tmdb_id: Optional[int] = None,
- imdb_id: Optional[str] = None,
- tvdb_id: Optional[int] = None,
- tvdb_order: Optional[str] = None,
+ tag: str | None = None,
+ tmdb_id: int | None = None,
+ imdb_id: str | None = None,
+ tvdb_id: int | None = None,
+ tvdb_order: str | None = None,
continuous_episodes: bool = False,
- anilist_id: Optional[Union[int, str]] = None,
+ anilist_id: int | str | None = None,
enrich: bool = False,
daily: bool = False,
- output_dir: Optional[Path] = None,
- proxy_providers: Optional[list[Any]] = None,
+ output_dir: Path | None = None,
+ proxy_providers: list[Any] | None = None,
*_: Any,
**__: Any,
) -> None:
@@ -1166,7 +1164,7 @@ class dl:
# result() catches a download-worker failure, reports it, and returns rather than
# re-raising (so the CLI still exits cleanly). Keep it so an embedding caller (the API
# worker) can tell the title did not complete instead of reading it as a success.
- self.download_error: Optional[BaseException] = None
+ self.download_error: BaseException | None = None
if not config.output_template:
raise click.ClickException("No 'output_template' in your unshackle.yaml")
@@ -1251,7 +1249,7 @@ class dl:
},
)
- binary_versions: dict[str, Optional[dict[str, Optional[str]]]] = {}
+ binary_versions: dict[str, dict[str, str | None] | None] = {}
for name, binary in [
("shaka_packager", binaries.ShakaPackager),
("mp4decrypt", binaries.Mp4decrypt),
@@ -1457,21 +1455,21 @@ class dl:
quality: list[int],
vcodec: list[Video.Codec],
acodec: list[Audio.Codec],
- vbitrate: Optional[int],
- abitrate: Optional[int],
- vbitrate_range: Optional[str],
- abitrate_range: Optional[str],
+ vbitrate: int | None,
+ abitrate: int | None,
+ vbitrate_range: str | None,
+ abitrate_range: str | None,
range_: list[Video.Range],
- channels: Optional[float],
+ channels: float | None,
no_atmos: bool,
select_titles: bool,
wanted: list[str],
latest_episode: bool,
- latest_episodes: Optional[int],
+ latest_episodes: int | None,
lang: list[str],
- v_lang: Optional[list[str]],
- a_lang: Optional[list[str]],
- s_lang: Optional[list[str]],
+ v_lang: list[str] | None,
+ a_lang: list[str] | None,
+ s_lang: list[str] | None,
require_audio: list[str],
require_video: list[str],
require_subs: list[str],
@@ -1480,8 +1478,8 @@ class dl:
forced_subs_only: bool,
forced_s_lang: list[str],
exact_lang: bool,
- sub_format: Optional[Union[Subtitle.Codec, str]],
- sub_font: Optional[str],
+ sub_format: Subtitle.Codec | str | None,
+ sub_font: str | None,
video_only: bool,
audio_only: bool,
subs_only: bool,
@@ -1494,33 +1492,33 @@ class dl:
no_attachments: bool,
audio_description: bool,
audio_description_only: bool,
- slow: Optional[tuple[int, int]],
+ slow: tuple[int, int] | None,
list_: bool,
list_titles: bool,
skip_dl: bool,
- export: Optional[bool],
- cdm_only: Optional[bool],
+ export: bool | None,
+ cdm_only: bool | None,
no_proxy: bool,
no_proxy_download: bool,
- proxy_download: Optional[str],
+ proxy_download: str | None,
no_folder: bool,
no_source: bool,
no_mux: bool,
- sample: Optional[tuple[int, int]],
+ sample: tuple[int, int] | None,
include_sample: bool,
- workers: Optional[int],
+ workers: int | None,
adaptive_workers: bool,
download_processes: int,
continue_downloads: bool,
downloads: int,
worst: bool,
best_available: bool,
- speed_limit: Optional[str] = None,
- split_audio: Optional[bool] = None,
- merge_video: Optional[bool] = None,
+ speed_limit: str | None = None,
+ split_audio: bool | None = None,
+ merge_video: bool | None = None,
real_video_bitrate: bool = False,
real_audio_bitrate: bool = False,
- progress_sink: Optional[Callable[[dict[str, Any]], None]] = None,
+ progress_sink: Callable[[dict[str, Any]], None] | None = None,
postscript: Sequence[str] = (),
no_postscript: bool = False,
all_drm: bool = False,
@@ -1739,9 +1737,9 @@ 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
- enrich_lang: Optional[Language] = None
- enrich_title: Optional[str] = None
- enrich_year: Optional[int] = None
+ enrich_lang: Language | None = None
+ enrich_title: str | None = None
+ enrich_year: int | None = None
if self.enrich:
sample_title = titles[0] if hasattr(titles, "__getitem__") else titles
kind = "tv" if isinstance(sample_title, Episode) else "movie"
@@ -2003,7 +2001,7 @@ class dl:
if isinstance(title, Episode) and not self.tmdb_searched:
kind = "tv"
- tmdb_title: Optional[str] = None
+ tmdb_title: str | None = None
has_ids = bool(self.tmdb_id or self.imdb_id or self.tvdb_id or self.anilist_id)
result = providers.resolve_by_ids(
self.tmdb_id,
@@ -2099,7 +2097,7 @@ class dl:
year=enrich_year,
language=enrich_lang,
workers=workers,
- on_probe=lambda: tracks_spinner.update(text="Probing HDR10 tracks for HDR10+..."),
+ on_probe=partial(tracks_spinner.update, text="Probing HDR10 tracks for HDR10+..."),
)
except Exception as e:
if self.debug_logger:
@@ -2267,9 +2265,6 @@ class dl:
download_table = Table.grid()
download_table.add_row(selected_tracks)
- def prepare_drm_for(track: AnyTrack) -> partial:
- return self.keys.licence_for(track, title, download_table, title_all_drm)
-
server_cdm_type = None
if self._remote_service and self._remote_service.server_cdm:
server_cdm_type = self._remote_service.server_cdm_type
@@ -2312,6 +2307,7 @@ class dl:
self.keys.all_drm_warned.add(name)
self.log.warning(f"The {name} CDM is remote and can answer with cached content keys")
+ prepare_drm_for = partial(self.keys.licence_for, title=title, table=download_table, all_drm=title_all_drm)
self.keys.take_server_keys(title)
if sample and not skip_dl:
@@ -2331,7 +2327,14 @@ class dl:
try:
with SyncLive(Padding(download_table, (1, 5)), console=console, refresh_per_second=20):
- def download_track(track: AnyTrack, i: int) -> None:
+ def download_track(
+ track: AnyTrack,
+ i: int,
+ *,
+ title: Title_T,
+ prepare_drm_for: Callable[[AnyTrack], partial],
+ progress_callables: list[partial],
+ ) -> None:
track.download(
session=track.session or service.session,
no_proxy_download=no_proxy_download,
@@ -2341,7 +2344,7 @@ class dl:
max_workers=workers,
adaptive_workers=adaptive_workers,
download_processes=download_processes,
- progress=tracks_progress_callables[i],
+ progress=progress_callables[i],
)
if (
track.path
@@ -2349,7 +2352,7 @@ class dl:
and not DOWNLOAD_CANCELLED.is_set()
and not DOWNLOAD_LICENCE_ONLY.is_set()
):
- progress = tracks_progress_callables[i]
+ progress = progress_callables[i]
progress(downloaded="Decrypting", completed=0, total=None)
cbcs.decrypt_file(
track.path, lambda _l, entry: service.get_sample_decrypter(track, entry.index)
@@ -2362,7 +2365,7 @@ class dl:
if export_path:
self.write_export(export_path, title, track)
- def on_subtitle_skipped(track: Subtitle) -> None:
+ def on_subtitle_skipped(track: Subtitle, *, title: Title_T) -> None:
lang = str(track.language)
self.log.warning(f"Subtitle {lang} failed to download, skipping it.")
self.skipped_subtitles.append(SkippedSubtitle(id=track.id, language=lang, title=str(title)))
@@ -2376,9 +2379,14 @@ class dl:
download_tracks_in_passes(
title.tracks,
downloads,
- download_track,
+ partial(
+ download_track,
+ title=title,
+ prepare_drm_for=prepare_drm_for,
+ progress_callables=tracks_progress_callables,
+ ),
skip_subtitle_errors=skip_subtitle_errors,
- on_subtitle_skipped=on_subtitle_skipped,
+ on_subtitle_skipped=partial(on_subtitle_skipped, title=title),
)
for attachment in title.tracks.attachments:
@@ -2464,7 +2472,7 @@ class dl:
skip_subtitle_mux = subtitle_output_mode == "sidecar" and (title.tracks.videos or title.tracks.audio)
sidecar_subtitles: list[Subtitle] = []
sidecar_original_paths: dict[str, Path] = {}
- sidecar_files: dict[Optional[Path], list[Path]] = {}
+ sidecar_files: dict[Path | None, list[Path]] = {}
if subtitle_output_mode in ("sidecar", "both") and not no_mux:
sidecar_subtitles = [s for s in title.tracks.subtitles if s.path and s.path.exists()]
if sidecar_format == "original":
@@ -2586,7 +2594,7 @@ class dl:
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:
+ except OSError:
self.log.error(
"Cannot extract Closed Captions as the ccextractor executable was not found..."
)
@@ -2816,17 +2824,17 @@ class dl:
if returncode > 1 or not output.exists():
self.log.warning(f"mkvmerge wrote no sample for {source.name}")
- def anime_hint(self, title: Optional[Title_T] = None) -> bool:
+ def anime_hint(self, title: Title_T | None = None) -> bool:
"""Whether metadata lookups for this title should prefer AniList."""
per_title = getattr(title, "anime", None)
return self.service_anime if per_title is None else bool(per_title)
- def daily_hint(self, title: Optional[Title_T] = None) -> bool:
+ def daily_hint(self, title: Title_T | None = None) -> bool:
"""Whether this title is daily content named by air date."""
per_title = getattr(title, "daily", None)
return self.daily or (self.service_daily if per_title is None else bool(per_title))
- def fill_air_dates(self, titles: Series, tvdb_id: Optional[int] = None) -> None:
+ def fill_air_dates(self, titles: Series, tvdb_id: int | None = None) -> None:
"""Fill in missing episode air dates from TVDB.
Additive only: an air date the service already set is kept.
@@ -2882,7 +2890,7 @@ class dl:
if filled:
self.log.info("Filled air dates for %d episode(s) from TVDB (ID %s).", filled, tvdb_id)
- def fill_absolute_numbers(self, titles: Series, tvdb_id: Optional[int] = None) -> None:
+ def fill_absolute_numbers(self, titles: Series, tvdb_id: int | None = None) -> None:
"""Fill in missing absolute episode numbers from TVDB's absolute order.
Additive only: season and number are never written, and an absolute number the
@@ -2946,9 +2954,9 @@ class dl:
self,
titles: Series,
title_cacher: Any = None,
- cache_title_id: Optional[str] = None,
- cache_region: Optional[str] = None,
- cache_account_hash: Optional[str] = None,
+ cache_title_id: str | None = None,
+ cache_region: str | None = None,
+ cache_account_hash: str | None = None,
) -> Series:
"""Renumber episodes from the service's own numbering into a TVDB season order."""
tvdb = providers.get_provider("tvdb")
@@ -3041,7 +3049,7 @@ class dl:
records the track, manifest, chapter and attachment info. unshackle's full track
dicts, title meta and manifest snapshot go under ``x-unshackle`` for its own importer.
"""
- namer: Optional[ExportNamer] = getattr(self, "export_namer", None)
+ namer: ExportNamer | None = getattr(self, "export_namer", None)
snapshots = getattr(self, "export_snapshots", None)
if snapshots is None:
snapshots = self.export_snapshots = {}
@@ -3143,7 +3151,7 @@ class dl:
def log_export_title(self, title: Title_T) -> None:
"""Log what the export holds for one title: its track counts and its keys."""
- namer: Optional[ExportNamer] = getattr(self, "export_namer", None)
+ namer: ExportNamer | None = getattr(self, "export_namer", None)
entry = None
if namer and namer.path:
try:
@@ -3162,7 +3170,7 @@ class dl:
def log_export_summary(self) -> None:
"""Log where the run's export is and what it holds, and that it must stay private."""
- namer: Optional[ExportNamer] = getattr(self, "export_namer", None)
+ namer: ExportNamer | None = getattr(self, "export_namer", None)
if not namer or not namer.path:
self.log.warning("Nothing was exported")
return
@@ -3302,7 +3310,7 @@ class dl:
return [":x: Download Failed...", f" {line}"]
def start_key_resolution(
- self, service: Service, *, cdm_only: bool, vaults_only: bool, best_available: bool, export: Optional[Path]
+ self, service: Service, *, cdm_only: bool, vaults_only: bool, best_available: bool, export: Path | None
) -> None:
"""Build the run's content-key resolution and make its verified decrypt the decrypt hook."""
self.keys = ContentKeyResolver(
@@ -3319,7 +3327,7 @@ class dl:
)
verify.DECRYPT_HOOK = self.keys.decrypt_verified
- def cdm_for(self, system: str, quality: Optional[int] = None) -> Optional[object]:
+ def cdm_for(self, system: str, quality: int | None = None) -> object | None:
"""Get the CDM for one DRM system, ``widevine`` or ``playready``.
A quality key that names one device applies to both DRM systems. When that device is for
@@ -3341,9 +3349,9 @@ class dl:
def get_cdm(
self,
service: str,
- profile: Optional[str] = None,
- drm: Optional[str] = None,
- quality: Optional[int] = None,
+ profile: str | None = None,
+ drm: str | None = None,
+ quality: int | None = None,
) -> Any:
"""
Get CDM for a specified service (either Local or Remote CDM).
@@ -3428,7 +3436,7 @@ class dl:
if not isinstance(cdm_name, str):
return load_cdm(cdm_name, service_name=service, vaults=self.vaults)
- cdm_cache: dict[tuple[str, Optional[str], str], Any] = getattr(self, "_cdm_cache", {})
+ cdm_cache: dict[tuple[str, str | None, str], Any] = getattr(self, "_cdm_cache", {})
self._cdm_cache = cdm_cache
cache_key = (service, profile, cdm_name)
diff --git a/unshackle/commands/env.py b/unshackle/commands/env.py
index 8405b90f..ba688705 100644
--- a/unshackle/commands/env.py
+++ b/unshackle/commands/env.py
@@ -3,7 +3,6 @@ import os
import shutil
import sys
from pathlib import Path
-from typing import Optional
import click
from rich.padding import Padding
@@ -419,7 +418,7 @@ def clear() -> None:
@clear.command()
@click.argument("service", type=str, required=False)
-def cache(service: Optional[str]) -> None:
+def cache(service: str | None) -> None:
"""Clear the environment cache directory."""
log = logging.getLogger("env")
cache_dir = config.directories.cache
diff --git a/unshackle/commands/import.py b/unshackle/commands/import.py
index 3aa69653..59b054bf 100644
--- a/unshackle/commands/import.py
+++ b/unshackle/commands/import.py
@@ -34,7 +34,7 @@ class ImportCommand:
try:
doc = mediaexport.read(export_file)
except mediaexport.ExportError as e:
- raise click.ClickException(f"{export_file} is not a usable export file: {e}")
+ raise click.ClickException(f"{export_file} is not a usable export file: {e}") from e
service_tag = doc.service_tag
if not service_tag:
diff --git a/unshackle/commands/kv.py b/unshackle/commands/kv.py
index fe8763c1..44b4788f 100644
--- a/unshackle/commands/kv.py
+++ b/unshackle/commands/kv.py
@@ -1,8 +1,9 @@
import logging
import re
+from collections.abc import Iterable
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
-from typing import Iterable, Optional, Union, cast
+from typing import cast
from uuid import UUID
import click
@@ -71,7 +72,7 @@ class _PaddedProgress(Progress):
def add_keys_with_progress(vault: Vault, service: str, kid_keys: dict[str, str], log: logging.Logger) -> int:
"""Add content keys to a vault. Network vaults write in batches behind a progress bar."""
if type(vault).__name__ in ("MySQL", "SQLite"):
- return vault.add_keys(service, cast(dict[Union[UUID, str], str], kid_keys))
+ return vault.add_keys(service, cast(dict[UUID | str, str], kid_keys))
def chunk(i: int) -> int:
# Probe with one key so a server that rejects batches costs one row, not 500.
@@ -97,7 +98,7 @@ def add_keys_with_progress(vault: Vault, service: str, kid_keys: dict[str, str],
task = progress.add_task(f"{service} → {vault}", total=len(kids), added=0)
i = 0
while i < len(kids):
- batch: dict[Union[UUID, str], str] = {kid: kid_keys[kid] for kid in kids[i : i + chunk(i)]}
+ batch: dict[UUID | str, str] = {kid: kid_keys[kid] for kid in kids[i : i + chunk(i)]}
added += vault.add_keys(service, batch)
i += len(batch)
progress.update(task, advance=len(batch), added=added)
@@ -105,7 +106,7 @@ def add_keys_with_progress(vault: Vault, service: str, kid_keys: dict[str, str],
def copy_service_data(
- to_vault: Vault, from_vault: Vault, service: str, log: logging.Logger, to_service: Optional[str] = None
+ to_vault: Vault, from_vault: Vault, service: str, log: logging.Logger, to_service: str | None = None
) -> int:
"""Copy data for a single service between vaults, into the `to_service` table when given."""
if service.lower() == "bad_keys":
@@ -160,7 +161,7 @@ def kv() -> None:
def copy(
to_vault_name: str,
from_vault_names: list[str],
- service: Optional[str] = None,
+ service: str | None = None,
local_only: bool = False,
) -> None:
"""
@@ -192,14 +193,14 @@ def copy(
if service and local_only:
raise click.UsageError("--service and --local-only are mutually exclusive.")
- source_tables: Optional[list[str]] = None
+ source_tables: list[str] | None = None
if service:
tag, service = Services.get_tag(service), Services.get_vault_tag(service)
# a vault filled outside unshackle can hold the keys under the plain tag, not the VAULT_TAG
source_tables = [service] if tag.lower() == service.lower() else [service, tag]
log.info(f"Filtering by service: {service}")
- installed: Optional[set[str]] = None
+ installed: set[str] | None = None
if local_only:
installed = {t.upper() for t in Services.get_tags()}
log.info(f"Filtering by locally installed services ({len(installed)} found)")
@@ -246,7 +247,7 @@ def copy(
def sync(
ctx: click.Context,
vaults: list[str],
- service: Optional[str] = None,
+ service: str | None = None,
local_only: bool = False,
) -> None:
"""
@@ -319,10 +320,10 @@ def add(file: Path, service: str, vaults: list[str]) -> None:
log.info("Done!")
-def search_vault(vault: Vault, kid: str, services: list[str], log: logging.Logger) -> Optional[tuple[str, str]]:
+def search_vault(vault: Vault, kid: str, services: list[str], log: logging.Logger) -> tuple[str, str] | None:
"""Return the service and content key from the first service table in a vault holding the KID."""
- def probe(svc: str) -> Optional[tuple[str, str]]:
+ def probe(svc: str) -> tuple[str, str] | None:
try:
key = vault.get_key(kid, svc)
except Exception as e:
@@ -355,7 +356,7 @@ def search_vault(vault: Vault, kid: str, services: list[str], log: logging.Logge
@click.option(
"-v", "--vault", "vault_name", type=str, default=None, help="Limit search to a specific configured vault by name."
)
-def search(kid: str, service: Optional[str], vault_name: Optional[str]) -> None:
+def search(kid: str, service: str | None, vault_name: str | None) -> None:
"""
Examine configured Key Vault(s) for a KID and report the content key it finds.
diff --git a/unshackle/commands/prd.py b/unshackle/commands/prd.py
index 22b1025c..e8706221 100644
--- a/unshackle/commands/prd.py
+++ b/unshackle/commands/prd.py
@@ -1,6 +1,5 @@
import logging
from pathlib import Path
-from typing import Optional
import click
import requests
@@ -45,9 +44,9 @@ def prd() -> None:
def new(
ctx: click.Context,
paths: tuple[Path, ...],
- encryption_key: Optional[Path],
- signing_key: Optional[Path],
- output: Optional[Path],
+ encryption_key: Path | None,
+ signing_key: Path | None,
+ output: Path | None,
) -> None:
"""Make a new .PRD device file.
@@ -155,9 +154,9 @@ def new(
def reprovision_device(
ctx: click.Context,
prd_path: Path,
- encryption_key: Optional[Path],
- signing_key: Optional[Path],
- output: Optional[Path] = None,
+ encryption_key: Path | None,
+ signing_key: Path | None,
+ output: Path | None = None,
) -> None:
"""Reprovision a PlayReady Device (.prd) file."""
if not prd_path.is_file():
diff --git a/unshackle/commands/search.py b/unshackle/commands/search.py
index 558fa867..897dc99a 100644
--- a/unshackle/commands/search.py
+++ b/unshackle/commands/search.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import logging
import re
import sys
-from typing import Any, Optional
+from typing import Any
import click
from rich.padding import Padding
@@ -67,11 +67,11 @@ from unshackle.core.utils.click_types import ContextData
def search(
ctx: click.Context,
no_proxy: bool,
- profile: Optional[str] = None,
- proxy: Optional[str] = None,
+ profile: str | None = None,
+ proxy: str | None = None,
local_proxy: bool = False,
remote: bool = False,
- server: Optional[str] = None,
+ server: str | None = None,
) -> None:
if not ctx.invoked_subcommand:
raise ValueError("A subcommand to invoke was not specified, the main code cannot continue.")
@@ -127,7 +127,7 @@ def search(
@search.result_callback()
-def result(service: Service, profile: Optional[str] = None, remote: bool = False, **_: Any) -> None:
+def result(service: Service, profile: str | None = None, remote: bool = False, **_: Any) -> None:
log = logging.getLogger("search")
service_tag = service.__class__.__name__
diff --git a/unshackle/commands/serve.py b/unshackle/commands/serve.py
index e65226ec..d8721c3d 100644
--- a/unshackle/commands/serve.py
+++ b/unshackle/commands/serve.py
@@ -10,7 +10,7 @@ from contextlib import suppress
from datetime import datetime
from functools import partial
from pathlib import Path
-from typing import Any, Optional
+from typing import Any
import click
from aiohttp import web
@@ -134,7 +134,7 @@ RESTART_KEYS = ("remote_only", "services_refresh_interval")
log = logging.getLogger("serve")
-def _prepare_serve(serve: dict, no_key: bool, app_config: Any = None) -> Optional[str]:
+def _prepare_serve(serve: dict, no_key: bool, app_config: Any = None) -> str | None:
"""Glob the device directories into ``serve``, validate it in place and return the api_secret.
``app_config`` is the config ``serve`` belongs to, so a reload checks key devices against the new file.
@@ -159,7 +159,7 @@ def _prepare_serve(serve: dict, no_key: bool, app_config: Any = None) -> Optiona
try:
parse_speed_limit(serve.get("global_speed_limit"))
except ValueError as e:
- raise ValueError(f"serve.global_speed_limit: {e}")
+ raise ValueError(f"serve.global_speed_limit: {e}") from e
users = serve.get("users", {})
if isinstance(users, dict):
@@ -195,7 +195,7 @@ def _prepare_serve(serve: dict, no_key: bool, app_config: Any = None) -> Optiona
def _build_cdm_config(
- serve: dict, api_secret: Optional[str], serve_widevine: bool, serve_playready: bool
+ serve: dict, api_secret: str | None, serve_widevine: bool, serve_playready: bool
) -> tuple[dict, dict]:
"""The ``app["config"]`` for the main app and the PlayReady sub-app, derived from a prepared ``serve``.
@@ -467,7 +467,7 @@ def serve(
try:
api_secret = _prepare_serve(config.serve, no_key)
except ValueError as e:
- raise click.ClickException(str(e))
+ raise click.ClickException(str(e)) from e
remote_only = remote_only or config.serve.get("remote_only", False)
if remote_only:
@@ -492,7 +492,7 @@ def serve(
try:
server_accounts = validate_server_accounts()
except ValueError as e:
- raise click.ClickException(str(e))
+ raise click.ClickException(str(e)) from e
for tag in server_accounts:
regions = server_account_regions(tag) or {}
covered = list(regions.get("regions") or []) + (["global"] if regions.get("global") else [])
diff --git a/unshackle/commands/setup.py b/unshackle/commands/setup.py
index 65dd195c..9593e563 100644
--- a/unshackle/commands/setup.py
+++ b/unshackle/commands/setup.py
@@ -8,7 +8,7 @@ import zipfile
from fnmatch import fnmatch
from functools import partial
from pathlib import Path, PurePosixPath
-from typing import Any, Optional
+from typing import Any
import click
import yaml
@@ -146,20 +146,20 @@ def versioned(tool: str, text: str) -> str:
return text.format(v=version, dashed=version.replace(".", "-"))
-def platform_spec(tool: str, system: Optional[str] = None) -> dict[str, Any]:
+def platform_spec(tool: str, system: str | None = None) -> dict[str, Any]:
"""Return a tool's entry with the overrides for this platform applied."""
entry = TOOLS[tool]
return {**entry, **entry.get(system or sys.platform, {})}
-def label(tool: str, system: Optional[str] = None) -> str:
+def label(tool: str, system: str | None = None) -> str:
"""Return the tool name with its pinned version and download size, for prompts."""
spec = platform_spec(tool, system)
text = tool if spec["version"] == "latest" else f"{tool} {spec['version']}"
return f"{text}, {spec['size']}" if spec.get("size") else text
-def asset_url(tool: str, system: Optional[str] = None, machine: Optional[str] = None) -> Optional[str]:
+def asset_url(tool: str, system: str | None = None, machine: str | None = None) -> str | None:
"""Return the download URL of a tool for a platform, or None when it has no portable build."""
machine = (machine or platform.machine()).lower()
machine = {"amd64": "x86_64", "arm64": "aarch64"}.get(machine, machine)
@@ -231,7 +231,7 @@ def install(tool: str, url: str, dest: Path) -> bool:
say(f"Downloading {tool} ({spec['version']}) ...", end=" ")
try:
with tempfile.TemporaryDirectory() as tmp:
- downloaded: Optional[Path] = None
+ downloaded: Path | None = None
for event in requests(url, Path(tmp), url.rsplit("/", 1)[-1], session=session()):
downloaded = event.get("file_downloaded") or downloaded
if downloaded is None:
@@ -287,7 +287,7 @@ def data_dirs(data_root: Path) -> dict[str, Any]:
return dirs
-def write_config(path: Path, downloads: Path, data_root: Optional[Path]) -> Optional[dict[str, Any]]:
+def write_config(path: Path, downloads: Path, data_root: Path | None) -> dict[str, Any] | None:
"""Write a minimal config to path and return its data, or None when path exists.
With a data_root, the data folders move there, out of the package folder.
diff --git a/unshackle/commands/tunnel_test.py b/unshackle/commands/tunnel_test.py
index 56e1d889..dc142eca 100644
--- a/unshackle/commands/tunnel_test.py
+++ b/unshackle/commands/tunnel_test.py
@@ -1,5 +1,4 @@
import logging
-from typing import Optional
import click
import requests
@@ -19,7 +18,7 @@ from unshackle.core.utils.redact import safe_display_url
@click.option(
"--proxy", type=str, default=None, help="Check the tunnel through this proxy, as --local-proxy --proxy does."
)
-def tunnel_test(server: Optional[str], proxy: Optional[str]) -> None:
+def tunnel_test(server: str | None, proxy: str | None) -> None:
"""Check --local-proxy before a real --remote run.
The command finds the exit IP of this machine (through --proxy when given), opens a tunnel to the server,
diff --git a/unshackle/commands/util.py b/unshackle/commands/util.py
index f12d040c..858abcb7 100644
--- a/unshackle/commands/util.py
+++ b/unshackle/commands/util.py
@@ -90,7 +90,7 @@ def crop(path: Path, aspect: str, letter: bool, offset: int, preview: bool) -> N
try:
video_track = next(iter(MediaInfo.parse(video_path).video_tracks or []))
except StopIteration:
- raise click.ClickException("There's no video tracks in the provided file.")
+ raise click.ClickException("There's no video tracks in the provided file.") from None
crop_filter = {"HEVC": "hevc_metadata", "AVC": "h264_metadata"}.get(video_track.commercial_name)
if not crop_filter:
@@ -193,7 +193,7 @@ def range_(path: Path, full: bool, preview: bool) -> None:
try:
video_track = next(iter(MediaInfo.parse(video_path).video_tracks or []))
except StopIteration:
- raise click.ClickException("There's no video tracks in the provided file.")
+ raise click.ClickException("There's no video tracks in the provided file.") from None
metadata_key = {"HEVC": "hevc_metadata", "AVC": "h264_metadata"}.get(video_track.commercial_name)
if not metadata_key:
diff --git a/unshackle/commands/wvd.py b/unshackle/commands/wvd.py
index 57e05ce2..df4121cd 100644
--- a/unshackle/commands/wvd.py
+++ b/unshackle/commands/wvd.py
@@ -1,7 +1,6 @@
import logging
import shutil
from pathlib import Path
-from typing import Optional
import click
import yaml
@@ -129,7 +128,7 @@ def dump(wvd_paths: list[Path], out_dir: Path) -> None:
if not wvd_paths:
console.log(f"[bright_blue]{config.directories.wvds.absolute()}[/] is empty...")
- for i, (wvd_path, out_path) in enumerate(zip(wvd_paths, (out_dir / x.stem for x in wvd_paths))):
+ for i, (wvd_path, out_path) in enumerate(zip(wvd_paths, (out_dir / x.stem for x in wvd_paths), strict=True)):
if i > 0:
log.info("")
@@ -203,10 +202,10 @@ def new(
name: str,
private_key: Path,
client_id: Path,
- file_hashes: Optional[Path],
+ file_hashes: Path | None,
type_: str,
level: int,
- output: Optional[Path],
+ output: Path | None,
) -> None:
"""
Make a new .WVD Widevine provision file.
@@ -223,7 +222,7 @@ def new(
# TODO: Remove need for name, create name based on Client IDs ClientInfo values
name = unidecode(name.strip().lower().replace(" ", "_"))
except UnidecodeError as e:
- raise click.UsageError(f"name: Failed to sanitise name, {e}", ctx)
+ raise click.UsageError(f"name: Failed to sanitise name, {e}", ctx) from e
if not name:
raise click.UsageError("name: Empty after sanitising", ctx)
if not private_key.is_file():
diff --git a/unshackle/core/__init__.py b/unshackle/core/__init__.py
index e0ddf85e..09b91aed 100644
--- a/unshackle/core/__init__.py
+++ b/unshackle/core/__init__.py
@@ -1,7 +1,7 @@
import hashlib
import os
+from collections.abc import Callable
from pathlib import Path
-from typing import Callable, Optional
from rich_click.patch import patch as _patch_click_help
@@ -31,8 +31,8 @@ def code_files() -> list[str]:
def code_hash(
- files: Optional[list[str]] = None,
- read: Optional[Callable[[str], bytes]] = None,
+ files: list[str] | None = None,
+ read: Callable[[str], bytes] | None = None,
) -> str:
"""
sha1 of the framework source. Two installs on the same version differ here if their code does.
diff --git a/unshackle/core/api/download_manager.py b/unshackle/core/api/download_manager.py
index 9a84229c..086ad0b5 100644
--- a/unshackle/core/api/download_manager.py
+++ b/unshackle/core/api/download_manager.py
@@ -9,12 +9,13 @@ import tempfile
import threading
import uuid
from collections import deque
+from collections.abc import Callable
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 TYPE_CHECKING, Any, Callable, Dict, List, Optional, cast
+from typing import TYPE_CHECKING, Any, cast
from unshackle.core.api.events import bus, publish_service_event
from unshackle.core.api.sanitize import sanitize_log
@@ -33,7 +34,7 @@ log = logging.getLogger("download_manager")
SENSITIVE_PARAM_KEYS = ("credential", "credentials", "password", "token", "api_key")
-def redact_parameters(parameters: Dict[str, Any]) -> Dict[str, Any]:
+def redact_parameters(parameters: dict[str, Any]) -> dict[str, Any]:
"""Return a copy of job parameters with secrets masked, safe to serialise."""
if not isinstance(parameters, dict):
return parameters
@@ -48,7 +49,7 @@ def redact_parameters(parameters: Dict[str, Any]) -> Dict[str, Any]:
return redacted
-def credential_secrets(value: Any) -> List[str]:
+def credential_secrets(value: Any) -> list[str]:
"""The secret parts of one credential in any form ``Credential.from_config`` loads."""
try:
credential = Credential.from_config(value)
@@ -63,11 +64,11 @@ def credential_secrets(value: Any) -> List[str]:
return [part for part in parts if len(part) >= 4] # short parts would blanket-replace and garble the text
-def secret_values(parameters: Dict[str, Any], service: Optional[str] = None) -> List[str]:
+def secret_values(parameters: dict[str, Any], service: str | None = None) -> list[str]:
"""Raw secret strings carried in job parameters and the credentials configured for ``service``, longest first."""
if not isinstance(parameters, dict):
return []
- secrets: List[str] = []
+ secrets: list[str] = []
if service:
from unshackle.core.config import config
@@ -92,14 +93,14 @@ def secret_values(parameters: Dict[str, Any], service: Optional[str] = None) ->
return sorted(set(secrets), key=len, reverse=True) # longest first so substrings don't survive
-def owner_id(api_key: Optional[str]) -> Optional[str]:
+def owner_id(api_key: str | None) -> str | None:
"""A short digest of an API key for the on-disk history, so the key itself never lands in a file."""
if api_key is None:
return None
return hashlib.sha256(api_key.encode()).hexdigest()[:16]
-def _redact_text(text: Optional[str], parameters: Dict[str, Any], service: Optional[str] = None) -> Optional[str]:
+def _redact_text(text: str | None, parameters: dict[str, Any], service: str | None = None) -> str | None:
"""Mask proxy userinfo and any known parameter secrets that leaked into a free-text field
(error message / details / traceback / job worker stderr) before the API returns the field."""
return redact_text(text, secret_values(parameters, service))
@@ -127,54 +128,54 @@ class DownloadJob:
created_time: datetime
service: str
title_id: str
- parameters: Dict[str, Any]
+ parameters: dict[str, Any]
- started_time: Optional[datetime] = None
- completed_time: Optional[datetime] = None
+ started_time: datetime | None = None
+ completed_time: datetime | None = None
progress: float = 0.0
- output_files: List[str] = field(default_factory=list)
- error_message: Optional[str] = None
- error_details: Optional[str] = None
- error_code: Optional[str] = None
- error_traceback: Optional[str] = None
- worker_stderr: Optional[str] = None
+ output_files: list[str] = field(default_factory=list)
+ error_message: str | None = None
+ error_details: str | None = None
+ error_code: str | None = None
+ error_traceback: str | None = None
+ worker_stderr: str | None = None
- phase: Optional[str] = None
- title: Optional[str] = None
- current_title: Optional[str] = None
+ phase: str | None = None
+ title: str | None = None
+ current_title: str | None = None
completed_tracks: int = 0
total_tracks: int = 0
- active_tracks: List[str] = field(default_factory=list)
- track_progress: List[Dict[str, Any]] = field(default_factory=list)
+ active_tracks: list[str] = field(default_factory=list)
+ track_progress: list[dict[str, Any]] = field(default_factory=list)
segments_done: float = 0.0
segments_total: float = 0.0
- speed: Optional[str] = None
+ speed: str | None = None
# Prompt a service raised through prompt_user() and waits on; answered by submit_input().
- input_prompt: Optional[str] = None
+ input_prompt: str | None = None
# Message a service shows through show_notice() while it waits for an approval; needs no answer.
- notice: Optional[str] = None
+ notice: str | None = None
# Subtitles skipped under skip_subtitle_errors (non-fatal). Each entry is a dl.SkippedSubtitle
# dict (id / language / title) so a client can report which weren't available.
- skipped_subtitles: List[Dict[str, Any]] = field(default_factory=list)
+ skipped_subtitles: list[dict[str, Any]] = field(default_factory=list)
# Titles skipped because a requested track or language is missing; each a dl.SkippedTitle (title / reason).
- skipped_titles: List[Dict[str, Any]] = field(default_factory=list)
+ skipped_titles: list[dict[str, Any]] = field(default_factory=list)
cancel_event: threading.Event = field(default_factory=threading.Event)
# Guards against writing the same job to the persistent history file twice.
history_recorded: bool = False
- redacted: Optional[tuple[tuple, Dict[str, Optional[str]]]] = field(default=None, repr=False, compare=False)
+ redacted: tuple[tuple, dict[str, str | None]] | None = field(default=None, repr=False, compare=False)
# X-Secret-Key that created the job; scopes per-caller access, never serialized into to_dict().
- owner_key: Optional[str] = None
+ owner_key: str | None = None
- def to_dict(self, include_full_details: bool = False) -> Dict[str, Any]:
+ def to_dict(self, include_full_details: bool = False) -> dict[str, Any]:
"""Convert job to dictionary for JSON response."""
- result: Dict[str, Any] = {
+ result: dict[str, Any] = {
"job_id": self.job_id,
"status": self.status.value,
"created_time": self.created_time.isoformat(),
@@ -207,7 +208,7 @@ class DownloadJob:
raw,
{
name: redact_path(_redact_text(text, self.parameters, self.service))
- for name, text in zip(names, raw)
+ for name, text in zip(names, raw, strict=True)
},
)
result.update(
@@ -285,9 +286,7 @@ def record_job_history(job: DownloadJob) -> None:
log.warning(f"Could not write job history: {e}")
-def read_job_history(
- limit: int = 100, service: Optional[str] = None, owner: Optional[str] = None
-) -> List[Dict[str, Any]]:
+def read_job_history(limit: int = 100, service: str | None = None, owner: str | None = None) -> list[dict[str, Any]]:
"""Read persisted job history, newest first.
With ``owner`` (an :func:`owner_id`), only that owner's entries and ownerless legacy
@@ -301,7 +300,7 @@ def read_job_history(
except OSError as e:
log.warning(f"Could not read job history: {e}")
return []
- entries: List[Dict[str, Any]] = []
+ entries: list[dict[str, Any]] = []
for line in lines:
line = line.strip()
if not line:
@@ -321,7 +320,7 @@ def read_job_history(
return entries[:limit] if limit and limit > 0 else entries
-def delete_job_history(job_id: str, allowed: Optional[set] = None, owner: Optional[str] = None) -> bool:
+def delete_job_history(job_id: str, allowed: set | None = None, owner: str | None = None) -> bool:
"""Remove a history entry by job_id (rewriting the file). Returns True if it removed one.
When you give `allowed`, this function treats an entry outside the caller's service
@@ -335,7 +334,7 @@ def delete_job_history(job_id: str, allowed: Optional[set] = None, owner: Option
except OSError as e:
log.warning(f"Could not read job history: {e}")
return False
- kept: List[str] = []
+ kept: list[str] = []
deleted = False
for line in lines:
stripped = line.strip()
@@ -362,7 +361,7 @@ def delete_job_history(job_id: str, allowed: Optional[set] = None, owner: Option
return True
-def client_sent_keys(params: Dict[str, Any]) -> set[str]:
+def client_sent_keys(params: dict[str, Any]) -> set[str]:
"""Pop the server's ``client_keys`` stamp; a job without one counts every parameter as client-sent."""
return set(params.pop("client_keys", params))
@@ -371,9 +370,9 @@ def perform_download(
job_id: str,
service: str,
title_id: str,
- params: Dict[str, Any],
- progress_callback: Optional[Callable[[Dict[str, Any]], None]] = None,
-) -> List[str]:
+ params: dict[str, Any],
+ progress_callback: Callable[[dict[str, Any]], None] | None = None,
+) -> list[str]:
"""Do the synchronous download work for a job.
``params`` holds the API's form of the ``dl`` options; ``api_plan`` checks and casts them into the dl context,
@@ -455,14 +454,14 @@ def perform_download(
except RunStopped as exc:
log.debug("Stdout: %s", stdout_capture.getvalue())
- raise APIError(APIErrorCode.DOWNLOAD_ERROR, f"Download failed: {exc.reason}")
+ raise APIError(APIErrorCode.DOWNLOAD_ERROR, f"Download failed: {exc.reason}") from exc
except SystemExit as exc:
if exc.code != 0:
log.error(f"Download exited with code {exc.code}")
log.debug("Stdout: %s", stdout_capture.getvalue())
log.debug("Stderr: %s", stderr_capture.getvalue())
- raise APIError(APIErrorCode.DOWNLOAD_ERROR, f"Download failed with exit code {exc.code}")
+ raise APIError(APIErrorCode.DOWNLOAD_ERROR, f"Download failed with exit code {exc.code}") from exc
outcome = dl_instance.outcome()
except Exception as exc: # noqa: BLE001 - propagate to caller
@@ -493,25 +492,23 @@ class DownloadQueueManager:
self.max_concurrent_downloads = max_concurrent_downloads
self.job_retention_hours = job_retention_hours
- self._jobs: Dict[str, DownloadJob] = {}
+ self._jobs: dict[str, DownloadJob] = {}
self._job_queue: asyncio.Queue = asyncio.Queue()
# asyncio.Queue has no reorder, so prioritized jobs go in a deque workers drain first.
self._priority_jobs: deque = deque()
self._promoted_ids: set = set() # their stale FIFO-queue copies get skipped via this set
- self._active_downloads: Dict[str, asyncio.Task] = {}
- self._download_processes: Dict[str, asyncio.subprocess.Process] = {}
- self._job_temp_files: Dict[str, Dict[str, str]] = {}
+ self._active_downloads: dict[str, asyncio.Task] = {}
+ self._download_processes: dict[str, asyncio.subprocess.Process] = {}
+ self._job_temp_files: dict[str, dict[str, str]] = {}
self._workers_started = False
self._shutdown_event = asyncio.Event()
- self._subscribers: Dict[str, List[asyncio.Queue]] = {}
+ self._subscribers: dict[str, list[asyncio.Queue]] = {}
log.info(
f"Initialized download queue manager: max_concurrent={max_concurrent_downloads}, retention_hours={job_retention_hours}"
)
- def create_job(
- self, service: str, title_id: str, owner_key: Optional[str] = None, **parameters: Any
- ) -> DownloadJob:
+ def create_job(self, service: str, title_id: str, owner_key: str | None = None, **parameters: Any) -> DownloadJob:
"""Make a new download job and add it to the queue."""
from unshackle.core.api.session_store import refuse_while_draining
@@ -534,11 +531,11 @@ class DownloadQueueManager:
bus.publish("job", {"event": "queued", **job.to_dict(include_full_details=True)})
return job
- def get_job(self, job_id: str) -> Optional[DownloadJob]:
+ def get_job(self, job_id: str) -> DownloadJob | None:
"""Get job by ID."""
return self._jobs.get(job_id)
- def list_jobs(self) -> List[DownloadJob]:
+ def list_jobs(self) -> list[DownloadJob]:
"""Get all jobs."""
return list(self._jobs.values())
@@ -585,7 +582,7 @@ class DownloadQueueManager:
schedule_pending_reload()
@staticmethod
- def put(queue: asyncio.Queue, item: Optional[Dict[str, Any]]) -> None:
+ def put(queue: asyncio.Queue, item: dict[str, Any] | None) -> None:
"""Enqueue an item, discarding the oldest when a slow listener has filled the queue."""
try:
queue.put_nowait(item)
@@ -651,7 +648,7 @@ class DownloadQueueManager:
log.info(f"Removed job {sanitize_log(job_id)}")
return True
- def clear_finished_jobs(self, owner_key: Optional[str] = None) -> int:
+ def clear_finished_jobs(self, owner_key: str | None = None) -> int:
"""Remove terminal (completed/failed/cancelled) jobs, returning the count removed.
With ``owner_key`` only that key's jobs and ownerless legacy jobs go.
@@ -739,7 +736,7 @@ class DownloadQueueManager:
for job_id, process in list(self._download_processes.items()):
try:
await asyncio.wait_for(process.wait(), timeout=5)
- except asyncio.TimeoutError:
+ except TimeoutError:
log.warning(f"Worker process for job {job_id} did not exit, killing")
process.kill()
await process.wait()
@@ -806,7 +803,7 @@ class DownloadQueueManager:
if job.job_id in self._active_downloads:
del self._active_downloads[job.job_id]
- except asyncio.TimeoutError:
+ except TimeoutError:
continue
except Exception as e:
log.error(f"Worker {worker_name} error: {e}")
@@ -839,7 +836,7 @@ class DownloadQueueManager:
log.error(f"Download failed for job {job.job_id}: {_redact_text(str(e), job.parameters, job.service)}")
raise
- def worker_speed_limit(self) -> Optional[float]:
+ def worker_speed_limit(self) -> float | None:
"""Return one job worker's share of the locked global speed limit, or None when unset."""
requests_downloader = importlib.import_module("unshackle.core.downloaders.requests")
@@ -848,7 +845,7 @@ class DownloadQueueManager:
return None
return limiter.rate / max(1, self.max_concurrent_downloads)
- async def run_download_async(self, job: DownloadJob) -> List[str]:
+ async def run_download_async(self, job: DownloadJob) -> list[str]:
"""Invoke a job worker subprocess to do the download."""
payload = {
@@ -894,8 +891,8 @@ class DownloadQueueManager:
stdout_bytes = b""
stderr_bytes = b""
- last_progress_stat: Optional[tuple[int, int]] = None # (st_mtime_ns, st_size) of last parse
- last_published: Optional[Dict[str, Any]] = None
+ last_progress_stat: tuple[int, int] | None = None # (st_mtime_ns, st_size) of last parse
+ last_published: dict[str, Any] | None = None
try:
while True:
@@ -906,7 +903,7 @@ class DownloadQueueManager:
stat = os.stat(progress_path)
stat_key = (stat.st_mtime_ns, stat.st_size)
if stat_key != last_progress_stat:
- with open(progress_path, "r", encoding="utf-8") as handle:
+ with open(progress_path, encoding="utf-8") as handle:
progress_data = json.load(handle)
prompt_before = job.input_prompt
if progress_data.get("phase") and progress_data["phase"] != job.phase:
@@ -964,7 +961,7 @@ class DownloadQueueManager:
process.terminate()
try:
await asyncio.wait_for(communicate_task, timeout=5)
- except asyncio.TimeoutError:
+ except TimeoutError:
log.warning(f"Worker process for job {job.job_id} did not terminate, killing")
process.kill()
await asyncio.wait_for(communicate_task, timeout=5)
@@ -987,10 +984,10 @@ class DownloadQueueManager:
else:
log.debug(f"Worker stderr for job {job.job_id}: {safe_stderr}")
- result_data: Optional[Dict[str, Any]] = None
+ result_data: dict[str, Any] | None = None
for attempt in range(5):
try:
- with open(result_path, "r", encoding="utf-8") as handle:
+ with open(result_path, encoding="utf-8") as handle:
result_data = json.load(handle)
except FileNotFoundError:
log.error(f"Result file missing for job {job.job_id}")
@@ -1049,7 +1046,7 @@ class DownloadQueueManager:
# Global instance
-download_manager: Optional[DownloadQueueManager] = None
+download_manager: DownloadQueueManager | None = None
def get_download_manager() -> DownloadQueueManager:
@@ -1077,10 +1074,10 @@ def busy_services() -> set[str]:
return busy
-_reload_task: Optional[asyncio.Task[None]] = None
+_reload_task: asyncio.Task[None] | None = None
-def schedule_pending_reload(tag: Optional[str] = None) -> None:
+def schedule_pending_reload(tag: str | None = None) -> None:
"""Swap in staged service updates whose last job or remote session has ended, off the event loop.
Runs on every job completion and remote session removal, because a busy service on a popular
diff --git a/unshackle/core/api/download_worker.py b/unshackle/core/api/download_worker.py
index edc6eacf..c8c87ec5 100644
--- a/unshackle/core/api/download_worker.py
+++ b/unshackle/core/api/download_worker.py
@@ -11,8 +11,9 @@ import sys
import threading
import time
import traceback
+from collections.abc import Callable
from pathlib import Path
-from typing import Any, Callable, Dict
+from typing import Any
from uuid import uuid4
from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT
@@ -25,7 +26,7 @@ from .download_manager import perform_download
log = logging.getLogger("download_worker")
-def read_payload(path: Path) -> Dict[str, Any]:
+def read_payload(path: Path) -> dict[str, Any]:
with path.open("r", encoding="utf-8") as handle:
return json.load(handle)
@@ -33,7 +34,7 @@ def read_payload(path: Path) -> Dict[str, Any]:
_replace_lock = threading.Lock()
-def write_result(path: Path, payload: Dict[str, Any]) -> None:
+def write_result(path: Path, payload: dict[str, Any]) -> None:
"""Write the payload with an atomic replace, because the parent polls this file during the write.
Each call gets its own temp name, so two threads writing this destination cannot replace away
@@ -60,7 +61,7 @@ def write_result(path: Path, payload: Dict[str, Any]) -> None:
raise
-def relay_prompts(progress_callback: Callable[[Dict[str, Any]], None]) -> None:
+def relay_prompts(progress_callback: Callable[[dict[str, Any]], None]) -> None:
"""Send each prompt_user() prompt to the parent as ``input_prompt`` progress, and read the answer from stdin.
The parent writes each answer as one JSON string per line, so an answer can hold a newline. The reader
@@ -97,7 +98,7 @@ def relay_prompts(progress_callback: Callable[[Dict[str, Any]], None]) -> None:
set_notice_handler(lambda message: progress_callback({"notice": message}))
-def apply_payload_speed_limit(payload: Dict[str, Any]) -> None:
+def apply_payload_speed_limit(payload: dict[str, Any]) -> None:
"""Lock this worker's share of the server speed limit so the job cannot clear it."""
limit = payload.get("speed_limit")
if not limit:
@@ -118,7 +119,7 @@ def main(argv: list[str]) -> int:
result_path = Path(argv[2])
progress_path = Path(argv[3]) if len(argv) > 3 else None
- result: Dict[str, Any] = {}
+ result: dict[str, Any] = {}
exit_code = 0
try:
@@ -132,10 +133,10 @@ def main(argv: list[str]) -> int:
log.info(f"Worker starting job {job_id} ({service}:{title_id})")
# Merged so sparse keys (current_title, output_files) survive later writes.
- progress_state: Dict[str, Any] = {}
+ progress_state: dict[str, Any] = {}
progress_lock = threading.Lock()
- def progress_callback(progress_data: Dict[str, Any]) -> None:
+ def progress_callback(progress_data: dict[str, Any]) -> None:
"""Write progress updates to file for main process to read."""
if progress_path:
try:
diff --git a/unshackle/core/api/errors.py b/unshackle/core/api/errors.py
index ab14f2a7..0fd546b2 100644
--- a/unshackle/core/api/errors.py
+++ b/unshackle/core/api/errors.py
@@ -9,7 +9,7 @@ from __future__ import annotations
import secrets
import traceback
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from typing import Any
from aiohttp import web
@@ -118,7 +118,7 @@ def build_error_response(
"error_code": error_code,
"message": f"{message} (ref {ref})",
"ref": ref,
- "timestamp": datetime.now(timezone.utc).isoformat(),
+ "timestamp": datetime.now(UTC).isoformat(),
}
if details:
diff --git a/unshackle/core/api/events.py b/unshackle/core/api/events.py
index 51409b99..b150550a 100644
--- a/unshackle/core/api/events.py
+++ b/unshackle/core/api/events.py
@@ -6,18 +6,18 @@ import asyncio
import threading
from collections import deque
from contextlib import suppress
-from typing import Any, Deque, Dict, List, Optional
+from typing import Any
class EventBus:
"""Fan events out to every subscriber queue; drop when a subscriber falls behind."""
def __init__(self, history: int = 20000) -> None:
- self._subs: List[asyncio.Queue] = []
+ self._subs: list[asyncio.Queue] = []
self.seq = 0
- self.history: Deque[Dict[str, Any]] = deque(maxlen=history)
- self._loop: Optional[asyncio.AbstractEventLoop] = None
- self._loop_thread: Optional[threading.Thread] = None
+ self.history: deque[dict[str, Any]] = deque(maxlen=history)
+ self._loop: asyncio.AbstractEventLoop | None = None
+ self._loop_thread: threading.Thread | None = None
self._lock = threading.RLock()
def subscribe(self) -> asyncio.Queue:
@@ -31,7 +31,7 @@ class EventBus:
with suppress(ValueError):
self._subs.remove(queue)
- def since(self, seq: int) -> List[Dict[str, Any]]:
+ def since(self, seq: int) -> list[dict[str, Any]]:
"""Return the history after ``seq``.
``deque.copy()`` is one C call, so it is atomic against an append from another thread.
@@ -40,7 +40,7 @@ class EventBus:
"""
return [item for item in self.history.copy() if item["seq"] > seq]
- def publish(self, event: str, data: Dict[str, Any]) -> None:
+ def publish(self, event: str, data: dict[str, Any]) -> None:
"""Record and fan out one event; safe to call from any thread.
The lock is re-entrant because a log call inside it publishes again. ``seq``
@@ -62,7 +62,7 @@ class EventBus:
self._loop.call_soon_threadsafe(_put_drop, queue, item)
-def _put_drop(queue: asyncio.Queue, item: Dict[str, Any]) -> None:
+def _put_drop(queue: asyncio.Queue, item: dict[str, Any]) -> None:
with suppress(asyncio.QueueFull):
queue.put_nowait(item)
@@ -70,18 +70,18 @@ def _put_drop(queue: asyncio.Queue, item: Dict[str, Any]) -> None:
bus = EventBus()
-def publish_service_event(action: str, tags: List[str], errors: Optional[List[str]] = None) -> None:
+def publish_service_event(action: str, tags: list[str], errors: list[str] | None = None) -> None:
"""Tell dashboard listeners that services were staged, applied, or failed to reload.
Lives here rather than in ``core.services`` so the service loader never imports the API layer.
"""
- data: Dict[str, Any] = {"action": action, "tags": list(tags)}
+ data: dict[str, Any] = {"action": action, "tags": list(tags)}
if errors:
data["errors"] = list(errors)
bus.publish("service", data)
-def publish_refresh_events(repos: List[Dict[str, Any]]) -> None:
+def publish_refresh_events(repos: list[dict[str, Any]]) -> None:
"""Publish the ``service`` events one ``refresh_and_reload`` result implies.
A tag counts as applied only when it changed, was not deferred, and did not fail to
diff --git a/unshackle/core/api/handlers.py b/unshackle/core/api/handlers.py
index a970d7a4..f1351d7a 100644
--- a/unshackle/core/api/handlers.py
+++ b/unshackle/core/api/handlers.py
@@ -11,12 +11,14 @@ import time
import uuid
import zlib
from collections import Counter
+from collections.abc import Callable, Iterable
+from collections.abc import Set as AbstractSet
from contextlib import suppress
from dataclasses import dataclass, field
from functools import partial
from http.cookiejar import CookieJar
from pathlib import Path
-from typing import AbstractSet, Any, Callable, Dict, Iterable, List, Optional, Set
+from typing import Any, Optional
from urllib.parse import urlsplit
import click
@@ -118,9 +120,7 @@ LIST_HANDLER_TRANSPORT_KEYS = {
}
-def load_full_cdm(
- service: str, profile: Optional[str], cdm_type: Optional[str] = None, app_config: Any = None
-) -> Optional[Any]:
+def load_full_cdm(service: str, profile: str | None, cdm_type: str | None = None, app_config: Any = None) -> Any | None:
"""Load a real CDM object for the given service.
Services often touch ``ctx.obj.cdm.security_level`` / ``.device_type`` / ``.system_id``
@@ -153,7 +153,7 @@ def load_full_cdm(
return resolve_server_cdm(service, profile, cdm_type, app_config)
-def cast_or_refuse(params: Iterable[click.Parameter], ctx: Any, options: Dict[str, Any]) -> Dict[str, Any]:
+def cast_or_refuse(params: Iterable[click.Parameter], ctx: Any, options: dict[str, Any]) -> dict[str, Any]:
"""``cast_service_options``, with a refused value as ``400 INVALID_PARAMETERS``."""
try:
return cast_service_options(params, ctx, options)
@@ -168,7 +168,7 @@ def instantiate_service(
parent_ctx: Any,
service_module: Any,
title: str,
- data: Optional[Dict[str, Any]] = None,
+ data: dict[str, Any] | None = None,
transport_keys: AbstractSet[str] = frozenset(),
) -> Any:
"""Instantiate a service by invoking its click cli with the ``service_options`` in ``data``.
@@ -193,7 +193,7 @@ def instantiate_service(
def server_login_material(
- data: Dict[str, Any], normalized_service: str, account: Optional[str], profile: Optional[str]
+ data: dict[str, Any], normalized_service: str, account: str | None, profile: str | None
) -> tuple:
"""(cookies, credential) for a list or search call.
@@ -210,7 +210,7 @@ def server_login_material(
return load_client_cookies(data.get("cookies")), client_credential(data)
-def client_credential(data: Dict[str, Any]) -> Any:
+def client_credential(data: dict[str, Any]) -> Any:
"""The Credential a client sent as ``credentials``, or None when it sent no username."""
from unshackle.core.credential import Credential
@@ -222,7 +222,7 @@ def client_credential(data: Dict[str, Any]) -> Any:
)
-def api_key_namespace(request: Optional[web.Request]) -> str:
+def api_key_namespace(request: web.Request | None) -> str:
"""Name of the caller's cache directories, derived from its API key so no caller can guess another's."""
return key_namespace(caller_key(request))
@@ -271,13 +271,13 @@ def write_client_cache(cache_data: Any, cache_tag: str) -> None:
log.warning(f"Skipping session cache key {sanitize_log(key)}: {e}")
-def collect_cache_files(cache_tag: str) -> Dict[str, str]:
+def collect_cache_files(cache_tag: str) -> dict[str, str]:
"""Read the cache directory ``cache_tag`` back as a ``cache`` map for the client.
The map has the same form that :func:`write_client_cache` reads. It leaves out the
``titles_`` files, because they hold no login state.
"""
- cache_data: Dict[str, str] = {}
+ cache_data: dict[str, str] = {}
cache_dir = config.directories.cache / cache_tag
if cache_dir.is_dir():
for f in sorted(cache_dir.rglob("*.json")):
@@ -301,17 +301,17 @@ class RequestCache:
"""
def __init__(self) -> None:
- self.tag: Optional[str] = None
+ self.tag: str | None = None
self.client_auth = False
def attach(
self,
service_instance: Any,
- data: Dict[str, Any],
+ data: dict[str, Any],
normalized_service: str,
- request: Optional[web.Request],
+ request: web.Request | None,
client_login: bool,
- user_config: Dict[str, Any],
+ user_config: dict[str, Any],
) -> None:
"""Give the service a new cache directory, seeded from the client's ``cache``.
@@ -335,7 +335,7 @@ class RequestCache:
write_client_cache(cache_data, self.tag)
self.client_auth = client_login or bool(cache_data)
- async def json_response(self, payload: Dict[str, Any]) -> web.Response:
+ async def json_response(self, payload: dict[str, Any]) -> web.Response:
"""Answer with ``payload``, plus the updated ``cache`` for a client that logged in itself."""
if self.tag and self.client_auth:
cache_data = await asyncio.to_thread(collect_cache_files, self.tag)
@@ -362,7 +362,7 @@ def remote_list(name: Any) -> list[dict]:
return services
-def remote_server(data: Dict[str, Any], request: Optional[web.Request] = None) -> Optional[tuple[str, dict]]:
+def remote_server(data: dict[str, Any], request: web.Request | None = None) -> tuple[str, dict] | None:
"""The ``remote_services`` server and service a request names in ``remote``, as the CLI resolves it and the
caller's key allows it; None for a local service. Blocks on the remote list."""
from unshackle.core.remote_service import find_remote_service
@@ -382,7 +382,7 @@ def remote_server(data: Dict[str, Any], request: Optional[web.Request] = None) -
return name, info
-def geofence_proxy(data: Dict[str, Any], info: dict, request: Optional[web.Request] = None) -> Dict[str, Any]:
+def geofence_proxy(data: dict[str, Any], info: dict, request: web.Request | None = None) -> dict[str, Any]:
"""``{"proxy": region}`` for a geofenced remote service the request sends no proxy for; else {}.
The remote counterpart of a local service's geofence auto-proxy, under the same ``server_proxy`` gate.
@@ -395,8 +395,8 @@ def geofence_proxy(data: Dict[str, Any], info: dict, request: Optional[web.Reque
async def relay_target(
- data: Dict[str, Any], request: Optional[web.Request] = None
-) -> tuple[Optional[str], Optional[dict], Dict[str, Any]]:
+ data: dict[str, Any], request: web.Request | None = None
+) -> tuple[str | None, dict | None, dict[str, Any]]:
"""``(server, info, data)`` for a request naming ``remote``, ``data`` carrying the resolved tag and any
geofence proxy; ``(None, None, data)`` for a local one."""
if not data.get("remote"):
@@ -408,7 +408,7 @@ async def relay_target(
return server, info, {**data, "service": info["tag"], **geofence_proxy(data, info, request)}
-def relay_label(data: Dict[str, Any]) -> str:
+def relay_label(data: dict[str, Any]) -> str:
"""How the remote server's dashboard names this relay: the REST client's own ``client_name``, if it sent one."""
name = data.get("client_name")
return f"serve ({name[:64] if isinstance(name, str) and name.strip() else 'REST API'})"
@@ -420,7 +420,7 @@ def relay_error(exc: Any, service: str) -> APIError:
def relay_service(
- data: Dict[str, Any], server: str, profile: Optional[str], title_id: str, request: Optional[web.Request] = None
+ data: dict[str, Any], server: str, profile: str | None, title_id: str, request: web.Request | None = None
) -> Any:
"""A RemoteService for ``data["service"]`` on a ``remote_services`` server, with this server's login files."""
from unshackle.core.remote_service import make_remote_service
@@ -438,7 +438,7 @@ def relay_service(
def setup_remote_service(
- data: Dict[str, Any], server: str, profile: Optional[str], title_id: str, request: Optional[web.Request] = None
+ data: dict[str, Any], server: str, profile: str | None, title_id: str, request: web.Request | None = None
) -> Any:
"""Open and authenticate a remote session and fetch its titles; the caller must close() it."""
from unshackle.core.remote_service import RemoteError
@@ -478,7 +478,7 @@ class RemoteLogin:
bridge: InputBridge = field(default_factory=InputBridge)
-_remote_logins: Dict[str, RemoteLogin] = {}
+_remote_logins: dict[str, RemoteLogin] = {}
async def remote_logins_handler(request: web.Request) -> web.Response:
@@ -499,7 +499,7 @@ async def remote_logins_handler(request: web.Request) -> web.Response:
return web.json_response({"logins": logins})
-async def remote_login_input_handler(login_id: str, data: Dict[str, Any], request: web.Request) -> web.Response:
+async def remote_login_input_handler(login_id: str, data: dict[str, Any], request: web.Request) -> web.Response:
"""Answer the prompt (an OTP, a PIN) a remote login a list call waits on is asking."""
login = _remote_logins.get(login_id)
if login is None or not (is_admin(request) or login.owner == caller_key(request)):
@@ -525,18 +525,18 @@ class RemoteLease:
key: tuple = field(repr=False) # holds the caller's API key
lock: asyncio.Lock = field(default_factory=asyncio.Lock)
service: Any = None
- error: Optional[Exception] = None
+ error: Exception | None = None
busy: int = 0
used: float = 0.0
dead: bool = False
-_remote_pool: Dict[tuple, RemoteLease] = {}
+_remote_pool: dict[tuple, RemoteLease] = {}
_remote_sweeper: Optional["asyncio.Task[None]"] = None
def remote_pool_key(
- data: Dict[str, Any], server: str, info: dict, profile: Optional[str], title_id: str, request: Optional[web.Request]
+ data: dict[str, Any], server: str, info: dict, profile: str | None, title_id: str, request: web.Request | None
) -> tuple:
"""What opens a remote session for one API key; requests that differ only in episode selection share one."""
from unshackle.core.remote_service import remote_service_params
@@ -555,7 +555,7 @@ def remote_pool_key(
)
-def close_remote_services(services: List[Any]) -> None:
+def close_remote_services(services: list[Any]) -> None:
for service in services:
with suppress(Exception, SystemExit):
service.close()
@@ -593,12 +593,12 @@ def reset_remote_pool() -> None:
async def lease_remote_service(
- data: Dict[str, Any],
+ data: dict[str, Any],
server: str,
info: dict,
- profile: Optional[str],
+ profile: str | None,
title_id: str,
- request: Optional[web.Request] = None,
+ request: web.Request | None = None,
fresh_titles: bool = False,
) -> RemoteLease:
"""A pooled lease on an authenticated RemoteService with its titles fetched; return it with release_remote_service.
@@ -653,12 +653,12 @@ async def remote_call(lease: RemoteLease, method: Callable[..., Any], *args: Any
async def leased_titles(
- data: Dict[str, Any],
+ data: dict[str, Any],
server: str,
info: dict,
- profile: Optional[str],
+ profile: str | None,
title_id: str,
- request: Optional[web.Request],
+ request: web.Request | None,
fresh_titles: bool,
) -> tuple[RemoteLease, Any]:
"""Lease a remote session and get its titles, once more on a new session when the pooled one broke.
@@ -676,14 +676,12 @@ async def leased_titles(
raise AssertionError("unreachable")
-def remote_services_info(name: str, allowed: Optional[List[str]]) -> List[Dict[str, Any]]:
+def remote_services_info(name: str, allowed: list[str] | None) -> list[dict[str, Any]]:
"""The services of one ``remote_services`` server, each marked with that server's name in ``remote``."""
return [{**svc, "remote": name} for svc in remote_list(name) if allowed is None or svc.get("tag") in allowed]
-def remote_search(
- data: Dict[str, Any], server: str, query: str, request: Optional[web.Request] = None
-) -> Dict[str, Any]:
+def remote_search(data: dict[str, Any], server: str, query: str, request: web.Request | None = None) -> dict[str, Any]:
"""Run a search on a ``remote_services`` server, sending this server's login files as ``search --remote`` does."""
from unshackle.core.remote_service import RemoteError
@@ -699,12 +697,12 @@ def remote_search(
def setup_list_service(
- data: Dict[str, Any],
+ data: dict[str, Any],
normalized_service: str,
- profile: Optional[str],
+ profile: str | None,
title_id: str,
- request: Optional[web.Request] = None,
- request_cache: Optional[RequestCache] = None,
+ request: web.Request | None = None,
+ request_cache: RequestCache | None = None,
) -> Any:
"""Assemble and authenticate a service instance for list_titles / list_tracks.
@@ -746,12 +744,12 @@ def setup_list_service(
def run_service_search(
- data: Dict[str, Any],
+ data: dict[str, Any],
normalized_service: str,
query: str,
- request: Optional[web.Request] = None,
- request_cache: Optional[RequestCache] = None,
-) -> List[Dict[str, Any]]:
+ request: web.Request | None = None,
+ request_cache: RequestCache | None = None,
+) -> list[dict[str, Any]]:
"""Assemble and authenticate a service instance, then run its search.
The same preamble as :func:`setup_list_service`, without the service option extras,
@@ -797,7 +795,7 @@ def run_service_search(
APIErrorCode.SERVICE_ERROR,
f"Failed to initialize service: {exc}",
details={"service": normalized_service},
- )
+ ) from exc
if account:
account_tag = f"_accounts/{normalized_service}/{account}"
@@ -809,7 +807,7 @@ def run_service_search(
if not anonymous:
service_instance.authenticate(cookies, credential)
- results: List[Dict[str, Any]] = []
+ results: list[dict[str, Any]] = []
try:
for result in service_instance.search():
results.append(result.to_dict())
@@ -818,21 +816,21 @@ def run_service_search(
APIErrorCode.SERVICE_ERROR,
f"Search is not supported by {normalized_service}",
details={"service": normalized_service},
- )
+ ) from None
return results
-def allowed_services_for_key(secret_key: Optional[str]) -> Optional[List[str]]:
+def allowed_services_for_key(secret_key: str | None) -> list[str] | None:
"""Effective service allowlist for an API key: the global list intersected with the key's.
Returns None when nothing restricts the services.
"""
global_allowed = config.serve.get("services")
- global_set: Optional[set[str]] = None
+ global_set: set[str] | None = None
if global_allowed:
global_set = {Services.get_tag(s) for s in global_allowed}
- key_set: Optional[set[str]] = None
+ key_set: set[str] | None = None
if secret_key:
users = config.serve.get("users", {})
user_config = users.get(secret_key, {})
@@ -851,12 +849,12 @@ def allowed_services_for_key(secret_key: Optional[str]) -> Optional[List[str]]:
return list(result)
-def get_allowed_services(request: Optional[web.Request] = None) -> Optional[List[str]]:
+def get_allowed_services(request: web.Request | None = None) -> list[str] | None:
"""The effective service allowlist for a request's API key, or None when unrestricted."""
return allowed_services_for_key(request_secret_key(request) if request else None)
-def is_admin(request: Optional[web.Request]) -> bool:
+def is_admin(request: web.Request | None) -> bool:
"""Whether the calling key is the admin secret (no ``users`` entry) or has ``admin: true``."""
if not request:
return True
@@ -864,14 +862,14 @@ def is_admin(request: Optional[web.Request]) -> bool:
return user_config is None or (isinstance(user_config, dict) and user_config.get("admin") is True)
-def require_admin(request: Optional[web.Request]) -> None:
+def require_admin(request: web.Request | None) -> None:
"""FORBIDDEN unless the calling key is the admin secret or has ``admin: true`` in ``serve.users``."""
if is_admin(request):
return
raise APIError(APIErrorCode.FORBIDDEN, "This API key may not run server maintenance.")
-def serve_user_config(api_key: str) -> Dict[str, Any]:
+def serve_user_config(api_key: str) -> dict[str, Any]:
"""The ``serve.users`` entry for an API key.
An API key absent from ``serve.users`` (the admin secret, or any caller in no-key mode) keeps
@@ -890,20 +888,20 @@ def serve_user_config(api_key: str) -> Dict[str, Any]:
class KeyCdmConfig:
"""The app config as one API key sees it: ``cdm`` is the key's map, every other setting is the server's."""
- def __init__(self, cdm: Dict[str, Any]) -> None:
+ def __init__(self, cdm: dict[str, Any]) -> None:
self.cdm = cdm
def __getattr__(self, name: str) -> Any:
return getattr(config, name)
-def own_cdm(user_config: Optional[Dict[str, Any]]) -> Dict[str, Any]:
+def own_cdm(user_config: dict[str, Any] | None) -> dict[str, Any]:
"""The API key's own ``cdm`` map; empty when it sets none."""
own = (user_config or {}).get("cdm")
return own if isinstance(own, dict) else {}
-def key_cdm_config(user_config: Optional[Dict[str, Any]]) -> Any:
+def key_cdm_config(user_config: dict[str, Any] | None) -> Any:
"""The config the CDM lookups read for an API key: ``config`` itself unless the key maps a device of its own.
Each service entry of the key's own ``cdm`` replaces the server's whole entry for that service.
@@ -915,19 +913,19 @@ def key_cdm_config(user_config: Optional[Dict[str, Any]]) -> Any:
return KeyCdmConfig({**{t: e for t, e in (config.cdm or {}).items() if str(t).lower() not in tags}, **own})
-def key_service_config(user_config: Optional[Dict[str, Any]], service: str) -> Dict[str, Any]:
+def key_service_config(user_config: dict[str, Any] | None, service: str) -> dict[str, Any]:
"""The API key's own ``service_config`` block for ``service``; empty when it sets none."""
blocks = (user_config or {}).get("service_config")
block = ci_get(blocks, Services.get_tag(service)) if isinstance(blocks, dict) else None
return block if isinstance(block, dict) else {}
-def key_owns_identity(user_config: Optional[Dict[str, Any]], service: str) -> bool:
+def key_owns_identity(user_config: dict[str, Any] | None, service: str) -> bool:
"""Whether the API key sets its own device or service config for ``service``."""
return bool(key_service_config(user_config, service)) or ci_get(own_cdm(user_config), service) is not None
-def key_service_yaml(normalized_service: str, user_config: Optional[Dict[str, Any]]) -> dict:
+def key_service_yaml(normalized_service: str, user_config: dict[str, Any] | None) -> dict:
""":func:`load_service_config` with the API key's own block merged over it.
A top-level section that sets one of the block's plain values (a profile section with its own identity) takes
@@ -950,7 +948,7 @@ def keyed_cache(
service_instance: Any,
service: str,
api_key: str,
- user_config: Dict[str, Any],
+ user_config: dict[str, Any],
temporary: bool = False,
client_identity: bool = False,
) -> Cacher:
@@ -969,7 +967,7 @@ def keyed_cache(
return Cacher(tag)
-@functools.lru_cache(maxsize=None)
+@functools.cache
def warn_no_identity_cache(service: str) -> None:
"""Warn once per service that an API key's own config runs on a service that marks no identity cache keys."""
log.warning(f"{service}: an API key sets its own config, but the service lists no IDENTITY_CACHE")
@@ -984,17 +982,17 @@ def drop_identity_cache(api_keys: Iterable[str]) -> None:
SessionStore.cleanup_cache_dir(f"_identity/{key_namespace(api_key)}")
-def server_cdm_allowed(request: Optional[web.Request] = None, service: Optional[str] = None) -> bool:
+def server_cdm_allowed(request: web.Request | None = None, service: str | None = None) -> bool:
"""Whether the calling API key may have the server operate the CDM licensing for ``service``."""
return key_grant_allows(request, service, "server_cdm")
-def server_vault_allowed(request: Optional[web.Request] = None, service: Optional[str] = None) -> bool:
+def server_vault_allowed(request: web.Request | None = None, service: str | None = None) -> bool:
"""Whether the calling API key may read the server vault in a remote session its own device licenses."""
return key_grant_allows(request, service, "server_vault") or server_cdm_allowed(request, service)
-def key_grant_allows(request: Optional[web.Request], service: Optional[str], name: str) -> bool:
+def key_grant_allows(request: web.Request | None, service: str | None, name: str) -> bool:
"""Whether the calling API key holds the ``name`` grant for ``service``.
Configured API keys opt in with ``: true`` for every service, or with a list of
@@ -1022,7 +1020,7 @@ def is_whole_number(value: Any) -> bool:
return isinstance(value, int) and not isinstance(value, bool) and value >= 0
-def server_cdm_max_height_error(where: str, value: Any) -> Optional[str]:
+def server_cdm_max_height_error(where: str, value: Any) -> str | None:
"""Why *value* cannot serve as ``server_cdm_max_height``, or None when it can (unset included)."""
def bad(height: Any) -> bool:
@@ -1039,7 +1037,7 @@ def server_cdm_max_height_error(where: str, value: Any) -> Optional[str]:
return None
-def key_config_error(where: str, user_cfg: Dict[str, Any], app_config: Any = None) -> Optional[str]:
+def key_config_error(where: str, user_cfg: dict[str, Any], app_config: Any = None) -> str | None:
"""Why the ``services``, ``cdm`` or ``service_config`` of one serve.users entry cannot work; None when it can.
Devices are looked up in ``app_config`` (a reload passes the new file). A tag that names no service the server
@@ -1079,7 +1077,7 @@ def key_config_error(where: str, user_cfg: Dict[str, Any], app_config: Any = Non
return None
-def server_cdm_max_height(request: Optional[web.Request], service: Optional[str]) -> Optional[int]:
+def server_cdm_max_height(request: web.Request | None, service: str | None) -> int | None:
"""The tallest video track the server CDM licenses live for this API key on ``service``; None for no cap.
The setting is one height, or a map of service tag to height where ``default`` covers a missing or null tag.
@@ -1093,7 +1091,7 @@ def server_cdm_max_height(request: Optional[web.Request], service: Optional[str]
return cap if is_whole_number(cap) else None
-def capped_error(message: str, cap: Optional[int] = None) -> APIError:
+def capped_error(message: str, cap: int | None = None) -> APIError:
"""The SERVER_CDM_CAPPED refusal; a client reads ``details`` to license the track itself."""
details = {"reason": "server_cdm_max_height", "max_height": cap} if cap is not None else {"reason": "client_device"}
return APIError(APIErrorCode.SERVER_CDM_CAPPED, message, details=details)
@@ -1104,21 +1102,19 @@ def requested_heights(quality: Any) -> list[int]:
try:
heights = QUALITY_LIST.convert(quality or [])
except click.BadParameter as e:
- raise APIError(APIErrorCode.INVALID_INPUT, f"quality: {e.message}")
+ raise APIError(APIErrorCode.INVALID_INPUT, f"quality: {e.message}") from e
if any(height <= 0 for height in heights):
raise APIError(APIErrorCode.INVALID_INPUT, f"quality: every height must be above 0, not {quality!r}")
return heights
-def requested_height(quality: Any) -> Optional[int]:
+def requested_height(quality: Any) -> int | None:
"""The tallest height a client asked for with ``-q``; None when it asked for the best there is."""
heights = requested_heights(quality)
return max(heights) if heights else None
-def choose_session_cdm(
- request: Optional[web.Request], service: str, data: Dict[str, Any]
-) -> tuple[bool, Optional[int]]:
+def choose_session_cdm(request: web.Request | None, service: str, data: dict[str, Any]) -> tuple[bool, int | None]:
"""``(server_cdm, max_height)`` for a new remote session.
The service picks its manifest from the CDM it sees, so it decides once, before any tracks.
@@ -1144,7 +1140,7 @@ def choose_session_cdm(
)
-def live_licence_refusal(session: SessionEntry, track: Any) -> Optional[APIError]:
+def live_licence_refusal(session: SessionEntry, track: Any) -> APIError | None:
"""Why the server CDM must not make a live licence for ``track`` in ``session``; None when it may.
Only a live licence spends the server's device, so a vault hit always passes. A track measures as the
@@ -1171,12 +1167,12 @@ def live_licence_refusal(session: SessionEntry, track: Any) -> Optional[APIError
)
-_account_counters: Dict[str, int] = {}
+_account_counters: dict[str, int] = {}
# the event loop holds only weak references to tasks, so a running login task needs a strong one
-_auth_tasks: Set["asyncio.Task[None]"] = set()
+_auth_tasks: set["asyncio.Task[None]"] = set()
-def validate_server_accounts() -> Dict[str, Any]:
+def validate_server_accounts() -> dict[str, Any]:
"""Check ``serve.server_accounts`` at startup; raise ValueError on a bad shape or unknown profile."""
accounts = config.serve.get("server_accounts") or {}
if not isinstance(accounts, dict):
@@ -1218,7 +1214,7 @@ def _regions(value: Any) -> set[str]:
return {str(v).lower() for v in values}
-def server_account_cookies(service: str, profile: Optional[str]) -> Any:
+def server_account_cookies(service: str, profile: str | None) -> Any:
"""Cookies for a server account: the profile's own file only, so a bare ``cookies/{service}.txt`` cannot shadow it."""
if profile is None:
return login.get_cookie_jar(service, None)
@@ -1226,7 +1222,7 @@ def server_account_cookies(service: str, profile: Optional[str]) -> Any:
return login.load_cookie_file(path) if path.exists() else None
-def load_client_cookies(cookie_text: Any) -> Optional[CookieJar]:
+def load_client_cookies(cookie_text: Any) -> CookieJar | None:
"""Read the cookie jar a client sent with its request, or None when it sent none.
The client sends a Netscape cookie file compressed and base64 encoded. It is parsed
@@ -1240,10 +1236,10 @@ def load_client_cookies(cookie_text: Any) -> Optional[CookieJar]:
cookie_str = safe_inflate(base64.b64decode(cookie_text)).decode("utf-8-sig")
return login.parse_cookie_text(cookie_str, "client cookies")
except (ValueError, zlib.error, OSError) as e:
- raise APIError(APIErrorCode.INVALID_INPUT, f"cookies is not a compressed Netscape cookie file: {e}")
+ raise APIError(APIErrorCode.INVALID_INPUT, f"cookies is not a compressed Netscape cookie file: {e}") from e
-def server_account_regions(service: str) -> Optional[Dict[str, Any]]:
+def server_account_regions(service: str) -> dict[str, Any] | None:
"""What ``GET /api/services`` advertises: the union of regions the server's accounts cover."""
spec = server_account_spec(service)
if not spec:
@@ -1256,7 +1252,7 @@ def server_account_regions(service: str) -> Optional[Dict[str, Any]]:
return {"regions": sorted(union - {"global"}), "global": "global" in union}
-def server_region() -> Optional[str]:
+def server_region() -> str | None:
"""The server's own country code, from the cached IP lookup; None when unknown."""
try:
from unshackle.core.utils.ip_info import get_ip_info
@@ -1267,7 +1263,7 @@ def server_region() -> Optional[str]:
return None
-def server_account_pool(service: str, region: Optional[str]) -> Optional[list[Optional[str]]]:
+def server_account_pool(service: str, region: str | None) -> list[str | None] | None:
"""Profiles of the server's own accounts usable in ``region``; None when the service is client-managed."""
spec = server_account_spec(service)
if not spec:
@@ -1279,7 +1275,7 @@ def server_account_pool(service: str, region: Optional[str]) -> Optional[list[Op
return sorted(p for p, v in spec.items() if {"global", region} & _regions(v))
-def next_server_profile(service: str, region: Optional[str]) -> Optional[str]:
+def next_server_profile(service: str, region: str | None) -> str | None:
"""Round-robin the next server account profile for ``region``."""
pool = server_account_pool(service, region) or []
if not pool:
@@ -1296,7 +1292,7 @@ def next_server_profile(service: str, region: Optional[str]) -> Optional[str]:
return pool[n % len(pool)]
-def server_accounts_allowed(request: Optional[web.Request] = None, service: Optional[str] = None) -> bool:
+def server_accounts_allowed(request: web.Request | None = None, service: str | None = None) -> bool:
"""Whether the calling API key may authenticate ``service`` with one of the server's own accounts.
Same shape as ``server_cdm``: ``server_accounts: true`` on the ``serve.users`` entry for every
@@ -1307,7 +1303,7 @@ def server_accounts_allowed(request: Optional[web.Request] = None, service: Opti
return key_grant_allows(request, service, "server_accounts")
-def resolve_server_account(request: Optional[web.Request], service: str, region: Any) -> Optional[str]:
+def resolve_server_account(request: web.Request | None, service: str, region: Any) -> str | None:
"""Profile of the server account a search or list call runs on; None when the service is client-managed.
Raises FORBIDDEN for an API key without the ``server_accounts`` opt-in.
@@ -1323,12 +1319,12 @@ def resolve_server_account(request: Optional[web.Request], service: str, region:
return next_server_profile(service, region if isinstance(region, str) else None) or "default"
-def server_account_for(request: Optional[web.Request], service: str) -> bool:
+def server_account_for(request: web.Request | None, service: str) -> bool:
"""True when this request's remote session for ``service`` should run on a server account."""
return server_account_spec(service) is not None and server_accounts_allowed(request, service)
-def server_proxy_allowed(request: Optional[web.Request] = None) -> bool:
+def server_proxy_allowed(request: web.Request | None = None) -> bool:
"""Whether the calling API key may use the server's own configured proxy providers.
Configured API keys opt in with ``server_proxy: true``, a real yaml boolean, so a
@@ -1360,7 +1356,7 @@ CORS_HEADERS = {
}
-def request_secret_key(request: web.Request) -> Optional[str]:
+def request_secret_key(request: web.Request) -> str | None:
"""The caller's API key: the X-Secret-Key header, or on SSE routes the secret_key query param."""
key = request.headers.get("X-Secret-Key")
if not key:
@@ -1370,7 +1366,7 @@ def request_secret_key(request: web.Request) -> Optional[str]:
return key
-def dashboard_key() -> Optional[str]:
+def dashboard_key() -> str | None:
"""The developer dashboard key from serve.dashboard.key, or None when the dashboard is off."""
dashboard = (config.serve or {}).get("dashboard")
key = dashboard.get("key") if isinstance(dashboard, dict) else None
@@ -1397,7 +1393,7 @@ async def dashboard_authentication(request: web.Request, handler: Any) -> web.St
return await handler(request)
-def rate_limit_response(secret_key: str) -> Optional[web.Response]:
+def rate_limit_response(secret_key: str) -> web.Response | None:
"""A 429 when *secret_key* is over its hourly limit, else None after counting the request.
Call only once the API key is known to be valid, so an invalid API key cannot burn someone else's
@@ -1448,14 +1444,14 @@ async def api_key_authentication(request: web.Request, handler: Any) -> web.Stre
return rate_limit_response(secret_key) or add_rate_limit_headers(await handler(request), secret_key)
-def caller_key(request: Optional[web.Request] = None) -> str:
+def caller_key(request: web.Request | None = None) -> str:
"""The authenticating API key for a request, or 'anonymous' when unauthenticated."""
if not request:
return "anonymous"
return request_secret_key(request) or "anonymous"
-def owns_job(job: Any, request: Optional[web.Request] = None) -> bool:
+def owns_job(job: Any, request: web.Request | None = None) -> bool:
"""Whether the calling API key owns this job.
Jobs created without an owner (no-key mode / legacy) stay shared. Otherwise, only the
@@ -1469,7 +1465,7 @@ def owns_job(job: Any, request: Optional[web.Request] = None) -> bool:
return hmac.compare_digest(owner, caller_key(request))
-def validate_service(service_tag: str, request: Optional[web.Request] = None) -> Optional[str]:
+def validate_service(service_tag: str, request: web.Request | None = None) -> str | None:
"""Validate and normalise the service tag, and examine the allowlist."""
if not isinstance(service_tag, str):
return None
@@ -1489,7 +1485,7 @@ def validate_service(service_tag: str, request: Optional[web.Request] = None) ->
PROFILE_RE = re.compile(r"^[A-Za-z0-9_.-]{1,64}$")
-def client_profile(data: Dict[str, Any]) -> Optional[str]:
+def client_profile(data: dict[str, Any]) -> str | None:
"""The request's ``profile``, or an INVALID_INPUT error when it could name a path."""
profile = data.get("profile")
if profile is None or profile == "":
@@ -1499,7 +1495,7 @@ def client_profile(data: Dict[str, Any]) -> Optional[str]:
return profile
-def require_fields(data: Dict[str, Any], *names: str) -> None:
+def require_fields(data: dict[str, Any], *names: str) -> None:
"""Raise INVALID_INPUT for the first missing/falsy required field."""
for name in names:
if not data.get(name):
@@ -1510,7 +1506,7 @@ def require_fields(data: Dict[str, Any], *names: str) -> None:
)
-def part_key_suffix(part: Optional[int]) -> str:
+def part_key_suffix(part: int | None) -> str:
"""`.2` selection-syntax suffix for a part-ful episode, empty otherwise."""
return f".{part}" if part is not None else ""
@@ -1522,7 +1518,7 @@ def listed_titles(titles: Any) -> list[Any]:
return list(titles) if hasattr(titles, "__iter__") and not isinstance(titles, str) else [titles]
-def stamp_service_flags(serialized: Dict[str, Any], service_instance: Any) -> Dict[str, Any]:
+def stamp_service_flags(serialized: dict[str, Any], service_instance: Any) -> dict[str, Any]:
"""Fill anime/daily from the service class for titles that set neither.
The client rebuilds titles from this JSON against a synthetic service class, so a
@@ -1536,7 +1532,7 @@ def stamp_service_flags(serialized: Dict[str, Any], service_instance: Any) -> Di
return serialized
-def drm_preference_name(track: Any) -> Optional[str]:
+def drm_preference_name(track: Any) -> str | None:
"""The track's drm_preference as a full DRM system name, "widevine" or "playready"; None when unset."""
preference = getattr(track, "drm_preference", None)
if not preference:
@@ -1544,7 +1540,7 @@ def drm_preference_name(track: Any) -> Optional[str]:
return {"wv": "widevine", "pr": "playready"}.get(preference, preference)
-async def search_handler(data: Dict[str, Any], request: Optional[web.Request] = None) -> web.Response:
+async def search_handler(data: dict[str, Any], request: web.Request | None = None) -> web.Response:
"""Answer the request to find titles."""
service_tag = data.get("service")
query = data.get("query")
@@ -1585,7 +1581,7 @@ async def search_handler(data: Dict[str, Any], request: Optional[web.Request] =
await request_cache.cleanup()
-async def list_titles_handler(data: Dict[str, Any], request: Optional[web.Request] = None) -> web.Response:
+async def list_titles_handler(data: dict[str, Any], request: web.Request | None = None) -> web.Response:
"""Answer the list-titles request."""
require_fields(data, "service", "title_id")
service_tag = data["service"]
@@ -1633,7 +1629,7 @@ async def list_titles_handler(data: Dict[str, Any], request: Optional[web.Reques
await request_cache.cleanup()
-async def list_tracks_handler(data: Dict[str, Any], request: Optional[web.Request] = None) -> web.Response:
+async def list_tracks_handler(data: dict[str, Any], request: web.Request | None = None) -> web.Response:
"""Answer the list-tracks request."""
require_fields(data, "service", "title_id")
service_tag = data["service"]
@@ -1680,7 +1676,7 @@ async def list_tracks_handler(data: Dict[str, Any], request: Optional[web.Reques
APIErrorCode.INVALID_PARAMETERS,
f"Invalid wanted parameter: {e.message}",
details={"wanted": wanted_param, "service": normalized_service},
- )
+ ) from e
elif season is not None and episode is not None:
wanted = [f"{season}x{episode}{part_key_suffix(part)}"]
@@ -1737,13 +1733,13 @@ async def list_tracks_handler(data: Dict[str, Any], request: Optional[web.Reques
failed_episodes.append(f"S{title.season}E{title.number:02d}{part_key_suffix(title.part)}")
log.debug(f"Episode {title.season}x{title.number} not available, skipping")
continue
- except (Exception, SystemExit) as e:
+ except Exception as e:
failed_episodes.append(f"S{title.season}E{title.number:02d}{part_key_suffix(title.part)}")
log.debug(f"Error getting tracks for {title.season}x{title.number}: {e}")
continue
if episodes_data:
- response: Dict[str, Any] = {"episodes": episodes_data}
+ response: dict[str, Any] = {"episodes": episodes_data}
if failed_episodes:
response["unavailable_episodes"] = failed_episodes
return await request_cache.json_response(response)
@@ -1785,7 +1781,7 @@ async def list_tracks_handler(data: Dict[str, Any], request: Optional[web.Reques
await request_cache.cleanup()
-def resolve_vcodec(value: Any) -> Optional[list]:
+def resolve_vcodec(value: Any) -> list | None:
"""Map a client's vcodec field to codec enums.
Session routes do not run validate_download_parameters, so this must answer junk with a 400
@@ -1796,10 +1792,10 @@ def resolve_vcodec(value: Any) -> Optional[list]:
try:
return VIDEO_CODEC_LIST.convert(value) or None
except click.UsageError as e:
- raise APIError(APIErrorCode.INVALID_INPUT, f"Invalid vcodec: {e.format_message()}")
+ raise APIError(APIErrorCode.INVALID_INPUT, f"Invalid vcodec: {e.format_message()}") from e
-def wanted_refusal(wanted: Any) -> Optional[str]:
+def wanted_refusal(wanted: Any) -> str | None:
"""Why dl could not parse ``wanted``, or None when it can."""
try:
SEASON_RANGE.convert(wanted or [])
@@ -1808,7 +1804,7 @@ def wanted_refusal(wanted: Any) -> Optional[str]:
return None
-def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]:
+def validate_download_parameters(data: dict[str, Any]) -> str | None:
"""
Validate download parameters and return error message if invalid.
@@ -1918,7 +1914,7 @@ def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]:
return None
-def enforce_download_gates(params: Dict[str, Any], request: Optional[web.Request] = None) -> None:
+def enforce_download_gates(params: dict[str, Any], request: web.Request | None = None) -> None:
"""Enforce serve-config gates on per-job cdm overrides and client-supplied credentials.
A per-request `cdm` selects a server-side device, so this function gates it here rather than
@@ -2003,11 +1999,11 @@ def enforce_download_gates(params: Dict[str, Any], request: Optional[web.Request
)
-def service_dl_defaults(service: str) -> Dict[str, Any]:
+def service_dl_defaults(service: str) -> dict[str, Any]:
"""The ``services..dl`` values that name an API download parameter, keyed as the API names them."""
from unshackle.core.services import ROUTING_PARAMS
- result: Dict[str, Any] = {}
+ result: dict[str, Any] = {}
for key, value in ((ci_get(config.services, service) or {}).get("dl") or {}).items():
key = DL_OPTION_API_NAMES.get(key, key)
if value is None or key in ROUTING_PARAMS:
@@ -2020,7 +2016,7 @@ def service_dl_defaults(service: str) -> Dict[str, Any]:
async def enqueue_job(
- service: str, title_id: str, params: Dict[str, Any], request: Optional[web.Request], gate_service: str
+ service: str, title_id: str, params: dict[str, Any], request: web.Request | None, gate_service: str
) -> web.Response:
"""Check the download gates for ``gate_service``, then queue a job with ``params`` and answer 202.
@@ -2039,7 +2035,7 @@ async def enqueue_job(
)
-async def download_handler(data: Dict[str, Any], request: Optional[web.Request] = None) -> web.Response:
+async def download_handler(data: dict[str, Any], request: web.Request | None = None) -> web.Response:
"""Answer the download request: make a download job and add it to the queue."""
require_fields(data, "service", "title_id")
@@ -2069,7 +2065,7 @@ async def download_handler(data: Dict[str, Any], request: Optional[web.Request]
try:
service_module = None if server else Services.load(normalized_service)
- service_params: Optional[Dict[str, Any]] = None
+ service_params: dict[str, Any] | None = None
# Service options travel nested, so a flat key the worker reads stays a dl value; click fills the defaults
# when the worker builds the service. A remote service applies its own on the remote server.
@@ -2112,7 +2108,7 @@ async def download_handler(data: Dict[str, Any], request: Optional[web.Request]
)
-async def list_download_jobs_handler(data: Dict[str, Any], request: Optional[web.Request] = None) -> web.Response:
+async def list_download_jobs_handler(data: dict[str, Any], request: web.Request | None = None) -> web.Response:
"""Answer the request to show download jobs, with optional filtering and sorting."""
from unshackle.core.api.download_manager import get_download_manager
@@ -2181,7 +2177,7 @@ async def list_download_jobs_handler(data: Dict[str, Any], request: Optional[web
)
-def client_job_view(job: Dict[str, Any], request: Optional[web.Request]) -> Dict[str, Any]:
+def client_job_view(job: dict[str, Any], request: web.Request | None) -> dict[str, Any]:
"""Drop a job's traceback and stderr for API clients unless the server runs with ``--debug-api``.
Redaction masks only the job's own secrets, so these fields can still carry server-side values.
@@ -2191,7 +2187,7 @@ def client_job_view(job: Dict[str, Any], request: Optional[web.Request]) -> Dict
return {k: v for k, v in job.items() if k not in ("error_traceback", "worker_stderr")}
-async def get_download_job_handler(job_id: str, request: Optional[web.Request] = None) -> web.Response:
+async def get_download_job_handler(job_id: str, request: web.Request | None = None) -> web.Response:
"""Answer the request for one specific download job."""
from unshackle.core.api.download_manager import get_download_manager
@@ -2247,12 +2243,12 @@ async def download_job_events_handler(job_id: str, request: web.Request) -> web.
)
await response.prepare(request)
- async def send(event: str, data: Dict[str, Any]) -> None:
+ async def send(event: str, data: dict[str, Any]) -> None:
payload = json.dumps(client_job_view(data, request), separators=(",", ":"), default=str)
await response.write(f"event: {event}\ndata: {payload}\n\n".encode())
- queue: Optional[asyncio.Queue] = None
- get_task: Optional[asyncio.Task] = None
+ queue: asyncio.Queue | None = None
+ get_task: asyncio.Task | None = None
try:
await send("snapshot", job.to_dict(include_full_details=True))
@@ -2285,7 +2281,7 @@ async def download_job_events_handler(job_id: str, request: web.Request) -> web.
return response
-def configured_service_tags() -> List[str]:
+def configured_service_tags() -> list[str]:
"""The installed services this server names in its config, for the dashboard.
The global ``serve.services`` list, else the union of every ``serve.users`` key's ``services``, else every
@@ -2303,7 +2299,7 @@ def configured_service_tags() -> List[str]:
return [tag for tag in tags if tag in named]
-def dashboard_status() -> Dict[str, Any]:
+def dashboard_status() -> dict[str, Any]:
"""Server-wide stats for the developer dashboard."""
from unshackle.core.api.download_manager import get_download_manager
from unshackle.core.api.session_store import get_session_store
@@ -2357,7 +2353,7 @@ async def dashboard_jobs_handler(request: web.Request) -> web.Response:
return web.json_response([job.to_dict(include_full_details=True) for job in get_download_manager().list_jobs()])
-def _poll_cursor(before: int, items: List[Dict[str, Any]]) -> int:
+def _poll_cursor(before: int, items: list[dict[str, Any]]) -> int:
"""Cursor for the next poll, from the buffer's seq read *before* its ``since()`` call.
This poll or the next one returns a record added between the two reads; no poll skips it.
@@ -2428,7 +2424,7 @@ async def dashboard_keys_handler(request: web.Request) -> web.Response:
api_secret = str(config.serve.get("api_secret") or "")
dashboard = dashboard_key() or ""
- def row(secret_key: str, role: str) -> Dict[str, Any]:
+ def row(secret_key: str, role: str) -> dict[str, Any]:
entry = stats.keys.get(key_id(secret_key))
api_access = role != "dashboard" or secret_key in users
return {
@@ -2484,7 +2480,7 @@ async def dashboard_services_handler(request: web.Request) -> web.Response:
sessions = Counter(entry.service_tag for entry in get_session_store().list())
jobs = Counter(job.service for job in get_download_manager().list_jobs() if job.status not in TERMINAL_STATUSES)
errors = {err.split(":", 1)[0]: err for err in services_module.LOAD_ERRORS if ":" in err}
- staged_commits: Dict[Any, Optional[str]] = {}
+ staged_commits: dict[Any, str | None] = {}
tags = Services.get_tags() if request.query.get("all") == "1" else configured_service_tags()
catalogue = await asyncio.to_thread(service_catalogue, [tag for tag in tags if tag in services_module.MODULES])
@@ -2492,7 +2488,7 @@ async def dashboard_services_handler(request: web.Request) -> web.Response:
for tag in tags:
error = errors.get(tag)
staged = tag in services_module.PENDING
- row: Dict[str, Any] = {
+ row: dict[str, Any] = {
**catalogue.get(tag, SERVICE_DEFAULTS),
"tag": tag,
"state": "failed" if error else "staged" if staged else "loaded",
@@ -2521,8 +2517,8 @@ HEALTH_DETAIL_MAX = 256
HEALTH_PROBE_TIMEOUT = 15.0
HEALTH_SECRET_MIN = 4
SECRET_KEYS = ("password", "passwd", "pwd", "token", "api_key", "apikey", "secret", "auth", "ssl_key_password")
-_health_cache: Dict[str, Any] = {}
-_health_lock: Optional[asyncio.Lock] = None
+_health_cache: dict[str, Any] = {}
+_health_lock: asyncio.Lock | None = None
async def dashboard_health_handler(request: web.Request) -> web.Response:
@@ -2540,10 +2536,10 @@ async def dashboard_health_handler(request: web.Request) -> web.Response:
if cached and now - _health_cache.get("at", 0.0) < HEALTH_CACHE_TTL:
return web.json_response(cached)
- checks: List[Dict[str, Any]] = []
+ checks: list[dict[str, Any]] = []
try:
await asyncio.wait_for(asyncio.to_thread(run_health_checks, checks), HEALTH_PROBE_TIMEOUT)
- except asyncio.TimeoutError:
+ except TimeoutError:
checks = list(checks)
checks.append(
{
@@ -2564,7 +2560,7 @@ async def dashboard_health_handler(request: web.Request) -> web.Response:
return web.json_response(payload)
-def config_secrets(section: Any, nested: bool = False) -> List[str]:
+def config_secrets(section: Any, nested: bool = False) -> list[str]:
"""Values in a vault or proxy config that must never reach a health detail.
Name-based at the top level, and every scalar below it: a nested mapping is driver
@@ -2579,7 +2575,7 @@ def config_secrets(section: Any, nested: bool = False) -> List[str]:
else:
return [str(section)] if nested and section is not None else []
- found: List[str] = []
+ found: list[str] = []
for key, value in items:
if isinstance(value, (dict, list, tuple)):
found += config_secrets(value, nested=True)
@@ -2588,7 +2584,7 @@ def config_secrets(section: Any, nested: bool = False) -> List[str]:
return [secret for secret in found if len(secret) >= HEALTH_SECRET_MIN]
-def health_check(check_id: str, label: str, probe: Any, secrets: Iterable[str] = ()) -> Dict[str, Any]:
+def health_check(check_id: str, label: str, probe: Any, secrets: Iterable[str] = ()) -> dict[str, Any]:
"""Time one health probe and turn any exception into a failed check.
*secrets* are masked out of the detail: a driver's error string can echo the DSN or URL
@@ -2613,7 +2609,7 @@ def health_check(check_id: str, label: str, probe: Any, secrets: Iterable[str] =
}
-def run_health_checks(checks: Optional[List[Dict[str, Any]]] = None) -> List[Dict[str, Any]]:
+def run_health_checks(checks: list[dict[str, Any]] | None = None) -> list[dict[str, Any]]:
"""Probe binaries, CDM devices, key vaults and proxy providers. Blocking; run in a thread.
Appends to *checks* as each probe finishes rather than returning only at the end, so a
@@ -2718,7 +2714,7 @@ async def dashboard_events_handler(request: web.Request) -> web.StreamResponse:
)
await response.prepare(request)
- async def send(event: str, data: Dict[str, Any], event_id: Optional[int] = None) -> None:
+ async def send(event: str, data: dict[str, Any], event_id: int | None = None) -> None:
payload = json.dumps(data, separators=(",", ":"), default=str)
head = f"id: {event_id}\n" if event_id is not None else ""
await response.write(f"{head}event: {event}\ndata: {payload}\n\n".encode())
@@ -2727,7 +2723,7 @@ async def dashboard_events_handler(request: web.Request) -> web.StreamResponse:
await send("stats", dashboard_status())
queue = bus.subscribe()
- get_task: Optional[asyncio.Task] = None
+ get_task: asyncio.Task | None = None
loop = asyncio.get_running_loop()
try:
await send_stats()
@@ -2759,7 +2755,7 @@ async def dashboard_events_handler(request: web.Request) -> web.StreamResponse:
return response
-async def cancel_download_job_handler(job_id: str, request: Optional[web.Request] = None) -> web.Response:
+async def cancel_download_job_handler(job_id: str, request: web.Request | None = None) -> web.Response:
"""Answer the cancel/remove download job request."""
from unshackle.core.api.download_manager import TERMINAL_STATUSES, get_download_manager
@@ -2802,7 +2798,7 @@ async def cancel_download_job_handler(job_id: str, request: Optional[web.Request
)
-async def clear_finished_download_jobs_handler(request: Optional[web.Request] = None) -> web.Response:
+async def clear_finished_download_jobs_handler(request: web.Request | None = None) -> web.Response:
"""Answer the clear finished download jobs request."""
from unshackle.core.api.download_manager import get_download_manager
@@ -2823,7 +2819,7 @@ async def clear_finished_download_jobs_handler(request: Optional[web.Request] =
)
-async def retry_download_job_handler(job_id: str, request: Optional[web.Request] = None) -> web.Response:
+async def retry_download_job_handler(job_id: str, request: web.Request | None = None) -> web.Response:
"""Answer the retry download job request: enqueue a new job with the original's parameters."""
from unshackle.core.api.download_manager import TERMINAL_STATUSES, get_download_manager
@@ -2871,7 +2867,7 @@ async def retry_download_job_handler(job_id: str, request: Optional[web.Request]
)
-async def prioritize_download_job_handler(job_id: str, request: Optional[web.Request] = None) -> web.Response:
+async def prioritize_download_job_handler(job_id: str, request: web.Request | None = None) -> web.Response:
"""Answer the prioritise download job request: move a queued job to the front of the queue."""
from unshackle.core.api.download_manager import JobStatus, get_download_manager
@@ -2910,7 +2906,7 @@ async def prioritize_download_job_handler(job_id: str, request: Optional[web.Req
async def download_job_input_handler(
- data: Dict[str, Any], job_id: str, request: Optional[web.Request] = None
+ data: dict[str, Any], job_id: str, request: web.Request | None = None
) -> web.Response:
"""Answer the prompt a running job waits on (its ``input_prompt``), to unblock the service."""
from unshackle.core.api.download_manager import get_download_manager
@@ -2950,11 +2946,11 @@ def redact_config(value: Any) -> Any:
return value
-async def profiles_handler(request: Optional[web.Request] = None) -> web.Response:
+async def profiles_handler(request: web.Request | None = None) -> web.Response:
"""Answer the request for the credential profiles."""
try:
allowed = get_allowed_services(request)
- profiles: Dict[str, List[str]] = {}
+ profiles: dict[str, list[str]] = {}
for service, creds in (config.credentials or {}).items():
# a plain (non-dict) credential is unnamed; that service is omitted entirely
if not isinstance(creds, dict):
@@ -2974,7 +2970,7 @@ async def profiles_handler(request: Optional[web.Request] = None) -> web.Respons
return handle_api_exception(e, context={"operation": "profiles"}, debug_mode=debug_mode)
-async def server_config_handler(request: Optional[web.Request] = None) -> web.Response:
+async def server_config_handler(request: web.Request | None = None) -> web.Response:
"""Answer the read-only effective server config request (secrets redacted)."""
from unshackle.core.api.download_manager import get_download_manager
@@ -3024,7 +3020,7 @@ async def server_config_handler(request: Optional[web.Request] = None) -> web.Re
return handle_api_exception(e, context={"operation": "server_config"}, debug_mode=debug_mode)
-async def download_history_handler(data: Dict[str, Any], request: Optional[web.Request] = None) -> web.Response:
+async def download_history_handler(data: dict[str, Any], request: web.Request | None = None) -> web.Response:
"""Answer the persisted download history request."""
from unshackle.core.api.download_manager import owner_id, read_job_history
@@ -3037,7 +3033,7 @@ async def download_history_handler(data: Dict[str, Any], request: Optional[web.R
except (TypeError, ValueError):
raise APIError(
APIErrorCode.INVALID_PARAMETERS, "limit must be an integer", details={"limit": limit_raw}
- )
+ ) from None
if limit < 1:
raise APIError(APIErrorCode.INVALID_PARAMETERS, "limit must be >= 1", details={"limit": limit_raw})
@@ -3063,7 +3059,7 @@ async def download_history_handler(data: Dict[str, Any], request: Optional[web.R
return handle_api_exception(e, context={"operation": "download_history"}, debug_mode=debug_mode)
-async def delete_history_handler(job_id: str, request: Optional[web.Request] = None) -> web.Response:
+async def delete_history_handler(job_id: str, request: web.Request | None = None) -> web.Response:
"""Delete one persisted history entry by job_id."""
from unshackle.core.api.download_manager import delete_job_history, owner_id
@@ -3095,7 +3091,7 @@ def require_no_active_downloads(operation: str) -> None:
)
-async def clear_cache_handler(request: Optional[web.Request] = None) -> web.Response:
+async def clear_cache_handler(request: web.Request | None = None) -> web.Response:
"""Answer the clear cache directory request."""
from unshackle.commands.env import clear_directory
@@ -3113,7 +3109,7 @@ async def clear_cache_handler(request: Optional[web.Request] = None) -> web.Resp
return handle_api_exception(e, context={"operation": "clear_cache"}, debug_mode=debug_mode)
-async def clear_temp_handler(request: Optional[web.Request] = None) -> web.Response:
+async def clear_temp_handler(request: web.Request | None = None) -> web.Response:
"""Answer the clear temp directory request."""
from unshackle.commands.env import clear_directory
@@ -3131,7 +3127,7 @@ async def clear_temp_handler(request: Optional[web.Request] = None) -> web.Respo
return handle_api_exception(e, context={"operation": "clear_temp"}, debug_mode=debug_mode)
-async def refresh_services_handler(request: Optional[web.Request] = None) -> web.Response:
+async def refresh_services_handler(request: web.Request | None = None) -> web.Response:
"""Refresh the service repos configured in directories.services and reload the changed services."""
from unshackle.core.api.download_manager import busy_services
from unshackle.core.api.events import publish_refresh_events
@@ -3151,11 +3147,11 @@ async def refresh_services_handler(request: Optional[web.Request] = None) -> web
return handle_api_exception(e, context={"operation": "refresh_services"}, debug_mode=debug_mode)
-async def env_check_handler(request: Optional[web.Request] = None) -> web.Response:
+async def env_check_handler(request: web.Request | None = None) -> web.Response:
"""Answer the environment dependency check request."""
from unshackle.commands.env import get_dependencies
- def run_checks() -> List[Dict[str, Any]]:
+ def run_checks() -> list[dict[str, Any]]:
checks = []
for dep in get_dependencies():
binary = dep["binary"]
@@ -3191,8 +3187,8 @@ MAX_CLIENT_CONFIG_BYTES = 16384
def client_config_overlay(
- service_config: Dict[str, Any], allowed: Iterable[str], supplied: Any
-) -> tuple[Dict[str, Any], bool]:
+ service_config: dict[str, Any], allowed: Iterable[str], supplied: Any
+) -> tuple[dict[str, Any], bool]:
"""The service config for a remote session that the client's own device licenses, and whether the client sent an identity.
Only the ``allowed`` keys come from the client, and a mapping merges its entries over the server's.
@@ -3232,7 +3228,7 @@ def client_config_overlay(
def client_device_cdm(
- data: Dict[str, Any], input_bridge: Optional[InputBridge], server_device: Optional[Callable[[], Any]] = None
+ data: dict[str, Any], input_bridge: InputBridge | None, server_device: Callable[[], Any] | None = None
) -> Any:
"""The service's view of the client's device: a relaying stand-in when the client can answer CDM calls."""
from unshackle.core.cdm.client_relay import ClientDeviceCdm
@@ -3263,15 +3259,15 @@ def client_device_cdm(
def create_service_instance(
normalized_service: str,
title_id: str,
- data: Dict[str, Any],
- proxy_param: Optional[str],
+ data: dict[str, Any],
+ proxy_param: str | None,
proxy_providers: list,
- profile: Optional[str],
+ profile: str | None,
server_account: bool = False,
server_cdm: bool = False,
client_device: bool = False,
- input_bridge: Optional[InputBridge] = None,
- user_config: Optional[Dict[str, Any]] = None,
+ input_bridge: InputBridge | None = None,
+ user_config: dict[str, Any] | None = None,
) -> Any:
"""Make a service instance and resolve its credentials and cookies.
@@ -3314,7 +3310,7 @@ def create_service_instance(
# Reconstruct enum track-selection params from client data so service code that reads
# ctx.parent.params (Service.__init__ proxy/range/vcodec/best_available block) sees enums.
range_names = data.get("range_")
- range_values: Optional[list] = None
+ range_values: list | None = None
if range_names:
range_values = []
for name in range_names:
@@ -3358,7 +3354,7 @@ def create_service_instance(
return service_instance, cookies, credential
-async def session_create_handler(data: Dict[str, Any], request: Optional[web.Request] = None) -> web.Response:
+async def session_create_handler(data: dict[str, Any], request: web.Request | None = None) -> web.Response:
"""Answer the remote session creation: authenticate + get titles + get tracks + get chapters.
This is the main entry point for remote-dl clients. It creates a persistent
@@ -3394,7 +3390,7 @@ async def session_create_handler(data: Dict[str, Any], request: Optional[web.Req
api_key = caller_key(request)
user_config = serve_user_config(api_key)
session_cache_dir = f"_sessions/{api_key_namespace(request)}/{session_id}/{normalized_service}"
- session_cache_tag: Optional[str] = session_cache_dir
+ session_cache_tag: str | None = session_cache_dir
server_account = server_account_for(request, normalized_service)
if server_account:
@@ -3526,7 +3522,7 @@ async def session_create_handler(data: Dict[str, Any], request: Optional[web.Req
)
-async def session_titles_handler(session_id: str, request: Optional[web.Request] = None) -> web.Response:
+async def session_titles_handler(session_id: str, request: web.Request | None = None) -> web.Response:
"""Get titles for the authenticated remote session.
Called after `session/create`. This is separate from auth so that
@@ -3566,7 +3562,7 @@ async def session_titles_handler(session_id: str, request: Optional[web.Request]
)
-def client_session_auth(session: Any) -> tuple[Dict[str, str], list[Dict[str, Any]]]:
+def client_session_auth(session: Any) -> tuple[dict[str, str], list[dict[str, Any]]]:
"""The service session headers and cookies (name, value, domain, path, secure) a remote client may receive.
A client whose own login succeeded gets them back. For a server account the cookie jar
@@ -3576,7 +3572,7 @@ def client_session_auth(session: Any) -> tuple[Dict[str, str], list[Dict[str, An
"""
svc_session = session.service_instance.session
headers = dict(svc_session.headers) if hasattr(svc_session, "headers") and svc_session.headers else {}
- cookies: list[Dict[str, Any]] = []
+ cookies: list[dict[str, Any]] = []
jar = svc_session.scoped_cookies() if isinstance(svc_session, RnetSession) else getattr(svc_session, "cookies", [])
for cookie in jar:
if hasattr(cookie, "name") and hasattr(cookie, "value"):
@@ -3596,12 +3592,12 @@ def client_session_auth(session: Any) -> tuple[Dict[str, str], list[Dict[str, An
return headers, cookies
-def cookie_values(cookies: list[Dict[str, Any]]) -> Dict[str, str]:
+def cookie_values(cookies: list[dict[str, Any]]) -> dict[str, str]:
"""The ``{name: value}`` form of :func:`client_session_auth` cookies, for clients that predate the jar."""
return {c["name"]: c["value"] for c in cookies}
-def session_user_config(session: Any, request: Optional[web.Request]) -> Dict[str, Any]:
+def session_user_config(session: Any, request: web.Request | None) -> dict[str, Any]:
"""The serve.users entry a remote session was created with, so a reload cannot change it for that session.
An API key with no ``cdm`` entry of its own for the service still follows the server's ``cdm`` after a reload.
@@ -3627,7 +3623,7 @@ def scrub_secret_keys(value: Any) -> Any:
return value
-def scrub_track_data(data: Optional[Dict[str, Any]], session: Any) -> Optional[Dict[str, Any]]:
+def scrub_track_data(data: dict[str, Any] | None, session: Any) -> dict[str, Any] | None:
"""Drop secret-looking keys, at any depth, from a serialised ``track.data`` when the login is the server's.
A service can stash a token in ``track.data`` for its license call; under the same rule as
@@ -3639,7 +3635,7 @@ def scrub_track_data(data: Optional[Dict[str, Any]], session: Any) -> Optional[D
async def session_tracks_handler(
- data: TracksRequest, session_id: str, request: Optional[web.Request] = None
+ data: TracksRequest, session_id: str, request: web.Request | None = None
) -> web.Response:
"""Get tracks and chapters for a specific title in the remote session.
@@ -3719,7 +3715,7 @@ async def session_tracks_handler(
else:
server_cdm_type = "playready"
- def serialize() -> Dict[str, list]:
+ def serialize() -> dict[str, list]:
"""The track and attachment lists, off the event loop: an attachment can be a 20 MB file."""
lists = serialize_tracks(tracks, title, include_url=True)
for d in lists["video"] + lists["audio"] + lists["subtitles"]:
@@ -3761,7 +3757,7 @@ async def session_tracks_handler(
async def session_segments_handler(
- data: Dict[str, Any], session_id: str, request: Optional[web.Request] = None
+ data: dict[str, Any], session_id: str, request: web.Request | None = None
) -> web.Response:
"""Get segment URLs for selected tracks.
@@ -3779,7 +3775,7 @@ async def session_segments_handler(
raise APIError(APIErrorCode.INVALID_INPUT, "track_ids must be an array of strings")
try:
- result: Dict[str, Any] = {}
+ result: dict[str, Any] = {}
headers, cookies = client_session_auth(session)
for track_id in track_ids:
@@ -3793,7 +3789,7 @@ async def session_segments_handler(
descriptor_name = track.descriptor.name if hasattr(track.descriptor, "name") else str(track.descriptor)
- track_info: Dict[str, Any] = {
+ track_info: dict[str, Any] = {
"descriptor": descriptor_name,
"url": str(track.url) if track.url else None,
"drm": serialize_drm(track.drm) if hasattr(track, "drm") and track.drm else None,
@@ -3827,9 +3823,7 @@ async def session_segments_handler(
)
-def resolve_server_cdm(
- service: str, profile: Optional[str], cdm_type: Optional[str], app_config: Any = None
-) -> Optional[Any]:
+def resolve_server_cdm(service: str, profile: str | None, cdm_type: str | None, app_config: Any = None) -> Any | None:
"""Get the CDM for the server context.
Checks the server's own CDM config (``config.cdm[service]``) to
@@ -3853,7 +3847,7 @@ def resolve_server_cdm(
return None
-def detect_cdm_type_for_service(service: str, app_config: Any) -> Optional[str]:
+def detect_cdm_type_for_service(service: str, app_config: Any) -> str | None:
"""The DRM system config.cdm settles for a service; None when the mapping leaves it open.
A mapping that names one system gets that system. A device name gets the type of the
@@ -3884,7 +3878,7 @@ def require_authenticated(session: SessionEntry) -> None:
)
-async def session_prompt_get_handler(session_id: str, request: Optional[web.Request] = None) -> web.Response:
+async def session_prompt_get_handler(session_id: str, request: web.Request | None = None) -> web.Response:
"""Poll for pending interactive prompts during authentication, and for CDM calls at any time.
Returns the current auth status and any pending prompt that the
@@ -3914,7 +3908,7 @@ async def session_prompt_get_handler(session_id: str, request: Optional[web.Requ
async def session_prompt_post_handler(
- data: PromptAnswer, session_id: str, request: Optional[web.Request] = None
+ data: PromptAnswer, session_id: str, request: web.Request | None = None
) -> web.Response:
"""Submit a response to a pending interactive prompt.
@@ -3936,7 +3930,7 @@ async def session_prompt_post_handler(
return web.json_response({"status": "accepted"})
-async def session_logs_handler(session_id: str, since: int = 0, request: Optional[web.Request] = None) -> web.Response:
+async def session_logs_handler(session_id: str, since: int = 0, request: web.Request | None = None) -> web.Response:
"""Drain the remote session's service log records newer than *since*.
Gives a remote client the service's server-side ``self.log`` output for
@@ -3950,7 +3944,7 @@ async def session_logs_handler(session_id: str, since: int = 0, request: Optiona
return web.json_response(LogsReply(session_id=session_id, logs=logs, last_seq=logs[-1]["seq"] if logs else since))
-async def get_validated_session(session_id: str, request: Optional[web.Request]) -> Any:
+async def get_validated_session(session_id: str, request: web.Request | None) -> Any:
"""Fetch a remote session and make sure that the caller owns it.
Ownership is bound to the authenticating X-Secret-Key rather than the source IP:
@@ -3983,7 +3977,7 @@ async def get_validated_session(session_id: str, request: Optional[web.Request])
return session
-def local_proxy_refusal(proxy: str) -> Optional[str]:
+def local_proxy_refusal(proxy: str) -> str | None:
"""Why an http(s) or socks proxy URI may reach the server's own machine or network, or None when it cannot.
The host must be a plain DNS name or an IP literal: an HTTP client that follows the WHATWG URL standard
@@ -4011,8 +4005,8 @@ def local_proxy_refusal(proxy: str) -> Optional[str]:
def resolve_handler_proxy(
- data: Dict[str, Any], normalized_service: str, request: Optional[web.Request] = None
-) -> tuple[Optional[str], list]:
+ data: dict[str, Any], normalized_service: str, request: web.Request | None = None
+) -> tuple[str | None, list]:
"""Get the proxy and the proxy providers for an API request.
``server_proxy`` on the calling API key decides whether the server spends its own proxy
@@ -4069,12 +4063,12 @@ def resolve_handler_proxy(
APIErrorCode.INVALID_PROXY,
f"Proxy error: {redact_text(str(e))}",
details={"proxy": redact_text(data.get("proxy")), "service": normalized_service},
- )
+ ) from e
raise APIError(
APIErrorCode.INVALID_PROXY,
"This server does not resolve country codes into proxies, pass a full proxy URI",
details={"service": normalized_service},
- )
+ ) from None
client_region = data.get("client_region")
if client_region is not None and not isinstance(client_region, str):
@@ -4134,7 +4128,7 @@ def find_title_for_track(track_id: str, session: Any) -> Any:
return None
-def extract_pssh_from_track(track: Any, drm_type: str) -> Optional[str]:
+def extract_pssh_from_track(track: Any, drm_type: str) -> str | None:
"""The base64 PSSH of the track's DRM object for `drm_type`; None when the track has none of that system."""
for drm_obj in track.drm or []:
drm_class = drm_obj.__class__.__name__
@@ -4149,7 +4143,7 @@ def extract_pssh_from_track(track: Any, drm_type: str) -> Optional[str]:
return None
-def fetch_init_segment(track: Any, session: Any = None) -> Optional[bytes]:
+def fetch_init_segment(track: Any, session: Any = None) -> bytes | None:
"""The init segment of a DASH track, or the head of a one-file track with DRM; None otherwise, or when the fetch fails."""
from unshackle.core.manifests import DASH as DASHManifest
@@ -4182,7 +4176,7 @@ def fetch_init_segment(track: Any, session: Any = None) -> Optional[bytes]:
return None
-def drm_from_init_segment(track: Any, session: Any = None, init_data: Optional[bytes] = None) -> list:
+def drm_from_init_segment(track: Any, session: Any = None, init_data: bytes | None = None) -> list:
"""Read the DRM headers out of a DASH track's init segment.
Some manifests carry no ContentProtection PSSH; the real header reaches the player only
@@ -4204,7 +4198,7 @@ def drm_from_init_segment(track: Any, session: Any = None, init_data: Optional[b
return drms
-def ensure_track_drm(track: Any, session: Any = None, init_data: Optional[bytes] = None) -> None:
+def ensure_track_drm(track: Any, session: Any = None, init_data: bytes | None = None) -> None:
"""Extract DRM from manifest data if track has none.
Supports DASH (ContentProtection elements, then the init segment), HLS
@@ -4284,7 +4278,7 @@ def resolve_device_name(user_config: dict, drm_type: str, service_tag: str = "")
return device_name
-def vault_candidates(client_drm_type: str) -> List[str]:
+def vault_candidates(client_drm_type: str) -> list[str]:
"""Both DRM systems, the client's first: a vault lookup needs only the KIDs, whatever device made the manifest."""
first = client_drm_type if client_drm_type in ("widevine", "playready") else "widevine"
return [first, "playready" if first == "widevine" else "widevine"]
@@ -4296,7 +4290,7 @@ def server_drm_candidates(
client_drm_type: str,
track: Any,
warn: Callable[[str], None] = log.warning,
-) -> List[str]:
+) -> list[str]:
"""The DRM systems the server can license a track with, in the order to try them.
The server's config.cdm mapping goes first; with no mapping, the client's choice goes
@@ -4307,7 +4301,7 @@ def server_drm_candidates(
app_config = key_cdm_config(user_config)
server_type = detect_cdm_type_for_service(service_tag, app_config)
first = server_type or (client_drm_type if client_drm_type in ("widevine", "playready") else "widevine")
- candidates: List[str] = []
+ candidates: list[str] = []
for drm_type in (first, *(system for system in ("widevine", "playready") if system != first)):
try:
device_name = resolve_device_name(user_config, drm_type, service_tag)
@@ -4329,7 +4323,7 @@ def server_drm_candidates(
return candidates
-def pick_server_pssh(track: Any, candidates: List[str]) -> Optional[tuple[str, str]]:
+def pick_server_pssh(track: Any, candidates: list[str]) -> tuple[str, str] | None:
"""`(drm_type, pssh)` for the first candidate the track carries a header for; None when it has none.
A track with only a PlayReady header still licenses under the Widevine device: the
@@ -4356,7 +4350,7 @@ def load_server_vaults(service_name: str) -> Any:
return load_config_vaults(Services.get_vault_tag(service_name))[0]
-def once(shared: Dict[Any, Any], key: Any, make: Callable[[], Any]) -> Any:
+def once(shared: dict[Any, Any], key: Any, make: Callable[[], Any]) -> Any:
"""``make()`` the first time ``key`` is asked for in ``shared``, the stored value after that."""
if key not in shared:
shared[key] = make()
@@ -4364,8 +4358,8 @@ def once(shared: Dict[Any, Any], key: Any, make: Callable[[], Any]) -> Any:
def check_vaults(
- kids: list, service_name: str, shared: Optional[Dict[str, Any]] = None, track_kid: Optional[uuid.UUID] = None
-) -> Optional[tuple[Dict[str, str], Dict[str, str]]]:
+ kids: list, service_name: str, shared: dict[str, Any] | None = None, track_kid: uuid.UUID | None = None
+) -> tuple[dict[str, str], dict[str, str]] | None:
"""Examine the server vaults for existing content keys that match the KIDs.
Returns `(KID:KEY, KID:vault name)` when every KID is found, or with ``track_kid`` when that
@@ -4376,8 +4370,8 @@ def check_vaults(
vaults = once({} if shared is None else shared, "vaults", lambda: load_server_vaults(service_name))
if not vaults.vaults:
return None
- keys: Dict[str, str] = {}
- sources: Dict[str, str] = {}
+ keys: dict[str, str] = {}
+ sources: dict[str, str] = {}
wanted = [kid if isinstance(kid, uuid.UUID) else uuid.UUID(hex=str(kid)) for kid in kids]
if track_kid:
wanted = [track_kid, *(kid for kid in wanted if kid != track_kid)]
@@ -4400,7 +4394,7 @@ def check_vaults(
CACHED_PAIRS: set[tuple[str, str, str]] = set()
-def cache_to_vaults(keys: Dict[str, str], service_name: str, shared: Optional[Dict[str, Any]] = None) -> None:
+def cache_to_vaults(keys: dict[str, str], service_name: str, shared: dict[str, Any] | None = None) -> None:
"""Cache the content keys of a CDM licence to the server vaults.
A PlayReady licence always runs, and a Widevine licence runs when one PSSH KID has no content
@@ -4430,7 +4424,7 @@ def cache_to_vaults(keys: Dict[str, str], service_name: str, shared: Optional[Di
log.warning(f"Failed to cache keys to vaults: {e}")
-def track_injected_keys(track: Any, drm_class: str) -> Dict[str, str]:
+def track_injected_keys(track: Any, drm_class: str) -> dict[str, str]:
"""`KID:KEY` pairs a service wrote onto the track's own DRM objects of `drm_class`.
Some services skip the CDM exchange: the licence callback fetches the keys itself,
@@ -4438,7 +4432,7 @@ def track_injected_keys(track: Any, drm_class: str) -> Dict[str, str]:
parse. ``dl.py`` accepts that failed parse because the object it licensed holds the
keys. The server licenses a rebuilt object, so it reads the track's objects instead.
"""
- keys: Dict[str, str] = {}
+ keys: dict[str, str] = {}
for drm in getattr(track, "drm", None) or []:
if drm.__class__.__name__ != drm_class:
continue
@@ -4447,7 +4441,7 @@ def track_injected_keys(track: Any, drm_class: str) -> Dict[str, str]:
return keys
-def license_with_track_fallback(drm: Any, track: Any, **kwargs: Any) -> Dict[str, str]:
+def license_with_track_fallback(drm: Any, track: Any, **kwargs: Any) -> dict[str, str]:
"""Run `drm.get_content_keys`, merge in the keys the service put on the track itself, and drop the null keys."""
try:
drm.get_content_keys(**kwargs)
@@ -4461,7 +4455,7 @@ def license_with_track_fallback(drm: Any, track: Any, **kwargs: Any) -> Dict[str
return {kid: key for kid, key in keys.items() if not is_null_key(key)}
-def client_track_kid(kid_hex: Any, track: Any) -> Optional[uuid.UUID]:
+def client_track_kid(kid_hex: Any, track: Any) -> uuid.UUID | None:
"""The KID a client asks the server CDM for, when the track's DRM names it; None for any other value."""
if not isinstance(kid_hex, str):
return None
@@ -4513,16 +4507,16 @@ def handle_single_server_cdm(
service: Any,
title: Any,
track: Any,
- pssh_b64: Optional[str],
+ pssh_b64: str | None,
drm_type: str,
- request: Optional[web.Request],
- sources: Optional[Dict[str, str]] = None,
- refusal: Optional[APIError] = None,
+ request: web.Request | None,
+ sources: dict[str, str] | None = None,
+ refusal: APIError | None = None,
vault_only: bool = False,
- shared: Optional[Dict[str, Any]] = None,
- track_kid: Optional[uuid.UUID] = None,
- user_config: Optional[Dict[str, Any]] = None,
-) -> Dict[str, str]:
+ shared: dict[str, Any] | None = None,
+ track_kid: uuid.UUID | None = None,
+ user_config: dict[str, Any] | None = None,
+) -> dict[str, str]:
"""Do the single-track server_cdm licensing with the DRM class get_content_keys() flow.
``sources`` is filled with the vault name for every returned content key a server vault
@@ -4546,7 +4540,7 @@ def handle_single_server_cdm(
if not pssh_b64:
raise APIError(APIErrorCode.INVALID_INPUT, "No PSSH available for server_cdm licensing")
- def from_vaults(kids: Iterable[uuid.UUID]) -> Optional[Dict[str, str]]:
+ def from_vaults(kids: Iterable[uuid.UUID]) -> dict[str, str] | None:
"""The vault keys for ``kids`` (see ``check_vaults``), with their sources noted."""
hit = check_vaults(list(kids), service_name, shared=shared, track_kid=track_kid)
if hit and sources is not None:
@@ -4641,7 +4635,7 @@ def handle_proxy_license(
service: Any,
title: Any,
track: Any,
- challenge_b64: Optional[str],
+ challenge_b64: str | None,
drm_type: str,
certificate: bool = False,
) -> web.Response:
@@ -4701,7 +4695,7 @@ def handle_proxy_license(
async def session_segment_filter_handler(
- data: SegmentFilterRequest, session_id: str, request: Optional[web.Request] = None
+ data: SegmentFilterRequest, session_id: str, request: web.Request | None = None
) -> web.Response:
"""Run the service's HLS ``OnSegmentFilter`` for one track and return the unwanted segment URIs.
@@ -4748,7 +4742,7 @@ async def session_segment_filter_handler(
async def session_samples_handler(
- session_id: str, track_id: str, entry: str, frame: bytes, request: Optional[web.Request] = None
+ session_id: str, track_id: str, entry: str, frame: bytes, request: web.Request | None = None
) -> web.Response:
"""Run the service's sample decrypter for one `stsd` entry of a track that `decrypts_samples` names.
@@ -4801,7 +4795,7 @@ async def session_samples_handler(
async def session_license_handler(
- data: LicenseRequest, session_id: str, request: Optional[web.Request] = None
+ data: LicenseRequest, session_id: str, request: web.Request | None = None
) -> web.Response:
"""Do the DRM licensing in proxy or server_cdm mode.
@@ -4820,9 +4814,7 @@ async def session_license_handler(
return await asyncio.to_thread(license_response, data, session, session_id, request)
-def license_response(
- data: LicenseRequest, session: Any, session_id: str, request: Optional[web.Request]
-) -> web.Response:
+def license_response(data: LicenseRequest, session: Any, session_id: str, request: web.Request | None) -> web.Response:
"""The licence response for :func:`session_license_handler`, made on a worker thread."""
track_id = data.get("track_id")
track_ids = data.get("track_ids")
@@ -4845,16 +4837,16 @@ def license_response(
service = session.service_instance
service_tag = session.service_tag
- all_keys: Dict[str, Dict[str, str]] = {}
+ all_keys: dict[str, dict[str, str]] = {}
vault_keys: list[str] = []
clear_tracks: list[str] = []
- drm_types: Dict[str, str] = {}
- keys_by_pssh: Dict[tuple, Dict[str, str]] = {}
- shared: Dict[str, Any] = {}
- sources_by_pssh: Dict[tuple, Dict[str, str]] = {}
- drm_type_by_pssh: Dict[tuple, str] = {}
- actual_drm_type: Optional[str] = None
- capped_tracks: Dict[str, Dict[str, Any]] = {}
+ drm_types: dict[str, str] = {}
+ keys_by_pssh: dict[tuple, dict[str, str]] = {}
+ shared: dict[str, Any] = {}
+ sources_by_pssh: dict[tuple, dict[str, str]] = {}
+ drm_type_by_pssh: dict[tuple, str] = {}
+ actual_drm_type: str | None = None
+ capped_tracks: dict[str, dict[str, Any]] = {}
def pssh_set(track: Any) -> tuple:
"""Every PSSH and KID the track carries, as the rest of the cache key.
@@ -4880,8 +4872,8 @@ def license_response(
session.log_buffer.append(logging.WARNING, message)
def license_track(
- track: Any, title: Any, candidates: list, track_kid: Optional[uuid.UUID]
- ) -> tuple[Dict[str, str], Optional[str], Optional[str]]:
+ track: Any, title: Any, candidates: list, track_kid: uuid.UUID | None
+ ) -> tuple[dict[str, str], str | None, str | None]:
"""`(keys, drm_type, pssh)` for the track's current DRM, licensing once per unique PSSH.
A cached vault answer that lacks ``track_kid`` is asked again for that KID. A track the server
@@ -4920,7 +4912,7 @@ def license_response(
drm_type_by_pssh[cache_key] = candidate
except SystemExit:
warn(f"Service exited while resolving keys for track {track_log_label(track)}, skipping")
- except (Exception, SystemExit) as e:
+ except Exception as e:
if isinstance(e, APIError) and e.error_code is APIErrorCode.SERVER_CDM_CAPPED:
del keys_by_pssh[cache_key], sources_by_pssh[cache_key]
capped_tracks[str(track.id)] = e.details
@@ -4949,7 +4941,7 @@ def license_response(
else server_drm_candidates(service_tag, user_config, drm_type, track, warn)
)
- probed: Optional[uuid.UUID] = None
+ probed: uuid.UUID | None = None
if init_data:
try:
probed = track.get_key_id(init_data)
@@ -5050,7 +5042,7 @@ def license_response(
require_track_pssh(track, pssh_b64, drm_type)
if drm_type == "playready":
track.pr_pssh = pssh_b64
- key_sources: Dict[str, str] = {}
+ key_sources: dict[str, str] = {}
keys = handle_single_server_cdm(
service,
title,
@@ -5083,8 +5075,8 @@ def license_response(
except APIError:
raise
except SystemExit:
- raise APIError(APIErrorCode.SERVICE_ERROR, "Service exited during license request")
- except (Exception, SystemExit) as e:
+ raise APIError(APIErrorCode.SERVICE_ERROR, "Service exited during license request") from None
+ except Exception as e:
log.exception(f"Error proxying license for track {sanitize_log(track_id)}")
debug_mode = request.app.get("debug_api", False) if request else False
return handle_api_exception(
@@ -5099,7 +5091,7 @@ def license_response(
)
-def note_served_keys(session: Any, keys: Dict[str, str], sources: Dict[str, str]) -> None:
+def note_served_keys(session: Any, keys: dict[str, str], sources: dict[str, str]) -> None:
"""Remember every KID:KEY the remote session handed out and which server vault supplied it.
The vault name stays on the server: a bad-key report names only the pair, and the
@@ -5110,7 +5102,7 @@ def note_served_keys(session: Any, keys: Dict[str, str], sources: Dict[str, str]
async def session_bad_key_handler(
- data: BadKeyReport, session_id: str, request: Optional[web.Request] = None
+ data: BadKeyReport, session_id: str, request: web.Request | None = None
) -> web.Response:
"""Flag a server-vault content key the client proved wrong, so the next licence reaches the CDM.
@@ -5155,7 +5147,7 @@ async def session_bad_key_handler(
return web.json_response({"flagged": True})
-async def session_keys_handler(data: TrackKeys, session_id: str, request: Optional[web.Request] = None) -> web.Response:
+async def session_keys_handler(data: TrackKeys, session_id: str, request: web.Request | None = None) -> web.Response:
"""Store the content keys a client proved on a track of this remote session in the server vaults.
The server takes a KID only when a track of the remote session names it and no local server vault holds a
@@ -5182,7 +5174,7 @@ async def session_keys_handler(data: TrackKeys, session_id: str, request: Option
ensure_track_drm(track, getattr(service, "session", None))
return {kid.hex for t in list(session.tracks.values()) for drm in t.drm or [] for kid in real_kids(drm)}
- def store(named: set[str]) -> tuple[Any, Dict[Any, str]]:
+ def store(named: set[str]) -> tuple[Any, dict[Any, str]]:
vaults = load_server_vaults(service.__class__.__name__)
local = [vault for vault in vaults.vaults if vault.local]
@@ -5195,7 +5187,7 @@ async def session_keys_handler(data: TrackKeys, session_id: str, request: Option
except Exception:
return True
- new: Dict[Any, str] = {}
+ new: dict[Any, str] = {}
for kid_hex, key in pairs.items():
if kid_hex not in named or session.served_keys.get(kid_hex, ("",))[0].lower() == key:
continue
@@ -5220,7 +5212,7 @@ async def session_keys_handler(data: TrackKeys, session_id: str, request: Option
return web.json_response({})
-async def session_info_handler(session_id: str, request: Optional[web.Request] = None) -> web.Response:
+async def session_info_handler(session_id: str, request: web.Request | None = None) -> web.Response:
"""Make sure that the remote session is valid, and get the remote session info."""
session = await get_validated_session(session_id, request)
@@ -5239,7 +5231,7 @@ async def session_info_handler(session_id: str, request: Optional[web.Request] =
)
-async def session_delete_handler(session_id: str, request: Optional[web.Request] = None) -> web.Response:
+async def session_delete_handler(session_id: str, request: web.Request | None = None) -> web.Response:
"""Delete a remote session, return updated cache files, and clean up server-side data."""
from unshackle.core.api.session_store import get_session_store
@@ -5269,7 +5261,7 @@ async def session_channel_handler(session_id: str, request: web.Request) -> web.
return ws
-def shared_key_client(request: web.Request) -> Optional[str]:
+def shared_key_client(request: web.Request) -> str | None:
"""The person behind a ``shared: true`` API key, from the ``X-Client-Id`` its gateway sets; None for other keys.
Only a shared key reads the header, so a client that talks to the server directly cannot use it to pass a limit.
@@ -5314,7 +5306,7 @@ async def tunnel_check_handler(request: web.Request) -> web.Response:
try:
info = await asyncio.to_thread(verify_proxy_exit, session)
except ConnectionError as e:
- raise APIError(APIErrorCode.INVALID_PROXY, str(e), http_status=424)
+ raise APIError(APIErrorCode.INVALID_PROXY, str(e), http_status=424) from e
if not info:
raise APIError(
APIErrorCode.INVALID_PROXY,
diff --git a/unshackle/core/api/input_bridge.py b/unshackle/core/api/input_bridge.py
index 93d56eb1..935fb0e7 100644
--- a/unshackle/core/api/input_bridge.py
+++ b/unshackle/core/api/input_bridge.py
@@ -12,7 +12,7 @@ import json
import threading
import uuid
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING, Any, Optional
+from typing import TYPE_CHECKING, Any
from unshackle.core.remote_protocol import APIErrorCode, AuthStatus, coded
@@ -40,10 +40,10 @@ class Ask:
id: str
prompt: str
- cdm_call: Optional[dict[str, Any]] = None
- owner: Optional[str] = None # CHANNEL or POLL: the path that carried the ask, and the only one that answers it
- response: Optional[str] = None
- error: Optional[str] = None # the client could not answer, and says why
+ cdm_call: dict[str, Any] | None = None
+ owner: str | None = None # CHANNEL or POLL: the path that carried the ask, and the only one that answers it
+ response: str | None = None
+ error: str | None = None # the client could not answer, and says why
picked_up: threading.Event = field(default_factory=threading.Event)
answered: threading.Event = field(default_factory=threading.Event)
@@ -56,13 +56,13 @@ class InputBridge:
answers through the remote session channel or the prompt routes.
"""
- channel: Optional[SessionChannel] = field(default=None, init=False, repr=False)
+ channel: SessionChannel | None = field(default=None, init=False, repr=False)
_asks: dict[str, Ask] = field(default_factory=dict, init=False, repr=False)
_status: AuthStatus = field(default=AuthStatus.AUTHENTICATING, init=False)
_cancelled: bool = field(default=False, init=False, repr=False)
_lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False)
- def _open(self, prompt: str, cdm_call: Optional[dict[str, Any]] = None) -> Ask:
+ def _open(self, prompt: str, cdm_call: dict[str, Any] | None = None) -> Ask:
"""Register an ask and offer it to the attached channel; call it with the lock held."""
if self._cancelled:
raise RuntimeError("Session was cancelled")
@@ -147,7 +147,7 @@ class InputBridge:
"""
return [a for a in self._asks.values() if not a.answered.is_set() and a.owner != CHANNEL]
- def get_pending_cdm_call(self) -> Optional[dict[str, Any]]:
+ def get_pending_cdm_call(self) -> dict[str, Any] | None:
"""Return the CDM call that service code waits on, if any, and mark it as fetched by a client."""
with self._lock:
ask = next((a for a in self._pollable() if a.cdm_call is not None), None)
@@ -157,7 +157,7 @@ class InputBridge:
ask.picked_up.set()
return ask.cdm_call
- def get_pending_prompt(self) -> Optional[str]:
+ def get_pending_prompt(self) -> str | None:
"""Return the prompt of the first ask the prompt routes can serve, and keep that ask on them."""
with self._lock:
ask = next(iter(self._pollable()), None)
@@ -180,7 +180,7 @@ class InputBridge:
self._answer(ask, response)
return True
- def answer(self, ask_id: str, response: str, error: Optional[str] = None) -> bool:
+ def answer(self, ask_id: str, response: str, error: str | None = None) -> bool:
"""Answer the ask with this id that the remote session channel carried; False when no such ask waits."""
with self._lock:
ask = self._asks.get(ask_id)
diff --git a/unshackle/core/api/progress.py b/unshackle/core/api/progress.py
index 291f0710..968ac685 100644
--- a/unshackle/core/api/progress.py
+++ b/unshackle/core/api/progress.py
@@ -7,7 +7,8 @@ a bitrate-weighted percentage, track counts, and the labels of the tracks downlo
from __future__ import annotations
import time
-from typing import Any, Callable, Optional
+from collections.abc import Callable
+from typing import Any
from unshackle.core.api.sanitize import sanitize_log
from unshackle.core.constants import AnyTrack
@@ -85,15 +86,17 @@ def build_job_progress_callables(
started = [False] * total
seg_done = [0.0] * total
seg_total = [0.0] * total
- speeds: list[Optional[str]] = [None] * total
+ speeds: list[str | None] = [None] * total
last_emit = 0.0
- last_shape: Optional[tuple[Any, ...]] = None
+ last_shape: tuple[Any, ...] | None = None
def emit() -> None:
nonlocal last_emit, last_shape
completed = sum(done)
# Downloads fill 0..DOWNLOAD_PROGRESS_CEILING; dl.result drives muxing up to 100.
- progress = sum(w * f for w, f in zip(weights, fractions)) * DOWNLOAD_PROGRESS_CEILING / total_weight
+ progress = (
+ sum(w * f for w, f in zip(weights, fractions, strict=False)) * DOWNLOAD_PROGRESS_CEILING / total_weight
+ )
active = [labels[i] for i in range(total) if started[i] and not done[i]]
if active:
phase = "downloading " + ", ".join(active[:3])
diff --git a/unshackle/core/api/routes.py b/unshackle/core/api/routes.py
index 775ab48b..4bfff7d8 100644
--- a/unshackle/core/api/routes.py
+++ b/unshackle/core/api/routes.py
@@ -4,7 +4,7 @@ import logging
import re
import time
from collections.abc import Awaitable, Callable
-from typing import Any, Optional
+from typing import Any
import click
from aiohttp import web
@@ -184,7 +184,7 @@ def categorized(handler: Handler) -> Handler:
MAX_LOGIN_BODY_BYTES = 8 * 1024 * 1024
-async def json_body(request: web.Request, max_size: Optional[int] = None) -> Any:
+async def json_body(request: web.Request, max_size: int | None = None) -> Any:
"""The request's JSON object; raises INVALID_INPUT when it does not parse or is not an object.
``max_size`` replaces the body limit of the application for this read.
@@ -256,10 +256,10 @@ def heartbeat(handler: Handler) -> Handler:
UPDATE_CHECK_TTL = 300.0
-UPDATE_CHECK: list[tuple[float, Optional[str]]] = []
+UPDATE_CHECK: list[tuple[float, str | None]] = []
-async def latest_release() -> Optional[str]:
+async def latest_release() -> str | None:
"""The newer release the update check reports, kept for ``UPDATE_CHECK_TTL`` seconds: clients poll health."""
if UPDATE_CHECK and time.monotonic() - UPDATE_CHECK[0][0] < UPDATE_CHECK_TTL:
return UPDATE_CHECK[0][1]
diff --git a/unshackle/core/api/sanitize.py b/unshackle/core/api/sanitize.py
index 7c69aa1a..f3490c65 100644
--- a/unshackle/core/api/sanitize.py
+++ b/unshackle/core/api/sanitize.py
@@ -5,7 +5,6 @@ from __future__ import annotations
import json
import re
from pathlib import PureWindowsPath
-from typing import Optional
MAX_CACHE_KEY_DEPTH = 8
MAX_SESSION_CACHE_KEYS = 256
@@ -20,7 +19,7 @@ def sanitize_log(value: object, keep_lines: bool = False) -> str:
return (CONTROL_CHARS_BUT_LF if keep_lines else CONTROL_CHARS).sub("", str(value))
-def safe_cache_key(key: object) -> Optional[str]:
+def safe_cache_key(key: object) -> str | None:
"""Return a relative posix path for a peer-supplied cache key, or None if it escapes its directory.
unshackle writes each cache key as ``.json`` inside a fixed directory, and a key may
diff --git a/unshackle/core/api/session_channel.py b/unshackle/core/api/session_channel.py
index 29251cad..f2784638 100644
--- a/unshackle/core/api/session_channel.py
+++ b/unshackle/core/api/session_channel.py
@@ -10,7 +10,7 @@ from __future__ import annotations
import asyncio
import json
-from typing import TYPE_CHECKING, Any, Optional, Union, cast
+from typing import TYPE_CHECKING, Any, cast
from aiohttp import WSMsgType, web
@@ -32,7 +32,7 @@ if TYPE_CHECKING:
from unshackle.core.api.input_bridge import Ask
from unshackle.core.api.session_store import SessionEntry
-Message = Union[ChannelPrompt, ChannelCdmCall, ChannelLog, ChannelStatus, ChannelDrain]
+Message = ChannelPrompt | ChannelCdmCall | ChannelLog | ChannelStatus | ChannelDrain
GONE = object()
@@ -56,9 +56,9 @@ class SessionChannel:
"""
def __init__(self) -> None:
- self.ws: Optional[web.WebSocketResponse] = None
- self.queue: Optional[asyncio.Queue[Any]] = None
- self.loop: Optional[asyncio.AbstractEventLoop] = None
+ self.ws: web.WebSocketResponse | None = None
+ self.queue: asyncio.Queue[Any] | None = None
+ self.loop: asyncio.AbstractEventLoop | None = None
self.ended = False
@property
@@ -134,7 +134,7 @@ class SessionChannel:
while True:
try:
message = await asyncio.wait_for(queue.get(), HEARTBEAT)
- except asyncio.TimeoutError:
+ except TimeoutError:
session.touch()
continue
if message is GONE:
@@ -150,7 +150,7 @@ def log_message(record: LogRecord) -> ChannelLog:
return cast(ChannelLog, {"type": ChannelMessage.LOG, **record})
-def ask_message(ask: Ask) -> Union[ChannelPrompt, ChannelCdmCall]:
+def ask_message(ask: Ask) -> ChannelPrompt | ChannelCdmCall:
if ask.cdm_call is not None:
return ChannelCdmCall(type=ChannelMessage.CDM_CALL, id=ask.id, call=ask.cdm_call)
return ChannelPrompt(type=ChannelMessage.PROMPT, id=ask.id, prompt=ask.prompt)
diff --git a/unshackle/core/api/session_log.py b/unshackle/core/api/session_log.py
index c1475475..738ddc00 100644
--- a/unshackle/core/api/session_log.py
+++ b/unshackle/core/api/session_log.py
@@ -18,7 +18,8 @@ import threading
import time
import traceback
from collections import deque
-from typing import Any, Callable, Deque, List, MutableMapping, Optional, Tuple
+from collections.abc import Callable, MutableMapping
+from typing import Any
from unshackle.core.api.sanitize import sanitize_log
from unshackle.core.remote_protocol import LogRecord
@@ -34,10 +35,10 @@ class SessionLogBuffer:
"""
def __init__(self, maxlen: int = MAX_RECORDS) -> None:
- self._records: Deque[LogRecord] = deque(maxlen=maxlen)
+ self._records: deque[LogRecord] = deque(maxlen=maxlen)
self._seq = 0
self._lock = threading.Lock()
- self.listener: Optional[Callable[[LogRecord], None]] = None
+ self.listener: Callable[[LogRecord], None] | None = None
def append(self, level: int, message: str) -> None:
with self._lock:
@@ -52,7 +53,7 @@ class SessionLogBuffer:
if self.listener is not None:
self.listener(record)
- def since(self, seq: int) -> List[LogRecord]:
+ def since(self, seq: int) -> list[LogRecord]:
"""Records with a sequence number greater than *seq*, oldest first."""
with self._lock:
return [r.copy() for r in self._records if r["seq"] > seq]
@@ -63,7 +64,7 @@ class SessionLogBuffer:
return self._seq
-def format_message(msg: Any, args: Tuple[Any, ...]) -> str:
+def format_message(msg: Any, args: tuple[Any, ...]) -> str:
"""Render a logging call's message the way ``LogRecord`` would."""
try:
return str(msg) % args if args else str(msg)
@@ -137,10 +138,10 @@ class capture_service_logs:
opened the window.
"""
- def __init__(self, logger_name: str, buffer: Optional[SessionLogBuffer]) -> None:
+ def __init__(self, logger_name: str, buffer: SessionLogBuffer | None) -> None:
self._logger = logging.getLogger(logger_name)
- self._handler: Optional[SessionLogHandler] = SessionLogHandler(buffer) if buffer else None
- self._prev_level: Optional[int] = None
+ self._handler: SessionLogHandler | None = SessionLogHandler(buffer) if buffer else None
+ self._prev_level: int | None = None
def __enter__(self) -> None:
if self._handler:
diff --git a/unshackle/core/api/session_store.py b/unshackle/core/api/session_store.py
index 3f1f4c4e..21ff23ab 100644
--- a/unshackle/core/api/session_store.py
+++ b/unshackle/core/api/session_store.py
@@ -9,12 +9,13 @@ remote session.
from __future__ import annotations
import asyncio
+import builtins
import logging
import uuid
from collections import Counter, deque
from dataclasses import dataclass, field
-from datetime import datetime, timezone
-from typing import Any, Deque, Dict, List, Optional
+from datetime import UTC, datetime
+from typing import Any
from unshackle.core.api.events import bus
from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, InputBridge
@@ -37,33 +38,33 @@ class SessionEntry:
service_tag: str
service_instance: Any
titles: Any = None # Titles_T from get_titles()
- title_map: Dict[str, Any] = field(default_factory=dict)
- current_title_id: Optional[str] = None # title the client last asked tracks for
- tracks: Dict[str, Track] = field(default_factory=dict)
- served_keys: Dict[str, tuple[str, str]] = field(
+ title_map: dict[str, Any] = field(default_factory=dict)
+ current_title_id: str | None = None # title the client last asked tracks for
+ tracks: dict[str, Track] = field(default_factory=dict)
+ served_keys: dict[str, tuple[str, str]] = field(
default_factory=dict
) # KID -> (KEY, serving vault name or "cdm") from server_cdm
- tracks_by_title: Dict[str, Dict[str, Track]] = field(default_factory=dict)
- chapters_by_title: Dict[str, List[Any]] = field(default_factory=dict)
+ tracks_by_title: dict[str, dict[str, Track]] = field(default_factory=dict)
+ chapters_by_title: dict[str, list[Any]] = field(default_factory=dict)
lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False, compare=False)
- creator_ip: Optional[str] = None
- owner_key: Optional[str] = None # X-Secret-Key that owns this session
- cache_tag: Optional[str] = None
- server_account: Optional[str] = None # profile name when the server lent its own account
+ creator_ip: str | None = None
+ owner_key: str | None = None # X-Secret-Key that owns this session
+ cache_tag: str | None = None
+ server_account: str | None = None # profile name when the server lent its own account
server_cdm: bool = False # False: the client's own device licenses this session
- server_cdm_max_height: Optional[int] = None
+ server_cdm_max_height: int | None = None
server_vault: bool = False # a session the client's device licenses may still take keys from the server vault
server_device: bool = False # its service runs on the server's lent device, so keys come only from a vault
client_auth: bool = False # the login is the client's: it succeeded without a server account
- user_config: Optional[Dict[str, Any]] = None # the serve.users entry the session was created with
- input_bridge: Optional[InputBridge] = None
- log_buffer: Optional[Any] = None # SessionLogBuffer mirroring the service's self.log
+ user_config: dict[str, Any] | None = None # the serve.users entry the session was created with
+ input_bridge: InputBridge | None = None
+ log_buffer: Any | None = None # SessionLogBuffer mirroring the service's self.log
channel: SessionChannel = field(default_factory=SessionChannel, repr=False, compare=False)
- auth_error: Optional[str] = None
- client: Dict[str, Any] = field(default_factory=dict) # version/argv/platform the client reported
- actions: Deque[Dict[str, Any]] = field(default_factory=lambda: deque(maxlen=500))
- created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
- last_accessed: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
+ auth_error: str | None = None
+ client: dict[str, Any] = field(default_factory=dict) # version/argv/platform the client reported
+ actions: deque[dict[str, Any]] = field(default_factory=lambda: deque(maxlen=500))
+ created_at: datetime = field(default_factory=lambda: datetime.now(UTC))
+ last_accessed: datetime = field(default_factory=lambda: datetime.now(UTC))
def __post_init__(self) -> None:
if self.input_bridge is not None:
@@ -78,13 +79,13 @@ class SessionEntry:
def add_tracks(self, title_id: str, tracks: Tracks) -> None:
"""Register the video, audio and subtitle tracks of a title, so the later routes find each one by its id."""
- title_tracks: Dict[str, Track] = {str(t.id): t for t in [*tracks.videos, *tracks.audio, *tracks.subtitles]}
+ title_tracks: dict[str, Track] = {str(t.id): t for t in [*tracks.videos, *tracks.audio, *tracks.subtitles]}
self.tracks.update(title_tracks)
self.tracks_by_title[title_id] = title_tracks
def touch(self) -> None:
"""Update last_accessed timestamp."""
- self.last_accessed = datetime.now(timezone.utc)
+ self.last_accessed = datetime.now(UTC)
@property
def in_use(self) -> bool:
@@ -101,11 +102,11 @@ class SessionEntry:
self.input_bridge.cancel()
self.channel.end()
- def summary(self, include_actions: bool = True) -> Dict[str, Any]:
+ def summary(self, include_actions: bool = True) -> dict[str, Any]:
"""Dashboard view of the session: no service instance, no raw owner key."""
from unshackle.core.api.stats import mask_key
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
title_id = (
self.current_title_id if self.current_title_id in self.title_map else next(iter(self.title_map), None)
)
@@ -144,7 +145,7 @@ def _schedule_pending_reload(service_tag: str) -> None:
def _publish(
- action: str, entry: SessionEntry, reason: Optional[str] = None, action_entry: Optional[Dict[str, Any]] = None
+ action: str, entry: SessionEntry, reason: str | None = None, action_entry: dict[str, Any] | None = None
) -> None:
"""Tell dashboard listeners about a remote session; ``action_entry`` replaces the action log with that one action."""
data = {"action": action, **entry.summary(include_actions=action_entry is None)}
@@ -159,9 +160,9 @@ class SessionStore:
"""Thread-safe remote session store with TTL-based expiration."""
def __init__(self) -> None:
- self._sessions: Dict[str, SessionEntry] = {}
+ self._sessions: dict[str, SessionEntry] = {}
self._lock = asyncio.Lock()
- self._cleanup_task: Optional[asyncio.Task] = None
+ self._cleanup_task: asyncio.Task | None = None
self.draining = False
@property
@@ -170,7 +171,7 @@ class SessionStore:
return config.serve.get("session_ttl", 300)
@property
- def max_sessions(self) -> Optional[int]:
+ def max_sessions(self) -> int | None:
"""Max concurrent sessions from config; None when the operator set no limit.
``max_sessions: null`` or ``0`` means unlimited, so a dashboard can tell "no cap" from
@@ -183,24 +184,24 @@ class SessionStore:
self,
service_tag: str,
service_instance: Any,
- session_id: Optional[str] = None,
+ session_id: str | None = None,
*,
- owner_key: Optional[str] = None,
- creator_ip: Optional[str] = None,
- server_account: Optional[str] = None,
- cache_tag: Optional[str] = None,
- user_config: Optional[Dict[str, Any]] = None,
+ owner_key: str | None = None,
+ creator_ip: str | None = None,
+ server_account: str | None = None,
+ cache_tag: str | None = None,
+ user_config: dict[str, Any] | None = None,
server_cdm: bool = False,
- server_cdm_max_height: Optional[int] = None,
+ server_cdm_max_height: int | None = None,
server_vault: bool = False,
server_device: bool = False,
client_auth: bool = False,
- client: Optional[Dict[str, Any]] = None,
- input_bridge: Optional[InputBridge] = None,
- log_buffer: Optional[Any] = None,
+ client: dict[str, Any] | None = None,
+ input_bridge: InputBridge | None = None,
+ log_buffer: Any | None = None,
) -> SessionEntry:
"""Make a new remote session, complete with every field the dashboard shows, and announce it."""
- evicted_tag: Optional[str] = None
+ evicted_tag: str | None = None
async with self._lock:
max_sessions = self.max_sessions
if max_sessions is not None and len(self._sessions) >= max_sessions:
@@ -242,7 +243,7 @@ class SessionStore:
await self.remove_cache_dirs([evicted_tag])
return entry
- async def get(self, session_id: str) -> Optional[SessionEntry]:
+ async def get(self, session_id: str) -> SessionEntry | None:
"""Get a remote session by ID, returns None if not found or expired."""
async with self._lock:
entry = self._sessions.get(session_id)
@@ -251,7 +252,7 @@ class SessionStore:
expired = False
if not entry.in_use and entry.auth_status != AuthStatus.AUTHENTICATING:
- elapsed = (datetime.now(timezone.utc) - entry.last_accessed).total_seconds()
+ elapsed = (datetime.now(UTC) - entry.last_accessed).total_seconds()
if elapsed > self.ttl:
log.info(f"Session {sanitize_log(session_id)} expired (elapsed={elapsed:.0f}s, ttl={self.ttl}s)")
_publish("delete", self._sessions.pop(session_id), "expired")
@@ -264,7 +265,7 @@ class SessionStore:
await self.remove_cache_dirs([entry.cache_tag])
return None
- def peek(self, session_id: str) -> Optional[SessionEntry]:
+ def peek(self, session_id: str) -> SessionEntry | None:
"""A remote session entry without touching it, for read-only observers.
``get`` refreshes ``last_accessed`` and expires stale entries, so an observer polling
@@ -288,7 +289,7 @@ class SessionStore:
async def cleanup_expired(self) -> int:
"""Remove all expired sessions. Returns count of removed sessions."""
async with self._lock:
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
expired = []
for sid, entry in self._sessions.items():
if entry.in_use:
@@ -300,7 +301,7 @@ class SessionStore:
elif elapsed > self.ttl:
expired.append(sid)
ended_tags: set[str] = set()
- cache_tags: list[Optional[str]] = []
+ cache_tags: list[str | None] = []
for sid in expired:
entry = self._sessions.pop(sid)
entry.end()
@@ -346,13 +347,13 @@ class SessionStore:
log.info(f"Cancelled bridges for {count} active session(s)")
@classmethod
- async def remove_cache_dirs(cls, cache_tags: List[Optional[str]]) -> None:
+ async def remove_cache_dirs(cls, cache_tags: builtins.list[str | None]) -> None:
"""Remove the cache directories of ended remote sessions on a worker thread, outside the store lock."""
if any(cache_tags):
await asyncio.to_thread(lambda: [cls.cleanup_cache_dir(tag) for tag in cache_tags])
@staticmethod
- def cleanup_cache_dir(cache_tag: Optional[str]) -> None:
+ def cleanup_cache_dir(cache_tag: str | None) -> None:
"""Remove the remote session cache directory and empty parents."""
if not cache_tag:
return
@@ -378,7 +379,7 @@ class SessionStore:
"""Tell dashboard listeners that a session's summary changed (titles or tracks loaded, auth settled)."""
_publish("update", entry)
- def record_action(self, session_id: str, action: Dict[str, Any]) -> None:
+ def record_action(self, session_id: str, action: dict[str, Any]) -> None:
"""Append one request to the session's action log and tell dashboard listeners."""
entry = self._sessions.get(session_id)
if entry is None:
@@ -386,7 +387,7 @@ class SessionStore:
entry.actions.append(action)
_publish("update", entry, action_entry=action)
- def list(self) -> List[SessionEntry]:
+ def list(self) -> builtins.list[SessionEntry]:
"""Snapshot of every live session."""
return list(self._sessions.values())
@@ -414,7 +415,7 @@ class SessionStore:
return len(self._sessions)
-session_store: Optional[SessionStore] = None
+session_store: SessionStore | None = None
def refuse_while_draining() -> None:
diff --git a/unshackle/core/api/stats.py b/unshackle/core/api/stats.py
index 57222d2a..943b5d34 100644
--- a/unshackle/core/api/stats.py
+++ b/unshackle/core/api/stats.py
@@ -9,8 +9,8 @@ import logging
import time
from collections import Counter, defaultdict, deque
from dataclasses import dataclass, field
-from functools import lru_cache
-from typing import Any, Deque, Dict, List, Optional, Tuple
+from functools import cache
+from typing import Any
from aiohttp import web
@@ -36,17 +36,17 @@ CDM_SESSION_ID_LIMIT = 64
CDM_DEVICE_LIMIT = 255
-def _users() -> Dict[str, Any]:
+def _users() -> dict[str, Any]:
users = (config.serve or {}).get("users")
return users if isinstance(users, dict) else {}
-def _user_config(key: Optional[str]) -> Optional[Dict[str, Any]]:
+def _user_config(key: str | None) -> dict[str, Any] | None:
user = _users().get(key) if key else None
return user if isinstance(user, dict) else None
-def configured_key(key: Optional[str]) -> Optional[str]:
+def configured_key(key: str | None) -> str | None:
"""``key`` when the config knows it (a user API key, the master secret or the dashboard API key), else None.
Open routes answer 200 to any header value, so attributing by the raw header would let an
@@ -62,7 +62,7 @@ def configured_key(key: Optional[str]) -> Optional[str]:
return key if key in known else None
-def mask_key(key: Optional[str]) -> str:
+def mask_key(key: str | None) -> str:
"""A display label for an API key: its configured username, else a truncated prefix."""
if not key:
return "anonymous"
@@ -72,7 +72,7 @@ def mask_key(key: Optional[str]) -> str:
return key[:4] + "…"
-def key_id(key: Optional[str]) -> str:
+def key_id(key: str | None) -> str:
"""A stable id for an API key. A hash prefix, so two unnamed keys never collide the way
``mask_key`` does, and the id carries no key material."""
if not key:
@@ -80,14 +80,14 @@ def key_id(key: Optional[str]) -> str:
return hashlib.sha256(key.encode()).hexdigest()[:12]
-def key_tier(key: Optional[str]) -> Optional[str]:
+def key_tier(key: str | None) -> str | None:
"""The tier name an API key references, when it names one that exists."""
user = _user_config(key)
tier = user.get("tier") if user else None
return str(tier) if tier else None
-def key_rate_limit(key: Optional[str], serve: Optional[Dict[str, Any]] = None) -> Optional[int]:
+def key_rate_limit(key: str | None, serve: dict[str, Any] | None = None) -> int | None:
"""Requests per hour allowed for a key: its own override, else its tier's, else unlimited.
``serve`` reads a config block that is not yet the live one, as the reload validator does.
@@ -107,7 +107,7 @@ def key_rate_limit(key: Optional[str], serve: Optional[Dict[str, Any]] = None) -
return limit if isinstance(limit, int) and limit > 0 else None
-def rate_limit_error(where: str, value: Any) -> Optional[str]:
+def rate_limit_error(where: str, value: Any) -> str | None:
"""Why *value* cannot serve as a rate limit, or None when it can. Unset is fine.
``key_rate_limit`` reads anything else as "no limit", so a mistyped value would silently
@@ -142,10 +142,10 @@ class ServerStats:
mode: str = "full"
requests_total: int = 0
requests_rejected: int = 0
- keys: Dict[str, KeyStats] = field(default_factory=dict)
- errors: Dict[str, Counter] = field(default_factory=lambda: defaultdict(Counter)) # service -> error_code -> count
+ keys: dict[str, KeyStats] = field(default_factory=dict)
+ errors: dict[str, Counter] = field(default_factory=lambda: defaultdict(Counter)) # service -> error_code -> count
- def key_stats(self, key: Optional[str]) -> KeyStats:
+ def key_stats(self, key: str | None) -> KeyStats:
"""The counters for an API key, created on first sight."""
kid = key_id(key)
entry = self.keys.get(kid)
@@ -165,7 +165,7 @@ class ServerStats:
counter[entry.label] += entry.requests
return counter
- def check_rate_limit(self, key: str) -> Optional[int]:
+ def check_rate_limit(self, key: str) -> int | None:
"""Seconds to wait when ``key`` is over its hourly limit, else None after counting the request.
A fixed window, not a sliding one: cheap, and an operator cap does not need the precision.
@@ -183,7 +183,7 @@ class ServerStats:
entry.window_used += 1
return None
- def rate_limit_headers(self, key: str) -> Dict[str, str]:
+ def rate_limit_headers(self, key: str) -> dict[str, str]:
"""The ``X-RateLimit-*`` headers for ``key``'s current window; none for an API key with no limit."""
limit = key_rate_limit(key)
if limit is None:
@@ -195,7 +195,7 @@ class ServerStats:
"X-RateLimit-Reset": str(max(0, int(entry.window_start + RATE_LIMIT_WINDOW - time.time()))),
}
- def to_dict(self) -> Dict[str, Any]:
+ def to_dict(self) -> dict[str, Any]:
return {
"version": __version__,
"code_hash": __code_hash__,
@@ -262,7 +262,7 @@ async def stats_middleware(request: web.Request, handler: Any) -> web.StreamResp
return response
-async def _request_service(request: web.Request, session_id: Optional[str]) -> str:
+async def _request_service(request: web.Request, session_id: str | None) -> str:
"""The installed service tag a request is for, from its remote session or its JSON body; ``-`` if none.
Only an installed tag counts, so a caller cannot grow ``stats.errors`` with made-up names.
@@ -282,10 +282,10 @@ class SeqRing:
"""Keep the last N records in memory, each with a ``seq`` one above the record before it."""
def __init__(self, maxlen: int) -> None:
- self.records: Deque[Dict[str, Any]] = deque(maxlen=maxlen)
+ self.records: deque[dict[str, Any]] = deque(maxlen=maxlen)
self.seq = 0
- def append(self, record: Dict[str, Any]) -> Dict[str, Any]:
+ def append(self, record: dict[str, Any]) -> dict[str, Any]:
"""Buffer one record; ``seq`` moves only after the append, as in ``EventBus``."""
seq = self.seq + 1
item = {"seq": seq, **record}
@@ -293,7 +293,7 @@ class SeqRing:
self.seq = seq
return item
- def since(self, seq: int = 0) -> List[Dict[str, Any]]:
+ def since(self, seq: int = 0) -> list[dict[str, Any]]:
"""The records after ``seq``, oldest first, from a copy: ``append()`` can run on a worker thread."""
return [r for r in self.records.copy() if r["seq"] > seq]
@@ -317,7 +317,7 @@ class RingLogHandler(SeqRing, logging.Handler):
)
bus.publish("log", item)
- def since(self, seq: int = 0, level: Optional[str] = None, logger: Optional[str] = None) -> List[Dict[str, Any]]:
+ def since(self, seq: int = 0, level: str | None = None, logger: str | None = None) -> list[dict[str, Any]]:
"""The records after ``seq`` at or above ``level``, from ``logger`` or one of its children."""
min_level = logging.getLevelName(level.upper()) if level else 0
if not isinstance(min_level, int):
@@ -335,8 +335,8 @@ ring = RingLogHandler()
cdm_calls = SeqRing(maxlen=5000)
-@lru_cache(maxsize=None)
-def _cdm_op(pattern: str) -> Optional[Tuple[str, str]]:
+@cache
+def _cdm_op(pattern: str) -> tuple[str, str] | None:
"""The ``(drm, op)`` of a route pattern, else None. Cached: the route table does not change."""
parts = pattern.strip("/").split("/")
drm = "widevine"
@@ -347,7 +347,7 @@ def _cdm_op(pattern: str) -> Optional[Tuple[str, str]]:
return drm, parts[1]
-def _cdm_route(request: web.Request) -> Optional[Tuple[str, str]]:
+def _cdm_route(request: web.Request) -> tuple[str, str] | None:
"""The ``(drm, op)`` of a CDM device route, else None.
Reads the matched route pattern, not the path, so a device name cannot pass for an operation
@@ -357,7 +357,7 @@ def _cdm_route(request: web.Request) -> Optional[Tuple[str, str]]:
return _cdm_op(resource.canonical) if resource is not None else None
-def _hex_id(value: Any) -> Optional[str]:
+def _hex_id(value: Any) -> str | None:
"""``value`` in lowercase when it is a hexadecimal string of a plausible length, else None."""
if not isinstance(value, str) or not value or len(value) > CDM_SESSION_ID_LIMIT:
return None
@@ -368,13 +368,13 @@ def _hex_id(value: Any) -> Optional[str]:
return value.lower()
-def _key_fields(secret_key: Optional[str]) -> Dict[str, str]:
+def _key_fields(secret_key: str | None) -> dict[str, str]:
"""The ``key_id`` and ``user`` of an API key: the ``id`` and ``label`` of its ``stats.keys`` entry."""
key = configured_key(secret_key)
return {"key_id": key_id(key), "user": mask_key(key)}
-def _reply_json(response: Any) -> Dict[str, Any]:
+def _reply_json(response: Any) -> dict[str, Any]:
"""The JSON object a handler answered, or ``{}``. ``compression_middleware`` runs inside the
CDM log middleware, so the body can arrive as gzip."""
try:
@@ -387,7 +387,7 @@ def _reply_json(response: Any) -> Dict[str, Any]:
return data if isinstance(data, dict) else {}
-async def _consumed_json(request: web.Request) -> Dict[str, Any]:
+async def _consumed_json(request: web.Request) -> dict[str, Any]:
"""The JSON object of the request body when the handler consumed it, else ``{}``.
``json_body`` keeps the object on the request, and aiohttp caches a direct read.
@@ -407,7 +407,7 @@ async def _consumed_json(request: web.Request) -> Dict[str, Any]:
return body if isinstance(body, dict) else {}
-async def _cdm_record(request: web.Request, drm: str, op: str, outcome: Any) -> Dict[str, Any]:
+async def _cdm_record(request: web.Request, drm: str, op: str, outcome: Any) -> dict[str, Any]:
"""The record of one call. ``outcome`` is the response, or the exception the handler raised.
An exception that is not an HTTP one gives its class name only: its text can hold the
@@ -416,7 +416,7 @@ async def _cdm_record(request: web.Request, drm: str, op: str, outcome: Any) ->
"""
from unshackle.core.api.handlers import request_secret_key
- reply: Dict[str, Any] = {}
+ reply: dict[str, Any] = {}
if isinstance(outcome, web.StreamResponse):
status = outcome.status
if status >= 400 or op == "open":
@@ -446,7 +446,7 @@ async def _cdm_record(request: web.Request, drm: str, op: str, outcome: Any) ->
async def _record_cdm_call(
- request: web.Request, route: Tuple[str, str], ts: float, started: float, outcome: Any
+ request: web.Request, route: tuple[str, str], ts: float, started: float, outcome: Any
) -> None:
"""Append one call to ``cdm_calls``. Logs a failure and does not raise it: it must never fail the CDM call."""
ms = round((time.perf_counter() - started) * 1000, 1)
@@ -475,7 +475,7 @@ async def cdm_log_middleware(request: web.Request, handler: Any) -> web.StreamRe
return response
-def cdm_sessions(app: web.Application) -> List[Dict[str, Any]]:
+def cdm_sessions(app: web.Application) -> list[dict[str, Any]]:
"""One row per live Cdm object: its open session count and the most it allows.
Both CDM libraries refuse an ``open`` only above ``MAX_NUM_OF_SESSIONS``, so the true limit
@@ -483,7 +483,7 @@ def cdm_sessions(app: web.Application) -> List[Dict[str, Any]]:
so those do not count as open.
"""
now = time.time()
- rows: List[Dict[str, Any]] = []
+ rows: list[dict[str, Any]] = []
for drm, owner in (("widevine", app), ("playready", app.get("playready_app"))):
cdms = owner.get("cdms") if owner is not None else None
for (secret_key, device), cdm in (cdms or {}).items():
diff --git a/unshackle/core/binaries.py b/unshackle/core/binaries.py
index 59a2562f..c544bdac 100644
--- a/unshackle/core/binaries.py
+++ b/unshackle/core/binaries.py
@@ -6,7 +6,6 @@ import subprocess # nosec B404
import sys
from contextlib import suppress
from pathlib import Path
-from typing import Optional
from appdirs import user_data_dir
@@ -16,7 +15,7 @@ package_binaries_dir = Path(__file__).resolve().parent.parent / "binaries"
user_binaries_dir = Path(user_data_dir("unshackle", False)) / "binaries"
-def find(*names: str, search_dirs: Optional[list[Path]] = None) -> Optional[Path]:
+def find(*names: str, search_dirs: list[Path] | None = None) -> Path | None:
"""Find the path of the first found binary name."""
services_dir = package_binaries_dir.parent / "services"
@@ -116,7 +115,7 @@ BARE_VERSION_TOOLS = {"mp4decrypt"}
PROBE_TIMEOUT = 5.0
-def parse_version(text: str) -> Optional[str]:
+def parse_version(text: str) -> str | None:
"""Return the version from the first line that says "version" or holds a dotted number.
That line is the tool's own banner; later lines carry library and compiler versions.
@@ -135,7 +134,7 @@ def parse_version(text: str) -> Optional[str]:
return None
-def probe_output(path: Path, args: list[str]) -> Optional[str]:
+def probe_output(path: Path, args: list[str]) -> str | None:
"""Run a binary and return its stdout and stderr, or None when it does not start or times out.
A timeout kills the whole tree: on Windows subprocess.run waits with no limit for a grandchild that holds the pipes.
@@ -168,7 +167,7 @@ def probe_output(path: Path, args: list[str]) -> Optional[str]:
return f"{out}\n{err}"
-def binary_version(path: Optional[Path]) -> Optional[str]:
+def binary_version(path: Path | None) -> str | None:
"""Best-effort version probe of a binary. Returns None when nothing is parseable.
BARE_VERSION_TOOLS run with no arguments because they print their version only in the usage text.
@@ -188,7 +187,7 @@ def binary_version(path: Optional[Path]) -> Optional[str]:
_services_loaded = False
-def __getattr__(name: str) -> Optional[Path]:
+def __getattr__(name: str) -> Path | None:
global _services_loaded
candidates = __binaries.get(name)
if candidates is None and not _services_loaded:
diff --git a/unshackle/core/cacher.py b/unshackle/core/cacher.py
index 8616711c..935f8326 100644
--- a/unshackle/core/cacher.py
+++ b/unshackle/core/cacher.py
@@ -7,14 +7,14 @@ import zlib
from datetime import datetime
from os import stat_result
from pathlib import Path
-from typing import Any, Optional, Union
+from typing import Any
import jsonpickle
import jwt
from unshackle.core.config import config
-EXP_T = Union[datetime, str, int, float]
+EXP_T = datetime | str | int | float
# A number below this is seconds until expiration; at or above it, a unix timestamp (2001-09-09 onwards).
ABSOLUTE_TIMESTAMP_MIN = 1_000_000_000
@@ -26,11 +26,11 @@ class Cacher:
def __init__(
self,
service_tag: str,
- key: Optional[str] = None,
- version: Optional[int] = 1,
- data: Optional[Any] = None,
- expiration: Optional[datetime] = None,
- route: Optional[tuple[tuple[str, ...], str]] = None,
+ key: str | None = None,
+ version: int | None = 1,
+ data: Any | None = None,
+ expiration: datetime | None = None,
+ route: tuple[tuple[str, ...], str] | None = None,
) -> None:
"""``route`` is ``(prefixes, tag)``: a cache key that starts with one of ``prefixes`` lives under ``tag``."""
self.service_tag = service_tag
@@ -87,7 +87,7 @@ class Cacher:
raise ValueError(f"The {self.service_tag} {key} cache is outdated, delete {cache.path}")
return cache
- def set(self, data: Any, expiration: Optional[EXP_T] = None) -> Any:
+ def set(self, data: Any, expiration: EXP_T | None = None) -> Any:
"""
Set the cached data of the service by cache key.
:param data: absolutely anything including None.
@@ -158,4 +158,4 @@ class Cacher:
timestamp += time.time()
return datetime.fromtimestamp(timestamp)
except (ValueError, OverflowError, OSError):
- raise ValueError(f"Unrecognized Timestamp value {timestamp!r}")
+ raise ValueError(f"Unrecognized Timestamp value {timestamp!r}") from None
diff --git a/unshackle/core/cdm/choice.py b/unshackle/core/cdm/choice.py
index 2b34285b..ee399efe 100644
--- a/unshackle/core/cdm/choice.py
+++ b/unshackle/core/cdm/choice.py
@@ -3,7 +3,7 @@
from __future__ import annotations
from dataclasses import dataclass
-from typing import Any, Literal, Optional
+from typing import Any, Literal
from unshackle.core.utils.collections import ci_get
@@ -11,7 +11,7 @@ SYSTEMS = ("widevine", "playready")
SYSTEM_NAMES = {"wv": "widevine", "widevine": "widevine", "pr": "playready", "playready": "playready"}
-def drm_system(name: Any) -> Optional[str]:
+def drm_system(name: Any) -> str | None:
"""``widevine`` or ``playready`` for either name or its short form in any case; None for anything else."""
return SYSTEM_NAMES.get(name.lower()) if isinstance(name, str) else None
@@ -25,12 +25,12 @@ class CdmChoice:
both: bool
@property
- def system(self) -> Optional[str]:
+ def system(self) -> str | None:
"""The DRM system the entry settles by its keys alone: the only one it names."""
return self.systems[0] if len(self.systems) == 1 else None
@property
- def name(self) -> Optional[str]:
+ def name(self) -> str | None:
"""The device as a device name; None when the entry gives none or an inline mapping."""
return self.device if isinstance(self.device, str) and self.device else None
@@ -38,8 +38,8 @@ class CdmChoice:
def choose_cdm(
cdm: dict[str, Any],
service: str,
- profile: Optional[str] = None,
- drm: Optional[str] = None,
+ profile: str | None = None,
+ drm: str | None = None,
*,
entry: Any = None,
view: Literal["load", "licence", "stub"] = "load",
diff --git a/unshackle/core/cdm/client_relay.py b/unshackle/core/cdm/client_relay.py
index 700164c9..fde47af7 100644
--- a/unshackle/core/cdm/client_relay.py
+++ b/unshackle/core/cdm/client_relay.py
@@ -12,7 +12,8 @@ import base64
import binascii
import contextlib
import uuid
-from typing import Any, Callable, Optional, Protocol, Union
+from collections.abc import Callable
+from typing import Any, Protocol
from uuid import UUID
from pywidevine import DeviceTypes
@@ -39,10 +40,10 @@ class ClientDeviceCdm:
self,
bridge: CdmCallBridge,
is_playready: bool,
- server_device: Optional[Callable[[], Any]] = None,
- security_level: Optional[int] = None,
- system_id: Optional[int] = None,
- device_type: Optional[DeviceTypes] = None,
+ server_device: Callable[[], Any] | None = None,
+ security_level: int | None = None,
+ system_id: int | None = None,
+ device_type: DeviceTypes | None = None,
) -> None:
self.bridge = bridge
self.is_playready = is_playready
@@ -54,7 +55,7 @@ class ClientDeviceCdm:
self.system_id = system_id
if device_type is not None:
self.device_type = device_type
- self._certificates: dict[bytes, Optional[str]] = {}
+ self._certificates: dict[bytes, str | None] = {}
self._client_sessions: dict[bytes, str] = {}
self._keys: dict[bytes, list[Key]] = {}
@@ -86,7 +87,7 @@ class ClientDeviceCdm:
with contextlib.suppress(Exception):
self.bridge.request_cdm({"op": "close", "session": client_session})
- def set_service_certificate(self, session_id: bytes, certificate: Optional[Union[bytes, str]]) -> None:
+ def set_service_certificate(self, session_id: bytes, certificate: bytes | str | None) -> None:
if isinstance(certificate, bytes):
certificate = base64.b64encode(certificate).decode()
self._certificates[session_id] = certificate
@@ -99,7 +100,7 @@ class ClientDeviceCdm:
privacy_mode: bool = True,
*_: Any,
**__: Any,
- ) -> Union[bytes, str]:
+ ) -> bytes | str:
"""Have the client's CDM make a challenge. Widevine returns bytes, PlayReady the challenge XML."""
if self.is_playready:
init_data = pssh_or_wrm if isinstance(pssh_or_wrm, str) else pssh_or_wrm.dumps()
@@ -119,7 +120,7 @@ class ClientDeviceCdm:
challenge = base64.b64decode(answer["challenge"])
return challenge.decode("utf-8") if self.is_playready else challenge
- def parse_license(self, session_id: bytes, license_message: Union[bytes, str]) -> None:
+ def parse_license(self, session_id: bytes, license_message: bytes | str) -> None:
client_session = self._client_sessions.get(session_id)
if client_session is None:
raise ValueError("No client CDM challenge was made in this session")
@@ -135,7 +136,7 @@ class ClientDeviceCdm:
for k in answer.get("keys") or []
]
- def get_keys(self, session_id: bytes, type_: Optional[str] = None) -> list[Key]:
+ def get_keys(self, session_id: bytes, type_: str | None = None) -> list[Key]:
keys = self._keys.get(session_id, [])
return [k for k in keys if type_ is None or k.type == type_]
@@ -158,7 +159,7 @@ def answer_cdm_call(cdm: Any, call: dict[str, Any], sessions: dict[str, bytes])
ref = uuid.uuid4().hex
sessions[ref] = session_id
if playready:
- challenge: Union[bytes, str] = cdm.get_license_challenge(session_id, str(call["init_data"]))
+ challenge: bytes | str = cdm.get_license_challenge(session_id, str(call["init_data"]))
challenge_bytes = challenge.encode("utf-8") if isinstance(challenge, str) else challenge
else:
if call.get("service_certificate"):
diff --git a/unshackle/core/cdm/custom_remote_cdm.py b/unshackle/core/cdm/custom_remote_cdm.py
index 467cdc0c..18647478 100644
--- a/unshackle/core/cdm/custom_remote_cdm.py
+++ b/unshackle/core/cdm/custom_remote_cdm.py
@@ -1,7 +1,7 @@
from __future__ import annotations
import base64
-from typing import Any, Dict, List, Optional
+from typing import Any
import requests
from requests import Session
@@ -53,15 +53,15 @@ class CustomRemoteCDM(HttpCdm):
def __init__(
self,
host: str,
- service_name: Optional[str] = None,
- vaults: Optional[Vaults] = None,
- device: Optional[Dict[str, Any]] = None,
- auth: Optional[Dict[str, Any]] = None,
- endpoints: Optional[Dict[str, Any]] = None,
- request_mapping: Optional[Dict[str, Any]] = None,
- response_mapping: Optional[Dict[str, Any]] = None,
- caching: Optional[Dict[str, Any]] = None,
- legacy: Optional[Dict[str, Any]] = None,
+ service_name: str | None = None,
+ vaults: Vaults | None = None,
+ device: dict[str, Any] | None = None,
+ auth: dict[str, Any] | None = None,
+ endpoints: dict[str, Any] | None = None,
+ request_mapping: dict[str, Any] | None = None,
+ response_mapping: dict[str, Any] | None = None,
+ caching: dict[str, Any] | None = None,
+ legacy: dict[str, Any] | None = None,
timeout: int = 30,
**kwargs: Any,
) -> None:
@@ -139,7 +139,7 @@ class CustomRemoteCDM(HttpCdm):
self.use_vaults = caching.get("use_vaults", True) and self.vaults is not None
self.apply_authentication(self._http_session)
- def get_nested_field(self, data: Dict[str, Any], field_path: str, default: Any = None) -> Any:
+ def get_nested_field(self, data: dict[str, Any], field_path: str, default: Any = None) -> Any:
"""
Get a nested field from a dictionary using dot notation.
@@ -238,7 +238,7 @@ class CustomRemoteCDM(HttpCdm):
return value
- def evaluate_condition(self, condition: str, context: Dict[str, Any]) -> bool:
+ def evaluate_condition(self, condition: str, context: dict[str, Any]) -> bool:
"""
Evaluate a simple condition against a context.
@@ -288,8 +288,8 @@ class CustomRemoteCDM(HttpCdm):
return False
def build_request_params(
- self, endpoint_name: str, base_params: Dict[str, Any], session: Optional[Dict[str, Any]] = None
- ) -> Dict[str, Any]:
+ self, endpoint_name: str, base_params: dict[str, Any], session: dict[str, Any] | None = None
+ ) -> dict[str, Any]:
"""
Assemble request parameters with mapping and transformations.
@@ -397,7 +397,7 @@ class CustomRemoteCDM(HttpCdm):
session.auth = HTTPBasicAuth(username, password)
- def parse_response_data(self, endpoint_name: str, response_data: Dict[str, Any]) -> Dict[str, Any]:
+ def parse_response_data(self, endpoint_name: str, response_data: dict[str, Any]) -> dict[str, Any]:
"""
Parse response data based on response mapping configuration.
@@ -452,7 +452,7 @@ class CustomRemoteCDM(HttpCdm):
return parsed
- def parse_keys_from_response(self, endpoint_name: str, response_data: Dict[str, Any]) -> List[Dict[str, Any]]:
+ def parse_keys_from_response(self, endpoint_name: str, response_data: dict[str, Any]) -> list[dict[str, Any]]:
"""
Parse content keys from response data with the key field mapping.
@@ -491,15 +491,15 @@ class CustomRemoteCDM(HttpCdm):
return keys
- def _call(self, endpoint_name: str, params: Dict[str, Any], failure: str) -> Dict[str, Any]:
+ def _call(self, endpoint_name: str, params: dict[str, Any], failure: str) -> dict[str, Any]:
"""POST to a configured endpoint and return its JSON body; raises on a status other than 200."""
endpoint = self.endpoints[endpoint_name]
return self._post(endpoint["path"], params, failure, endpoint["timeout"])
def _request_challenge(
self,
- session: Dict[str, Any],
- body: Dict[str, Any],
+ session: dict[str, Any],
+ body: dict[str, Any],
license_type: str,
privacy_mode: bool,
) -> bytes:
@@ -531,7 +531,7 @@ class CustomRemoteCDM(HttpCdm):
raise requests.RequestException("API response did not contain challenge or cached keys")
- def _request_keys(self, session: Dict[str, Any], body: Dict[str, Any]) -> List[Dict[str, Any]]:
+ def _request_keys(self, session: dict[str, Any], body: dict[str, Any]) -> list[dict[str, Any]]:
request_params = self.build_request_params("decrypt_response", body, session)
response_data = self._call("decrypt_response", request_params, "License decrypt failed")
parsed_response = self.parse_response_data("decrypt_response", response_data)
diff --git a/unshackle/core/cdm/decrypt_labs_remote_cdm.py b/unshackle/core/cdm/decrypt_labs_remote_cdm.py
index 01513022..aa57d2ac 100644
--- a/unshackle/core/cdm/decrypt_labs_remote_cdm.py
+++ b/unshackle/core/cdm/decrypt_labs_remote_cdm.py
@@ -1,7 +1,7 @@
from __future__ import annotations
import base64
-from typing import Any, Dict, List, Optional
+from typing import Any
import requests
@@ -23,11 +23,11 @@ class DecryptLabsRemoteCDM(HttpCdm):
secret: str,
host: str = "https://keyxtractor.decryptlabs.com",
device_name: str = "ChromeCDM",
- service_name: Optional[str] = None,
- vaults: Optional[Vaults] = None,
- device_type: Optional[str] = None,
- system_id: Optional[int] = None,
- security_level: Optional[int] = None,
+ service_name: str | None = None,
+ vaults: Vaults | None = None,
+ device_type: str | None = None,
+ system_id: int | None = None,
+ security_level: int | None = None,
**kwargs: Any,
) -> None:
"""
@@ -62,8 +62,8 @@ class DecryptLabsRemoteCDM(HttpCdm):
def _request_challenge(
self,
- session: Dict[str, Any],
- body: Dict[str, Any],
+ session: dict[str, Any],
+ body: dict[str, Any],
license_type: str,
privacy_mode: bool,
) -> bytes:
@@ -115,7 +115,7 @@ class DecryptLabsRemoteCDM(HttpCdm):
unexpected = f"Unexpected API response format: message_type={message_type}, available_fields={list(data)}"
raise requests.RequestException(self._api_error(f"API response: {data['message']} - {unexpected}", data))
- def _request_keys(self, session: Dict[str, Any], body: Dict[str, Any]) -> List[Dict[str, Any]]:
+ def _request_keys(self, session: dict[str, Any], body: dict[str, Any]) -> list[dict[str, Any]]:
data = self._post("/decrypt-response", body, "License decrypt failed")
if data.get("message") != "success":
@@ -125,7 +125,7 @@ class DecryptLabsRemoteCDM(HttpCdm):
return self.parse_keys_response(data)
@staticmethod
- def _api_error(message: str, data: Dict[str, Any]) -> str:
+ def _api_error(message: str, data: dict[str, Any]) -> str:
"""The message with the details and the error the API added to its answer."""
if "details" in data:
message += f" - Details: {data['details']}"
@@ -133,7 +133,7 @@ class DecryptLabsRemoteCDM(HttpCdm):
message += f" - Error: {data['Error']}"
return message
- def parse_cached_keys(self, cached_keys_data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
+ def parse_cached_keys(self, cached_keys_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Parse cached keys from API response.
Args:
@@ -154,7 +154,7 @@ class DecryptLabsRemoteCDM(HttpCdm):
pass
return keys
- def parse_keys_response(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
+ def parse_keys_response(self, data: dict[str, Any]) -> list[dict[str, Any]]:
"""Parse keys from decrypt response."""
keys = []
diff --git a/unshackle/core/cdm/detect.py b/unshackle/core/cdm/detect.py
index 3aba74e1..ebb18e91 100644
--- a/unshackle/core/cdm/detect.py
+++ b/unshackle/core/cdm/detect.py
@@ -7,10 +7,10 @@ is known by its class. For a device name in config, see ``loader.find_device``.
from __future__ import annotations
from types import SimpleNamespace
-from typing import Any, Optional
+from typing import Any
-def cdm_type_stub(cdm_type: str, security_level: Optional[int] = None) -> SimpleNamespace:
+def cdm_type_stub(cdm_type: str, security_level: int | None = None) -> SimpleNamespace:
"""A CDM stand-in that only carries its DRM system, for when another machine holds the device.
``security_level`` lets a service pick a robustness tier; the attribute is absent when unknown.
@@ -21,7 +21,7 @@ def cdm_type_stub(cdm_type: str, security_level: Optional[int] = None) -> Simple
return stub
-def cdm_system(cdm: Any) -> Optional[str]:
+def cdm_system(cdm: Any) -> str | None:
"""``playready`` or ``widevine`` for a CDM object; None for no CDM or one of neither system."""
if cdm is None:
return None
diff --git a/unshackle/core/cdm/http_cdm.py b/unshackle/core/cdm/http_cdm.py
index cc9e9ef0..68ba11cf 100644
--- a/unshackle/core/cdm/http_cdm.py
+++ b/unshackle/core/cdm/http_cdm.py
@@ -10,7 +10,8 @@ from __future__ import annotations
import base64
import secrets
from abc import ABC, abstractmethod
-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Union
+from collections.abc import Sequence
+from typing import TYPE_CHECKING, Any
from uuid import UUID
from pyplayready.system.wrmheader import WRMHeader
@@ -26,7 +27,7 @@ if TYPE_CHECKING:
from unshackle.core.vaults import Vaults
-def kid_uuid(kid: Union[str, UUID]) -> UUID:
+def kid_uuid(kid: str | UUID) -> UUID:
"""A KID as a UUID; zeros on the right fill a short hex KID."""
if isinstance(kid, UUID):
return kid
@@ -34,7 +35,7 @@ def kid_uuid(kid: Union[str, UUID]) -> UUID:
return UUID(hex=clean.ljust(32, "0"))
-def kid_hex(kid: Union[str, UUID]) -> str:
+def kid_hex(kid: str | UUID) -> str:
"""A KID as lower-case hex without dashes, the form the required KIDs use."""
return str(kid).replace("-", "").lower()
@@ -94,16 +95,16 @@ class HttpCdm(ABC):
is_remote_cdm = True
chain_suffix = "Remote"
privacy_cert_devices: tuple[str, ...] = ("L1",)
- label: Optional[str] = None
+ label: str | None = None
def __init__(
self,
host: str,
device_name: str,
- device_type: Optional[str],
- service_name: Optional[str],
- vaults: Optional[Vaults],
- headers: Dict[str, str],
+ device_type: str | None,
+ service_name: str | None,
+ vaults: Vaults | None,
+ headers: dict[str, str],
) -> None:
self.host = host.rstrip("/")
self.device_name = device_name
@@ -113,7 +114,7 @@ class HttpCdm(ABC):
self._is_playready = system_of(device_type, device_name) == "playready"
if device_type:
self.device_type = self.get_device_type_enum(device_type)
- self._sessions: Dict[bytes, Dict[str, Any]] = {}
+ self._sessions: dict[bytes, dict[str, Any]] = {}
self._http_session = Session()
self._http_session.headers.update({"Content-Type": "application/json", **headers})
@@ -135,7 +136,7 @@ class HttpCdm(ABC):
"""Store the base64 PSSH that a PlayReady CDM session sends as its init data."""
self._session(session_id)["pssh_b64"] = pssh_b64
- def set_required_kids(self, kids: Sequence[Union[str, UUID]], session_id: bytes) -> None:
+ def set_required_kids(self, kids: Sequence[str | UUID], session_id: bytes) -> None:
"""Store the KIDs a CDM session needs, so that content keys from the vaults or the API cache can skip the licence."""
self._session(session_id)["required_kids"] = [kid_hex(kid) for kid in kids]
@@ -143,7 +144,7 @@ class HttpCdm(ABC):
"""Make a unique session ID."""
return secrets.token_bytes(16)
- def get_init_data_from_pssh(self, pssh: Any, pssh_b64: Optional[str] = None) -> str:
+ def get_init_data_from_pssh(self, pssh: Any, pssh_b64: str | None = None) -> str:
"""Extract init data from various PSSH formats.
PlayReady sends ``pssh_b64`` when it is set. Without it, a WRM header (object or XML text) goes
@@ -180,12 +181,12 @@ class HttpCdm(ABC):
else:
raise ValueError(f"Unsupported PSSH type: {type(pssh)}")
- def _session(self, session_id: bytes) -> Dict[str, Any]:
+ def _session(self, session_id: bytes) -> dict[str, Any]:
if session_id not in self._sessions:
raise HttpCdmExceptions.InvalidSession(f"Invalid session ID: {session_id.hex()}")
return self._sessions[session_id]
- def _default_certificate(self) -> Optional[bytes]:
+ def _default_certificate(self) -> bytes | None:
"""The common privacy certificate for a Widevine device in ``privacy_cert_devices``, else None."""
if not self._is_playready and self.device_name in self.privacy_cert_devices:
return base64.b64decode(WidevineCdm.common_privacy_cert)
@@ -210,11 +211,11 @@ class HttpCdm(ABC):
self._session(session_id)
del self._sessions[session_id]
- def get_service_certificate(self, session_id: bytes) -> Optional[bytes]:
+ def get_service_certificate(self, session_id: bytes) -> bytes | None:
"""The service certificate of a CDM session, or None."""
return self._session(session_id)["service_certificate"]
- def set_service_certificate(self, session_id: bytes, certificate: Optional[Union[bytes, str]]) -> str:
+ def set_service_certificate(self, session_id: bytes, certificate: bytes | str | None) -> str:
"""Set the service certificate (bytes or base64) of a CDM session and return a status message.
With no certificate, a Widevine device in ``privacy_cert_devices`` gets the common privacy certificate.
@@ -246,14 +247,14 @@ class HttpCdm(ABC):
required = session.get("required_kids")
if self._keys_from_vaults(session, required):
return b""
- body: Dict[str, Any] = {"scheme": self.device_name, "init_data": session["init_data"]}
+ body: dict[str, Any] = {"scheme": self.device_name, "init_data": session["init_data"]}
if self.service_name:
body["service"] = self.service_name
if session["service_certificate"]:
body["service_certificate"] = base64.b64encode(session["service_certificate"]).decode("utf-8")
return self._request_challenge(session, body, license_type, privacy_mode)
- def _keys_from_vaults(self, session: Dict[str, Any], required: Optional[List[str]]) -> bool:
+ def _keys_from_vaults(self, session: dict[str, Any], required: list[str] | None) -> bool:
"""Look up the required KIDs in the vaults; True when they hold every one."""
if not (self.use_vaults and self.vaults and required):
return False
@@ -273,7 +274,7 @@ class HttpCdm(ABC):
session["vault_keys"] = vault_keys
return False
- def _take_cached_keys(self, session: Dict[str, Any], cached_keys: List[Dict[str, Any]]) -> bool:
+ def _take_cached_keys(self, session: dict[str, Any], cached_keys: list[dict[str, Any]]) -> bool:
"""Keep the keys the API cache returned; True when they and the vault keys cover every required KID.
Otherwise the cached keys wait in the CDM session for ``parse_license`` to merge with the licence keys.
@@ -287,12 +288,12 @@ class HttpCdm(ABC):
session["keys"] = available
return True
- def _keep_challenge(self, session: Dict[str, Any], challenge: bytes, remote_session_id: Any) -> bytes:
+ def _keep_challenge(self, session: dict[str, Any], challenge: bytes, remote_session_id: Any) -> bytes:
session["challenge"] = challenge
session["remote_session_id"] = remote_session_id
return challenge
- def _post(self, path: str, body: Dict[str, Any], failure: str, timeout: float = 30) -> Dict[str, Any]:
+ def _post(self, path: str, body: dict[str, Any], failure: str, timeout: float = 30) -> dict[str, Any]:
"""POST ``body`` to ``path`` on the host and return the JSON answer; raises on a status other than 200."""
response = self._http_session.post(f"{self.host}{path}", json=body, timeout=timeout)
if response.status_code != 200:
@@ -302,8 +303,8 @@ class HttpCdm(ABC):
@abstractmethod
def _request_challenge(
self,
- session: Dict[str, Any],
- body: Dict[str, Any],
+ session: dict[str, Any],
+ body: dict[str, Any],
license_type: str,
privacy_mode: bool,
) -> bytes:
@@ -313,10 +314,10 @@ class HttpCdm(ABC):
"""
@abstractmethod
- def _request_keys(self, session: Dict[str, Any], body: Dict[str, Any]) -> List[Dict[str, Any]]:
+ def _request_keys(self, session: dict[str, Any], body: dict[str, Any]) -> list[dict[str, Any]]:
"""Send the licence to the API and return the keys it holds; the adapter's wire form."""
- def parse_license(self, session_id: bytes, license_message: Union[bytes, str]) -> None:
+ def parse_license(self, session_id: bytes, license_message: bytes | str) -> None:
"""Have the API read a licence, then merge its keys with the vault and cached keys of the CDM session.
A content key from the vaults or the API cache wins over a licence key with the same KID. A CDM session
@@ -370,7 +371,7 @@ class HttpCdm(ABC):
if key_dict:
self.vaults.add_keys(key_dict)
- def get_keys(self, session_id: bytes, type_: Optional[str] = None) -> List[Key]:
+ def get_keys(self, session_id: bytes, type_: str | None = None) -> list[Key]:
"""The keys of a CDM session; only the keys of type ``type_`` when it is set."""
keys = [
Key(
diff --git a/unshackle/core/cdm/loader.py b/unshackle/core/cdm/loader.py
index 413d2bac..89dc53d9 100644
--- a/unshackle/core/cdm/loader.py
+++ b/unshackle/core/cdm/loader.py
@@ -10,7 +10,7 @@ from __future__ import annotations
import logging
from dataclasses import dataclass
from pathlib import Path
-from typing import Any, Optional, Union
+from typing import Any
log = logging.getLogger("cdm")
@@ -39,10 +39,10 @@ class Device:
"""A device config names: its DRM system, and its ``remote_cdm`` entry or its local file."""
system: str
- source: Union[dict[str, Any], Path]
+ source: dict[str, Any] | Path
-def find_device(name: str, app_config: Any = None) -> Optional[Device]:
+def find_device(name: str, app_config: Any = None) -> Device | None:
"""The device ``name`` names in ``remote_cdm`` or the device folders; None when there is none.
``app_config`` is an API key's view of the config; None reads the config itself.
@@ -62,7 +62,7 @@ def find_device(name: str, app_config: Any = None) -> Optional[Device]:
return Device("widevine", path) if path.is_file() else None
-def device_system(name: str, app_config: Any = None) -> Optional[str]:
+def device_system(name: str, app_config: Any = None) -> str | None:
"""``widevine`` or ``playready`` for the device ``name`` names, without loading it; None when there is none."""
device = find_device(name, app_config)
return device.system if device else None
@@ -72,7 +72,7 @@ def load_cdm(
cdm_name: str,
*,
service_name: str = "",
- vaults: Optional[Any] = None,
+ vaults: Any | None = None,
) -> Any:
"""Build the CDM a device name names: a remote CDM for a ``remote_cdm`` entry, else the local device.
@@ -86,7 +86,7 @@ def load_cdm(
return load_local_cdm(cdm_name, device.system, device.source)
-def load_remote_cdm(name: str, entry: dict[str, Any], system: str, service_name: str, vaults: Optional[Any]) -> Any:
+def load_remote_cdm(name: str, entry: dict[str, Any], system: str, service_name: str, vaults: Any | None) -> Any:
"""Build a remote CDM from its ``remote_cdm`` entry."""
from unshackle.core.config import config
@@ -147,7 +147,7 @@ def load_local_cdm(name: str, system: str, path: Path) -> Any:
if "expected 2 but parsed 1" in str(e):
raise ValueError(
f"{name}.wvd seems to be a v1 WVD file, use `pywidevine migrate --help` to migrate it to v2."
- )
- raise ValueError(f"{name}.wvd is an invalid or corrupt Widevine Device file, {e}")
+ ) from None
+ raise ValueError(f"{name}.wvd is an invalid or corrupt Widevine Device file, {e}") from e
return WidevineCdm.from_device(wvd)
diff --git a/unshackle/core/cdm/monalisa/monalisa_cdm.py b/unshackle/core/cdm/monalisa/monalisa_cdm.py
index 181a9ea3..2b7c56ba 100644
--- a/unshackle/core/cdm/monalisa/monalisa_cdm.py
+++ b/unshackle/core/cdm/monalisa/monalisa_cdm.py
@@ -14,7 +14,7 @@ import re
import sys
import uuid
from pathlib import Path
-from typing import Any, Dict, Union
+from typing import Any
import wasmtime
@@ -64,7 +64,7 @@ class MonaLisaCDM:
try:
data = json.loads(self.device_path.read_text(encoding="utf-8", errors="replace"))
except Exception as e:
- raise ValueError(f"Invalid device file (JSON): {e}")
+ raise ValueError(f"Invalid device file (JSON): {e}") from e
wasm_path_str = data.get("wasm_path")
if not wasm_path_str:
@@ -83,7 +83,7 @@ class MonaLisaCDM:
else:
self.module = wasmtime.Module(self.engine, wasm_path.read_bytes())
except Exception as e:
- raise RuntimeError(f"Failed to load WASM module: {e}")
+ raise RuntimeError(f"Failed to load WASM module: {e}") # noqa: B904
self.store: wasmtime.Store | None = None
self.memory: wasmtime.Memory | None = None
@@ -159,7 +159,7 @@ class MonaLisaCDM:
self.exports = {}
self.ctx = None
- def extract_keys(self, license_data: Union[str, bytes]) -> Dict:
+ def extract_keys(self, license_data: str | bytes) -> dict:
"""
Extract decryption keys from license/ticket data.
diff --git a/unshackle/core/cdm/unprobed_remote_cdm.py b/unshackle/core/cdm/unprobed_remote_cdm.py
index b8a4c682..15573e78 100644
--- a/unshackle/core/cdm/unprobed_remote_cdm.py
+++ b/unshackle/core/cdm/unprobed_remote_cdm.py
@@ -9,7 +9,7 @@ API now fails at the first API call instead.
from __future__ import annotations
import functools
-from typing import Any, Optional
+from typing import Any
import requests
from Crypto.PublicKey import RSA
@@ -29,7 +29,7 @@ class SecretSession(requests.Session):
prepared_request.headers.pop("X-Secret-Key", None)
-def _connect(cdm: Any, drm: str, host: Optional[str], secret: Optional[str], device_name: Optional[str]) -> None:
+def _connect(cdm: Any, drm: str, host: str | None, secret: str | None, device_name: str | None) -> None:
"""Set what upstream `__init__` sets after the probe, on the name-mangled upstream session."""
if not (host and secret and device_name):
raise ValueError(f"A {drm} remote CDM needs host, secret and device_name")
@@ -51,18 +51,16 @@ class UnprobedWidevineRemoteCdm(WidevineRemoteCdm):
device_type: Any,
system_id: int,
security_level: int,
- host: Optional[str],
- secret: Optional[str],
- device_name: Optional[str],
+ host: str | None,
+ secret: str | None,
+ device_name: str | None,
) -> None:
_connect(self, "Widevine", host, secret, device_name)
WidevineCdm.__init__(self, device_type, system_id, security_level, ClientIdentification(), _placeholder_key())
class UnprobedPlayReadyRemoteCdm(PlayReadyRemoteCdm):
- def __init__(
- self, security_level: int, host: Optional[str], secret: Optional[str], device_name: Optional[str]
- ) -> None:
+ def __init__(self, security_level: int, host: str | None, secret: str | None, device_name: str | None) -> None:
if not isinstance(security_level, int):
raise TypeError(f"A PlayReady remote CDM needs an int security_level, not {security_level!r}")
_connect(self, "PlayReady", host, secret, device_name)
diff --git a/unshackle/core/commands.py b/unshackle/core/commands.py
index f1829a55..b9d40267 100644
--- a/unshackle/core/commands.py
+++ b/unshackle/core/commands.py
@@ -1,6 +1,5 @@
import logging
from pathlib import Path
-from typing import Optional
import click
@@ -67,7 +66,7 @@ class Commands(click.Group):
check_load_errors()
return [x.stem.replace("_", "-") for x in COMMANDS]
- def get_command(self, ctx: click.Context, name: str) -> Optional[click.Command]:
+ def get_command(self, ctx: click.Context, name: str) -> click.Command | None:
"""Load the command code and return the main click command function."""
check_load_errors()
module = MODULES.get(name) or MODULES.get(name.replace("-", "_"))
diff --git a/unshackle/core/config.py b/unshackle/core/config.py
index b07a9f46..8de12218 100644
--- a/unshackle/core/config.py
+++ b/unshackle/core/config.py
@@ -4,7 +4,7 @@ import logging
import re
import warnings
from pathlib import Path
-from typing import Any, Optional, Union
+from typing import Any
import yaml
from appdirs import AppDirs
@@ -72,7 +72,7 @@ def resolve_cdm_name(cdm: dict, service: str, override: Any = None) -> Any:
return override or ci_get(cdm, service) or ci_get(cdm, "default")
-def cdm_entry_names_device(entry: Any, profile: Optional[str] = None) -> bool:
+def cdm_entry_names_device(entry: Any, profile: str | None = None) -> bool:
"""Whether a per-service ``cdm`` entry names a device when no quality is known.
An entry that selects only by quality, or by a different profile, names none.
@@ -186,7 +186,7 @@ class Config:
self.tvdb_api_key: str = kwargs.get("tvdb_api_key") or ""
self.tvdb_pin: str = kwargs.get("tvdb_pin") or ""
self.tvdb_order: str = (kwargs.get("tvdb_order") or "").lower()
- self.metadata_providers: Union[list, dict] = kwargs.get("metadata_providers") or []
+ self.metadata_providers: list | dict = kwargs.get("metadata_providers") or []
self.anilist_title_language: str = (kwargs.get("anilist_title_language") or "english").lower()
self.disable_metadata: bool = kwargs.get("disable_metadata", False)
self.simkl_client_id: str = kwargs.get("simkl_client_id") or ""
@@ -198,7 +198,7 @@ class Config:
# mask local base dirs (install root/venv/home) in logged paths; False shows full paths
self.redact_paths: bool = kwargs.get("redact_paths", True)
self.continue_downloads: bool = kwargs.get("continue_downloads", False)
- self.sample: Optional[tuple[int, int]] = None
+ self.sample: tuple[int, int] | None = None
self.post_scripts: list = kwargs.get("post_scripts") or []
self.language_tags: dict = kwargs.get("language_tags") or {}
@@ -316,13 +316,17 @@ class Config:
all_templates["folder"] = self.folder_template
for kind, tmpl in self.folder_templates.items():
if kind not in {"movies", "series", "sports", "songs", "albums"}:
- warnings.warn(f"Unknown folder template kind '{kind}' (expected movies/series/sports/songs/albums)")
+ warnings.warn(
+ f"Unknown folder template kind '{kind}' (expected movies/series/sports/songs/albums)", stacklevel=1
+ )
continue
all_templates[f"folder.{kind}"] = tmpl
for template_type, template_str in all_templates.items():
if not isinstance(template_str, str):
- warnings.warn(f"Template '{template_type}' must be a string, got {type(template_str).__name__}")
+ warnings.warn(
+ f"Template '{template_type}' must be a string, got {type(template_str).__name__}", stacklevel=1
+ )
continue
variables = re.findall(r"\{([^}]+)\}", template_str)
@@ -332,9 +336,11 @@ class Config:
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")
+ warnings.warn(f"Unknown template variable '{var}' in {template_type} template", stacklevel=1)
elif var_clean not in allowed:
- warnings.warn(f"Template variable '{var}' is not available in the {template_type} template")
+ warnings.warn(
+ f"Template variable '{var}' is not available in the {template_type} template", stacklevel=1
+ )
test_template = re.sub(r"\{[^}]+\}", "TEST", template_str)
if template_type.startswith("folder"):
@@ -342,10 +348,10 @@ class Config:
else:
unsafe_segment = bool(re.search(unsafe_chars, test_template))
if unsafe_segment:
- warnings.warn(f"Template '{template_type}' may contain filesystem-unsafe characters")
+ warnings.warn(f"Template '{template_type}' may contain filesystem-unsafe characters", stacklevel=1)
if not template_str.strip():
- warnings.warn(f"Template '{template_type}' is empty")
+ warnings.warn(f"Template '{template_type}' is empty", stacklevel=1)
def get_folder_template(self, kind: str) -> str:
"""Find the folder template for the given title kind.
@@ -446,7 +452,7 @@ POSSIBLE_CONFIG_PATHS = (
)
-def get_config_path() -> Optional[Path]:
+def get_config_path() -> Path | None:
"""
Get Path to Config from any one of the possible locations.
diff --git a/unshackle/core/console.py b/unshackle/core/console.py
index a37bb5c9..88ac3e19 100644
--- a/unshackle/core/console.py
+++ b/unshackle/core/console.py
@@ -5,10 +5,12 @@ import math
import shutil
import sys
import unicodedata
+from collections.abc import Callable, Iterable, Mapping, Sized
from datetime import datetime
from functools import lru_cache
+from itertools import pairwise
from types import ModuleType
-from typing import IO, Any, Callable, Iterable, List, Literal, Mapping, Optional, Sized, TextIO, Union, cast
+from typing import IO, Any, Literal, Optional, TextIO, cast
import rich.cells
from rich import box
@@ -38,12 +40,12 @@ class ComfyLogRenderer(LogRender):
self,
console: "Console",
renderables: Iterable["ConsoleRenderable"],
- log_time: Optional[datetime] = None,
- time_format: Optional[Union[str, FormatTimeCallable]] = None,
+ log_time: datetime | None = None,
+ time_format: str | FormatTimeCallable | None = None,
level: TextType = "",
- path: Optional[str] = None,
- line_no: Optional[int] = None,
- link_path: Optional[str] = None,
+ path: str | None = None,
+ line_no: int | None = None,
+ link_path: str | None = None,
) -> "Table":
from rich.containers import Renderables
@@ -56,7 +58,7 @@ class ComfyLogRenderer(LogRender):
output.add_column(ratio=1, style="log.message", overflow="fold")
if self.show_path and path:
output.add_column(style="log.path")
- row: List["RenderableType"] = []
+ row: list[RenderableType] = []
if self.show_time:
log_time = log_time or console.get_datetime()
time_format = time_format or self.time_format
@@ -91,28 +93,28 @@ class ComfyLogRenderer(LogRender):
class ComfyRichHandler(RichHandler):
def __init__(
self,
- level: Union[int, str] = logging.NOTSET,
- console: Optional[Console] = None,
+ level: int | str = logging.NOTSET,
+ console: Console | None = None,
*,
show_time: bool = True,
omit_repeated_times: bool = True,
show_level: bool = True,
show_path: bool = True,
enable_link_path: bool = True,
- highlighter: Optional[Highlighter] = None,
+ highlighter: Highlighter | None = None,
markup: bool = False,
rich_tracebacks: bool = False,
- tracebacks_width: Optional[int] = None,
+ tracebacks_width: int | None = None,
tracebacks_extra_lines: int = 3,
- tracebacks_theme: Optional[str] = None,
+ tracebacks_theme: str | None = None,
tracebacks_word_wrap: bool = True,
tracebacks_show_locals: bool = False,
- tracebacks_suppress: Iterable[Union[str, ModuleType]] = (),
+ tracebacks_suppress: Iterable[str | ModuleType] = (),
locals_max_length: int = 10,
locals_max_string: int = 80,
- log_time_format: Union[str, FormatTimeCallable] = "[%x %X]",
- keywords: Optional[List[str]] = None,
- log_renderer: Optional[LogRender] = None,
+ log_time_format: str | FormatTimeCallable = "[%x %X]",
+ keywords: list[str] | None = None,
+ log_renderer: LogRender | None = None,
) -> None:
super().__init__(
level=level,
@@ -140,6 +142,9 @@ class ComfyRichHandler(RichHandler):
self._log_render = log_renderer
+REPR_HIGHLIGHTER = ReprHighlighter()
+
+
class ComfyConsole(Console):
"""A comfy high level console interface.
@@ -184,35 +189,35 @@ class ComfyConsole(Console):
def __init__(
self,
*,
- color_system: Optional[Literal["auto", "standard", "256", "truecolor", "windows"]] = "auto",
- force_terminal: Optional[bool] = None,
- force_jupyter: Optional[bool] = None,
- force_interactive: Optional[bool] = None,
+ color_system: Literal["auto", "standard", "256", "truecolor", "windows"] | None = "auto",
+ force_terminal: bool | None = None,
+ force_jupyter: bool | None = None,
+ force_interactive: bool | None = None,
soft_wrap: bool = False,
- theme: Optional[Theme] = None,
+ theme: Theme | None = None,
stderr: bool = False,
- file: Optional[IO[str]] = None,
+ file: IO[str] | None = None,
quiet: bool = False,
- width: Optional[int] = None,
- height: Optional[int] = None,
- style: Optional[StyleType] = None,
- no_color: Optional[bool] = None,
+ width: int | None = None,
+ height: int | None = None,
+ style: StyleType | None = None,
+ no_color: bool | None = None,
tab_size: int = 8,
record: bool = False,
markup: bool = True,
emoji: bool = True,
- emoji_variant: Optional[EmojiVariant] = None,
+ emoji_variant: EmojiVariant | None = None,
highlight: bool = True,
log_time: bool = True,
log_path: bool = True,
- log_time_format: Union[str, FormatTimeCallable] = "[%X]",
- highlighter: Optional["HighlighterType"] = ReprHighlighter(),
- legacy_windows: Optional[bool] = None,
+ log_time_format: str | FormatTimeCallable = "[%X]",
+ highlighter: Optional["HighlighterType"] = REPR_HIGHLIGHTER,
+ legacy_windows: bool | None = None,
safe_box: bool = True,
- get_datetime: Optional[Callable[[], datetime]] = None,
- get_time: Optional[Callable[[], float]] = None,
- _environ: Optional[Mapping[str, str]] = None,
- log_renderer: Optional[LogRender] = None,
+ get_datetime: Callable[[], datetime] | None = None,
+ get_time: Callable[[], float] | None = None,
+ _environ: Mapping[str, str] | None = None,
+ log_renderer: LogRender | None = None,
) -> None:
super().__init__(
color_system=color_system,
@@ -256,7 +261,7 @@ class ComfyConsole(Console):
speed: float = 1.0,
refresh_per_second: float = 12.5,
pad: PaddingDimensions = (0, 5),
- ) -> Union[Live, Status]:
+ ) -> Live | Status:
"""Display a comfy status and spinner.
Args:
@@ -304,7 +309,7 @@ class ComfyConsole(Console):
markup: bool = True,
emoji: bool = True,
password: bool = False,
- stream: Optional[TextIO] = None,
+ stream: TextIO | None = None,
) -> str:
"""Displays a prompt and waits for input from the user, temporarily pausing any active Live displays."""
# Find active Live displays to prevent overlap / disappearing prompt.
@@ -390,7 +395,7 @@ class GradientPulseBarColumn(BarColumn):
class _GradientPulse:
- def __init__(self, lut: list[Style], offset: float, period: float, width: Optional[int]) -> None:
+ def __init__(self, lut: list[Style], offset: float, period: float, width: int | None) -> None:
self.lut = lut
self.offset = offset
self.period = period
@@ -436,9 +441,7 @@ def _cell_len(text: str, unicode_version: str) -> int:
width = _rich_cell_len(text, unicode_version)
if _JOINING_VIRAMAS.isdisjoint(text):
return width
- return width - sum(
- prev in _JOINING_VIRAMAS and unicodedata.category(char) == "Lo" for prev, char in zip(text, text[1:])
- )
+ return width - sum(prev in _JOINING_VIRAMAS and unicodedata.category(char) == "Lo" for prev, char in pairwise(text))
rich.cells.get_character_cell_size = _cell_size
@@ -478,7 +481,7 @@ def listing_panel(renderable: RenderableType, title: str) -> Panel:
return Panel(renderable, title=title, box=box.SQUARE, border_style="bright_black")
-def listing_table(title: Optional[str] = None, **kwargs: Any) -> Table:
+def listing_table(title: str | None = None, **kwargs: Any) -> Table:
"""Assemble a table in the style of the rich-click help tables, so listings and help screens match."""
kwargs.setdefault("box", box.HORIZONTALS)
kwargs.setdefault("show_edge", False) # no top or bottom rule, so the title runs straight into the header
@@ -511,10 +514,10 @@ def print_listing(renderable: RenderableType) -> None:
console.print(Padding(renderable, (0, 5)))
-_prompt_handler: Optional[Callable[[str], str]] = None
+_prompt_handler: Callable[[str], str] | None = None
-def set_prompt_handler(handler: Optional[Callable[[str], str]]) -> None:
+def set_prompt_handler(handler: Callable[[str], str] | None) -> None:
"""Route every :func:`prompt_user` call to *handler*, for a process with no terminal to prompt on."""
global _prompt_handler
_prompt_handler = handler
@@ -530,16 +533,16 @@ def prompt_user(prompt: str) -> str:
return console.input(body)
-_notice_handler: Optional[Callable[[Optional[str]], None]] = None
+_notice_handler: Callable[[str | None], None] | None = None
-def set_notice_handler(handler: Optional[Callable[[Optional[str]], None]]) -> None:
+def set_notice_handler(handler: Callable[[str | None], None] | None) -> None:
"""Route every :func:`show_notice` call to *handler*, for a process whose log output no user reads."""
global _notice_handler
_notice_handler = handler
-def show_notice(message: Optional[str]) -> None:
+def show_notice(message: str | None) -> None:
"""Give *message* to the notice handler, or None to clear it. Without a handler this does nothing."""
if _notice_handler is not None:
_notice_handler(message)
diff --git a/unshackle/core/credential.py b/unshackle/core/credential.py
index 8d64b34a..0facf1a7 100644
--- a/unshackle/core/credential.py
+++ b/unshackle/core/credential.py
@@ -4,13 +4,13 @@ import base64
import hashlib
import re
from pathlib import Path
-from typing import Any, Optional, Union
+from typing import Any
class Credential:
"""Username (or Email) and Password Credential."""
- def __init__(self, username: str, password: str, extra: Optional[str] = None) -> None:
+ def __init__(self, username: str, password: str, extra: str | None = None) -> None:
self.username = username
self.password = password
self.extra = extra
@@ -31,7 +31,7 @@ class Credential:
"""Return credential data as a string."""
return f"{self.username}:{self.password}" + (f":{self.extra}" if self.extra else "")
- def dump(self, path: Union[Path, str]) -> int:
+ def dump(self, path: Path | str) -> int:
"""Write credential data to a file."""
if isinstance(path, str):
path = Path(path)
diff --git a/unshackle/core/dl_options.py b/unshackle/core/dl_options.py
index f44fb2d5..ae113095 100644
--- a/unshackle/core/dl_options.py
+++ b/unshackle/core/dl_options.py
@@ -1,8 +1,9 @@
"""The dl option table: which dl options the REST API takes, their API defaults, and what a remote client forwards."""
import logging
+from collections.abc import Mapping
from dataclasses import dataclass
-from typing import Any, Dict, List, Literal, Mapping, Optional, get_args
+from typing import Any, Literal, get_args
import click
@@ -27,12 +28,12 @@ class ApiOption:
"""
default: Any
- remote: Optional[RemoteKind] = None
+ remote: RemoteKind | None = None
CLI_ONLY = None
-DL_OPTIONS: Dict[str, Optional[ApiOption]] = {
+DL_OPTIONS: dict[str, ApiOption | None] = {
"profile": ApiOption(None),
"quality": ApiOption([]),
"vcodec": ApiOption([]),
@@ -129,7 +130,7 @@ DL_OPTIONS: Dict[str, Optional[ApiOption]] = {
An option the REST API takes has an ``ApiOption``; a ``CLI_ONLY`` option never reaches dl from the API.
"""
-DEFAULT_DOWNLOAD_PARAMS: Dict[str, Any] = {name: option.default for name, option in DL_OPTIONS.items() if option}
+DEFAULT_DOWNLOAD_PARAMS: dict[str, Any] = {name: option.default for name, option in DL_OPTIONS.items() if option}
FORWARDED_DL_PARAMS = [
(name, option)
for kind in get_args(RemoteKind)
@@ -138,15 +139,15 @@ FORWARDED_DL_PARAMS = [
]
-def cast_dl_params(cli: click.Command, params: Dict[str, Any]) -> Dict[str, Any]:
+def cast_dl_params(cli: click.Command, params: dict[str, Any]) -> dict[str, Any]:
"""Cast each ``DEFAULT_DOWNLOAD_PARAMS`` parameter in ``params`` by its dl click type, under its dl option name.
A missing, ``None`` or empty-string parameter, and an empty ``range``, take the API default, so
``output_dir: ""`` is not the working directory. A parameter outside ``DEFAULT_DOWNLOAD_PARAMS`` never reaches
dl, so API clients cannot set a new CLI option until the table opens it. Raises ``click.BadParameter``.
"""
- kept: Dict[str, Any] = {}
- to_cast: Dict[str, Any] = {}
+ kept: dict[str, Any] = {}
+ to_cast: dict[str, Any] = {}
for key, default in DEFAULT_DOWNLOAD_PARAMS.items():
value = params.get(key)
if value is None or value == "" or (key == "range" and value == []):
@@ -160,12 +161,12 @@ def cast_dl_params(cli: click.Command, params: Dict[str, Any]) -> Dict[str, Any]
raise click.BadParameter(f"Invalid {key}: {e.message}") from e
-def remote_dl_params(params: Mapping[str, Any]) -> Dict[str, Any]:
+def remote_dl_params(params: Mapping[str, Any]) -> dict[str, Any]:
"""The ``dl_params`` a remote client sends when it creates a remote session, from its dl context params.
An empty list is sent as-is, because only an absent key falls back to the dl default on the server.
"""
- sent: Dict[str, Any] = {}
+ sent: dict[str, Any] = {}
for key, option in FORWARDED_DL_PARAMS:
if option.remote == "flag":
if key in params:
@@ -175,7 +176,7 @@ def remote_dl_params(params: Mapping[str, Any]) -> Dict[str, Any]:
return sent
-def forwarded_dl_params(data: Dict[str, Any]) -> Dict[str, Any]:
+def forwarded_dl_params(data: dict[str, Any]) -> dict[str, Any]:
"""Read the dl track selection that a remote-dl client sends under ``dl_params``.
Services read these values from ``ctx.parent.params`` to pick the manifests they
@@ -189,7 +190,7 @@ def forwarded_dl_params(data: Dict[str, Any]) -> Dict[str, Any]:
if not isinstance(raw, dict):
raw = {}
- def str_list(key: str) -> Optional[List[str]]:
+ def str_list(key: str) -> list[str] | None:
value = raw.get(key)
if isinstance(value, list) and all(isinstance(v, str) for v in value):
return list(value)
@@ -197,7 +198,7 @@ def forwarded_dl_params(data: Dict[str, Any]) -> Dict[str, Any]:
log.warning(f"Ignoring dl_params.{key}: it must be an array of strings")
return None
- params: Dict[str, Any] = {}
+ params: dict[str, Any] = {}
for key, option in FORWARDED_DL_PARAMS:
if option.remote == "flag":
params[key] = raw.get(key) is True
diff --git a/unshackle/core/downloaders/requests.py b/unshackle/core/downloaders/requests.py
index 93614ea0..517e9fc7 100644
--- a/unshackle/core/downloaders/requests.py
+++ b/unshackle/core/downloaders/requests.py
@@ -12,16 +12,18 @@ import threading
import time
import traceback
from collections import OrderedDict, deque
+from collections.abc import Callable, Generator, MutableMapping
from concurrent.futures import FIRST_COMPLETED, wait
from concurrent.futures.thread import ThreadPoolExecutor
from copy import copy
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from email.utils import parsedate_to_datetime
+from functools import partial
from http.cookiejar import CookieJar
from pathlib import Path
from queue import Empty, Queue
from string import Formatter
-from typing import Any, Callable, Generator, MutableMapping, Optional, Union, cast
+from typing import Any, cast
from requests import Session
from requests.adapters import HTTPAdapter, Retry
@@ -96,7 +98,7 @@ class SpeedWindow:
# zero-byte seed keeps early readings from exceeding the true rate
self.samples: deque[tuple[float, int]] = deque([(start, 0)])
- def rate(self, now: float, total: int) -> Optional[float]:
+ def rate(self, now: float, total: int) -> float | None:
self.samples.append((now, total))
while now - self.samples[0][0] > SPEED_ROLLING_WINDOW:
self.samples.popleft()
@@ -129,7 +131,7 @@ class TokenBucket:
DOWNLOAD_CANCELLED.wait(wait)
-speed_limiter: Optional[TokenBucket] = None
+speed_limiter: TokenBucket | None = None
speed_limit_locked = False
SPEED_UNITS = {
@@ -144,7 +146,7 @@ SPEED_UNITS = {
}
-def parse_speed_limit(value: Union[str, int, float, None]) -> Optional[float]:
+def parse_speed_limit(value: str | int | float | None) -> float | None:
"""
Parse a human-readable speed limit into bytes/sec, or None for unlimited.
@@ -173,7 +175,7 @@ def format_speed(bytes_per_sec: float) -> str:
return f"{filesize.decimal(int(bytes_per_sec))}/s"
-def set_speed_limit(bytes_per_sec: Optional[float], lock: bool = False) -> None:
+def set_speed_limit(bytes_per_sec: float | None, lock: bool = False) -> None:
"""
Set (or clear) the global download speed limit shared by all threads.
@@ -223,7 +225,7 @@ class AdaptiveWorkerController:
"""
def __init__(
- self, cap: int, start: Optional[int] = None, tick: float = ADAPTIVE_TICK, window: float = SPEED_ROLLING_WINDOW
+ self, cap: int, start: int | None = None, tick: float = ADAPTIVE_TICK, window: float = SPEED_ROLLING_WINDOW
) -> None:
self.cap = max(ADAPTIVE_MIN, cap)
base = self.cap if start is None else start
@@ -231,10 +233,10 @@ class AdaptiveWorkerController:
self.tick = tick
self.window = window
self._samples: deque[tuple[float, int]] = deque()
- self._first_sample: Optional[float] = None
+ self._first_sample: float | None = None
self._errors = 0
- self._last_tick: Optional[float] = None
- self._last_action: Optional[str] = None
+ self._last_tick: float | None = None
+ self._last_action: str | None = None
self._speed_before_increase = 0.0
self._target_before_increase = self.target
self._cooldown = False
@@ -253,7 +255,7 @@ class AdaptiveWorkerController:
def record_error(self, now: float) -> None:
self._errors += 1
- def speed(self, now: float, span: Optional[float] = None) -> float:
+ def speed(self, now: float, span: float | None = None) -> float:
"""Rolling bytes/sec over the window, or over the trailing ``span`` seconds when given."""
self.prune(now)
if not self._samples:
@@ -272,7 +274,7 @@ class AdaptiveWorkerController:
# measured from the first-ever sample so pruning cannot starve the check
return self._first_sample is not None and (now - self._first_sample) >= self.tick / 2
- def update(self, now: float, inflight_plus_remaining: Optional[int] = None) -> int:
+ def update(self, now: float, inflight_plus_remaining: int | None = None) -> int:
"""Evaluate the policy at most once per tick. Return the current target.
``inflight_plus_remaining`` (when given) is the count of segments still in flight or
@@ -303,7 +305,7 @@ class AdaptiveWorkerController:
self._last_action = None
return self.target
- reason: Optional[str] = None
+ reason: str | None = None
if errors >= ADAPTIVE_ERROR_BURST:
self.target = max(ADAPTIVE_MIN, self.target // 2)
self._cooldown = True
@@ -340,7 +342,7 @@ class AdaptiveWorkerController:
return self.target
-def permanent_status(exc: BaseException) -> Optional[int]:
+def permanent_status(exc: BaseException) -> int | None:
"""HTTP status of ``exc`` when it is a client error that no retry can fix.
408 and 429 do not count: they are transient, and a fan-out that trips a per-client rate
@@ -383,15 +385,15 @@ def retry_sleep(exc: Exception, attempts: int) -> float:
except Exception:
retry_after = None
if retry_after:
- wait: Optional[float] = None
+ wait: float | None = None
try:
wait = float(retry_after)
except ValueError:
try:
retry_date = parsedate_to_datetime(retry_after)
if retry_date.tzinfo is None:
- retry_date = retry_date.replace(tzinfo=timezone.utc)
- wait = (retry_date - datetime.now(timezone.utc)).total_seconds()
+ retry_date = retry_date.replace(tzinfo=UTC)
+ wait = (retry_date - datetime.now(UTC)).total_seconds()
except Exception:
wait = None
if wait is not None and math.isfinite(wait):
@@ -452,7 +454,7 @@ def is_outage(exc: BaseException) -> bool:
return False
-def is_content_encoded(value: Optional[str]) -> bool:
+def is_content_encoded(value: str | None) -> bool:
"""
Whether a Content-Encoding value names any coding other than absent or `identity`.
@@ -527,7 +529,7 @@ def range_covers_full_body(headers: MutableMapping[str, Any], content_length: in
return start == 0 and content_length == end + 1
-def parse_content_range(value: Any) -> Optional[tuple[int, int, Optional[int]]]:
+def parse_content_range(value: Any) -> tuple[int, int, int | None] | None:
"""Parse a 206's ``Content-Range`` into ``(start, end, total)``. Gives None when absent or unparseable.
``total`` is None for an unknown complete length (``*``). None fails closed: a caller
@@ -541,7 +543,7 @@ def parse_content_range(value: Any) -> Optional[tuple[int, int, Optional[int]]]:
return int(match.group(1)), int(match.group(2)), None if match.group(3) == "*" else int(match.group(3))
-def parse_content_range_unsatisfied(value: Any) -> Optional[int]:
+def parse_content_range_unsatisfied(value: Any) -> int | None:
"""Parse a 416's ``Content-Range`` into the complete length. Gives None when absent or unknown.
A 416 answers with ``bytes */N`` (or ``bytes */*``), which the 206 form does not cover.
@@ -552,7 +554,7 @@ def parse_content_range_unsatisfied(value: Any) -> Optional[int]:
return int(match.group(1)) if match else None
-def range_clamped_to_end(content_range: tuple[int, int, Optional[int]], slice_end: int) -> bool:
+def range_clamped_to_end(content_range: tuple[int, int, int | None], slice_end: int) -> bool:
"""Whether a 206 stops early only because the requested range ends past the resource.
RFC 9110 clamps a range end at or beyond the complete length to the last byte, so the
@@ -562,7 +564,7 @@ def range_clamped_to_end(content_range: tuple[int, int, Optional[int]], slice_en
return total is not None and end == total - 1 and slice_end >= total
-def request_range(headers: MutableMapping[str, Any]) -> Optional[tuple[int, Optional[int]]]:
+def request_range(headers: MutableMapping[str, Any]) -> tuple[int, int | None] | None:
"""
The request's ``Range`` as ``(start, end)``. Gives None when absent or not ``bytes=start-...``.
@@ -592,7 +594,7 @@ def force_unblock_stream(stream: Any) -> None:
pass
-def split_ranges(size: int, max_parts: Optional[int], part_target: int) -> list[tuple[int, int]]:
+def split_ranges(size: int, max_parts: int | None, part_target: int) -> list[tuple[int, int]]:
"""Split ``[0, size)`` into inclusive ``[start, end]`` byte ranges with no gaps or overlaps.
Parts of ~``part_target`` bytes each, at most ``max_parts`` of them when given. Pure, with no I/O, so testable.
@@ -758,15 +760,15 @@ def dispatch_parts(
def download(
url: str,
save_path: Path,
- session: Optional[Any] = None,
+ session: Any | None = None,
segmented: bool = False,
- part_offset: Optional[int] = None,
- part_end: Optional[int] = None,
- claimed: Optional[Callable[[], bool]] = None,
- racing: Optional[Callable[[], bool]] = None,
- abort: Optional[threading.Event] = None,
- on_retry: Optional[Callable[[Exception], None]] = None,
- register: Optional[Callable[[Any, bool], None]] = None,
+ part_offset: int | None = None,
+ part_end: int | None = None,
+ claimed: Callable[[], bool] | None = None,
+ racing: Callable[[], bool] | None = None,
+ abort: threading.Event | None = None,
+ on_retry: Callable[[Exception], None] | None = None,
+ register: Callable[[Any, bool], None] | None = None,
**kwargs: Any,
) -> Generator[dict[str, Any], None, None]:
"""
@@ -855,8 +857,8 @@ def download(
started = _time()
written = 0
resumes = 0
- request_limit: Optional[int] = None
- known_total: Optional[int] = None
+ request_limit: int | None = None
+ known_total: int | None = None
high_water = 0
progress_seeded = False
while True:
@@ -887,7 +889,7 @@ def download(
if not any(str(k).lower() == "accept-encoding" for k in req_headers):
req_headers["Accept-Encoding"] = "identity"
# inclusive end of this request when it covers only part of what is left, else None
- chunk_end: Optional[int] = None
+ chunk_end: int | None = None
if part_mode and part_offset is not None and part_end is not None: # spelled so mypy narrows
req_start = part_offset + written
chunk_end = part_end
@@ -928,7 +930,7 @@ def download(
yield dict(advance=1)
break
tmp_file.unlink(missing_ok=True)
- raise IOError(f"resume from byte {resume_offset} got a 416, complete length {complete}")
+ raise OSError(f"resume from byte {resume_offset} got a 416, complete length {complete}")
stream.raise_for_status()
@@ -950,14 +952,14 @@ def download(
resume_offset = 0
else:
tmp_file.unlink(missing_ok=True)
- raise IOError(f"resume from byte {resume_offset} got Content-Range {content_range!r}")
+ raise OSError(f"resume from byte {resume_offset} got Content-Range {content_range!r}")
elif content_range[2] is not None:
known_total = content_range[2]
if (not part_mode) and resume_offset > 0 and not resumed:
resume_offset = 0
if part_mode and part_offset is not None and part_end is not None: # spelled so mypy narrows
if stream.status_code != 206:
- raise IOError(f"expected 206 for ranged part, got {stream.status_code}")
+ raise OSError(f"expected 206 for ranged part, got {stream.status_code}")
content_range = parse_content_range(
stream.headers.get("Content-Range") or stream.headers.get("content-range")
)
@@ -971,7 +973,7 @@ def download(
# an end past what this request asked for would spill into a sibling
# part's region, and a total at or below part_end means the resource
# changed under the part plan; fail the attempt before any byte is written
- raise IOError(f"part {part_offset}-{part_end} got Content-Range {content_range!r}")
+ raise OSError(f"part {part_offset}-{part_end} got Content-Range {content_range!r}")
if use_rnet:
content_encoded = is_content_encoded(
stream.headers.get("Content-Encoding") or stream.headers.get("content-encoding")
@@ -996,7 +998,7 @@ def download(
)
if fresh_range is not None:
if fresh_range[0] != resume_offset:
- raise IOError(f"206 body starts at byte {fresh_range[0]}, expected {resume_offset}")
+ raise OSError(f"206 body starts at byte {fresh_range[0]}, expected {resume_offset}")
known_total = fresh_range[2]
if item_range and not part_mode and stream.status_code != 206:
@@ -1005,7 +1007,7 @@ def download(
# fail the attempt unless the slice spans the whole resource, in which case the
# 200 body is byte-identical to the 206 and safe to keep
if not (stream.status_code == 200 and range_covers_full_body(req_headers, content_length)):
- raise IOError(f"expected 206 for byte-range segment, got {stream.status_code}")
+ raise OSError(f"expected 206 for byte-range segment, got {stream.status_code}")
if item_range and not part_mode and stream.status_code == 206:
# a 206 for a different range than the slice asked for (e.g. the whole parent,
@@ -1026,7 +1028,7 @@ def download(
and not range_clamped_to_end(content_range, slice_end)
)
):
- raise IOError(
+ raise OSError(
f"byte-range segment got Content-Range {content_range!r}, "
f"expected {slice_start}-{slice_end if slice_end is not None else ''}"
)
@@ -1035,7 +1037,7 @@ def download(
if resumed and content_encoded:
tmp_file.unlink(missing_ok=True)
- raise IOError(f"resume from byte {resume_offset} came back content-encoded")
+ raise OSError(f"resume from byte {resume_offset} came back content-encoded")
limiter = speed_limiter
chunk_size = adaptive_chunk_size(content_length)
@@ -1080,9 +1082,9 @@ def download(
# only pay the per-arrival read1 tax while this segment is actually
# racing; a blocking full-chunk read otherwise (the common case)
_raw_read = stream.raw.read
- chunks = iter(lambda: _read1(chunk_size) if racing() else _raw_read(chunk_size), b"")
+ chunks = iter(lambda: _read1(chunk_size) if racing() else _raw_read(chunk_size), b"") # noqa: B023
else:
- chunks = iter(lambda: stream.raw.read(chunk_size), b"")
+ chunks = iter(partial(stream.raw.read, chunk_size), b"")
else:
chunks = stream.iter_content(chunk_size=chunk_size)
@@ -1142,7 +1144,7 @@ def download(
expected = part_end - part_offset + 1
target = expected if chunk_end is None else chunk_end - part_offset + 1
if written < target:
- raise IOError(f"Failed to read part {part_offset}-{part_end}: got {written}/{expected}")
+ raise OSError(f"Failed to read part {part_offset}-{part_end}: got {written}/{expected}")
if written < expected:
# this request's sub-range arrived whole; the rest of the part is the next
# request, not a retry, so the attempt budget starts over for it
@@ -1154,7 +1156,7 @@ def download(
# chunk loop ends without raising, so without this check a truncated segment would
# finalize as complete and corrupt the merge. content_length==0 (chunked/gzip)
# is unknown-length and correctly skips the check.
- raise IOError(f"Failed to read {content_length} bytes from the track URI.")
+ raise OSError(f"Failed to read {content_length} bytes from the track URI.")
if not part_mode:
if known_total is not None:
@@ -1163,7 +1165,7 @@ def download(
incomplete = written == 0 or (stream.status_code == 206 and not item_range)
if incomplete:
if resume_offset + written <= resume_start:
- raise IOError(f"range from byte {resume_start} returned no bytes past it")
+ raise OSError(f"range from byte {resume_start} returned no bytes past it")
resume_offset += written
if resume_offset > high_water:
high_water = resume_offset
@@ -1255,7 +1257,7 @@ def rebuildable_adapter(adapter: Any) -> bool:
return type(adapter) in (HTTPAdapter, TimeoutHTTPAdapter)
-def build_session_spec(session: Optional[Any]) -> Optional[dict[str, Any]]:
+def build_session_spec(session: Any | None) -> dict[str, Any] | None:
"""Picklable spec to rebuild ``session`` in a child process. Gives None when it is not cheaply rebuildable.
Live sessions (sockets, TLS state, threads) cannot cross a process boundary, so each child
@@ -1305,7 +1307,7 @@ def default_max_workers() -> int:
return min(16, (os.cpu_count() or 1) + 4)
-def rebuild_session(spec: dict[str, Any], max_workers: int) -> Optional[Any]:
+def rebuild_session(spec: dict[str, Any], max_workers: int) -> Any | None:
"""Reconstruct an HTTP session inside a child process from a spec built by ``build_session_spec``.
``max_workers`` sizes the connection pool to what this child runs. The rebuilt HTTP session
@@ -1384,9 +1386,9 @@ def download_multiprocess(
urls: list[Any],
output_dir: Path,
filename: str,
- headers: Optional[MutableMapping[str, Union[str, bytes]]],
- cookies: Optional[Union[MutableMapping[str, str], CookieJar]],
- proxy: Optional[str],
+ headers: MutableMapping[str, str | bytes] | None,
+ cookies: MutableMapping[str, str] | CookieJar | None,
+ proxy: str | None,
max_workers: int,
adaptive: bool,
spec: dict[str, Any],
@@ -1482,7 +1484,7 @@ def download_multiprocess(
for p in procs:
p.terminate()
codes = [p.exitcode for p in procs]
- raise RuntimeError(f"segment download child died without result (exitcodes: {codes})")
+ raise RuntimeError(f"segment download child died without result (exitcodes: {codes})") from None
if event is not None:
dead_ticks = 0
if "__mp_done__" in event:
@@ -1535,14 +1537,14 @@ def download_multiprocess(
def requests(
- urls: Union[str, dict[str, Any], list[str], list[dict[str, Any]], list[Union[str, dict[str, Any]]]],
+ urls: str | dict[str, Any] | list[str] | list[dict[str, Any]] | list[str | dict[str, Any]],
output_dir: Path,
filename: str,
- headers: Optional[MutableMapping[str, Union[str, bytes]]] = None,
- cookies: Optional[Union[MutableMapping[str, str], CookieJar]] = None,
- proxy: Optional[str] = None,
- max_workers: Optional[int] = None,
- session: Optional[Any] = None,
+ headers: MutableMapping[str, str | bytes] | None = None,
+ cookies: MutableMapping[str, str] | CookieJar | None = None,
+ proxy: str | None = None,
+ max_workers: int | None = None,
+ session: Any | None = None,
adaptive: bool = False,
processes: int = 1,
index_offset: int = 0,
@@ -1903,7 +1905,7 @@ def requests(
tail_skipped: set[int] = set()
part_aborts: list[threading.Event] = []
- def submit(count: int, only: Optional[set[int]] = None) -> None:
+ def submit(count: int, only: set[int] | None = None) -> None:
# only= submits just those indices (used in the tail window to release
# segments the boost declined while holding back boost candidates); with no
# `only`, submits the leading `count` segments in FIFO order.
@@ -1934,7 +1936,7 @@ def requests(
part_lock: threading.Lock,
req_kwargs: dict[str, Any],
) -> None:
- failure: Optional[Exception] = None
+ failure: Exception | None = None
try:
# part_mode download writes [start, end] into the pre-truncated target and
# emits only byte-`advance`; swallow those, since tail segments report at segment
diff --git a/unshackle/core/drm/__init__.py b/unshackle/core/drm/__init__.py
index cae582ad..7860257f 100644
--- a/unshackle/core/drm/__init__.py
+++ b/unshackle/core/drm/__init__.py
@@ -1,4 +1,4 @@
-from typing import Any, Union
+from typing import Any
from uuid import UUID
from unshackle.core.drm.blowfish_stripe import BlowfishStripe
@@ -10,7 +10,7 @@ from unshackle.core.drm.widevine import Widevine
from unshackle.core.vault import is_null_key
# BlowfishStripe stays out: the licensing paths typed on DRM_T never receive a DRM that needs no licence
-DRM_T = Union[ClearKey, ClearKeyCENC, Widevine, PlayReady, MonaLisa]
+DRM_T = ClearKey | ClearKeyCENC | Widevine | PlayReady | MonaLisa
def drop_null_keys(drm: Any) -> None:
diff --git a/unshackle/core/drm/blowfish_stripe.py b/unshackle/core/drm/blowfish_stripe.py
index 8e7d3b9c..3c188564 100644
--- a/unshackle/core/drm/blowfish_stripe.py
+++ b/unshackle/core/drm/blowfish_stripe.py
@@ -1,7 +1,6 @@
from __future__ import annotations
from pathlib import Path
-from typing import Union
from Cryptodome.Cipher import Blowfish
@@ -17,7 +16,7 @@ class BlowfishStripe:
CHUNK = 2048
IV = bytes(range(8))
- def __init__(self, key: Union[bytes, str]) -> None:
+ def __init__(self, key: bytes | str) -> None:
self.key: bytes = bytes.fromhex(key) if isinstance(key, str) else key
def decrypt_chunk(self, chunk: bytes) -> bytes:
diff --git a/unshackle/core/drm/cbcs.py b/unshackle/core/drm/cbcs.py
index 1b6fa510..997053f1 100644
--- a/unshackle/core/drm/cbcs.py
+++ b/unshackle/core/drm/cbcs.py
@@ -17,9 +17,10 @@ from __future__ import annotations
import shutil
import struct
+from collections.abc import Callable, Iterator
from dataclasses import dataclass, field
from pathlib import Path
-from typing import BinaryIO, Callable, Iterator, Optional, Union
+from typing import BinaryIO
from uuid import UUID
from Cryptodome.Cipher import AES
@@ -49,7 +50,7 @@ class SampleEntry:
crypt_block: int
skip_block: int
offset: int
- sinf_offset: Optional[int]
+ sinf_offset: int | None
@dataclass
@@ -79,7 +80,7 @@ class Layout:
return {entry.scheme for track in self.tracks.values() for entry in track.protected_entries}
-def iter_boxes(data: bytes, start: int = 0, end: Optional[int] = None) -> Iterator[tuple[bytes, int, int, int]]:
+def iter_boxes(data: bytes, start: int = 0, end: int | None = None) -> Iterator[tuple[bytes, int, int, int]]:
"""Yield (type, header_size, box_start, box_end) for each box in data[start:end]."""
if end is None:
end = len(data)
@@ -98,7 +99,7 @@ def iter_boxes(data: bytes, start: int = 0, end: Optional[int] = None) -> Iterat
pos += size
-def _find_child(data: bytes, start: int, end: int, wanted: bytes) -> Optional[tuple[int, int, int]]:
+def _find_child(data: bytes, start: int, end: int, wanted: bytes) -> tuple[int, int, int] | None:
for box_type, header, box_start, box_end in iter_boxes(data, start, end):
if box_type == wanted:
return header, box_start, box_end
@@ -205,7 +206,7 @@ def _walk(data: bytes, start: int, end: int, visit: Callable[[bytes, int, int, i
_walk(data, box_start + header, box_end, visit)
-def parse_moov(data: bytes, start: int = 0, end: Optional[int] = None) -> Layout:
+def parse_moov(data: bytes, start: int = 0, end: int | None = None) -> Layout:
"""Read the tracks, sample entries and `tenc` boxes out of a `moov` box at data[start:end]."""
layout = Layout()
current: list[TrackLayout] = []
@@ -240,10 +241,10 @@ def parse_moov(data: bytes, start: int = 0, end: Optional[int] = None) -> Layout
return layout
-def inspect(path: Path) -> Optional[Layout]:
+def inspect(path: Path) -> Layout | None:
"""Return the protection layout of a fragmented MP4, or None when it has no `moov`."""
with path.open("rb") as fh:
- for box_type, header, start, size in _top_level(fh):
+ for box_type, _header, start, size in _top_level(fh):
if box_type == b"moov":
fh.seek(start)
return parse_moov(fh.read(size))
@@ -294,13 +295,13 @@ def _parse_moof(data: bytes, moof_offset: int, layout: Layout) -> list[_Fragment
track_id = 0
entry_index = 0
default_size = 0
- base_offset: Optional[int] = None
+ base_offset: int | None = None
samples: list[tuple[int, int]] = []
ivs: list[bytes] = []
subsamples: list[list[tuple[int, int]]] = []
neutralise: list[int] = []
- next_offset: Optional[int] = None
- senc: Optional[tuple[int, int, int]] = None
+ next_offset: int | None = None
+ senc: tuple[int, int, int] | None = None
for child, child_header, child_start, child_end in iter_boxes(data, traf_start + header, traf_end):
# tfhd, trun and senc are full boxes: the payload follows version and flags.
body = child_start + child_header + 4
@@ -429,7 +430,7 @@ def strip_moov_protection(moov: bytearray, layout: Layout) -> None:
SampleDecrypter = Callable[[list[bytes]], list[bytes]]
"""Decrypts the protected samples of one fragment outside this module and returns them in order."""
-KeyResolver = Callable[[TrackLayout, SampleEntry], Union[bytes, SampleDecrypter]]
+KeyResolver = Callable[[TrackLayout, SampleEntry], bytes | SampleDecrypter]
SAMPLE_BATCH_BYTES = 8 * 1024 * 1024
"""The most sample bytes one remote `pack_samples` frame carries; a larger single sample travels alone."""
@@ -471,7 +472,7 @@ def decrypt_file(path: Path, key_for: KeyResolver) -> None:
if unsupported:
raise NotImplementedError(f"In-process decryption handles cbcs only, not {', '.join(sorted(unsupported))}")
- keys: dict[tuple[int, int], Union[bytes, SampleDecrypter]] = {}
+ keys: dict[tuple[int, int], bytes | SampleDecrypter] = {}
for track in layout.tracks.values():
for entry in track.protected_entries:
resolved = key_for(track, entry)
@@ -485,7 +486,7 @@ def decrypt_file(path: Path, key_for: KeyResolver) -> None:
work_path = path.with_stem(f"{path.stem}_decrypted")
shutil.copyfile(path, work_path)
with work_path.open("r+b") as fh:
- for box_type, header, start, size in list(_top_level(fh)):
+ for box_type, _header, start, size in list(_top_level(fh)):
if box_type == b"moov":
fh.seek(start)
moov = bytearray(fh.read(size))
@@ -508,7 +509,7 @@ def decrypt_file(path: Path, key_for: KeyResolver) -> None:
def _decrypt_fragment(
- fh: BinaryIO, fragment: _Fragment, layout: Layout, keys: dict[tuple[int, int], Union[bytes, SampleDecrypter]]
+ fh: BinaryIO, fragment: _Fragment, layout: Layout, keys: dict[tuple[int, int], bytes | SampleDecrypter]
) -> None:
if not fragment.samples:
return
@@ -572,10 +573,10 @@ def _decrypt_with(decrypter: SampleDecrypter, buf: bytearray, span_start: int, f
plaintexts = decrypter(ciphertexts)
if len(plaintexts) != len(ciphertexts):
raise ValueError(f"The sample decrypter returned {len(plaintexts)} samples for {len(ciphertexts)}")
- for number, (cipher, plain) in enumerate(zip(ciphertexts, plaintexts)):
+ for number, (cipher, plain) in enumerate(zip(ciphertexts, plaintexts, strict=True)):
if len(plain) != len(cipher):
raise ValueError(f"The sample decrypter returned {len(plain)} bytes for sample {number}, not {len(cipher)}")
- for runs, plain in zip(samples, plaintexts):
+ for runs, plain in zip(samples, plaintexts, strict=True):
cursor = 0
for start, length in runs:
buf[start : start + length] = plain[cursor : cursor + length]
diff --git a/unshackle/core/drm/clearkey.py b/unshackle/core/drm/clearkey.py
index dcfbbf12..83fac8dc 100644
--- a/unshackle/core/drm/clearkey.py
+++ b/unshackle/core/drm/clearkey.py
@@ -4,7 +4,6 @@ import base64
import logging
import shutil
from pathlib import Path
-from typing import Optional, Union
from urllib.parse import urljoin
from Cryptodome.Cipher import AES
@@ -28,7 +27,7 @@ TS_SYNC_CHECKS = 4
class ClearKey:
"""AES-128 ClearKey (HLS) DRM system."""
- def __init__(self, key: Union[bytes, str], iv: Optional[Union[bytes, str]] = None) -> None:
+ def __init__(self, key: bytes | str, iv: bytes | str | None = None) -> None:
"""
Give the IV where possible. If you do not give an IV, unshackle sets it to
\x00 of the same bit-size as the content key.
@@ -104,7 +103,7 @@ class ClearKey:
shutil.move(decrypted_path, path)
@classmethod
- def from_m3u_key(cls, m3u_key: Key, session: Optional[AnySession] = None) -> ClearKey:
+ def from_m3u_key(cls, m3u_key: Key, session: AnySession | None = None) -> ClearKey:
"""
Load a ClearKey from an M3U(8) Playlist's EXT-X-KEY.
diff --git a/unshackle/core/drm/clearkey_cenc.py b/unshackle/core/drm/clearkey_cenc.py
index cc685d21..5d287cf9 100644
--- a/unshackle/core/drm/clearkey_cenc.py
+++ b/unshackle/core/drm/clearkey_cenc.py
@@ -2,8 +2,9 @@ from __future__ import annotations
import base64
import json
+from collections.abc import Callable, Iterable
from pathlib import Path
-from typing import Any, Callable, Iterable, Optional, Union
+from typing import Any
from uuid import UUID
import click
@@ -38,9 +39,9 @@ class ClearKeyCENC:
def __init__(
self,
- kids: Iterable[Union[UUID, str, bytes]],
- laurl: Optional[str] = None,
- content_keys: Optional[dict[UUID, str]] = None,
+ kids: Iterable[UUID | str | bytes],
+ laurl: str | None = None,
+ content_keys: dict[UUID, str] | None = None,
**kwargs: Any,
) -> None:
kid_list: list[UUID] = []
@@ -56,12 +57,12 @@ class ClearKeyCENC:
raise ClearKeyCENC.Exceptions.KIDNotFound("No Key ID was provided.")
self.kids: list[UUID] = kid_list
- self.laurl: Optional[str] = laurl
+ self.laurl: str | None = laurl
self.content_keys: dict[UUID, str] = dict(content_keys or {})
self.data: dict = kwargs or {}
@property
- def kid(self) -> Optional[UUID]:
+ def kid(self) -> UUID | None:
"""Get first Key ID, if any."""
return next(iter(self.kids), None)
@@ -77,7 +78,7 @@ class ClearKeyCENC:
request = {"kids": [b64url_encode_nopad(kid.bytes) for kid in kids], "type": "temporary"}
return json.dumps(request).encode("utf8")
- def get_content_keys(self, *, licence: Callable, session: Optional[Session] = None) -> None:
+ def get_content_keys(self, *, licence: Callable, session: Session | None = None) -> None:
"""
Get Content Keys for this DRM Instance from a ClearKey license server.
@@ -171,7 +172,7 @@ class ClearKeyCENC:
"""Decrypt the file at ``path`` in place with this track's ClearKey (standard CENC) content keys."""
decrypt_cenc(self, path, "ClearKeyCENC")
- def mp4decrypt_key_args(self, track_kids: Optional[dict[int, UUID]] = None) -> list[str]:
+ def mp4decrypt_key_args(self, track_kids: dict[int, UUID] | None = None) -> list[str]:
"""Build the mp4decrypt --key arguments for every content key, and by track ID for each ``track_kids`` KID."""
key_args = []
for kid, key in self.content_keys.items():
@@ -185,8 +186,7 @@ class ClearKeyCENC:
def decrypt_with_shaka_packager(self, path: Path) -> None:
"""Decrypt with shaka-packager."""
keys = ",".join(
- "label={}:key_id={}:key={}".format(i, kid.hex, key.lower())
- for i, (kid, key) in enumerate(self.content_keys.items())
+ f"label={i}:key_id={kid.hex}:key={key.lower()}" for i, (kid, key) in enumerate(self.content_keys.items())
)
shaka_decrypt(path, keys, "ClearKey")
diff --git a/unshackle/core/drm/decrypters.py b/unshackle/core/drm/decrypters.py
index 248aebaa..ad6749a8 100644
--- a/unshackle/core/drm/decrypters.py
+++ b/unshackle/core/drm/decrypters.py
@@ -4,9 +4,10 @@ import logging
import shutil
import subprocess
import textwrap
+from collections.abc import Callable
from pathlib import Path
from time import monotonic
-from typing import Any, Callable
+from typing import Any
from uuid import UUID
import click
@@ -82,7 +83,7 @@ def decrypt_cenc(drm: Any, path: Path, drm_type: str) -> None:
def mp4decrypt(path: Path, key_args_for: Callable[[dict[int, UUID]], list[str]]) -> None:
"""Decrypt ``path`` in place with mp4decrypt, taking the ``--key`` arguments from ``key_args_for(track_kids)``."""
if not binaries.Mp4decrypt:
- raise coded(EnvironmentError("mp4decrypt executable not found but is required."), APIErrorCode.DRM_ERROR)
+ raise coded(OSError("mp4decrypt executable not found but is required."), APIErrorCode.DRM_ERROR)
output_path = path.with_stem(f"{path.stem}_decrypted")
key_args = key_args_for(kidless_track_kids(read_top_level_box(path, b"moov") or b""))
@@ -92,15 +93,14 @@ def mp4decrypt(path: Path, key_args_for: Callable[[dict[int, UUID]], list[str]])
subprocess.run(
cmd,
check=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
+ capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
except subprocess.CalledProcessError as e:
error_msg = e.stderr if e.stderr else f"mp4decrypt failed with exit code {e.returncode}"
- raise subprocess.CalledProcessError(e.returncode, cmd, output=e.stdout, stderr=error_msg)
+ raise subprocess.CalledProcessError(e.returncode, cmd, output=e.stdout, stderr=error_msg) from None
if not output_path.exists():
raise RuntimeError(f"mp4decrypt failed: output file {output_path} was not created")
@@ -117,7 +117,7 @@ def shaka_decrypt(path: Path, keys: str, label: str) -> None:
Only a non-zero exit is a failure; its non-noise log lines go to the console under ``[label]``.
"""
if not binaries.ShakaPackager:
- raise coded(EnvironmentError("Shaka Packager executable not found but is required."), APIErrorCode.DRM_ERROR)
+ raise coded(OSError("Shaka Packager executable not found but is required."), APIErrorCode.DRM_ERROR)
output_path = path.with_stem(f"{path.stem}_decrypted")
config.directories.temp.mkdir(parents=True, exist_ok=True)
@@ -170,5 +170,5 @@ def shaka_decrypt(path: Path, keys: str, label: str) -> None:
shutil.move(output_path, path)
except subprocess.CalledProcessError as e:
if e.returncode == 0xC000013A: # STATUS_CONTROL_C_EXIT
- raise KeyboardInterrupt()
+ raise KeyboardInterrupt() from None
raise
diff --git a/unshackle/core/drm/key_args.py b/unshackle/core/drm/key_args.py
index 528e69a5..481b0af2 100644
--- a/unshackle/core/drm/key_args.py
+++ b/unshackle/core/drm/key_args.py
@@ -3,7 +3,8 @@
from __future__ import annotations
import re
-from typing import Any, Iterable, Mapping, Optional
+from collections.abc import Iterable, Mapping
+from typing import Any
ZERO_KID = "00" * 16
SHAKA_NOISE = re.compile(r"^(?:[IWV]\d{4} |\[[^\]]*:(?:INFO|WARNING|VERBOSE\d*):)")
@@ -18,7 +19,7 @@ def _hex(value: Any) -> str:
return str(value).replace("-", "").lower()
-def zero_kid_key(content_keys: dict[Any, Any], own_kids: Iterable[Any]) -> Optional[str]:
+def zero_kid_key(content_keys: dict[Any, Any], own_kids: Iterable[Any]) -> str | None:
"""Return the content key to give the all-zero KID, or None when no content key is safe.
Some tracks carry an all-zero default KID in the init segment and signal the real KID
@@ -44,7 +45,7 @@ def zero_kid_key(content_keys: dict[Any, Any], own_kids: Iterable[Any]) -> Optio
return None
-def track_key_args(content_keys: dict[Any, Any], track_kids: Optional[Mapping[int, Any]]) -> list[str]:
+def track_key_args(content_keys: dict[Any, Any], track_kids: Mapping[int, Any] | None) -> list[str]:
"""Build the mp4decrypt --key arguments by track ID for each track whose own KID has a content key."""
keys = {_hex(kid): _hex(key) for kid, key in content_keys.items()}
key_args: list[str] = []
@@ -55,7 +56,7 @@ def track_key_args(content_keys: dict[Any, Any], track_kids: Optional[Mapping[in
def mp4decrypt_key_args(
- content_keys: dict[Any, Any], own_kids: Iterable[Any], track_kids: Optional[Mapping[int, Any]] = None
+ content_keys: dict[Any, Any], own_kids: Iterable[Any], track_kids: Mapping[int, Any] | None = None
) -> list[str]:
"""Build the mp4decrypt --key arguments: every content key, the zero-KID fallback and the ``track_kids`` keys."""
key_args: list[str] = []
diff --git a/unshackle/core/drm/key_resolution.py b/unshackle/core/drm/key_resolution.py
index 250afd42..06fd1787 100644
--- a/unshackle/core/drm/key_resolution.py
+++ b/unshackle/core/drm/key_resolution.py
@@ -5,13 +5,14 @@ from __future__ import annotations
import logging
import os
from collections import defaultdict
+from collections.abc import Callable
from concurrent import futures
from concurrent.futures import ThreadPoolExecutor
from contextlib import ExitStack
from functools import partial
from pathlib import Path
from threading import Lock
-from typing import TYPE_CHECKING, Any, Callable, Optional, Protocol, Union, cast
+from typing import TYPE_CHECKING, Any, Protocol, cast
from uuid import UUID
import click
@@ -66,7 +67,7 @@ class CdmChooser(Protocol):
cdm: Any
- def cdm_for(self, system: str, quality: Optional[int] = None) -> Optional[object]: ...
+ def cdm_for(self, system: str, quality: int | None = None) -> object | None: ...
class ContentKeyResolver:
@@ -91,12 +92,12 @@ class ContentKeyResolver:
cdms: CdmChooser,
service: Service,
tag: str,
- source: Optional[ServerKeySource] = None,
+ source: ServerKeySource | None = None,
cdm_only: bool = False,
vaults_only: bool = False,
best_available: bool = False,
- export: Optional[Callable[[Title_T, AnyTrack, Any], None]] = None,
- debug_logger: Optional[DebugLogger] = None,
+ export: Callable[[Title_T, AnyTrack, Any], None] | None = None,
+ debug_logger: DebugLogger | None = None,
) -> None:
self.log = logging.getLogger("download")
self.vaults = vaults
@@ -109,7 +110,7 @@ class ContentKeyResolver:
self.best_available = best_available
self.export = export
self.debug_logger = debug_logger
- self.vault_cache_tally: Optional[tuple[set[UUID], int]] = None
+ self.vault_cache_tally: tuple[set[UUID], int] | None = None
self.all_drm_attempted: defaultdict[type, set[UUID]] = defaultdict(set)
self.all_drm_warned: set[str] = set()
@@ -128,10 +129,10 @@ class ContentKeyResolver:
self,
drm: DRM_T,
path: Path,
- licence: Optional[Callable] = None,
- track_kid: Optional[UUID] = None,
+ licence: Callable | None = None,
+ track_kid: UUID | None = None,
decrypt: bool = True,
- track: Optional[AnyTrack] = None,
+ track: AnyTrack | None = None,
) -> None:
"""Decrypt the file, and when a vault supplied a content key, prove the output decodes.
@@ -235,7 +236,7 @@ class ContentKeyResolver:
windows = kid_map.windows if kid_map else {}
video = kid_map.video if kid_map else None
- def proven(passed: dict[UUID, Vault]) -> dict[Union[UUID, str], str]:
+ def proven(passed: dict[UUID, Vault]) -> dict[UUID | str, str]:
"""The licence keys and the vault keys in ``passed``, without null keys; a flagged pair never gets here."""
sourced = vault_kids()
return {
@@ -352,7 +353,7 @@ class ContentKeyResolver:
self._prefer_vault_keys(source, title)
self._cache_resolved_keys(source, title)
- def _prefer_vault_keys(self, source: "ServerKeySource", title: Title_T) -> None:
+ def _prefer_vault_keys(self, source: ServerKeySource, title: Title_T) -> None:
"""Let the client vaults answer before a content key the server batch licence returned.
The client only learns the KIDs from the batch response, so the server has already
@@ -363,7 +364,7 @@ class ContentKeyResolver:
waits in ``Vaults.candidates`` and gets the same check when its turn comes. Only the KIDs
the DRM names are looked up, each once, so sibling keys add no remote vault requests.
"""
- looked_up: dict[UUID, tuple[Optional[str], Any]] = {}
+ looked_up: dict[UUID, tuple[str | None, Any]] = {}
for track in title.tracks:
for drm in getattr(track, "drm", None) or []:
content_keys = getattr(drm, "content_keys", {})
@@ -384,7 +385,7 @@ class ContentKeyResolver:
self.LICENSE_KEY_CACHE[kid] = server_key
self._flush_vault_writes([partial(self._cache_keys_to_vaults, {kid: server_key})])
- def _cache_resolved_keys(self, source: "ServerKeySource", title: Title_T) -> None:
+ def _cache_resolved_keys(self, source: ServerKeySource, title: Title_T) -> None:
"""Cache the keys a batch licence or an import put on the tracks.
Both fill track.drm before any _prepare_drm call, so this is the only point where those
@@ -410,7 +411,7 @@ class ContentKeyResolver:
if not content_keys or not self.vaults:
return
self.vaults.clear_licensed_flags(content_keys)
- successful_caches = self.vaults.add_keys(cast(dict[Union[UUID, str], str], content_keys))
+ successful_caches = self.vaults.add_keys(cast(dict[UUID | str, str], content_keys))
kids, caches = self.vault_cache_tally or (set(), successful_caches)
self.vault_cache_tally = (kids | content_keys.keys(), min(caches, successful_caches))
@@ -437,11 +438,11 @@ class ContentKeyResolver:
def _take_licence_turn(
self,
turn: ExitStack,
- drm: Union[ClearKeyCENC, Widevine, PlayReady, MonaLisa],
+ drm: ClearKeyCENC | Widevine | PlayReady | MonaLisa,
kids: list[UUID],
track: AnyTrack,
- track_kid: Optional[UUID],
- cek_tree: Optional[Tree],
+ track_kid: UUID | None,
+ cek_tree: Tree | None,
) -> None:
"""Hold LICENCE_LOCK until ``turn`` closes, then take the content keys of ``kids`` an earlier licence cached.
@@ -457,11 +458,11 @@ class ContentKeyResolver:
def _take_cached_key(
self,
- drm: Union[ClearKeyCENC, Widevine, PlayReady, MonaLisa],
+ drm: ClearKeyCENC | Widevine | PlayReady | MonaLisa,
kid: UUID,
track: AnyTrack,
- track_kid: Optional[UUID],
- cek_tree: Optional[Tree],
+ track_kid: UUID | None,
+ cek_tree: Tree | None,
) -> bool:
"""Give the DRM the content key LICENSE_KEY_CACHE holds for ``kid``, and return whether it held one."""
key = self.LICENSE_KEY_CACHE.get(kid)
@@ -480,11 +481,11 @@ class ContentKeyResolver:
def _take_vault_key(
self,
- drm: Union[ClearKeyCENC, Widevine, PlayReady, MonaLisa],
+ drm: ClearKeyCENC | Widevine | PlayReady | MonaLisa,
kid: UUID,
track: AnyTrack,
- track_kid: Optional[UUID],
- cek_tree: Optional[Tree],
+ track_kid: UUID | None,
+ cek_tree: Tree | None,
) -> bool:
"""Give the DRM the content key a key vault holds for ``kid``, cache it for the run, and return whether one did."""
key, vault = self.vaults.get_key(kid)
@@ -510,7 +511,7 @@ class ContentKeyResolver:
return True
@staticmethod
- def _with_track_kid(drm: Any, track_kid: Optional[UUID]) -> list[UUID]:
+ def _with_track_kid(drm: Any, track_kid: UUID | None) -> list[UUID]:
"""Return the KIDs the DRM names, plus the track's own KID when the DRM leaves it out."""
kids = list(getattr(drm, "kids", None) or [])
if track_kid and track_kid not in kids:
@@ -519,11 +520,11 @@ class ContentKeyResolver:
def _take_known_keys(
self,
- drm: Union[ClearKeyCENC, Widevine, PlayReady, MonaLisa],
+ drm: ClearKeyCENC | Widevine | PlayReady | MonaLisa,
kids: list[UUID],
track: AnyTrack,
- track_kid: Optional[UUID],
- cek_tree: Optional[Tree],
+ track_kid: UUID | None,
+ cek_tree: Tree | None,
use_cache: bool = True,
use_vaults: bool = True,
stop_at_miss: bool = False,
@@ -548,11 +549,11 @@ class ContentKeyResolver:
def _license_drm(
self,
- drm: Union[ClearKeyCENC, Widevine, PlayReady],
+ drm: ClearKeyCENC | Widevine | PlayReady,
get_keys: Callable[[], None],
track: AnyTrack,
title: Title_T,
- track_kid: Optional[UUID],
+ track_kid: UUID | None,
table: Table,
cdm_only: bool,
force: bool,
@@ -565,7 +566,7 @@ class ContentKeyResolver:
A licence can answer a KID with a blank or null key; a vault key for that KID wins.
Every content key of the licence goes to the vaults and to the server key source's vault at once.
"""
- pssh: Optional[str] = None
+ pssh: str | None = None
if isinstance(drm, ClearKeyCENC):
name = "ClearKey"
else:
@@ -686,7 +687,7 @@ class ContentKeyResolver:
server_vault = self.source.server_vault if self.source else None
if server_vault is not None:
pending_vault_writes.append(
- partial(server_vault.add_keys, self.tag, cast(dict[Union[UUID, str], str], licensed), track)
+ partial(server_vault.add_keys, self.tag, cast(dict[UUID | str, str], licensed), track)
)
if track_kid and track_kid not in drm.content_keys:
@@ -701,7 +702,7 @@ class ContentKeyResolver:
self._flush_vault_writes(pending_vault_writes)
@staticmethod
- def _add_key_label(tree: Tree, kid: UUID, key: str, track_kid: Optional[UUID] = None, source: str = "") -> None:
+ def _add_key_label(tree: Tree, kid: UUID, key: str, track_kid: UUID | None = None, source: str = "") -> None:
"""Add ``kid:key`` to a content key tree once, with ``*`` on the track's own KID and ``source`` after it."""
if any(f"{kid.hex}:{key}" in str(x.label) for x in tree.children):
return
@@ -712,7 +713,7 @@ class ContentKeyResolver:
label += f" {source}"
tree.add(label)
- def _service_licence(self, drm_system: Optional[str] = None, **kwargs: Any) -> Any:
+ def _service_licence(self, drm_system: str | None = None, **kwargs: Any) -> Any:
"""Call the service's licence function for the track's DRM system.
Arguments go through declared_kwargs, so a service receives only the ones its own
@@ -726,7 +727,7 @@ class ContentKeyResolver:
fn = self.service.get_playready_license if drm_system == "playready" else self.service.get_widevine_license
return fn(**declared_kwargs(fn, kwargs))
- def _licence_one_drm(self, prepare: Callable, drm: Union[Widevine, PlayReady], track_kid: Optional[UUID]) -> None:
+ def _licence_one_drm(self, prepare: Callable, drm: Widevine | PlayReady, track_kid: UUID | None) -> None:
"""Send one challenge for the KIDs of this DRM, also when the DRM or a vault has the content keys.
This is the ``--cdm-only`` path. The challenge goes out the first time a run sees the KIDs
@@ -757,7 +758,7 @@ class ContentKeyResolver:
track: AnyTrack,
tolerate: bool,
drm: DRM_T,
- track_kid: Optional[UUID] = None,
+ track_kid: UUID | None = None,
force: bool = False,
) -> None:
"""License the track with each DRM system it offers, not only the one the downloader selected.
@@ -783,7 +784,7 @@ class ContentKeyResolver:
)
targets = [drm, *others[:1]]
- error: Optional[Exception] = None
+ error: Exception | None = None
with self.ALL_DRM_LOCK:
loaded_cdm = self.cdms.cdm
try:
@@ -814,11 +815,11 @@ class ContentKeyResolver:
def _prepare_drm(
self,
- drm: Union[ClearKeyCENC, Widevine, PlayReady, MonaLisa],
+ drm: ClearKeyCENC | Widevine | PlayReady | MonaLisa,
track: AnyTrack,
title: Title_T,
table: Table,
- track_kid: Optional[UUID] = None,
+ track_kid: UUID | None = None,
cdm_only: bool = False,
force: bool = False,
) -> None:
diff --git a/unshackle/core/drm/monalisa.py b/unshackle/core/drm/monalisa.py
index a45cd8d4..5d7fad85 100644
--- a/unshackle/core/drm/monalisa.py
+++ b/unshackle/core/drm/monalisa.py
@@ -9,7 +9,7 @@ from __future__ import annotations
import base64
import logging
from pathlib import Path
-from typing import Any, Optional, Union
+from typing import Any
from uuid import UUID
from unshackle.core.cdm.monalisa import MonaLisaCDM
@@ -41,9 +41,9 @@ class MonaLisa:
def __init__(
self,
- ticket: Union[str, bytes],
+ ticket: str | bytes,
device_path: Path,
- tool_path: Optional[Path] = None,
+ tool_path: Path | None = None,
**kwargs: Any,
) -> None:
"""
@@ -66,8 +66,8 @@ class MonaLisa:
self._device_path = device_path
self._tool_path = tool_path
self._decrypted_segments: int = 0
- self._kid: Optional[UUID] = None
- self._key: Optional[str] = None
+ self._kid: UUID | None = None
+ self._key: str | None = None
self.data: dict = kwargs or {}
self.extract_keys()
@@ -88,14 +88,14 @@ class MonaLisa:
finally:
cdm.close(session_id)
except Exception as e:
- raise MonaLisa.Exceptions.KeyExtractionFailed(f"Failed to extract keys: {e}")
+ raise MonaLisa.Exceptions.KeyExtractionFailed(f"Failed to extract keys: {e}") # noqa: B904
@classmethod
def from_ticket(
cls,
- ticket: Union[str, bytes],
+ ticket: str | bytes,
device_path: Path,
- tool_path: Optional[Path] = None,
+ tool_path: Path | None = None,
) -> MonaLisa:
"""
Make a MonaLisa DRM instance from a PSSH/ticket.
@@ -115,12 +115,12 @@ class MonaLisa:
)
@property
- def kid(self) -> Optional[UUID]:
+ def kid(self) -> UUID | None:
"""Get the Key ID."""
return self._kid
@property
- def key(self) -> Optional[str]:
+ def key(self) -> str | None:
"""Get the content key as hex string."""
return self._key
@@ -146,7 +146,7 @@ class MonaLisa:
return self._ticket
@property
- def content_id(self) -> Optional[str]:
+ def content_id(self) -> str | None:
"""
Extract the Content ID from the PSSH for display.
@@ -191,7 +191,7 @@ class MonaLisa:
return f"{self._kid.hex}:{self._key}"
return ""
- def decrypt_segment(self, segment_path: Path, output_path: Optional[Path] = None) -> None:
+ def decrypt_segment(self, segment_path: Path, output_path: Path | None = None) -> None:
"""
Decrypt an individual segment file using the configured CLI tool via subprocess.
@@ -202,7 +202,7 @@ class MonaLisa:
self._execute_decrypt(segment_path, output_path)
self._decrypted_segments += 1
- def decrypt(self, path: Path, output_path: Optional[Path] = None, *, is_segment: bool = False) -> None:
+ def decrypt(self, path: Path, output_path: Path | None = None, *, is_segment: bool = False) -> None:
"""
Decrypt a media file (segment or track) using the configured CLI tool via subprocess.
@@ -223,7 +223,7 @@ class MonaLisa:
self._execute_decrypt(path, output_path)
- def _execute_decrypt(self, path: Path, output_path: Optional[Path] = None) -> None:
+ def _execute_decrypt(self, path: Path, output_path: Path | None = None) -> None:
"""Run the external tool into a temporary file, which replaces the target only on success."""
if not path or not path.exists():
raise ValueError(f"Target file does not exist: {path}")
diff --git a/unshackle/core/drm/playready.py b/unshackle/core/drm/playready.py
index c44c4be4..f5201a85 100644
--- a/unshackle/core/drm/playready.py
+++ b/unshackle/core/drm/playready.py
@@ -2,9 +2,10 @@ from __future__ import annotations
import base64
import re
+from collections.abc import Callable
from pathlib import Path
from threading import Lock
-from typing import Any, Callable, Optional, Union
+from typing import Any
from uuid import UUID
import click
@@ -36,8 +37,8 @@ class PlayReady:
def __init__(
self,
pssh: PSSH,
- kid: Union[UUID, str, bytes, None] = None,
- pssh_b64: Optional[str] = None,
+ kid: UUID | str | bytes | None = None,
+ pssh_b64: str | None = None,
**kwargs: Any,
) -> None:
if not pssh:
@@ -55,7 +56,7 @@ class PlayReady:
if extra_kid not in kids:
kids.append(extra_kid)
- self._kid: Optional[UUID] = None
+ self._kid: UUID | None = None
if kid:
if isinstance(kid, str):
kid = UUID(hex=kid)
@@ -168,7 +169,7 @@ class PlayReady:
return []
@classmethod
- def from_pssh_b64(cls, pssh_b64: str, kid: Optional[UUID] = None) -> PlayReady:
+ def from_pssh_b64(cls, pssh_b64: str, kid: UUID | None = None) -> PlayReady:
"""Load a base64 PSSH box or PlayReady Object, or a bare UTF-16LE WRMHEADER that some packagers emit.
It wraps a bare WRMHEADER in a PlayReady Object and keeps that as `pssh_b64`, so remote CDMs and
@@ -188,12 +189,12 @@ class PlayReady:
return cls(pssh=pssh, kid=kid, pssh_b64=pssh_b64)
@classmethod
- def from_track(cls, track: AnyTrack, session: Optional[AnySession] = None) -> PlayReady:
+ def from_track(cls, track: AnyTrack, session: AnySession | None = None) -> PlayReady:
if not session:
session = run_proxy.fallback_session()
session.headers.update(config.headers)
- kid: Optional[UUID] = None
+ kid: UUID | None = None
pssh_boxes: list[Container] = []
tenc_boxes: list[Container] = []
@@ -238,7 +239,7 @@ class PlayReady:
if not isinstance(init_data, bytes):
raise TypeError(f"Expected init data to be bytes, not {init_data!r}")
- kid: Optional[UUID] = None
+ kid: UUID | None = None
pssh_boxes: list[Container] = list(get_boxes(init_data, b"pssh"))
tenc_boxes: list[Container] = list(get_boxes(init_data, b"tenc"))
@@ -265,11 +266,11 @@ class PlayReady:
return self._pssh
@property
- def pssh_b64(self) -> Optional[str]:
+ def pssh_b64(self) -> str | None:
return self.data.get("pssh_b64")
@property
- def kid(self) -> Optional[UUID]:
+ def kid(self) -> UUID | None:
return next(iter(self.kids), None)
def to_dict(self) -> dict[str, Any]:
@@ -450,7 +451,7 @@ class PlayReady:
self,
cdm: PlayReadyCdm,
header: WRMHeader,
- pssh_b64: Optional[str],
+ pssh_b64: str | None,
required_kids: list[UUID],
licence: Callable,
) -> dict[UUID, str]:
@@ -516,7 +517,7 @@ class PlayReady:
cdm.close(session_id)
@staticmethod
- def detect_revocation(text: str) -> Optional[str]:
+ def detect_revocation(text: str) -> str | None:
"""Return the decoded error string if a revocation HRESULT is present, else None.
Reads the code from the raw SOAP body (0x8004C065)
@@ -546,7 +547,7 @@ class PlayReady:
return [self._kid]
return self.kids
- def mp4decrypt_key_args(self, track_kids: Optional[dict[int, UUID]] = None) -> list[str]:
+ def mp4decrypt_key_args(self, track_kids: dict[int, UUID] | None = None) -> list[str]:
"""Build the mp4decrypt --key arguments for every content key, the zero-KID and the track ID fallbacks."""
return drm_key_args.mp4decrypt_key_args(self.content_keys, self.own_kids(), track_kids)
diff --git a/unshackle/core/drm/segment_decrypt.py b/unshackle/core/drm/segment_decrypt.py
index b286ece7..ff2109c1 100644
--- a/unshackle/core/drm/segment_decrypt.py
+++ b/unshackle/core/drm/segment_decrypt.py
@@ -6,7 +6,7 @@ import subprocess
import tempfile
from concurrent.futures import Future, ThreadPoolExecutor
from pathlib import Path
-from typing import Any, Optional, Union
+from typing import Any
from unshackle.core import binaries
from unshackle.core.config import config
@@ -16,12 +16,12 @@ from unshackle.core.drm.verify import kidless_track_kids
from unshackle.core.drm.widevine import Widevine
from unshackle.core.remote_protocol import APIErrorCode, coded
-SEGMENT_DRM_T = Union[Widevine, PlayReady, ClearKeyCENC]
+SEGMENT_DRM_T = Widevine | PlayReady | ClearKeyCENC
MAX_WORKERS = 16
-def can_use(drm: Any, decryption: str, init: Optional[bytes] = None) -> bool:
+def can_use(drm: Any, decryption: str, init: bytes | None = None) -> bool:
"""Whether unshackle can decrypt a track's segments one by one as they download.
A track whose ``init`` mp4decrypt cannot key goes to the whole-file decrypt, which has the shaka fallback.
@@ -47,9 +47,9 @@ class SegmentDecrypter:
bytes as decrypting the merged file in one pass.
"""
- def __init__(self, drm: SEGMENT_DRM_T, init_data: bytes, work_dir: Path, workers: Optional[int] = None) -> None:
+ def __init__(self, drm: SEGMENT_DRM_T, init_data: bytes, work_dir: Path, workers: int | None = None) -> None:
if not binaries.Mp4decrypt:
- raise coded(EnvironmentError("mp4decrypt executable not found but is required."), APIErrorCode.DRM_ERROR)
+ raise coded(OSError("mp4decrypt executable not found but is required."), APIErrorCode.DRM_ERROR)
self.drm = drm
self.key_args = drm.mp4decrypt_key_args(kidless_track_kids(init_data))
@@ -61,7 +61,7 @@ class SegmentDecrypter:
self.pool = ThreadPoolExecutor(max_workers=min(workers or os.cpu_count() or 4, MAX_WORKERS))
self.futures: list[Future] = []
- self._init_bytes: Optional[bytes] = None
+ self._init_bytes: bytes | None = None
def submit(self, segment: Path) -> Future:
"""Queue one downloaded segment for decryption and return its future."""
diff --git a/unshackle/core/drm/verify.py b/unshackle/core/drm/verify.py
index b8b8370d..550d3652 100644
--- a/unshackle/core/drm/verify.py
+++ b/unshackle/core/drm/verify.py
@@ -1,15 +1,16 @@
import logging
import os
import struct
+from collections.abc import Callable, Iterator
from pathlib import Path
-from typing import Any, BinaryIO, Callable, Iterator, NamedTuple, Optional
+from typing import Any, BinaryIO, NamedTuple
from uuid import UUID
from unshackle.core.config import config
log = logging.getLogger(__name__)
-DECRYPT_HOOK: Optional[Callable[..., None]] = None
+DECRYPT_HOOK: Callable[..., None] | None = None
CONTAINERS = {b"moov", b"trak", b"mdia", b"minf", b"stbl", b"mvex", b"moof", b"traf", b"sinf", b"schi"}
PIFF_TENC = bytes.fromhex("8974dbce7be74c5184f97148f9882554")
@@ -35,8 +36,8 @@ class KidMap(NamedTuple):
def decrypt_track(
drm: Any,
path: Path,
- licence: Optional[Callable] = None,
- track_kid: Optional[UUID] = None,
+ licence: Callable | None = None,
+ track_kid: UUID | None = None,
decrypt: bool = True,
track: Any = None,
) -> None:
@@ -51,7 +52,7 @@ def decrypt_track(
drm.decrypt(path)
-def children(data: bytes, start: int = 0, end: Optional[int] = None) -> Iterator[tuple[bytes, int, int]]:
+def children(data: bytes, start: int = 0, end: int | None = None) -> Iterator[tuple[bytes, int, int]]:
"""Yield (type, body start, box end) for each box in ``data[start:end]``."""
end = len(data) if end is None else end
while start + 8 <= end:
@@ -69,7 +70,7 @@ def children(data: bytes, start: int = 0, end: Optional[int] = None) -> Iterator
start += size
-def walk(data: bytes, start: int = 0, end: Optional[int] = None) -> Iterator[tuple[bytes, int, int]]:
+def walk(data: bytes, start: int = 0, end: int | None = None) -> Iterator[tuple[bytes, int, int]]:
"""Yield every box below ``data[start:end]``, descending into the container boxes."""
for kind, body, box_end in children(data, start, end):
yield kind, body, box_end
@@ -77,7 +78,7 @@ def walk(data: bytes, start: int = 0, end: Optional[int] = None) -> Iterator[tup
yield from walk(data, body, box_end)
-def seig_entries(data: bytes, body: int) -> Optional[list[Seig]]:
+def seig_entries(data: bytes, body: int) -> list[Seig] | None:
"""Parse an ``sgpd`` box. Returns its seig entries as (protected, KID), or None for another grouping."""
version = data[body]
if data[body + 4 : body + 8] != b"seig":
@@ -105,7 +106,7 @@ def seig_entries(data: bytes, body: int) -> Optional[list[Seig]]:
return entries
-def sbgp_runs(data: bytes, body: int) -> Optional[list[tuple[int, int]]]:
+def sbgp_runs(data: bytes, body: int) -> list[tuple[int, int]] | None:
"""Parse an ``sbgp`` box. Returns its seig runs as (sample count, group index), or None for another grouping."""
version = data[body]
if data[body + 4 : body + 8] != b"seig":
@@ -115,10 +116,10 @@ def sbgp_runs(data: bytes, body: int) -> Optional[list[tuple[int, int]]]:
if count * 8 > len(data) - pos - 4:
raise ValueError("sbgp entry count is larger than the box")
runs = struct.unpack_from(f">{count * 2}I", data, pos + 4)
- return list(zip(runs[::2], runs[1::2]))
+ return list(zip(runs[::2], runs[1::2], strict=True))
-def entry_kid(data: bytes, kind: bytes, entry: int, end: int) -> Optional[UUID]:
+def entry_kid(data: bytes, kind: bytes, entry: int, end: int) -> UUID | None:
"""Return the default KID of an encrypted sample entry, or None for a clear one."""
for fields in ENTRY_FIELDS.get(kind, ()):
boxes = list(walk(data, entry + fields, end))
@@ -132,7 +133,7 @@ def entry_kid(data: bytes, kind: bytes, entry: int, end: int) -> Optional[UUID]:
return None
-def sample_entries(data: bytes, body: int, end: int) -> tuple[list[Optional[UUID]], bool]:
+def sample_entries(data: bytes, body: int, end: int) -> tuple[list[UUID | None], bool]:
"""Parse an ``stsd`` box. Returns the default KID of each sample entry (None for a clear one), and
whether any entry is encrypted."""
found = list(children(data, body + 8, end))
@@ -148,7 +149,7 @@ def has_encrypted_entry(moov: bytes) -> bool:
)
-def read_top_level_box(path: Path, box_type: bytes) -> Optional[bytes]:
+def read_top_level_box(path: Path, box_type: bytes) -> bytes | None:
"""Read a single top-level box from an MP4 file.
This function walks only the box headers, so the wanted box is the only payload it reads into memory.
@@ -195,7 +196,7 @@ def has_encrypted_sample_entry(path: Path) -> bool:
return False
-def kidless_kid(data: bytes, kind: bytes, entry: int, end: int) -> Optional[UUID]:
+def kidless_kid(data: bytes, kind: bytes, entry: int, end: int) -> UUID | None:
"""Return the KID of an encrypted sample entry whose first sinf holds no CENC tenc (a PIFF sinf, say)."""
for fields in ENTRY_FIELDS.get(kind, ()):
sinfs = [(body, box_end) for box, body, box_end in children(data, entry + fields, end) if box == b"sinf"]
@@ -224,7 +225,7 @@ def kidless_track_kids(data: bytes) -> dict[int, UUID]:
return kids
-def find_child_box(buf: bytes, box_type: bytes) -> Optional[bytes]:
+def find_child_box(buf: bytes, box_type: bytes) -> bytes | None:
"""Return the first box of the given type nested anywhere in buf, header included."""
i = buf.find(box_type, 4)
while i != -1:
@@ -269,7 +270,7 @@ def senc_protects_samples(buf: bytes, body: int, end: int) -> bool:
return int.from_bytes(buf[pos : pos + 4], "big") > 0
-def read_top_boxes(f: BinaryIO) -> Iterator[tuple[bytes, Optional[bytes]]]:
+def read_top_boxes(f: BinaryIO) -> Iterator[tuple[bytes, bytes | None]]:
"""Yield each top-level box type, with the body of a moov or moof. Every other body is skipped.
Raises ValueError when a moov or moof claims more bytes than the file has left.
@@ -296,7 +297,7 @@ def read_top_boxes(f: BinaryIO) -> Iterator[tuple[bytes, Optional[bytes]]]:
yield kind, None
-def kid_windows(path: Path) -> Optional[KidMap]:
+def kid_windows(path: Path) -> KidMap | None:
"""Map each KID that encrypts part of a fragmented MP4 to a few fragment time windows, in seconds.
Reads only the moov and moof boxes of the ciphertext and skips every mdat, so a large
@@ -312,7 +313,7 @@ def kid_windows(path: Path) -> Optional[KidMap]:
"""
timescales: dict[int, int] = {}
handlers: dict[int, bytes] = {}
- entries: dict[int, list[Optional[UUID]]] = {}
+ entries: dict[int, list[UUID | None]] = {}
defaults: dict[int, tuple[int, int]] = {}
moov_groups: dict[int, list[Seig]] = {}
fragments: list[Fragment] = []
@@ -426,7 +427,7 @@ def trun_totals(moof: bytes, truns: list[int], default_duration: int) -> tuple[i
def read_fragment(
moof: bytes,
- entries: dict[int, list[Optional[UUID]]],
+ entries: dict[int, list[UUID | None]],
defaults: dict[int, tuple[int, int]],
moov_groups: dict[int, list[Seig]],
clock: dict[int, int],
@@ -443,7 +444,7 @@ def read_fragment(
continue
track, time, entry, default_duration = 0, None, 0, 0
groups: list[Seig] = []
- runs: Optional[list[tuple[int, int]]] = None
+ runs: list[tuple[int, int]] | None = None
truns: list[int] = []
for kind_, body, box_end in children(moof, traf, traf_end):
if kind_ == b"tfhd":
diff --git a/unshackle/core/drm/widevine.py b/unshackle/core/drm/widevine.py
index bf978d15..979a9368 100644
--- a/unshackle/core/drm/widevine.py
+++ b/unshackle/core/drm/widevine.py
@@ -1,8 +1,9 @@
from __future__ import annotations
import base64
+from collections.abc import Callable
from pathlib import Path
-from typing import Any, Callable, Optional, Union
+from typing import Any
from uuid import UUID
import click
@@ -33,7 +34,7 @@ class Widevine:
UUID("00010203-0405-0607-0809-101112131415"), # Shaka Packager test pattern
}
- def __init__(self, pssh: PSSH, kid: Union[UUID, str, bytes, None] = None, **kwargs: Any) -> None:
+ def __init__(self, pssh: PSSH, kid: UUID | str | bytes | None = None, **kwargs: Any) -> None:
if not pssh:
raise ValueError("Provided PSSH is empty.")
if not isinstance(pssh, PSSH):
@@ -42,7 +43,7 @@ class Widevine:
if pssh.system_id == PSSH.SystemId.PlayReady:
pssh = self.from_playready(pssh)
- self._kid: Optional[UUID] = None
+ self._kid: UUID | None = None
if kid:
if isinstance(kid, str):
kid = UUID(hex=kid)
@@ -86,7 +87,7 @@ class Widevine:
return PSSH.new(system_id=PSSH.SystemId.Widevine, key_ids=list(dict.fromkeys(kids)))
@classmethod
- def from_track(cls, track: AnyTrack, session: Optional[AnySession] = None) -> Widevine:
+ def from_track(cls, track: AnyTrack, session: AnySession | None = None) -> Widevine:
"""
Get PSSH and KID from within the Initiation Segment of the Track Data.
It also tries to get PSSH and KID from other track data like M3U8 data
@@ -107,7 +108,7 @@ class Widevine:
session = run_proxy.fallback_session()
session.headers.update(config.headers)
- kid: Optional[UUID] = None
+ kid: UUID | None = None
pssh_boxes: list[Container] = []
tenc_boxes: list[Container] = []
@@ -160,7 +161,7 @@ class Widevine:
if not isinstance(init_data, bytes):
raise TypeError(f"Expected init data to be bytes, not {init_data!r}")
- kid: Optional[UUID] = None
+ kid: UUID | None = None
pssh_boxes: list[Container] = list(get_boxes(init_data, b"pssh"))
tenc_boxes: list[Container] = list(get_boxes(init_data, b"tenc"))
@@ -188,7 +189,7 @@ class Widevine:
return self._pssh
@property
- def kid(self) -> Optional[UUID]:
+ def kid(self) -> UUID | None:
"""Get first Key ID, if any."""
return next(iter(self.kids), None)
@@ -297,7 +298,7 @@ class Widevine:
return [self._kid]
return self.kids
- def mp4decrypt_key_args(self, track_kids: Optional[dict[int, UUID]] = None) -> list[str]:
+ def mp4decrypt_key_args(self, track_kids: dict[int, UUID] | None = None) -> list[str]:
"""Build the mp4decrypt --key arguments for every content key, the zero-KID and the track ID fallbacks."""
return drm_key_args.mp4decrypt_key_args(self.content_keys, self.own_kids(), track_kids)
diff --git a/unshackle/core/events.py b/unshackle/core/events.py
index fe09ff36..127d0b30 100644
--- a/unshackle/core/events.py
+++ b/unshackle/core/events.py
@@ -1,8 +1,9 @@
from __future__ import annotations
+from collections.abc import Callable
from copy import deepcopy
from enum import Enum
-from typing import Any, Callable
+from typing import Any
class Events:
diff --git a/unshackle/core/export_name.py b/unshackle/core/export_name.py
index 0b6efee7..f518df1a 100644
--- a/unshackle/core/export_name.py
+++ b/unshackle/core/export_name.py
@@ -10,7 +10,7 @@ from __future__ import annotations
import os
from collections.abc import Collection, Iterable, Mapping, Sequence
from pathlib import Path
-from typing import Any, Optional
+from typing import Any
from unshackle.core.constants import AnyTrack
from unshackle.core.titles import Episode, Movie, Song, Title_T
@@ -105,7 +105,7 @@ def scope_part(titles: Sequence[Title_T], seasons: Mapping[int, Collection[int]]
return ".".join(parts)
-def resolution(track: Video) -> Optional[int]:
+def resolution(track: Video) -> int | None:
"""The resolution a release name uses, the same as the {resolution} template variable."""
return standard_resolution(track.width, track.height) if track.height else None
@@ -155,7 +155,7 @@ def export_name(
titles: Sequence[Title_T],
tracks: Iterable[AnyTrack],
service_tag: str,
- seasons: Optional[Mapping[int, Collection[int]]] = None,
+ seasons: Mapping[int, Collection[int]] | None = None,
) -> str:
"""The export file name without ``.json``, from the exported ``titles`` and ``tracks``.
@@ -185,12 +185,12 @@ def move_export(current: Path, name: str) -> Path:
class ExportNamer:
"""The state of one run's export: its titles, tracks, and the current file path."""
- def __init__(self, service_tag: str, seasons: Optional[Mapping[int, Collection[int]]] = None) -> None:
+ def __init__(self, service_tag: str, seasons: Mapping[int, Collection[int]] | None = None) -> None:
self.service_tag = service_tag
self.seasons: dict[int, set[int]] = {season: set(numbers) for season, numbers in (seasons or {}).items()}
self.titles: dict[str, Title_T] = {}
self.tracks: dict[str, AnyTrack] = {}
- self.path: Optional[Path] = None
+ self.path: Path | None = None
def add(self, title: Title_T, track: AnyTrack) -> None:
"""Record ``track`` and the video and audio tracks selected for ``title``.
diff --git a/unshackle/core/import_service.py b/unshackle/core/import_service.py
index 8509aca2..03ccf8d1 100644
--- a/unshackle/core/import_service.py
+++ b/unshackle/core/import_service.py
@@ -1,10 +1,11 @@
from __future__ import annotations
import logging
+from collections.abc import Callable
from enum import Enum
from http.cookiejar import CookieJar
from pathlib import Path
-from typing import Any, Callable, Optional, TypeVar, Union
+from typing import Any, TypeVar
from uuid import UUID
import click
@@ -36,7 +37,7 @@ PARSERS: dict[str, type[DASH] | type[HLS] | type[ISM]] = {"DASH": DASH, "HLS": H
MANIFEST_DATA_KEYS = {"DASH": "dash", "ISM": "ism"}
-def fallback_language(language: Any) -> Optional[Any]:
+def fallback_language(language: Any) -> Any | None:
"""The title language if the parsers would accept it, else None so they raise.
DASH drops an und/invalid fallback but ISM does not, and a truthy 'und' there silently
@@ -48,7 +49,7 @@ def fallback_language(language: Any) -> Optional[Any]:
return language
-def hls_audio_language(manifest: HLS) -> Optional[str]:
+def hls_audio_language(manifest: HLS) -> str | None:
"""The language of the default audio rendition, else of the first audio rendition, else None.
An HLS master playlist gives no language for a video variant, so the parser needs a
@@ -59,7 +60,7 @@ def hls_audio_language(manifest: HLS) -> Optional[str]:
return str(audio[0].language) if audio else None
-def hls_playlist_kids(track: Any, session: Optional[requests.Session] = None) -> Optional[set[UUID]]:
+def hls_playlist_kids(track: Any, session: requests.Session | None = None) -> set[UUID] | None:
"""Return the KIDs that the Widevine and PlayReady keys of the track's media playlist name.
Return None when the playlist has no key or only AES-128 keys: the download gets an AES-128
@@ -86,7 +87,7 @@ def hls_playlist_kids(track: Any, session: Optional[requests.Session] = None) ->
return None
-def content_period_filter(manifest: Any, kept: Any, title: Any) -> Optional[Callable[[Any], bool]]:
+def content_period_filter(manifest: Any, kept: Any, title: Any) -> Callable[[Any], bool] | None:
"""A DASH period_filter that drops every period not in ``kept``, the export's ``content_periods`` for this manifest.
None when there is nothing to filter, or when no kept id is in the re-fetched manifest: the server can name its
@@ -123,13 +124,13 @@ def manifest_fetch_error(manifest_type: str, title: Any, error: Exception) -> cl
def resolve_import_manifest_data(
tracks: Tracks,
- manifest_type: Optional[str],
+ manifest_type: str | None,
*,
session: requests.Session,
language: Any,
title: Title_T,
- saved: Optional[dict[str, Any]] = None,
- content_periods: Optional[dict[str, list[str]]] = None,
+ saved: dict[str, Any] | None = None,
+ content_periods: dict[str, list[str]] | None = None,
) -> None:
"""Fill ``track.data`` for DASH/ISM tracks rebuilt from export dicts.
@@ -167,11 +168,11 @@ def resolve_import_manifest_data(
except MissingLanguageError:
raise click.ClickException(
f"No language for '{title}': the {manifest_type} manifest has none and Title.language is unset"
- )
+ ) from None
except ValueError as e:
- raise click.ClickException(f"Failed to parse the {manifest_type} manifest for '{title}': {e}")
+ raise click.ClickException(f"Failed to parse the {manifest_type} manifest for '{title}': {e}") # noqa: B904
except Exception as e:
- raise manifest_fetch_error(manifest_type, title, e)
+ raise manifest_fetch_error(manifest_type, title, e) # noqa: B904
local_tracks = [*parsed.videos, *parsed.audio, *parsed.subtitles]
for track in pending:
@@ -189,7 +190,7 @@ def resolve_import_manifest_data(
tracks.select_subtitles(lambda t: str(t.id) not in unmatched)
-def parse_codec(codec: type[E], parse: Callable[[str], E], value: Any) -> Optional[E]:
+def parse_codec(codec: type[E], parse: Callable[[str], E], value: Any) -> E | None:
"""The codec a row names by enum name (``hevc``) or as ``parse`` reads it, else None."""
if not value:
return None
@@ -201,7 +202,7 @@ def parse_codec(codec: type[E], parse: Callable[[str], E], value: Any) -> Option
return None
-def video_range(value: Any) -> Optional[Video.Range]:
+def video_range(value: Any) -> Video.Range | None:
"""The range a row names, by enum name (``hdr10p``) or value (``HDR10+``), else None for SDR."""
name = str(value or "").upper()
if name in Video.Range.__members__:
@@ -209,7 +210,7 @@ def video_range(value: Any) -> Optional[Video.Range]:
return next((r for r in Video.Range if r.value.upper() == name), None)
-def int_or_none(value: Any) -> Optional[int]:
+def int_or_none(value: Any) -> int | None:
"""The integer a row field holds, else None."""
try:
return int(value)
@@ -232,14 +233,14 @@ class ImportService:
server_cdm = True
local_cdm = None
- def __init__(self, ctx: click.Context, service_tag: str, title: str, import_file: Optional[str]) -> None:
+ def __init__(self, ctx: click.Context, service_tag: str, title: str, import_file: str | None) -> None:
self.__class__.__name__ = service_tag
self.service_tag = service_tag
self.title_id = title
self.ctx = ctx
self.log = logging.getLogger(service_tag)
- self.credential: Optional[Credential] = None
- self.current_region: Optional[str] = None
+ self.credential: Credential | None = None
+ self.current_region: str | None = None
self.title_cache = None
if not import_file:
@@ -251,15 +252,15 @@ class ImportService:
try:
self.doc = mediaexport.read(export_path)
except mediaexport.ExportError as e:
- raise click.ClickException(f"Cannot import {export_path.name}: {e}")
+ raise click.ClickException(f"Cannot import {export_path.name}: {e}") from e
for refused in self.doc.refused:
self.log.warning(f"Skipping exported title {refused.raw.get('id')!r}: {refused.reason}")
if not self.doc.titles:
raise click.ClickException(f"Cannot import {export_path.name}: it has no title unshackle can use")
self.titles_data: dict[str, Any] = {e.id: self.legacy_entry(e) for e in self.doc.titles}
- self.region: Optional[str] = self.doc.region or None
- self.titles: Optional[Titles_T] = None
+ self.region: str | None = self.doc.region or None
+ self.titles: Titles_T | None = None
self.tracks_by_title: dict[str, Tracks] = {}
self.server_cdm_type = "playready" if self.exported_drm_system() == "playready" else "widevine"
@@ -312,7 +313,7 @@ class ImportService:
@staticmethod
def build_session(
- ctx: click.Context, region: Optional[str] = None, headers: Optional[dict[str, str]] = None
+ ctx: click.Context, region: str | None = None, headers: dict[str, str] | None = None
) -> requests.Session:
"""HTTP session for re-fetching the manifest.
@@ -338,7 +339,7 @@ class ImportService:
proxy = resolve_proxy_arg(proxy_query)
except Exception as e:
if explicit:
- raise click.ClickException(f"Failed to resolve proxy '{proxy_query}': {e}")
+ raise click.ClickException(f"Failed to resolve proxy '{proxy_query}': {e}") from None
log.warning(f"No proxy for export region '{region}', continuing without one: {e}")
proxy = None
@@ -353,7 +354,7 @@ class ImportService:
def title(self) -> str:
return self.title_id
- def authenticate(self, cookies: Optional[CookieJar] = None, credential: Optional[Credential] = None) -> None:
+ def authenticate(self, cookies: CookieJar | None = None, credential: Credential | None = None) -> None:
self.credential = credential
def get_titles(self) -> Titles_T:
@@ -385,7 +386,7 @@ class ImportService:
)
return {**meta, "language": source["language"]} if source else meta
- def get_titles_cached(self, title_id: Optional[str] = None) -> Titles_T:
+ def get_titles_cached(self, title_id: str | None = None) -> Titles_T:
"""Apply the service's title_map to titles reconstructed from the export sidecar."""
title_map = (ci_get(config.services, self.service_tag) or {}).get("title_map") or {}
return remap_titles(self.get_titles(), title_map)
@@ -425,12 +426,12 @@ class ImportService:
try:
parsed = snapshot.parse(entry.get("snapshot"), str(manifest_url), language)
except MissingLanguageError:
- raise click.ClickException(no_language)
+ raise click.ClickException(no_language) from None
if parsed is None:
try:
manifest = parser.from_url(url=manifest_url, session=self.session)
except Exception as e:
- raise manifest_fetch_error(manifest_type, title, e)
+ raise manifest_fetch_error(manifest_type, title, e) # noqa: B904
if language is None and isinstance(manifest, HLS):
language = hls_audio_language(manifest)
if language is None:
@@ -445,9 +446,11 @@ class ImportService:
else manifest.to_tracks(language=language)
)
except MissingLanguageError:
- raise click.ClickException(no_language)
+ raise click.ClickException(no_language) from None
except Exception as e:
- raise click.ClickException(f"Failed to parse the {manifest_type} manifest for '{title}': {e}")
+ raise click.ClickException( # noqa: B904
+ f"Failed to parse the {manifest_type} manifest for '{title}': {e}"
+ )
for parsed_track in parsed:
tracks.add(parsed_track)
parsed_ids = {str(t.id) for t in tracks}
@@ -560,7 +563,7 @@ class ImportService:
)
)
continue
- track: Union[Video, Audio]
+ track: Video | Audio
try:
if kind == "video":
track = Video(
@@ -593,7 +596,7 @@ class ImportService:
out.append(track)
return out
- def key_pool(self, title_id: Optional[str] = None) -> dict[UUID, str]:
+ def key_pool(self, title_id: str | None = None) -> dict[UUID, str]:
"""Exported KID:KEY pairs as {UUID: key_hex}, for one title or across every title."""
entry = self.doc.get(title_id) if title_id else None
keys = entry.keys if entry else self.doc.key_pool()
@@ -618,7 +621,7 @@ class ImportService:
out.append({"system": system, "pssh_b64": d.pssh, "kids": list(entry.keys)})
return out
- def exported_kids(self, title_id: str, track_id: str) -> Optional[set[str]]:
+ def exported_kids(self, title_id: str, track_id: str) -> set[str] | None:
"""Return the KIDs (hex) the export's row for the track lists, or None when it lists none."""
entry = self.doc.get(title_id)
row = next((r for r in (entry.tracks if entry else []) if str(r.get("id", "")) == track_id), None)
@@ -634,7 +637,7 @@ class ImportService:
entry = self.doc.get(title_id)
return {UUID(hex=kid): key for kid, key in (entry.keys_for(track_id) if entry else {}).items()}
- def rebuild_drm(self, track_dict: dict[str, Any], title_id: str) -> Optional[list[Any]]:
+ def rebuild_drm(self, track_dict: dict[str, Any], title_id: str) -> list[Any] | None:
"""Rebuild a DRM object (from stored PSSH, falling back to a stub) with the exported keys.
Keys and DRM are title-level in the shared format; a legacy v2 track dict that still
@@ -692,7 +695,7 @@ class ImportService:
"""Always False: an import licenses nothing."""
return False
- def license_track(self, track: AnyTrack, drm: Any, kid: Optional[UUID] = None) -> Optional[dict[UUID, str]]:
+ def license_track(self, track: AnyTrack, drm: Any, kid: UUID | None = None) -> dict[UUID, str] | None:
"""Raise the error that names the KIDs of ``track`` neither the export nor a vault holds."""
raise self.missing_key(track)
@@ -729,7 +732,7 @@ class ImportService:
continue
row_kids = self.exported_kids(title_id, str(track.id))
if row_kids:
- declared: Optional[set[UUID]] = {UUID(hex=kid) for kid in row_kids}
+ declared: set[UUID] | None = {UUID(hex=kid) for kid in row_kids}
keys = self.exported_keys(title_id, str(track.id))
else:
declared = self.track_kids(track, self.session)
@@ -749,12 +752,12 @@ class ImportService:
self.server_cdm_type = drm_obj.__class__.__name__.lower()
@classmethod
- def track_is_encrypted(cls, track: Any, session: Optional[requests.Session] = None) -> bool:
+ def track_is_encrypted(cls, track: Any, session: requests.Session | None = None) -> bool:
"""True if the track carries DRM, its manifest declares protection, or its init segment does."""
return cls.track_kids(track, session) is not None
@staticmethod
- def track_kids(track: Any, session: Optional[requests.Session] = None) -> Optional[set[UUID]]:
+ def track_kids(track: Any, session: requests.Session | None = None) -> set[UUID] | None:
"""Return the KIDs an encrypted track declares, or None when the track is not encrypted.
An empty set means that the track is encrypted but declares no KID. The KIDs come from
@@ -820,12 +823,10 @@ class ImportService:
]
)
- def get_widevine_service_certificate(self, **_: Any) -> Optional[str]:
+ def get_widevine_service_certificate(self, **_: Any) -> str | None:
return None
- def get_clearkey_license(
- self, *, challenge: bytes, title: Title_T, track: AnyTrack
- ) -> Optional[Union[bytes, str, dict]]:
+ def get_clearkey_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | dict | None:
raise self.missing_key(track)
@staticmethod
diff --git a/unshackle/core/launch.py b/unshackle/core/launch.py
index 97dea804..fc0fdb8c 100644
--- a/unshackle/core/launch.py
+++ b/unshackle/core/launch.py
@@ -2,7 +2,7 @@
import copy
from pathlib import Path
-from typing import Any, Dict, Optional, TypedDict, cast
+from typing import Any, TypedDict, cast
import click
@@ -29,19 +29,19 @@ class LaunchKeys(TypedDict, total=False):
client_device: bool
client_identity: bool
client_argv: str
- proxy_arg: Optional[str]
- proxy_query: Optional[str]
- proxy_provider: Optional[str]
+ proxy_arg: str | None
+ proxy_query: str | None
+ proxy_provider: str | None
-def launch(ctx: click.Context, keys: LaunchKeys, obj: Optional[ContextData] = None) -> None:
+def launch(ctx: click.Context, keys: LaunchKeys, obj: ContextData | None = None) -> None:
"""Write the launch ``keys`` into ``ctx.params``, and ``obj`` as ``ctx.obj`` when given."""
ctx.params.update(keys)
if obj is not None:
ctx.obj = obj
-def served_context(obj: ContextData, params: Dict[str, Any], keys: LaunchKeys) -> click.Context:
+def served_context(obj: ContextData, params: dict[str, Any], keys: LaunchKeys) -> click.Context:
"""A new parent context for a service that a serve runs for an API client, with the dl options in ``params``."""
ctx = click.Context(click.Command("serve"))
# dl defaults -q to [], and services iterate it
@@ -50,7 +50,7 @@ def served_context(obj: ContextData, params: Dict[str, Any], keys: LaunchKeys) -
return ctx
-SERVICE_YAML: Dict[Path, tuple[tuple[int, int], dict]] = {}
+SERVICE_YAML: dict[Path, tuple[tuple[int, int], dict]] = {}
def load_service_config(tag: str, local: bool = True) -> dict:
diff --git a/unshackle/core/login.py b/unshackle/core/login.py
index 25f4e377..3ad6f444 100644
--- a/unshackle/core/login.py
+++ b/unshackle/core/login.py
@@ -6,13 +6,12 @@ import html
from http.cookiejar import CookieJar, MozillaCookieJar
from io import StringIO
from pathlib import Path
-from typing import Optional
from unshackle.core.config import config
from unshackle.core.credential import Credential
-def get_cookie_path(service: str, profile: Optional[str]) -> Optional[Path]:
+def get_cookie_path(service: str, profile: str | None) -> Path | None:
"""Get Service Cookie File Path for Profile."""
direct_cookie_file = config.directories.cookies / f"{service}.txt"
profile_cookie_file = config.directories.cookies / service / f"{profile}.txt"
@@ -27,7 +26,7 @@ def get_cookie_path(service: str, profile: Optional[str]) -> Optional[Path]:
return None
-def get_cookie_jar(service: str, profile: Optional[str]) -> Optional[CookieJar]:
+def get_cookie_jar(service: str, profile: str | None) -> CookieJar | None:
"""
Get Service Cookies for Profile.
@@ -99,7 +98,7 @@ def save_cookies(path: Path, cookies: CookieJar) -> None:
cookie_jar.save(ignore_discard=True, ignore_expires=True)
-def get_credentials(service: str, profile: Optional[str]) -> Optional[Credential]:
+def get_credentials(service: str, profile: str | None) -> Credential | None:
"""Get Service Credentials for Profile."""
credentials = config.credentials.get(service)
if credentials:
diff --git a/unshackle/core/manifests/dash.py b/unshackle/core/manifests/dash.py
index d308fcde..9327a303 100644
--- a/unshackle/core/manifests/dash.py
+++ b/unshackle/core/manifests/dash.py
@@ -8,11 +8,12 @@ import os
import re
import shutil
from bisect import bisect_right
+from collections.abc import Callable, Collection
from contextlib import suppress
from copy import deepcopy
-from functools import lru_cache, partial
+from functools import cache, partial
from pathlib import Path
-from typing import Any, BinaryIO, Callable, Collection, Optional, Union, cast
+from typing import Any, BinaryIO, cast
from urllib.parse import urljoin, urlparse
from uuid import UUID
from zlib import crc32
@@ -59,7 +60,7 @@ COUNT_CHANNEL_SCHEMES = (
"urn:dts:dash:audio_channel_configuration:2012",
)
CICP_CHANNEL_SCHEME = "urn:mpeg:mpegB:cicp:ChannelConfiguration"
-CICP_CHANNEL_LAYOUTS: dict[int, Union[float, str]] = {
+CICP_CHANNEL_LAYOUTS: dict[int, float | str] = {
1: 1.0,
2: 2.0,
3: 3.0,
@@ -97,14 +98,16 @@ def missing_language(where: str, fallback: Any) -> MissingLanguageError:
def rebase_webvtt_files(groups: list[list[Path]], bounds_ms: list[int]) -> None:
"""Rewrite the WebVTT segment files of each period or discontinuity block, shifted by webvtt_block_offsets."""
texts = [[try_ensure_utf8(path.read_bytes()).decode("utf8") for path in group] for group in groups]
- for group, parts, offset in zip(groups, texts, webvtt_block_offsets(["\n\n".join(t) for t in texts], bounds_ms)):
+ for group, parts, offset in zip(
+ groups, texts, webvtt_block_offsets(["\n\n".join(t) for t in texts], bounds_ms), strict=False
+ ):
if not offset:
continue
- for path, text in zip(group, parts):
+ for path, text in zip(group, parts, strict=True):
path.write_bytes(shift_webvtt(text, offset).encode("utf8"))
-def mdhd_timescale(init_data: bytes) -> Optional[int]:
+def mdhd_timescale(init_data: bytes) -> int | None:
"""The media timescale of the first track in an init segment, or None when it has no mdhd."""
for kind, body, box_end in walk(init_data):
if kind == b"mdhd":
@@ -142,8 +145,8 @@ class PeriodRebase:
self.periods = periods
self.timescale = timescale
self.offset = 0
- self.base: Optional[int] = None
- self.previous: Optional[tuple[int, int, int]] = None
+ self.base: int | None = None
+ self.previous: tuple[int, int, int] | None = None
self.joins: set[int] = set()
def append(self, dst: BinaryIO, segment_file: Path) -> None:
@@ -195,7 +198,7 @@ class PeriodRebase:
self.previous = (first + self.offset, length, media_start + self.offset + length)
-def rep_shape(adaptation_set: Element, rep: Element) -> tuple[Optional[str], ...]:
+def rep_shape(adaptation_set: Element, rep: Element) -> tuple[str | None, ...]:
"""The attributes a Representation must keep to continue a track into another Period."""
return tuple(DASH.get_attr(a, adaptation_set, rep) for a in ("codecs", "width", "height", "audioSamplingRate"))
@@ -207,7 +210,7 @@ def rep_bandwidth(rep: Element) -> float:
return 0.0
-def kind_and_lang(adaptation_set: Element) -> tuple[Optional[str], str]:
+def kind_and_lang(adaptation_set: Element) -> tuple[str | None, str]:
"""Content type and language subtag, without the region, of an AdaptationSet."""
mime = DASH.get_attr("mimeType", adaptation_set, adaptation_set.find("Representation")) or ""
kind = adaptation_set.get("contentType") or mime.split("/")[0] or None
@@ -230,7 +233,7 @@ class DASH:
self.url = url
@classmethod
- def from_url(cls, url: str, session: Optional[Union[Session, RnetSession]] = None, **args: Any) -> DASH:
+ def from_url(cls, url: str, session: Session | RnetSession | None = None, **args: Any) -> DASH:
"""Fetch and parse an MPD. The XML declaration gives the encoding, then the HTTP charset."""
if not url:
raise requests.URLRequired("DASH manifest URL must be provided for relative path computations.")
@@ -278,9 +281,7 @@ class DASH:
return cls(manifest, url)
- def to_tracks(
- self, language: Optional[Union[str, Language]] = None, period_filter: Optional[Callable] = None
- ) -> Tracks:
+ def to_tracks(self, language: str | Language | None = None, period_filter: Callable | None = None) -> Tracks:
"""
Convert an MPEG-DASH document to Video, Audio and Subtitle Track objects.
@@ -346,7 +347,9 @@ class DASH:
content_type = "text"
mime_type = f"application/mp4; codecs='{real_codec.value.lower()}'"
except ValueError:
- raise ValueError(f"Unsupported content type '{content_type}' with codecs of '{codecs}'")
+ raise ValueError(
+ f"Unsupported content type '{content_type}' with codecs of '{codecs}'"
+ ) from None
if content_type == "text" and mime_type and "/mp4" not in mime_type:
# mimeType likely specifies the subtitle codec better than `codecs`
@@ -487,7 +490,7 @@ class DASH:
manifest: ElementTree = track.data["dash"]["manifest"]
adaptation_set: Element = track.data["dash"]["adaptation_set"]
representation: Element = track.data["dash"]["representation"]
- rep_id: Optional[str] = track.data["dash"].get("representation_id") or representation.get("id")
+ rep_id: str | None = track.data["dash"].get("representation_id") or representation.get("id")
filtered_period_ids = set(track.data["dash"].get("filtered_period_ids", []))
# Preserve existing DRM if it was set by the service, especially when service set Widevine
@@ -547,20 +550,20 @@ class DASH:
drm_obj.content_keys[kid] = key
all_periods = manifest.findall("Period")
- segments: list[tuple[str, Optional[str]]] = []
- seen_segments: set[tuple[str, Optional[str]]] = set()
+ segments: list[tuple[str, str | None]] = []
+ seen_segments: set[tuple[str, str | None]] = set()
segment_durations: list[int] = []
segment_timescale: float = 0
- init_data: Optional[bytes] = None
- track_kid: Optional[UUID] = None
+ init_data: bytes | None = None
+ track_kid: UUID | None = None
period_starts: dict[int, tuple[float, float, float]] = {}
timed = True
content_periods = [p for p in all_periods if DASH.is_content_period(p, filtered_period_ids)]
period_count = len(content_periods)
- durations = dict(zip(map(id, all_periods), DASH.period_durations(manifest)))
- content_timing: list[tuple[Optional[float], Optional[float]]] = []
- elapsed: Optional[float] = 0.0
+ durations = dict(zip(map(id, all_periods), DASH.period_durations(manifest), strict=True))
+ content_timing: list[tuple[float | None, float | None]] = []
+ elapsed: float | None = 0.0
for content_period in content_periods:
duration = durations[id(content_period)]
content_timing.append((elapsed, duration))
@@ -569,7 +572,7 @@ class DASH:
if period_count > 1:
log.debug(f"Multi-period manifest detected with {period_count} content periods")
- stored_period: Optional[Element] = track.data["dash"].get("period")
+ stored_period: Element | None = track.data["dash"].get("period")
for period_idx, content_period in enumerate(content_periods):
if content_period is stored_period:
@@ -687,7 +690,7 @@ class DASH:
{"url": url, "headers": {"Range": f"bytes={bytes_range}"} if bytes_range else {}}
for url, bytes_range in segments
]
- output_dir, filename = save_dir, "{i:0%d}.mp4" % (len(str(len(segments))))
+ output_dir, filename = save_dir, f"{{i:0{len(str(len(segments)))}}}.mp4"
log_event(
"manifest_dash_download_start",
@@ -708,11 +711,11 @@ class DASH:
not drm and isinstance(track, Subtitle) and track.codec not in (Subtitle.Codec.fVTT, Subtitle.Codec.fTTML)
)
- decrypter: Optional[SegmentDecrypter] = None
+ decrypter: SegmentDecrypter | None = None
if use_segment_decrypt and init_data:
decrypter = SegmentDecrypter(cast(SEGMENT_DRM_T, drm), init_data, save_dir.parent, ctx.max_workers)
- rebase: Optional[PeriodRebase] = None
+ rebase: PeriodRebase | None = None
known = timed and len(period_starts) > 1
timescale = mdhd_timescale(init_data) if known and init_data and not is_text_subtitle else None
if timescale:
@@ -824,7 +827,7 @@ class DASH:
complete_track(track, ctx, drm, decrypt=not decrypter)
@staticmethod
- def find_segment_element(name: str, adaptation_set: Element, representation: Element) -> Optional[Element]:
+ def find_segment_element(name: str, adaptation_set: Element, representation: Element) -> Element | None:
"""Find a segment description element on the representation, or else on its adaptation set."""
element = representation.find(name)
return element if element is not None else adaptation_set.find(name)
@@ -846,9 +849,9 @@ class DASH:
@staticmethod
def collapsible_single_url(
is_subtitle: bool,
- segments: list[tuple[str, Optional[str]]],
+ segments: list[tuple[str, str | None]],
init_len: int,
- ) -> Optional[tuple[int, int]]:
+ ) -> tuple[int, int] | None:
"""
Get the first and last byte of the segments when every segment is a byte range of one
parent resource that follows an init of init_len bytes, so unshackle can download the
@@ -890,7 +893,7 @@ class DASH:
@staticmethod
def single_url_prefix_matches(
- session: Union[Session, RnetSession],
+ session: Session | RnetSession,
url: str,
span: tuple[int, int],
init_data: bytes,
@@ -924,7 +927,7 @@ class DASH:
return True
@staticmethod
- def period_durations(manifest: ElementTree) -> list[Optional[float]]:
+ def period_durations(manifest: ElementTree) -> list[float | None]:
"""The duration in seconds of every Period, None where the manifest does not give it.
A Period without @start starts at 0 when it is the first, else where the previous Period
@@ -932,7 +935,7 @@ class DASH:
or to the end of the presentation. A duration that is not positive counts as unknown.
"""
periods = manifest.findall("Period")
- starts: list[Optional[float]] = []
+ starts: list[float | None] = []
for i, period in enumerate(periods):
previous = periods[i - 1] if i else None
if period.get("start"):
@@ -944,9 +947,9 @@ class DASH:
else:
starts.append(None)
total = manifest.get("mediaPresentationDuration")
- durations: list[Optional[float]] = []
- for i, (period, start) in enumerate(zip(periods, starts)):
- duration: Optional[float] = None
+ durations: list[float | None] = []
+ for i, (period, start) in enumerate(zip(periods, starts, strict=True)):
+ duration: float | None = None
if period.get("duration"):
duration = DASH.pt_to_sec(period.get("duration"))
elif start is not None and i + 1 < len(periods):
@@ -958,7 +961,7 @@ class DASH:
return durations
@staticmethod
- def period_duration(manifest: ElementTree, period: Element) -> Optional[float]:
+ def period_duration(manifest: ElementTree, period: Element) -> float | None:
"""The duration in seconds of one Period, by DASH.period_durations."""
index = next((i for i, p in enumerate(manifest.findall("Period")) if p is period), None)
if index is None:
@@ -977,7 +980,7 @@ class DASH:
return int(element.get("presentationTimeOffset") or 0) / (float(element.get("timescale") or 1) or 1.0)
@staticmethod
- def merge_segment_templates(adaptation_set: Element, representation: Element) -> Optional[Element]:
+ def merge_segment_templates(adaptation_set: Element, representation: Element) -> Element | None:
"""
Assemble the effective SegmentTemplate for a Representation by cascading the
AdaptationSet > Representation levels (ISO/IEC 23009-1 5.3.9.1).
@@ -1010,16 +1013,16 @@ class DASH:
manifest: ElementTree,
track: Track,
track_url: str,
- session: Union[Session, RnetSession],
+ session: Session | RnetSession,
probe_kid: bool = True,
- window: Optional[tuple[int, int]] = None,
- duration: Optional[float] = None,
+ window: tuple[int, int] | None = None,
+ duration: float | None = None,
) -> tuple[
- Optional[bytes],
- list[tuple[str, Optional[str]]],
+ bytes | None,
+ list[tuple[str, str | None]],
float,
list[int],
- Optional[UUID],
+ UUID | None,
]:
"""
Extract segments from a single period's representation.
@@ -1047,7 +1050,7 @@ class DASH:
period_duration = (
duration or DASH.period_duration(manifest, period) or (DASH.pt_to_sec(total) if total else None)
)
- init_data: Optional[bytes] = None
+ init_data: bytes | None = None
segment_template = DASH.merge_segment_templates(adaptation_set, representation)
@@ -1055,10 +1058,10 @@ class DASH:
segment_base = DASH.find_segment_element("SegmentBase", adaptation_set, representation)
- segments: list[tuple[str, Optional[str]]] = []
+ segments: list[tuple[str, str | None]] = []
segment_timescale: float = 0
segment_durations: list[int] = []
- track_kid: Optional[UUID] = None
+ track_kid: UUID | None = None
if segment_template is not None:
start_number = int(segment_template.get("startNumber") or 1)
@@ -1131,7 +1134,7 @@ class DASH:
if not end_number:
end_number = start_number + len(segment_durations) - 1
- for t, n in zip(segment_durations, range(start_number, end_number + 1)):
+ for t, n in zip(segment_durations, range(start_number, end_number + 1), strict=False):
segments.append(
(
DASH.replace_fields(
@@ -1248,7 +1251,7 @@ class DASH:
return init_data, segments, segment_timescale, segment_durations, track_kid
@staticmethod
- def get_attr(item: str, adaptation_set: Element, representation: Optional[Element] = None) -> Optional[Any]:
+ def get_attr(item: str, adaptation_set: Element, representation: Element | None = None) -> Any | None:
"""Helper to get a requested item from the Representation, otherwise from the AdaptationSet."""
adaptation_set_item = adaptation_set.get(item)
if representation is None:
@@ -1262,7 +1265,7 @@ class DASH:
@staticmethod
def find_elements(
- item: str, adaptation_set: Element, representation: Optional[Element] = None, both: bool = False
+ item: str, adaptation_set: Element, representation: Element | None = None, both: bool = False
) -> list[Any]:
"""
Helper to get all requested items from the Representation, otherwise from the AdaptationSet.
@@ -1285,9 +1288,9 @@ class DASH:
@staticmethod
def get_language(
adaptation_set: Element,
- representation: Optional[Element] = None,
- fallback: Optional[Union[str, Language]] = None,
- ) -> Optional[Language]:
+ representation: Element | None = None,
+ fallback: str | Language | None = None,
+ ) -> Language | None:
"""
Get Language (if any) from the AdaptationSet or Representation.
@@ -1364,7 +1367,7 @@ class DASH:
)
@staticmethod
- def adaptation_set_key(adaptation_set: Element) -> tuple[Optional[str], ...]:
+ def adaptation_set_key(adaptation_set: Element) -> tuple[str | None, ...]:
"""Identity of an AdaptationSet, used to re-find its counterpart in another Period."""
return tuple(
adaptation_set.get(attr)
@@ -1373,8 +1376,8 @@ class DASH:
@staticmethod
def resolve_representation(
- period: Element, rep_id: Optional[str], adaptation_set: Element
- ) -> Optional[tuple[Element, Element]]:
+ period: Element, rep_id: str | None, adaptation_set: Element
+ ) -> tuple[Element, Element] | None:
"""
Find the (AdaptationSet, Representation) in another Period that continues rep_id.
@@ -1389,7 +1392,7 @@ class DASH:
def same_shape(as_: Element) -> list[Element]:
return sorted((r for r in as_.findall("Representation") if rep_shape(as_, r) == want), key=rep_bandwidth)
- def sets(within: Optional[Element], key: Callable[[Element], Any]) -> list[Element]:
+ def sets(within: Element | None, key: Callable[[Element], Any]) -> list[Element]:
found = within.findall("AdaptationSet") if within is not None else []
target = key(adaptation_set)
return [a for a in found if key(a) == target and not DASH.is_trick_mode(a) and same_shape(a)]
@@ -1458,7 +1461,7 @@ class DASH:
)
@staticmethod
- def get_audio_channels(adaptation_set: Element, representation: Optional[Element]) -> Union[float, str, None]:
+ def get_audio_channels(adaptation_set: Element, representation: Element | None) -> float | str | None:
"""
Channel layout from the first AudioChannelConfiguration whose scheme is known, decoded by that scheme.
@@ -1479,7 +1482,7 @@ class DASH:
return None
@staticmethod
- def get_ddp_complexity_index(adaptation_set: Element, representation: Optional[Element]) -> Optional[int]:
+ def get_ddp_complexity_index(adaptation_set: Element, representation: Element | None) -> int | None:
"""Get the DD+ Complexity Index (if any) from the AdaptationSet or Representation."""
return next(
(
@@ -1604,7 +1607,7 @@ class DASH:
return drm
@staticmethod
- def pt_to_sec(d: Union[str, float]) -> float:
+ def pt_to_sec(d: str | float) -> float:
if isinstance(d, float):
return d
has_ymd = d[0:8] == "P0Y0M0DT"
@@ -1618,7 +1621,7 @@ class DASH:
return sum(float(x[0:-1]) * {"H": 60 * 60, "M": 60, "S": 1}[x[-1].upper()] for x in m)
@staticmethod
- @lru_cache(maxsize=None)
+ @cache
def field_format_pattern(field: str) -> re.Pattern:
# printf-style `$Field%fmt$` matcher, compiled once per field name
return re.compile(rf"\${re.escape(field)}%([a-z0-9]+)\$", flags=re.I)
diff --git a/unshackle/core/manifests/hls.py b/unshackle/core/manifests/hls.py
index 8a0c2906..8e0f9933 100644
--- a/unshackle/core/manifests/hls.py
+++ b/unshackle/core/manifests/hls.py
@@ -9,11 +9,12 @@ import re
import shutil
import subprocess
import time
+from collections.abc import Callable
from contextlib import suppress
from functools import partial
from itertools import accumulate
from pathlib import Path
-from typing import Any, BinaryIO, Callable, Optional, Union, cast
+from typing import Any, BinaryIO, cast
from urllib.parse import urljoin, urlparse
from uuid import UUID
from zlib import crc32
@@ -61,9 +62,9 @@ class HLS:
def __init__(
self,
manifest: M3U8,
- session: Optional[Union[Session, RnetSession]] = None,
- url: Optional[str] = None,
- raw_text: Optional[str] = None,
+ session: Session | RnetSession | None = None,
+ url: str | None = None,
+ raw_text: str | None = None,
) -> None:
if not manifest:
raise ValueError("HLS manifest must be provided.")
@@ -78,7 +79,7 @@ class HLS:
self.raw_text = raw_text
@classmethod
- def from_url(cls, url: str, session: Optional[Union[Session, RnetSession]] = None, **args: Any) -> HLS:
+ def from_url(cls, url: str, session: Session | RnetSession | None = None, **args: Any) -> HLS:
if not url:
raise requests.URLRequired("HLS manifest URL must be provided.")
if not isinstance(url, str):
@@ -149,9 +150,7 @@ class HLS:
return out
@staticmethod
- def select_audio_codec(
- candidates: Optional[list[tuple[str, Audio.Codec]]], uri: Optional[str]
- ) -> Optional[Audio.Codec]:
+ def select_audio_codec(candidates: list[tuple[str, Audio.Codec]] | None, uri: str | None) -> Audio.Codec | None:
"""
Choose the Audio Codec of one rendition from the codecs its variant declares.
@@ -184,7 +183,7 @@ class HLS:
)
return candidates[0][1]
- def to_tracks(self, language: Optional[Union[str, Language]]) -> Tracks:
+ def to_tracks(self, language: str | Language | None) -> Tracks:
"""
Convert a Variant Playlist M3U(8) document to Video, Audio and Subtitle Track objects.
@@ -236,8 +235,8 @@ class HLS:
(raw.get("stream_info") or {}).get("req_video_layout")
for raw in (getattr(self.manifest, "data", None) or {}).get("playlists", [])
]
- for playlist, video_layout in zip(self.manifest.playlists, video_layouts):
- video_codec: Optional[Video.Codec] = None
+ for playlist, video_layout in zip(self.manifest.playlists, video_layouts, strict=False):
+ video_codec: Video.Codec | None = None
primary_track_type: type[Audio] | type[Video]
try:
# TODO: Any better way to figure out the primary track type?
@@ -397,8 +396,8 @@ class HLS:
@staticmethod
def probe_ts_info(
- variant_url: str, session: Optional[Union[Session, RnetSession]] = None
- ) -> Optional[tuple[int, int, Video.Codec]]:
+ variant_url: str, session: Session | RnetSession | None = None
+ ) -> tuple[int, int, Video.Codec] | None:
"""Probe the first TS segment of a variant playlist to extract resolution and codec."""
if not session:
session = run_proxy.fallback_session()
@@ -417,7 +416,7 @@ class HLS:
return HLS.parse_ts_video_info(data)
@staticmethod
- def parse_ts_video_info(data: bytes) -> Optional[tuple[int, int, Video.Codec]]:
+ def parse_ts_video_info(data: bytes) -> tuple[int, int, Video.Codec] | None:
"""Parse H.264/H.265 NAL units from TS segment data to extract resolution and codec."""
class _BitReader:
@@ -572,10 +571,10 @@ class HLS:
@staticmethod
def resolve_segment_key(
- segment_keys: list[Union[m3u8.model.SessionKey, m3u8.model.Key]],
+ segment_keys: list[m3u8.model.SessionKey | m3u8.model.Key],
cdm: object,
- drm_preference: Optional[str] = None,
- ) -> Optional[m3u8.Key]:
+ drm_preference: str | None = None,
+ ) -> m3u8.Key | None:
"""Pick the EXT-X-KEY for a segment, preferring one the CDM can handle."""
if cdm:
cdm_segment_keys = HLS.filter_keys_for_cdm(segment_keys, cdm, drm_preference)
@@ -585,7 +584,7 @@ class HLS:
@staticmethod
def fetch_init_section(
- session: Union[Session, RnetSession],
+ session: Session | RnetSession,
init_section: m3u8.model.InitializationSection,
range_offset: int,
) -> tuple[bytes, int]:
@@ -610,9 +609,9 @@ class HLS:
@staticmethod
def single_init_no_rotation(
wanted_segments: list[Any],
- initial_key: Optional[m3u8.Key],
+ initial_key: m3u8.Key | None,
cdm: object,
- drm_preference: Optional[str] = None,
+ drm_preference: str | None = None,
) -> bool:
"""Whether every wanted segment shares one init segment and one EXT-X-KEY, with no discontinuity.
@@ -826,8 +825,8 @@ class HLS:
},
)
- map_data: Optional[tuple[m3u8.model.InitializationSection, bytes]] = None
- segment_decrypter: Optional[SegmentDecrypter] = None
+ map_data: tuple[m3u8.model.InitializationSection, bytes] | None = None
+ segment_decrypter: SegmentDecrypter | None = None
if use_segment_decrypt or use_rolling_merge:
init_section = wanted_segments[0].init_section
init_content, _ = HLS.fetch_init_section(session, init_section, 0)
@@ -844,7 +843,7 @@ class HLS:
"HLS",
urls,
segment_save_dir,
- "{i:0%d}{ext}" % len(str(len(urls))),
+ f"{{i:0{len(str(len(urls)))}}}{{ext}}",
rolling=use_rolling_merge,
init=map_data[1] if map_data else None,
decrypter=segment_decrypter,
@@ -887,10 +886,140 @@ class HLS:
# First segment's Media Sequence Number - used as the AES-128 IV when EXT-X-KEY has
# no explicit IV (RFC 8216 §5.2), where each segment's IV is its sequence number.
media_sequence_start = getattr(master, "media_sequence", None) or 0
- encryption_data: Optional[tuple[Optional[m3u8.Key], DRM_T]] = None
+ encryption_data: tuple[m3u8.Key | None, DRM_T] | None = None
if session_drm:
encryption_data = (initial_drm_key, session_drm)
+ def merge(to: Path, via: list[Path], delete: bool = False, include_map_data: bool = False) -> None:
+ """
+ Merge all files to a given path, optionally including map data.
+
+ Parameters:
+ to: The output file with all merged data.
+ via: List of files to merge, in sequence.
+ delete: Delete each source file after this function merges it.
+ include_map_data: Whether to include the init map data.
+ """
+ prepend = include_map_data and map_data and map_data[1]
+ if len(via) == 1 and not prepend and delete:
+ try:
+ os.replace(via[0], to)
+ return
+ except OSError:
+ pass
+ with open(to, "wb") as x:
+ if prepend:
+ assert map_data is not None
+ x.write(map_data[1])
+ for file in via:
+ with open(file, "rb") as segment:
+ shutil.copyfileobj(segment, x, 1024 * 1024)
+ x.flush()
+ if delete:
+ file.unlink()
+
+ def decrypt(include_this_segment: bool) -> Path | None:
+ """
+ Decrypt all segments that uses the currently set DRM.
+
+ This function merges every segment of this DRM together in sequence, adds
+ the init data (if any) at the start, and then deletes the segment files. It
+ then decrypts the merged file. The merged and decrypted file names state the
+ range of segments the file holds.
+
+ Parameters:
+ include_this_segment: Whether to include the current segment in the
+ list of segments to merge and decrypt. This should be False if
+ decrypting on EXT-X-KEY changes, or True when decrypting on the
+ last segment.
+
+ Returns the decrypted path.
+ """
+ nonlocal map_data
+ assert encryption_data is not None
+ drm = encryption_data[1]
+ first_segment_i = next(
+ (int(file.stem) for file in sorted(segment_save_dir.iterdir()) if file.stem.isdigit()), None
+ )
+ last_segment_i = max(0, i - int(not include_this_segment))
+ if first_segment_i is None or first_segment_i > last_segment_i:
+ return None
+ range_len = (last_segment_i - first_segment_i) + 1
+
+ segment_range = f"{str(first_segment_i).zfill(name_len)}-{str(last_segment_i).zfill(name_len)}"
+ ext = get_extension(wanted_segments[last_segment_i].uri) or ""
+ merged_path = segment_save_dir / f"{segment_range}{ext}"
+ decrypted_path = segment_save_dir / f"{merged_path.stem}_decrypted{merged_path.suffix}"
+
+ files = [
+ file
+ for file in sorted(segment_save_dir.iterdir())
+ if file.stem.isdigit() and first_segment_i <= int(file.stem) <= last_segment_i
+ ]
+ if not files:
+ raise ValueError(f"None of the segment files for {segment_range} exist...")
+ elif len(files) != range_len:
+ raise ValueError(f"Missing {range_len - len(files)} segment files for {segment_range}...")
+
+ if isinstance(drm, (Widevine, PlayReady)):
+ if segment_decrypter:
+ if not map_data:
+ raise ValueError("Segment decryption needs an EXT-X-MAP init segment.")
+ assert decrypted_init is not None
+ map_data = (map_data[0], decrypted_init)
+ merge(to=merged_path, via=files, delete=True, include_map_data=True)
+ decrypt_track(drm, merged_path, license_widevine, decrypt=not segment_decrypter, track=track)
+ assert_fragments_decrypted(merged_path)
+ merged_path.rename(decrypted_path)
+ else:
+ # AES segments must be decrypted individually before merging: each segment
+ # likely carries its own 16-byte padding
+ key_obj = encryption_data[0]
+ # AES-128 with no explicit IV: each segment's IV is its media sequence
+ # number (RFC 8216 §5.2). Without this the engine used a zero IV and the
+ # output decrypted to garbage.
+ seq_iv = isinstance(drm, ClearKey) and not (key_obj and key_obj.iv)
+ for file in files:
+ if seq_iv and isinstance(drm, ClearKey) and file.stem.isdigit():
+ download_i = int(file.stem)
+ seq = getattr(wanted_segments[download_i], "media_sequence", None)
+ if seq is None:
+ seq = media_sequence_start + download_i
+ drm.iv = int(seq).to_bytes(16, "big")
+ drm.decrypt(file)
+ merge(to=merged_path, via=files, delete=True, include_map_data=True)
+
+ events.emit(events.Types.TRACK_DECRYPTED, track=track, drm=drm, segment=decrypted_path)
+
+ return decrypted_path
+
+ def merge_discontinuity(include_this_segment: bool, include_map_data: bool = True) -> None:
+ """
+ Merge all segments of the discontinuity.
+
+ The caller must download every segment file of this discontinuity first.
+ The caller must also decrypt them, when they need decryption.
+
+ Parameters:
+ include_this_segment: Whether to include the current segment in the
+ list of segments to merge and decrypt. This should be False if
+ decrypting on EXT-X-KEY changes, or True when decrypting on the
+ last segment.
+ include_map_data: Whether to prepend the init map data before the
+ segment files when merging.
+ """
+ last_segment_i = max(0, i - int(not include_this_segment))
+
+ files = [
+ file
+ for file in sorted(segment_save_dir.iterdir())
+ if int(file.stem.replace("_decrypted", "").split("-")[-1]) <= last_segment_i
+ ]
+ if files:
+ to_dir = segment_save_dir.parent
+ to_path = to_dir / f"{str(discon_i).zfill(name_len)}{files[-1].suffix}"
+ merge(to=to_path, via=files, delete=True, include_map_data=include_map_data)
+
i = -1
for real_i, segment in enumerate(master.segments):
if segment not in unwanted_segments:
@@ -898,136 +1027,6 @@ class HLS:
is_last_segment = (real_i + 1) == len(master.segments)
- def merge(to: Path, via: list[Path], delete: bool = False, include_map_data: bool = False) -> None:
- """
- Merge all files to a given path, optionally including map data.
-
- Parameters:
- to: The output file with all merged data.
- via: List of files to merge, in sequence.
- delete: Delete each source file after this function merges it.
- include_map_data: Whether to include the init map data.
- """
- prepend = include_map_data and map_data and map_data[1]
- if len(via) == 1 and not prepend and delete:
- try:
- os.replace(via[0], to)
- return
- except OSError:
- pass
- with open(to, "wb") as x:
- if prepend:
- assert map_data is not None
- x.write(map_data[1])
- for file in via:
- with open(file, "rb") as segment:
- shutil.copyfileobj(segment, x, 1024 * 1024)
- x.flush()
- if delete:
- file.unlink()
-
- def decrypt(include_this_segment: bool) -> Optional[Path]:
- """
- Decrypt all segments that uses the currently set DRM.
-
- This function merges every segment of this DRM together in sequence, adds
- the init data (if any) at the start, and then deletes the segment files. It
- then decrypts the merged file. The merged and decrypted file names state the
- range of segments the file holds.
-
- Parameters:
- include_this_segment: Whether to include the current segment in the
- list of segments to merge and decrypt. This should be False if
- decrypting on EXT-X-KEY changes, or True when decrypting on the
- last segment.
-
- Returns the decrypted path.
- """
- nonlocal map_data
- assert encryption_data is not None
- drm = encryption_data[1]
- first_segment_i = next(
- (int(file.stem) for file in sorted(segment_save_dir.iterdir()) if file.stem.isdigit()), None
- )
- last_segment_i = max(0, i - int(not include_this_segment))
- if first_segment_i is None or first_segment_i > last_segment_i:
- return None
- range_len = (last_segment_i - first_segment_i) + 1
-
- segment_range = f"{str(first_segment_i).zfill(name_len)}-{str(last_segment_i).zfill(name_len)}"
- ext = get_extension(wanted_segments[last_segment_i].uri) or ""
- merged_path = segment_save_dir / f"{segment_range}{ext}"
- decrypted_path = segment_save_dir / f"{merged_path.stem}_decrypted{merged_path.suffix}"
-
- files = [
- file
- for file in sorted(segment_save_dir.iterdir())
- if file.stem.isdigit() and first_segment_i <= int(file.stem) <= last_segment_i
- ]
- if not files:
- raise ValueError(f"None of the segment files for {segment_range} exist...")
- elif len(files) != range_len:
- raise ValueError(f"Missing {range_len - len(files)} segment files for {segment_range}...")
-
- if isinstance(drm, (Widevine, PlayReady)):
- if segment_decrypter:
- if not map_data:
- raise ValueError("Segment decryption needs an EXT-X-MAP init segment.")
- assert decrypted_init is not None
- map_data = (map_data[0], decrypted_init)
- merge(to=merged_path, via=files, delete=True, include_map_data=True)
- decrypt_track(drm, merged_path, license_widevine, decrypt=not segment_decrypter, track=track)
- assert_fragments_decrypted(merged_path)
- merged_path.rename(decrypted_path)
- else:
- # AES segments must be decrypted individually before merging: each segment
- # likely carries its own 16-byte padding
- key_obj = encryption_data[0]
- # AES-128 with no explicit IV: each segment's IV is its media sequence
- # number (RFC 8216 §5.2). Without this the engine used a zero IV and the
- # output decrypted to garbage.
- seq_iv = isinstance(drm, ClearKey) and not (key_obj and key_obj.iv)
- for file in files:
- if seq_iv and isinstance(drm, ClearKey) and file.stem.isdigit():
- download_i = int(file.stem)
- seq = getattr(wanted_segments[download_i], "media_sequence", None)
- if seq is None:
- seq = media_sequence_start + download_i
- drm.iv = int(seq).to_bytes(16, "big")
- drm.decrypt(file)
- merge(to=merged_path, via=files, delete=True, include_map_data=True)
-
- events.emit(events.Types.TRACK_DECRYPTED, track=track, drm=drm, segment=decrypted_path)
-
- return decrypted_path
-
- def merge_discontinuity(include_this_segment: bool, include_map_data: bool = True) -> None:
- """
- Merge all segments of the discontinuity.
-
- The caller must download every segment file of this discontinuity first.
- The caller must also decrypt them, when they need decryption.
-
- Parameters:
- include_this_segment: Whether to include the current segment in the
- list of segments to merge and decrypt. This should be False if
- decrypting on EXT-X-KEY changes, or True when decrypting on the
- last segment.
- include_map_data: Whether to prepend the init map data before the
- segment files when merging.
- """
- last_segment_i = max(0, i - int(not include_this_segment))
-
- files = [
- file
- for file in sorted(segment_save_dir.iterdir())
- if int(file.stem.replace("_decrypted", "").split("-")[-1]) <= last_segment_i
- ]
- if files:
- to_dir = segment_save_dir.parent
- to_path = to_dir / f"{str(discon_i).zfill(name_len)}{files[-1].suffix}"
- merge(to=to_path, via=files, delete=True, include_map_data=include_map_data)
-
if segment not in unwanted_segments:
if isinstance(track, Subtitle):
segment_file_ext = get_extension(segment.uri) or ""
@@ -1195,7 +1194,7 @@ class HLS:
return plain
@staticmethod
- def merge_segments(segments: list[Path], save_path: Path, progress: Optional[Any] = None) -> int:
+ def merge_segments(segments: list[Path], save_path: Path, progress: Any | None = None) -> int:
"""
Concatenate Segments using FFmpeg concat with binary fallback.
@@ -1301,9 +1300,7 @@ class HLS:
return save_path.stat().st_size
@staticmethod
- def parse_session_data_keys(
- manifest: M3U8, session: Optional[Union[Session, RnetSession]] = None
- ) -> list[m3u8.model.Key]:
+ def parse_session_data_keys(manifest: M3U8, session: Session | RnetSession | None = None) -> list[m3u8.model.Key]:
"""Parse the `com.apple.hls.keys` `EXT-X-SESSION-DATA` entry into `Key` objects."""
keys: list[m3u8.model.Key] = []
@@ -1355,10 +1352,10 @@ class HLS:
@staticmethod
def filter_keys_for_cdm(
- keys: list[Union[m3u8.model.SessionKey, m3u8.model.Key]],
+ keys: list[m3u8.model.SessionKey | m3u8.model.Key],
cdm: object,
- drm_preference: Optional[str] = None,
- ) -> list[Union[m3u8.model.SessionKey, m3u8.model.Key]]:
+ drm_preference: str | None = None,
+ ) -> list[m3u8.model.SessionKey | m3u8.model.Key]:
"""
Filter EXT-X-KEY entries to only include those matching the CDM type.
@@ -1389,10 +1386,10 @@ class HLS:
@staticmethod
def alternate_drm(
- keys: list[Union[m3u8.model.SessionKey, m3u8.model.Key]],
+ keys: list[m3u8.model.SessionKey | m3u8.model.Key],
chosen: DRM_T,
- session: Optional[Union[Session, RnetSession]] = None,
- kid: Optional[UUID] = None,
+ session: Session | RnetSession | None = None,
+ kid: UUID | None = None,
) -> list[DRM_T]:
"""Build the Widevine or PlayReady DRM that the EXT-X-KEY entries offer next to ``chosen``.
@@ -1412,9 +1409,9 @@ class HLS:
def get_track_kid_from_init(
master: M3U8,
track: AnyTrack,
- session: Union[Session, RnetSession],
- init_section: Optional[m3u8.model.InitializationSection] = None,
- ) -> Optional[UUID]:
+ session: Session | RnetSession,
+ init_section: m3u8.model.InitializationSection | None = None,
+ ) -> UUID | None:
"""
Extract the track's Key ID from an init segment (EXT-X-MAP), by default the first in the playlist.
@@ -1445,7 +1442,7 @@ class HLS:
return None
@staticmethod
- def get_supported_key(keys: list[Union[m3u8.model.SessionKey, m3u8.model.Key]]) -> Optional[m3u8.Key]:
+ def get_supported_key(keys: list[m3u8.model.SessionKey | m3u8.model.Key]) -> m3u8.Key | None:
"""
Get the first DRM system unshackle can use from the given `EXT-X-KEY` entries.
@@ -1484,9 +1481,9 @@ class HLS:
@staticmethod
def get_drm(
- key: Union[m3u8.model.SessionKey, m3u8.model.Key],
- session: Optional[Union[Session, RnetSession]] = None,
- kid: Optional[UUID] = None,
+ key: m3u8.model.SessionKey | m3u8.model.Key,
+ session: Session | RnetSession | None = None,
+ kid: UUID | None = None,
) -> DRM_T:
"""
Convert HLS EXT-X-KEY data to an initialized DRM object.
@@ -1534,11 +1531,11 @@ class HLS:
@staticmethod
def get_drm_or_probe(
- key: Union[m3u8.model.SessionKey, m3u8.model.Key],
+ key: m3u8.model.SessionKey | m3u8.model.Key,
master: M3U8,
track: AnyTrack,
- session: Optional[Union[Session, RnetSession]] = None,
- init_section: Optional[m3u8.model.InitializationSection] = None,
+ session: Session | RnetSession | None = None,
+ init_section: m3u8.model.InitializationSection | None = None,
probe_session: Any = None,
) -> DRM_T:
"""
@@ -1557,9 +1554,7 @@ class HLS:
return HLS.get_drm(key, session, kid=kid)
@staticmethod
- def get_all_drm(
- keys: list[Union[m3u8.model.SessionKey, m3u8.model.Key]], proxy: Optional[str] = None
- ) -> list[DRM_T]:
+ def get_all_drm(keys: list[m3u8.model.SessionKey | m3u8.model.Key], proxy: str | None = None) -> list[DRM_T]:
"""
Convert HLS EXT-X-KEY data to initialized DRM objects.
diff --git a/unshackle/core/manifests/ism.py b/unshackle/core/manifests/ism.py
index 51a464f0..5c4d58e1 100644
--- a/unshackle/core/manifests/ism.py
+++ b/unshackle/core/manifests/ism.py
@@ -10,7 +10,7 @@ import struct
import urllib.parse
from contextlib import suppress
from pathlib import Path
-from typing import Any, BinaryIO, Optional, Union
+from typing import Any, BinaryIO
import requests
from langcodes import Language, tag_is_valid
@@ -60,7 +60,7 @@ class ISM:
self.url = url
@classmethod
- def from_url(cls, url: str, session: Optional[Union[Session, RnetSession]] = None, **kwargs: Any) -> "ISM":
+ def from_url(cls, url: str, session: Session | RnetSession | None = None, **kwargs: Any) -> ISM:
if not url:
raise requests.URLRequired("ISM manifest URL must be provided")
if not session:
@@ -80,7 +80,7 @@ class ISM:
return cls(load_xml(res.content), url)
@classmethod
- def from_text(cls, text: str, url: str) -> "ISM":
+ def from_text(cls, text: str, url: str) -> ISM:
if not text:
raise ValueError("ISM manifest text must be provided")
if not url:
@@ -113,7 +113,7 @@ class ISM:
return drm
@staticmethod
- def get_video_range_and_fps(fourcc: str, codec_private_data: str) -> tuple[Video.Range, Optional[float]]:
+ def get_video_range_and_fps(fourcc: str, codec_private_data: str) -> tuple[Video.Range, float | None]:
"""Derive colour range and fps from the SPS VUI in CodecPrivateData,
since Smooth manifests carry neither as attributes. Range soft-fails to
SDR. fps is None for non-HEVC codecs and VUIs without timing info."""
@@ -134,9 +134,7 @@ class ISM:
return ISM.get_video_range_and_fps(fourcc, codec_private_data)[0]
@staticmethod
- def init_segment(
- track: AnyTrack, session_drm: Optional[DRM_T], first_segment: Optional[bytes] = None
- ) -> Optional[bytes]:
+ def init_segment(track: AnyTrack, session_drm: DRM_T | None, first_segment: bytes | None = None) -> bytes | None:
# Smooth fragments are moof+mdat only; rebuild the ftyp+moov init box from
# the manifest CodecPrivateData (and KID, when encrypted) so the merged file
# is a valid MP4 that shaka/mp4decrypt can parse.
@@ -165,7 +163,7 @@ class ISM:
except LookupError:
language = "und"
- kid: Optional[bytes] = None
+ kid: bytes | None = None
if session_drm is not None:
kid_uuid = next(iter(getattr(session_drm, "kids", None) or []), None)
if kid_uuid is not None:
@@ -233,7 +231,7 @@ class ISM:
)
return None
- def to_tracks(self, language: Optional[Union[str, Language]] = None) -> Tracks:
+ def to_tracks(self, language: str | Language | None = None) -> Tracks:
if (self.manifest.get("IsLive") or "").upper() == "TRUE":
raise ValueError("Live Smooth Streaming manifests are not supported")
tracks = Tracks()
@@ -477,7 +475,7 @@ class ISM:
"ISM",
[{"url": url} for url in segments],
save_dir,
- "{i:0%d}.mp4" % len(str(len(segments))),
+ f"{{i:0{len(str(len(segments)))}}}.mp4",
rolling=use_rolling_merge,
append=append_ism,
)
diff --git a/unshackle/core/manifests/ism_init.py b/unshackle/core/manifests/ism_init.py
index 1cb4bf5f..3372695a 100644
--- a/unshackle/core/manifests/ism_init.py
+++ b/unshackle/core/manifests/ism_init.py
@@ -18,7 +18,7 @@ from __future__ import annotations
import binascii
import struct
-from typing import Iterator, Optional
+from collections.abc import Iterator
u8 = struct.Struct(">B")
u16 = struct.Struct(">H")
@@ -221,7 +221,7 @@ def skip_hevc_st_ref_pic_set(r: BitReader, idx: int, num_delta_pocs: list[int])
return num_negative + num_positive
-def parse_hevc_sps_vui(sps_rbsp: bytes) -> tuple[Optional[tuple[int, int, int]], Optional[float]]:
+def parse_hevc_sps_vui(sps_rbsp: bytes) -> tuple[tuple[int, int, int] | None, float | None]:
"""((colour_primaries, transfer_characteristics, matrix_coeffs), fps) from a
de-emulated HEVC SPS VUI. Either element is None when absent."""
r = BitReader(sps_rbsp)
@@ -257,12 +257,12 @@ def parse_hevc_sps_vui(sps_rbsp: bytes) -> tuple[Optional[tuple[int, int, int]],
r.read_bits(32) # sar_width + sar_height
if r.read_bits(1): # overscan_info_present_flag
r.read_bits(1) # overscan_appropriate_flag
- colour: Optional[tuple[int, int, int]] = None
+ colour: tuple[int, int, int] | None = None
if r.read_bits(1): # video_signal_type_present_flag
r.read_bits(4) # video_format + video_full_range_flag
if r.read_bits(1): # colour_description_present_flag
colour = (r.read_bits(8), r.read_bits(8), r.read_bits(8))
- fps: Optional[float] = None
+ fps: float | None = None
try:
if r.read_bits(1): # chroma_loc_info_present_flag
r.read_ue() # chroma_sample_loc_type_top_field
@@ -286,7 +286,7 @@ HEVC_FOURCCS = frozenset(("HVC1", "HEV1", "HEVC", "H265", "DVHE", "DVH1"))
def parse_codec_private_data_vui(
fourcc: str, codec_private_data: bytes
-) -> tuple[Optional[tuple[int, int, int]], Optional[float]]:
+) -> tuple[tuple[int, int, int] | None, float | None]:
"""(colour triple, fps) from the SPS VUI in HEVC CodecPrivateData. Gives
(None, None) for a codec this parser does not read, and for malformed data.
This parser excludes H.264 on purpose: its VUI timing is field-based and
@@ -303,14 +303,14 @@ def parse_codec_private_data_vui(
return None, None
-def parse_codec_private_data_colour(fourcc: str, codec_private_data: bytes) -> Optional[tuple[int, int, int]]:
+def parse_codec_private_data_colour(fourcc: str, codec_private_data: bytes) -> tuple[int, int, int] | None:
"""SPS VUI colour triple from HEVC CodecPrivateData. Gives None for a codec
this parser does not read, for data with no colour description, and for
malformed data."""
return parse_codec_private_data_vui(fourcc, codec_private_data)[0]
-def iter_boxes(data: bytes, start: int, end: int) -> Iterator[tuple[bytes, Optional[bytes], int, int]]:
+def iter_boxes(data: bytes, start: int, end: int) -> Iterator[tuple[bytes, bytes | None, int, int]]:
"""Yield (type, uuid_usertype, payload_start, box_end) for each child box.
Stops silently at the first box with a declared size the walk cannot follow.
@@ -338,7 +338,7 @@ def iter_boxes(data: bytes, start: int, end: int) -> Iterator[tuple[bytes, Optio
offset += size
-def find_box(data: bytes, start: int, end: int, target: bytes) -> Optional[tuple[int, int]]:
+def find_box(data: bytes, start: int, end: int, target: bytes) -> tuple[int, int] | None:
"""Find the first child box of the given type. Returns (payload_start, end)."""
for box_type, _, body, box_end in iter_boxes(data, start, end):
if box_type == target:
@@ -346,7 +346,7 @@ def find_box(data: bytes, start: int, end: int, target: bytes) -> Optional[tuple
return None
-def read_track_id(fragment: bytes) -> Optional[int]:
+def read_track_id(fragment: bytes) -> int | None:
"""Read the track_ID from a fragment's moof/traf/tfhd box, if present.
Smooth fragments declare their own track_ID. The synthesized moov must use
@@ -369,7 +369,7 @@ def read_track_id(fragment: bytes) -> Optional[int]:
return struct.unpack(">I", fragment[body + 4 : body + 8])[0]
-def read_per_sample_iv_size(fragment: bytes) -> Optional[int]:
+def read_per_sample_iv_size(fragment: bytes) -> int | None:
"""
Derive the per-sample IV size (8 or 16) from a fragment's sample-encryption
metadata, for the synthesized tenc default_Per_Sample_IV_Size.
@@ -385,8 +385,8 @@ def read_per_sample_iv_size(fragment: bytes) -> Optional[int]:
if not traf:
return None
- senc: Optional[tuple[int, int]] = None
- saiz_default: Optional[int] = None
+ senc: tuple[int, int] | None = None
+ saiz_default: int | None = None
senc_has_subsamples = False
for box_type, usertype, body, box_end in iter_boxes(fragment, *traf):
if box_type == b"senc" or (box_type == b"uuid" and usertype == PIFF_SENC_UUID):
@@ -453,7 +453,7 @@ def piff_senc_to_cenc(fragment: bytes, iv_size: int = 8) -> bytes:
override disagrees, since tenc is the only IV width a CENC decrypter consults and a
mismatch misparses every IV.
"""
- out: Optional[bytearray] = None
+ out: bytearray | None = None
limit = len(fragment)
trafs = [
(body, min(box_end, limit))
@@ -539,7 +539,7 @@ DV_LEVELS = (
)
-def infer_dv_profile(cicp: Optional[tuple[int, int, int]]) -> tuple[int, int]:
+def infer_dv_profile(cicp: tuple[int, int, int] | None) -> tuple[int, int]:
"""Derive (dv_profile, dv_bl_signal_compatibility_id) from the base layer's colour description.
Profile 5 carries no usable description, while profile 8 stays backward compatible
@@ -553,7 +553,7 @@ def infer_dv_profile(cicp: Optional[tuple[int, int, int]]) -> tuple[int, int]:
return 5, 0
-def build_dvcc(width: int, height: int, fps: Optional[float], cicp: Optional[tuple[int, int, int]]) -> bytes:
+def build_dvcc(width: int, height: int, fps: float | None, cicp: tuple[int, int, int] | None) -> bytes:
"""
Assemble the Dolby Vision decoder config box for a single-layer Dolby Vision track:
dvcC, or dvvC when the profile is cross-compatible.
@@ -666,7 +666,7 @@ def build_esds(codec_private_data: bytes) -> bytes:
return full_box(b"esds", 0, 0, es)
-def build_dec3(codec_private_data: bytes) -> Optional[bytes]:
+def build_dec3(codec_private_data: bytes) -> bytes | None:
"""Assemble a dec3 (EC-3 specific) box from Smooth EC-3 CodecPrivateData.
Smooth EC-3 CodecPrivateData ([MS-SSTR] AudioTag 65534) serializes a
@@ -705,7 +705,7 @@ def build_sinf(
original_format: bytes,
kid: bytes,
iv_size: int = 8,
- constant_iv: Optional[bytes] = None,
+ constant_iv: bytes | None = None,
) -> bytes:
"""Assemble a sinf protection box (frma + schm CENC + schi/tenc) for CENC.
@@ -743,9 +743,9 @@ def build_init_segment(
sampling_rate: int = 48000,
track_id: int = 1,
nal_length_size: int = 4,
- kid: Optional[bytes] = None,
+ kid: bytes | None = None,
iv_size: int = 8,
- constant_iv: Optional[bytes] = None,
+ constant_iv: bytes | None = None,
) -> bytes:
"""
Assemble a complete ftyp + moov initialization segment.
diff --git a/unshackle/core/manifests/m3u8.py b/unshackle/core/manifests/m3u8.py
index 27199915..352399a1 100644
--- a/unshackle/core/manifests/m3u8.py
+++ b/unshackle/core/manifests/m3u8.py
@@ -2,8 +2,6 @@
from __future__ import annotations
-from typing import Optional, Union
-
import m3u8
from requests import Session
@@ -17,8 +15,8 @@ def parse(
master: m3u8.M3U8,
language: str,
*,
- session: Optional[Union[Session, RnetSession]] = None,
- url: Optional[str] = None,
+ session: Session | RnetSession | None = None,
+ url: str | None = None,
) -> Tracks:
"""Parse a variant playlist to ``Tracks`` with basic information, defer DRM loading."""
tracks = HLS(master, session=session, url=url).to_tracks(language)
diff --git a/unshackle/core/manifests/segment_pipeline.py b/unshackle/core/manifests/segment_pipeline.py
index 7999a921..36631943 100644
--- a/unshackle/core/manifests/segment_pipeline.py
+++ b/unshackle/core/manifests/segment_pipeline.py
@@ -8,10 +8,11 @@ from __future__ import annotations
import html
import shutil
+from collections.abc import Callable, Iterator
from concurrent.futures import Future
from contextlib import ExitStack, closing, contextmanager
from pathlib import Path
-from typing import Any, BinaryIO, Callable, Iterator, Optional
+from typing import Any, BinaryIO
from uuid import UUID
from unshackle.core.constants import DOWNLOAD_CANCELLED, AnyTrack
@@ -54,13 +55,13 @@ class RollingMerge:
landed (ISM), passes its own.
"""
- def __init__(self, dst: BinaryIO, append: Optional[Callable[[BinaryIO, Path], None]] = None) -> None:
+ def __init__(self, dst: BinaryIO, append: Callable[[BinaryIO, Path], None] | None = None) -> None:
self.dst = dst
self.append = append or (lambda dst, path: append_segment(dst, path, is_text_subtitle=False))
self.cursor = 0
- self.ready: dict[int, tuple[Path, Optional[Future]]] = {}
+ self.ready: dict[int, tuple[Path, Future | None]] = {}
- def add(self, index: int, segment_file: Path, future: Optional[Future] = None) -> None:
+ def add(self, index: int, segment_file: Path, future: Future | None = None) -> None:
# runs on the downloader's own loop, so a decrypt wait or a catch-up burst
# delays new submissions; move the drain to a writer thread if throughput measurably drops
self.ready[index] = (segment_file, future)
@@ -105,10 +106,10 @@ LICENSABLE: dict[Track.Descriptor, tuple[type, ...]] = {
def license_drm(
track: AnyTrack,
- drm: Optional[DRM_T],
+ drm: DRM_T | None,
ctx: DownloadContext,
- kid: Optional[UUID] = None,
- probe: Optional[Callable[[], Optional[UUID]]] = None,
+ kid: UUID | None = None,
+ probe: Callable[[], UUID | None] | None = None,
) -> None:
"""The licence step: get the content keys of `drm` for `track` through ctx.license_widevine, with progress.
@@ -146,17 +147,17 @@ def fetch_segments(
filename: str,
*,
rolling: bool = False,
- init: Optional[bytes] = None,
- append: Optional[Callable[[BinaryIO, Path], None]] = None,
- decrypter: Optional[SegmentDecrypter] = None,
-) -> tuple[Optional[RollingMerge], Optional[bytes]]:
+ init: bytes | None = None,
+ append: Callable[[BinaryIO, Path], None] | None = None,
+ decrypter: SegmentDecrypter | None = None,
+) -> tuple[RollingMerge | None, bytes | None]:
"""Download the segment requests and return the rolling merge, if any, and the init that heads the output.
With `rolling`, the init (or the decrypter's decrypted init) and each segment go into ctx.save_path
as they land. A decrypter gets every segment before its SEGMENT_DOWNLOADED event. Any failure closes
the decrypter and removes a rolling output. The returned init is the decrypter's decrypted init, else `init`.
"""
- merger: Optional[RollingMerge] = None
+ merger: RollingMerge | None = None
try:
with ExitStack() as stack:
if rolling:
@@ -251,7 +252,7 @@ def remove_segment_dir(save_dir: Path) -> None:
shutil.rmtree(save_dir, ignore_errors=True)
-def complete_track(track: AnyTrack, ctx: DownloadContext, drm: Optional[DRM_T], decrypt: bool = True) -> None:
+def complete_track(track: AnyTrack, ctx: DownloadContext, drm: DRM_T | None, decrypt: bool = True) -> None:
"""Hand the merged file to the track: TRACK_DOWNLOADED, then the decryption, then the segment directory cleanup."""
track.path = ctx.save_path
events.emit(events.Types.TRACK_DOWNLOADED, track=track)
diff --git a/unshackle/core/manifests/snapshot.py b/unshackle/core/manifests/snapshot.py
index da63093b..a56ac235 100644
--- a/unshackle/core/manifests/snapshot.py
+++ b/unshackle/core/manifests/snapshot.py
@@ -11,7 +11,7 @@ import base64
import logging
import zlib
from copy import deepcopy
-from typing import Any, Optional
+from typing import Any
from lxml import etree
@@ -45,7 +45,7 @@ def restore(tracks: Tracks, snapshot: Any, language: Any = None) -> None:
restore_manifests(tracks, entries(snapshot, "manifests"), budget, language)
-def parse(snapshot: Any, url: str, language: Any = None) -> Optional[Tracks]:
+def parse(snapshot: Any, url: str, language: Any = None) -> Tracks | None:
"""Every track of the saved whole manifest for ``url``, with its filtered periods, else None.
The URL also matches without its query, since a service can sign the URL it fetches. A saved
@@ -112,11 +112,11 @@ def whole_manifests(tracks: Tracks, level: int, counts: dict[int, int]) -> list[
for kind, tag in (("dash", ".//Representation"), ("ism", ".//QualityLevel")):
data = track.data.get(kind) or {}
if data.get("manifest") is not None:
+ size = counted(data["manifest"], tag, counts)
break
else:
continue
url = str(track.url)
- size = counted(data["manifest"], tag, counts)
if url not in best or size > best[url][0]:
best[url] = (size, kind, data)
@@ -169,9 +169,11 @@ def fragments(tracks: Tracks, level: int, counts: dict[int, int]) -> list[dict[s
period = dash.get("period")
representation = dash.get("representation")
periods = manifest.findall("Period")
- durations = dict(zip(map(id, periods), DASH.period_durations(manifest)))
+ durations = dict(zip(map(id, periods), DASH.period_durations(manifest), strict=True))
- def kept(source: Any, new_period: Any) -> None:
+ def kept(
+ source: Any, new_period: Any, durations: dict[int, float | None] = durations, root: Any = root
+ ) -> None:
"""Append a fragment period with its duration written out, as the periods dropped beside it are gone."""
duration = durations.get(id(source))
if duration is not None and not new_period.get("duration"):
@@ -229,7 +231,7 @@ def restore_fragments(tracks: Tracks, saved: list[dict[str, Any]], budget: list[
track.descriptor = Track.Descriptor.DASH
-def to_tracks(entry: dict[str, Any], language: Any, budget: list[int]) -> Optional[Tracks]:
+def to_tracks(entry: dict[str, Any], language: Any, budget: list[int]) -> Tracks | None:
"""The tracks of one whole-manifest entry, with the service's filtered periods dropped again."""
root = unpack(entry["data"], budget)
if entry.get("type") == "dash":
@@ -273,14 +275,14 @@ def restore_manifests(tracks: Tracks, saved: list[dict[str, Any]], budget: list[
track.drm = matched.drm
-def same_bitrate(local: Optional[int], remote: Optional[int]) -> bool:
+def same_bitrate(local: int | None, remote: int | None) -> bool:
"""Equal to the nearest kb/s. A server that predates ``bitrate_bps`` rounds to kb/s in transit."""
if not local or not remote:
return not local and not remote
return round(local / 1000) == round(remote / 1000)
-def match_track(remote_track: Track, local_tracks: list) -> Optional[Track]:
+def match_track(remote_track: Track, local_tracks: list) -> Track | None:
"""Find the locally-parsed track that matches a remote track by ID or by attributes.
A range matches the ones ``PROBED_RANGES`` lets the server's probe relabel it to, because the local
diff --git a/unshackle/core/manifests/trim.py b/unshackle/core/manifests/trim.py
index 767b0d47..53482903 100644
--- a/unshackle/core/manifests/trim.py
+++ b/unshackle/core/manifests/trim.py
@@ -4,8 +4,10 @@ from __future__ import annotations
import logging
import mmap
+from collections.abc import Collection
+from itertools import pairwise
from pathlib import Path
-from typing import Collection, NamedTuple, Optional, cast
+from typing import NamedTuple, cast
from unshackle.core.drm.verify import ENTRY_FIELDS, children, walk
from unshackle.core.manifests.ism_init import box
@@ -56,7 +58,7 @@ class FragmentSamples(NamedTuple):
trimmable: bool
-def senc_ends(data: bytes, start: int, end: int, iv_size: int) -> Optional[list[int]]:
+def senc_ends(data: bytes, start: int, end: int, iv_size: int) -> list[int] | None:
"""The end offset of each sample entry of a senc box, or None when the entries do not fill it exactly."""
flags, pos, ends = be32(data, start + 8) & 0xFFFFFF, start + 16, []
for _ in range(be32(data, start + 12)):
@@ -73,7 +75,7 @@ def senc_ends(data: bytes, start: int, end: int, iv_size: int) -> Optional[list[
def cenc_entries(
data: bytes, named: dict[bytes, tuple[int, int]], moof: int, count: int, iv_size: int
-) -> Optional[list[int]]:
+) -> list[int] | None:
"""The senc entry ends of a traf whose senc, saiz and saio describe ``count`` samples, saio pointing at senc."""
if not CENC <= named.keys() or iv_size < 0:
return None
@@ -92,7 +94,7 @@ def cenc_entries(
return ends if fits else None
-def group_runs(data: bytes, start: int, end: int) -> Optional[Runs]:
+def group_runs(data: bytes, start: int, end: int) -> Runs | None:
"""The entry count offset and (sample count, group index) runs of an sbgp box, or None when they overrun it."""
at = start + 16 + 4 * (data[start + 8] == 1)
count = be32(data, at)
@@ -102,8 +104,8 @@ def group_runs(data: bytes, start: int, end: int) -> Optional[Runs]:
def read_samples(
- data: bytes, moof: tuple[int, int], mdat: Optional[tuple[int, int]], defaults: tuple[int, int], iv_size: int
-) -> Optional[FragmentSamples]:
+ data: bytes, moof: tuple[int, int], mdat: tuple[int, int] | None, defaults: tuple[int, int], iv_size: int
+) -> FragmentSamples | None:
"""Parse a moof and the mdat right after it; None when it has no single traf with a tfdt and one bounded trun."""
start, end = moof
trafs = [b for b in child_boxes(data, start + 8, end) if b[0] == b"traf"]
@@ -259,7 +261,7 @@ def write_trimmed(data: bytes, temp: Path, joins: Collection[int]) -> int:
keep: dict[int, int] = {}
untrimmable = 0
- for (i, fragment), (_, following) in zip(fragments, fragments[1:]):
+ for (i, fragment), (_, following) in pairwise(fragments):
join = following.decode_time
if join not in joins or fragment.decode_time + sum(fragment.durations) <= join:
continue
diff --git a/unshackle/core/music/extract.py b/unshackle/core/music/extract.py
index c592bd4d..29b48b6f 100644
--- a/unshackle/core/music/extract.py
+++ b/unshackle/core/music/extract.py
@@ -10,7 +10,7 @@ reuse them.
from __future__ import annotations
import re
-from typing import Any, Optional
+from typing import Any
from unshackle.core.titles.music import Music, Song
@@ -42,7 +42,7 @@ def first_text(*values: Any, default: str = "") -> str:
return default
-def first_number(*values: Any) -> Optional[float]:
+def first_number(*values: Any) -> float | None:
"""Return the first value parseable as a float, else ``None``."""
for value in values:
if value in (None, ""):
@@ -60,7 +60,7 @@ def year_from_value(value: Any) -> int:
return int(match.group("year")) if match else 1900
-def duration_seconds(value: Any) -> Optional[float]:
+def duration_seconds(value: Any) -> float | None:
"""Coerce a duration to seconds, treating large numbers (>10000) as milliseconds."""
number = first_number(value)
if number is None:
@@ -104,7 +104,7 @@ def format_names(value: Any, sep: str = ", ") -> str:
return sep.join(names)
-def classify_release_kind(raw_kind: str, tracks_count: Optional[float]) -> str:
+def classify_release_kind(raw_kind: str, tracks_count: float | None) -> str:
"""Normalise an already-extracted release-kind string to a canonical value.
Returns one of ``single | ep | album | compilation | live | download |
@@ -138,10 +138,10 @@ def build_music_from_songs(
songs: list[Song],
*,
kind: str,
- title: Optional[str] = None,
- artist: Optional[str] = None,
- owner: Optional[str] = None,
- description: Optional[str] = None,
+ title: str | None = None,
+ artist: str | None = None,
+ owner: str | None = None,
+ description: str | None = None,
empty_error: str = "No songs were returned.",
) -> Music:
"""Assemble a :class:`Music` release from a list of :class:`Song` objects.
diff --git a/unshackle/core/music/renderer.py b/unshackle/core/music/renderer.py
index a0349da5..1284c71f 100644
--- a/unshackle/core/music/renderer.py
+++ b/unshackle/core/music/renderer.py
@@ -1,7 +1,7 @@
from __future__ import annotations
import re
-from typing import Any, Optional
+from typing import Any
from rich.console import Group, RenderableType
from rich.panel import Panel
@@ -29,7 +29,7 @@ class MusicRenderer:
return Group(header, Text(""), tracks)
return tracks
- def render_header(self, music: Music) -> Optional[Table]:
+ def render_header(self, music: Music) -> Table | None:
if not music:
return None
diff --git a/unshackle/core/music/tagger.py b/unshackle/core/music/tagger.py
index 7f441e39..a03c409f 100644
--- a/unshackle/core/music/tagger.py
+++ b/unshackle/core/music/tagger.py
@@ -8,7 +8,7 @@ from base64 import b64encode
from dataclasses import dataclass
from io import BytesIO
from pathlib import Path
-from typing import Any, Optional, Union
+from typing import Any
from unshackle.core import binaries
from unshackle.core.config import config
@@ -56,7 +56,7 @@ except ImportError: # pragma: no cover - optional tagging dependency
log = logging.getLogger("MUSIC_TAGGER")
-TagValues = dict[str, Union[str, list[str]]]
+TagValues = dict[str, str | list[str]]
MAX_COVER_BYTES = 2**24 - 1 # a FLAC metadata block length is 24 bits
@@ -185,7 +185,7 @@ def build_tag_values(song: Any, *, source_md5: str = "") -> TagValues:
return {key: value for key, value in tags.items() if value}
-def write_flac_tags(path: Path, tags: TagValues, cover_data: Optional[bytes], mime_type: str) -> None:
+def write_flac_tags(path: Path, tags: TagValues, cover_data: bytes | None, mime_type: str) -> None:
audio = FLAC(path)
for key, value in tags.items():
audio[key] = as_list(value)
@@ -196,7 +196,7 @@ def write_flac_tags(path: Path, tags: TagValues, cover_data: Optional[bytes], mi
audio.save()
-def build_picture(cover_data: Optional[bytes], mime_type: str) -> Optional[Any]:
+def build_picture(cover_data: bytes | None, mime_type: str) -> Any | None:
"""Build a FLAC Picture block, which Ogg reuses base64-encoded."""
if not cover_data or Picture is None:
return None
@@ -215,9 +215,7 @@ def build_picture(cover_data: Optional[bytes], mime_type: str) -> Optional[Any]:
return picture
-def write_ogg_tags(
- path: Path, tags: TagValues, cover_data: Optional[bytes], mime_type: str, reader: Any = None
-) -> None:
+def write_ogg_tags(path: Path, tags: TagValues, cover_data: bytes | None, mime_type: str, reader: Any = None) -> None:
audio = (reader or OggVorbis)(path)
for key, value in tags.items():
audio[key] = as_list(value)
@@ -228,7 +226,7 @@ def write_ogg_tags(
audio.save()
-def write_mp3_tags(path: Path, tags: TagValues, cover_data: Optional[bytes], mime_type: str, reader: Any) -> None:
+def write_mp3_tags(path: Path, tags: TagValues, cover_data: bytes | None, mime_type: str, reader: Any) -> None:
"""Write ID3 frames; ``reader`` is mutagen's MP3 or WAVE, both of which carry ID3."""
try:
audio = reader(path)
@@ -272,7 +270,7 @@ def write_mp3_tags(path: Path, tags: TagValues, cover_data: Optional[bytes], mim
audio.save()
-def write_mp4_tags(path: Path, tags: TagValues, cover_data: Optional[bytes], mime_type: str) -> None:
+def write_mp4_tags(path: Path, tags: TagValues, cover_data: bytes | None, mime_type: str) -> None:
audio = MP4(path)
if tags.get("TITLE"):
audio["\xa9nam"] = [tags["TITLE"]]
@@ -326,7 +324,7 @@ def write_mp4_tags(path: Path, tags: TagValues, cover_data: Optional[bytes], mim
audio.save()
-def download_cover(session: Any, artwork_url: str) -> tuple[Optional[bytes], str]:
+def download_cover(session: Any, artwork_url: str) -> tuple[bytes | None, str]:
if not session or not artwork_url:
return None, ""
try:
@@ -342,7 +340,7 @@ def download_cover(session: Any, artwork_url: str) -> tuple[Optional[bytes], str
return None, ""
-def attachment_cover(song: Any) -> tuple[Optional[bytes], str]:
+def attachment_cover(song: Any) -> tuple[bytes | None, str]:
"""Return the first downloaded image attachment of the Song, for a service that gives no artwork_url."""
tracks = getattr(song, "tracks", None)
for attachment in getattr(tracks, "attachments", None) or []:
@@ -353,7 +351,7 @@ def attachment_cover(song: Any) -> tuple[Optional[bytes], str]:
return None, ""
-def usable_cover(cover_data: Optional[bytes], mime_type: str, name: str) -> tuple[Optional[bytes], str]:
+def usable_cover(cover_data: bytes | None, mime_type: str, name: str) -> tuple[bytes | None, str]:
"""Convert a WebP cover to JPEG, which every container takes, and drop one too large to embed."""
if cover_data and mime_type == "image/webp":
try:
diff --git a/unshackle/core/mux_step.py b/unshackle/core/mux_step.py
index f1009733..7cd09b2e 100644
--- a/unshackle/core/mux_step.py
+++ b/unshackle/core/mux_step.py
@@ -5,12 +5,13 @@ from __future__ import annotations
import logging
import shutil
import sys
+from collections.abc import Callable, Sequence
from concurrent import futures
from concurrent.futures import ThreadPoolExecutor
from copy import deepcopy
from functools import partial
from pathlib import Path
-from typing import Any, Callable, Optional, Sequence, Union
+from typing import Any
import click
from pymediainfo import MediaInfo
@@ -28,7 +29,7 @@ from unshackle.core.tracks.hybrid import Hybrid
from unshackle.core.tracks.selection import select_hybrid_bases
from unshackle.core.utilities import standard_resolution
-MuxOutput = tuple[Path, Optional[Audio.Codec]]
+MuxOutput = tuple[Path, Audio.Codec | None]
def group_videos_by_variant(videos: list[Video], *, merge: bool) -> list[list[Video]]:
@@ -47,7 +48,7 @@ def group_videos_by_variant(videos: list[Video], *, merge: bool) -> list[list[Vi
return list(groups.values())
-def hybrid_plan(videos: Sequence[Video], generate_dv: bool) -> tuple[list[Video], Optional[Video]]:
+def hybrid_plan(videos: Sequence[Video], generate_dv: bool) -> tuple[list[Video], Video | None]:
"""The hybrid bases and the 2D DV track to pair with them.
With no DV track, a base qualifies only with ``--generate-dv``. A resolution with a
@@ -60,7 +61,7 @@ def hybrid_plan(videos: Sequence[Video], generate_dv: bool) -> tuple[list[Video]
return select_hybrid_bases(base_pool), matching_dv
-def hybrid_source_tracks(base: Video, dv: Optional[Video], base_container: Optional[Path] = None) -> list[Video]:
+def hybrid_source_tracks(base: Video, dv: Video | None, base_container: Path | None = None) -> list[Video]:
"""Copies of the base and DV tracks for the hybrid step, with the base on its container file.
The hybrid step reads the duration and seeks, and the raw stream from the DV fixup
@@ -71,7 +72,7 @@ def hybrid_source_tracks(base: Video, dv: Optional[Video], base_container: Optio
return tracks
-def hybrid_step_error(tracks: list[Video], source: str, output_name: str) -> Optional[str]:
+def hybrid_step_error(tracks: list[Video], source: str, output_name: str) -> str | None:
"""Run the hybrid step for one resolution; the error that failed it, or None.
A failure here is this resolution's alone: the title goes on with its other resolutions.
@@ -83,7 +84,7 @@ def hybrid_step_error(tracks: list[Video], source: str, output_name: str) -> Opt
return None
-def missing_hybrid_error(bases: Sequence[Video], made: int) -> Optional[str]:
+def missing_hybrid_error(bases: Sequence[Video], made: int) -> str | None:
"""Why the title has no hybrid file, or None when at least one was made."""
if made:
return None
@@ -93,29 +94,29 @@ def missing_hybrid_error(bases: Sequence[Video], made: int) -> Optional[str]:
def mux_title(
- title: Union[Movie, Episode],
+ title: Movie | Episode,
placement: Placement,
*,
log: logging.Logger,
service_tag: str,
- split_audio: Optional[bool],
- merge_video: Optional[bool],
+ split_audio: bool | None,
+ merge_video: bool | None,
audio_expected: bool,
skip_subtitles: bool,
quality: Sequence[Any],
range_: Sequence[Video.Range],
vcodec: Sequence[Any],
generate_dv: bool,
- progress_sink: Optional[Callable[[dict[str, Any]], None]],
- write_sidecars: Optional[Callable[[str, Path], list[Path]]],
-) -> tuple[list[MuxOutput], dict[Optional[Path], list[Path]]]:
+ progress_sink: Callable[[dict[str, Any]], None] | None,
+ write_sidecars: Callable[[str, Path], list[Path]] | None,
+) -> tuple[list[MuxOutput], dict[Path | None, list[Path]]]:
"""Mux the tracks of a title, then delete them; the muxed files and the sidecar files of each.
Each output is a muxed file with the audio codec it holds when the audio is split by codec.
A failed mux exits the run.
"""
outputs: list[MuxOutput] = []
- sidecars: dict[Optional[Path], list[Path]] = {}
+ sidecars: dict[Path | None, list[Path]] = {}
progress = Progress(
TextColumn("[progress.description]{task.description}"),
SpinnerColumn(finished_text=""),
@@ -131,7 +132,7 @@ def mux_title(
merge_video = merge_video if merge_video is not None else config.muxing.get("merge_video", False)
- multiplex_tasks: list[tuple[TaskID, Tracks, Optional[Audio.Codec]]] = []
+ multiplex_tasks: list[tuple[TaskID, Tracks, Audio.Codec | None]] = []
mux_futures: list[futures.Future[tuple[Path, int, list[str]]]] = []
# Track hybrid-processing outputs explicitly so we can always clean them up,
# even if muxing fails early (e.g. SystemExit) before the normal delete loop.
@@ -148,8 +149,8 @@ def mux_title(
task_tracks.attachments = list(base_tracks.attachments)
return task_tracks
- def unique_mux_output(task_tracks: Tracks, index: int) -> Optional[Path]:
- src: Optional[Path] = None
+ def unique_mux_output(task_tracks: Tracks, index: int) -> Path | None:
+ src: Path | None = None
ext = ".muxed.mkv"
if task_tracks.videos:
src = task_tracks.videos[0].path
@@ -183,7 +184,7 @@ def mux_title(
mux_futures.append(pool.submit(mux_one, len(multiplex_tasks), task_id, base_tracks))
return
- audio_by_codec: dict[Optional[Audio.Codec], list[Audio]] = {}
+ audio_by_codec: dict[Audio.Codec | None, list[Audio]] = {}
for audio_track in base_tracks.audio:
audio_by_codec.setdefault(audio_track.codec, []).append(audio_track)
@@ -197,7 +198,7 @@ def mux_title(
multiplex_tasks.append((task_id, task_tracks, audio_codec))
mux_futures.append(pool.submit(mux_one, len(multiplex_tasks), task_id, task_tracks))
- def mux_video_group(video_tracks: list[Optional[Video]]) -> None:
+ def mux_video_group(video_tracks: list[Video | None]) -> None:
for video_track in video_tracks:
if video_track and video_track.dv_compatible_bitstream:
container = apply_dv_fixup(video_track, keep_source=video_track.id in hybrid_base_ids)
@@ -223,7 +224,7 @@ def mux_title(
enqueue_mux_tasks(task_description, task_tracks)
- def group_file_size(video_tracks: Sequence[Optional[Video]]) -> int:
+ def group_file_size(video_tracks: Sequence[Video | None]) -> int:
return sum(v.path.stat().st_size for v in video_tracks if v and v.path and v.path.exists())
if progress_sink:
@@ -246,7 +247,7 @@ def mux_title(
original_videos = list(title.tracks.videos)
standalone_videos = [v for v in original_videos if not v.hybrid_base_only]
- standalone_groups: list[list[Optional[Video]]] = [
+ standalone_groups: list[list[Video | None]] = [
list(g) for g in group_videos_by_variant(standalone_videos, merge=merge_video)
]
hybrid_bases, matching_dv = hybrid_plan(
@@ -302,15 +303,15 @@ def mux_title(
console.print()
else:
- groups: list[list[Optional[Video]]] = [
+ groups: list[list[Video | None]] = [
list(g) for g in group_videos_by_variant(title.tracks.videos, merge=merge_video)
] or [[None]]
for group in sorted(groups, key=group_file_size, reverse=True):
mux_video_group(group)
mux_results = [f.result() for f in mux_futures]
- for (task_id, task_tracks, audio_codec), (muxed_path, return_code, errors) in zip(
- multiplex_tasks, mux_results
+ for (_, _, audio_codec), (muxed_path, return_code, errors) in zip(
+ multiplex_tasks, mux_results, strict=True
):
outputs.append((muxed_path, audio_codec))
if return_code >= 2:
@@ -328,7 +329,7 @@ def mux_title(
sys.exit(1)
if write_sidecars:
- sidecar_targets: list[tuple[Optional[Path], str, Path]] = []
+ sidecar_targets: list[tuple[Path | None, str, Path]] = []
for path, _ in outputs:
media_info = MediaInfo.parse(path)
sidecar_targets.append((path, placement.name(media_info), placement.folder(media_info)))
diff --git a/unshackle/core/placement.py b/unshackle/core/placement.py
index 84d003d1..0ba83155 100644
--- a/unshackle/core/placement.py
+++ b/unshackle/core/placement.py
@@ -3,7 +3,7 @@
from __future__ import annotations
from pathlib import Path
-from typing import Any, Optional
+from typing import Any
from pymediainfo import MediaInfo
@@ -68,7 +68,7 @@ class Placement:
or bool(isinstance(self.title, Movie) and config.get_folder_template("movies"))
)
- def folder(self, media_info: Optional[MediaInfo]) -> Path:
+ def folder(self, media_info: MediaInfo | None) -> Path:
"""The folder of the title: the title folder when the title has one, then the Sample folder."""
folder = self.root
if media_info and self.has_title_folder:
@@ -80,7 +80,7 @@ class Placement:
name = self.title.get_filename(media_info, show_service=not self.no_source)
return sample_name(name, self.title) if self.sample else name
- def claim(self, folder: Path, stem: str, suffix: str, audio_codec: Optional[Audio.Codec] = None) -> Path:
+ def claim(self, folder: Path, stem: str, suffix: str, audio_codec: Audio.Codec | None = None) -> Path:
"""The final path for ``stem`` and ``suffix`` in ``folder``, which this title then holds."""
folder.mkdir(parents=True, exist_ok=True)
sep = config.get_template_separator(template_type(self.title))
@@ -95,7 +95,7 @@ class Placement:
self.used.add(path)
return path
- def track_file(self, folder: Path, track: Any, media_info: MediaInfo, stem: Optional[str] = None) -> Path:
+ def track_file(self, folder: Path, track: Any, media_info: MediaInfo, stem: str | None = None) -> Path:
"""The final path of a track file saved on its own, named after ``stem`` or else the title."""
stem = f"{stem or self.name(media_info)}{track_file_suffix(track)}"
return self.claim(folder, stem, no_mux_extension(track, track.path, media_info))
diff --git a/unshackle/core/providers/__init__.py b/unshackle/core/providers/__init__.py
index 7a98c64d..464e6337 100644
--- a/unshackle/core/providers/__init__.py
+++ b/unshackle/core/providers/__init__.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Optional, Union
+from typing import TYPE_CHECKING
import requests
@@ -27,7 +27,7 @@ ALIASES: dict[str, str] = {"imdbapi": "imdb"}
DEFAULT_ORDER: tuple[str, ...] = ("imdb", "omdb", "simkl", "tmdb", "tvdb", "anilist")
-def provider_order(kind: Optional[str] = None, anime: bool = False) -> list[type[MetadataProvider]]:
+def provider_order(kind: str | None = None, anime: bool = False) -> list[type[MetadataProvider]]:
"""Metadata provider classes in the order configured by `metadata_providers`.
`metadata_providers` is either a flat list applying to both kinds, or a mapping of
@@ -54,7 +54,7 @@ def get_available_providers() -> list[MetadataProvider]:
return [cls() for cls in provider_order() if cls().is_available()]
-def get_provider(name: str) -> Optional[MetadataProvider]:
+def get_provider(name: str) -> MetadataProvider | None:
"""Get one specific metadata provider by name."""
cls = REGISTRY.get(name)
if not cls:
@@ -65,14 +65,14 @@ def get_provider(name: str) -> Optional[MetadataProvider]:
def search_metadata(
title: str,
- year: Optional[int],
+ year: int | None,
kind: str,
- title_cacher: Optional[TitleCacher] = None,
- cache_title_id: Optional[str] = None,
- cache_region: Optional[str] = None,
- cache_account_hash: Optional[str] = None,
+ title_cacher: TitleCacher | None = None,
+ cache_title_id: str | None = None,
+ cache_region: str | None = None,
+ cache_account_hash: str | None = None,
anime: bool = False,
-) -> Optional[MetadataResult]:
+) -> MetadataResult | None:
"""Find metadata in every available metadata provider. Returns the best result."""
from unshackle.core.config import config
@@ -128,11 +128,11 @@ def search_metadata(
def get_title_by_id(
tmdb_id: int,
kind: str,
- title_cacher: Optional[TitleCacher] = None,
- cache_title_id: Optional[str] = None,
- cache_region: Optional[str] = None,
- cache_account_hash: Optional[str] = None,
-) -> Optional[str]:
+ title_cacher: TitleCacher | None = None,
+ cache_title_id: str | None = None,
+ cache_region: str | None = None,
+ cache_account_hash: str | None = None,
+) -> str | None:
"""Get title name by TMDB ID."""
if title_cacher and cache_title_id:
cached = title_cacher.get_cached_provider("tmdb", cache_title_id, kind, cache_region, cache_account_hash)
@@ -170,11 +170,11 @@ def get_title_by_id(
def get_year_by_id(
tmdb_id: int,
kind: str,
- title_cacher: Optional[TitleCacher] = None,
- cache_title_id: Optional[str] = None,
- cache_region: Optional[str] = None,
- cache_account_hash: Optional[str] = None,
-) -> Optional[int]:
+ title_cacher: TitleCacher | None = None,
+ cache_title_id: str | None = None,
+ cache_region: str | None = None,
+ cache_account_hash: str | None = None,
+) -> int | None:
"""Get release year by TMDB ID."""
if title_cacher and cache_title_id:
cached = title_cacher.get_cached_provider("tmdb", cache_title_id, kind, cache_region, cache_account_hash)
@@ -213,11 +213,11 @@ def get_year_by_id(
def get_language_by_id(
tmdb_id: int,
kind: str,
- title_cacher: Optional[TitleCacher] = None,
- cache_title_id: Optional[str] = None,
- cache_region: Optional[str] = None,
- cache_account_hash: Optional[str] = None,
-) -> Optional[str]:
+ title_cacher: TitleCacher | None = None,
+ cache_title_id: str | None = None,
+ cache_region: str | None = None,
+ cache_account_hash: str | None = None,
+) -> str | None:
"""Get original language by TMDB ID."""
if title_cacher and cache_title_id:
cached = title_cacher.get_cached_provider("tmdb", cache_title_id, kind, cache_region, cache_account_hash)
@@ -236,10 +236,10 @@ def get_language_by_id(
def fetch_external_ids(
tmdb_id: int,
kind: str,
- title_cacher: Optional[TitleCacher] = None,
- cache_title_id: Optional[str] = None,
- cache_region: Optional[str] = None,
- cache_account_hash: Optional[str] = None,
+ title_cacher: TitleCacher | None = None,
+ cache_title_id: str | None = None,
+ cache_region: str | None = None,
+ cache_account_hash: str | None = None,
) -> ExternalIds:
"""Get external IDs by TMDB ID."""
if title_cacher and cache_title_id:
@@ -281,20 +281,20 @@ def fetch_external_ids(
def resolve_by_ids(
- tmdb_id: Optional[int] = None,
- imdb_id: Optional[str] = None,
- tvdb_id: Optional[int] = None,
- anilist_id: Optional[Union[int, str]] = None,
+ tmdb_id: int | None = None,
+ imdb_id: str | None = None,
+ tvdb_id: int | None = None,
+ anilist_id: int | str | None = None,
*,
- title: Optional[str] = None,
- year: Optional[int] = None,
+ title: str | None = None,
+ year: int | None = None,
kind: str = "movie",
- title_cacher: Optional[TitleCacher] = None,
- cache_title_id: Optional[str] = None,
- cache_region: Optional[str] = None,
- cache_account_hash: Optional[str] = None,
+ title_cacher: TitleCacher | None = None,
+ cache_title_id: str | None = None,
+ cache_region: str | None = None,
+ cache_account_hash: str | None = None,
anime: bool = False,
-) -> Optional[MetadataResult]:
+) -> MetadataResult | None:
"""Get metadata from user-supplied external IDs, and find the title by name only without them.
A supplied ID is authoritative. unshackle looks it up directly through the metadata
@@ -302,7 +302,7 @@ def resolve_by_ids(
always survives into `external_ids` whatever a metadata provider answers. Without any
supplied ID, unshackle finds the title by a fuzzy name comparison.
"""
- supplied: dict[str, Union[int, str]] = {}
+ supplied: dict[str, int | str] = {}
if tmdb_id is not None:
supplied["tmdb"] = tmdb_id
if imdb_id:
@@ -317,7 +317,7 @@ def resolve_by_ids(
return None
return search_metadata(title, year, kind, title_cacher, cache_title_id, cache_region, cache_account_hash, anime)
- result: Optional[MetadataResult] = None
+ result: MetadataResult | None = None
for cls in provider_order(kind, anime):
provider_id = supplied.get(cls.ID_KIND or "")
if provider_id is None:
@@ -365,7 +365,7 @@ def resolve_by_ids(
ENRICHMENT_AUTHORITY: tuple[str, ...] = ("tmdb", "simkl", "tvdb")
-def enrichment_providers(kind: Optional[str] = None) -> list[str]:
+def enrichment_providers(kind: str | None = None) -> list[str]:
"""Names of the configured metadata providers that can find a title by IMDB ID, most trusted first."""
configured = {cls.NAME for cls in provider_order(kind) if hasattr(cls, "find_by_imdb_id")}
return [name for name in ENRICHMENT_AUTHORITY if name in configured]
@@ -478,7 +478,7 @@ def external_ids_to_dict(ext: ExternalIds) -> dict:
return result
-def cached_to_result(cached: dict, provider_name: str, kind: str) -> Optional[MetadataResult]:
+def cached_to_result(cached: dict, provider_name: str, kind: str) -> MetadataResult | None:
"""Convert a cached metadata provider dict back to a MetadataResult."""
if provider_name == "tmdb":
detail = cached.get("detail", {})
diff --git a/unshackle/core/providers/_base.py b/unshackle/core/providers/_base.py
index f42b4353..f8c6dc8e 100644
--- a/unshackle/core/providers/_base.py
+++ b/unshackle/core/providers/_base.py
@@ -5,7 +5,6 @@ import re
from abc import ABCMeta, abstractmethod
from dataclasses import dataclass, field
from difflib import SequenceMatcher
-from typing import Optional, Union
import requests
from requests.adapters import HTTPAdapter, Retry
@@ -22,24 +21,24 @@ YEAR_RE = re.compile(r"\s*\(?[12][0-9]{3}\)?$")
class ExternalIds:
"""Normalized external IDs across providers."""
- imdb_id: Optional[str] = None
- tmdb_id: Optional[int] = None
- tmdb_kind: Optional[str] = None # "movie" or "tv"
- tvdb_id: Optional[int] = None
- anilist_id: Optional[int] = None
+ imdb_id: str | None = None
+ tmdb_id: int | None = None
+ tmdb_kind: str | None = None # "movie" or "tv"
+ tvdb_id: int | None = None
+ anilist_id: int | None = None
@dataclass
class MetadataResult:
"""Unified metadata result from any metadata provider."""
- title: Optional[str] = None
- year: Optional[int] = None
- kind: Optional[str] = None # "movie" or "tv"
+ title: str | None = None
+ year: int | None = None
+ kind: str | None = None # "movie" or "tv"
external_ids: ExternalIds = field(default_factory=ExternalIds)
- original_language: Optional[str] = None # alpha-2 or alpha-3, whichever the provider speaks
+ original_language: str | None = None # alpha-2 or alpha-3, whichever the provider speaks
source: str = ""
- raw: Optional[dict] = None
+ raw: dict | None = None
class MetadataProvider(metaclass=ABCMeta):
@@ -47,11 +46,11 @@ class MetadataProvider(metaclass=ABCMeta):
NAME: str = ""
REQUIRES_KEY: bool = True
- ID_KIND: Optional[str] = None
+ ID_KIND: str | None = None
def __init__(self) -> None:
self.log = logging.getLogger(f"METADATA.{self.NAME.upper()}")
- self._session: Optional[requests.Session] = None
+ self._session: requests.Session | None = None
@property
def session(self) -> requests.Session:
@@ -75,15 +74,15 @@ class MetadataProvider(metaclass=ABCMeta):
"""Return True if this metadata provider has the credentials/keys it needs."""
@abstractmethod
- def search(self, title: str, year: Optional[int], kind: str) -> Optional[MetadataResult]:
+ def search(self, title: str, year: int | None, kind: str) -> MetadataResult | None:
"""Find a title and return its metadata, or None on failure or when nothing matches."""
@abstractmethod
- def get_by_id(self, provider_id: Union[int, str], kind: str) -> Optional[MetadataResult]:
+ def get_by_id(self, provider_id: int | str, kind: str) -> MetadataResult | None:
"""Fetch metadata by this provider's native ID."""
@abstractmethod
- def get_external_ids(self, provider_id: Union[int, str], kind: str) -> ExternalIds:
+ def get_external_ids(self, provider_id: int | str, kind: str) -> ExternalIds:
"""Fetch external IDs for a title by this provider's native ID."""
diff --git a/unshackle/core/providers/anilist.py b/unshackle/core/providers/anilist.py
index e5f2d9dc..a7ae918f 100644
--- a/unshackle/core/providers/anilist.py
+++ b/unshackle/core/providers/anilist.py
@@ -1,7 +1,6 @@
from __future__ import annotations
from difflib import SequenceMatcher
-from typing import Optional, Union
import requests
@@ -13,10 +12,10 @@ MEDIA_FIELDS = "id idMal title { romaji english native } format startDate { year
SEARCH_QUERY = (
"query UnshackleAniListSearch($search: String) { Page(perPage: 10) "
- "{ media(search: $search, type: ANIME, sort: SEARCH_MATCH) { %s } } }" % MEDIA_FIELDS
+ f"{{ media(search: $search, type: ANIME, sort: SEARCH_MATCH) {{ {MEDIA_FIELDS} }} }} }}"
)
-MEDIA_QUERY = "query UnshackleAniListMedia($id: Int) { Media(id: $id, type: ANIME) { %s } }" % MEDIA_FIELDS
-MAL_QUERY = "query UnshackleAniListMal($idMal: Int) { Media(idMal: $idMal, type: ANIME) { %s } }" % MEDIA_FIELDS
+MEDIA_QUERY = f"query UnshackleAniListMedia($id: Int) {{ Media(id: $id, type: ANIME) {{ {MEDIA_FIELDS} }} }}"
+MAL_QUERY = f"query UnshackleAniListMal($idMal: Int) {{ Media(idMal: $idMal, type: ANIME) {{ {MEDIA_FIELDS} }} }}"
TITLE_LANGUAGES: tuple[str, ...] = ("english", "romaji", "native")
@@ -25,7 +24,7 @@ TITLE_LANGUAGES: tuple[str, ...] = ("english", "romaji", "native")
COUNTRY_TO_LANGUAGE: dict[str, str] = {"JP": "ja", "KR": "ko", "CN": "zh", "TW": "zh", "HK": "zh"}
-def parse_anilist_ref(value: Union[int, str]) -> Optional[tuple[str, int]]:
+def parse_anilist_ref(value: int | str) -> tuple[str, int] | None:
"""Split an AniList reference into its namespace and number.
A bare number is an AniList ID. ``mal:12345`` is a MyAnimeList ID, which AniList
@@ -55,7 +54,7 @@ class AniListProvider(MetadataProvider):
def is_available(self) -> bool:
return True
- def graphql(self, query: str, variables: dict) -> Optional[dict]:
+ def graphql(self, query: str, variables: dict) -> dict | None:
try:
r = self.session.post(GRAPHQL_URL, json={"query": query, "variables": variables}, timeout=30)
body = r.json()
@@ -69,7 +68,7 @@ class AniListProvider(MetadataProvider):
return None
return body.get("data")
- def title_variant(self, titles: dict) -> Optional[str]:
+ def title_variant(self, titles: dict) -> str | None:
from unshackle.core.config import config
configured = (config.anilist_title_language or "english").lower()
@@ -79,7 +78,7 @@ class AniListProvider(MetadataProvider):
return str(value)
return None
- def to_result(self, node: dict) -> Optional[MetadataResult]:
+ def to_result(self, node: dict) -> MetadataResult | None:
title = self.title_variant(node.get("title") or {})
if not title:
return None
@@ -93,7 +92,7 @@ class AniListProvider(MetadataProvider):
raw=node,
)
- def search(self, title: str, year: Optional[int], kind: str) -> Optional[MetadataResult]:
+ def search(self, title: str, year: int | None, kind: str) -> MetadataResult | None:
self.log.debug("Searching AniList for %r (%s, %s)", title, kind, year)
data = self.graphql(SEARCH_QUERY, {"search": title})
@@ -116,7 +115,7 @@ class AniListProvider(MetadataProvider):
self.log.debug("AniList -> %s (ID %s)", result.title, result.external_ids.anilist_id)
return result
- def get_by_id(self, provider_id: Union[int, str], kind: str) -> Optional[MetadataResult]:
+ def get_by_id(self, provider_id: int | str, kind: str) -> MetadataResult | None:
"""Fetch metadata by AniList ID, or by MyAnimeList ID when given as 'mal:12345'."""
ref = parse_anilist_ref(provider_id)
if not ref:
@@ -135,7 +134,7 @@ class AniListProvider(MetadataProvider):
return None
return self.to_result(node)
- def get_external_ids(self, provider_id: Union[int, str], kind: str) -> ExternalIds:
+ def get_external_ids(self, provider_id: int | str, kind: str) -> ExternalIds:
"""Return external IDs. AniList knows no western IDs, so only its own."""
ref = parse_anilist_ref(provider_id)
if not ref:
diff --git a/unshackle/core/providers/imdb.py b/unshackle/core/providers/imdb.py
index 908b7232..6fb1fbbd 100644
--- a/unshackle/core/providers/imdb.py
+++ b/unshackle/core/providers/imdb.py
@@ -3,7 +3,6 @@ from __future__ import annotations
import hashlib
import json
from difflib import SequenceMatcher
-from typing import Optional, Union
import requests
@@ -34,14 +33,14 @@ def escape_graphql(value: str) -> str:
return value.replace("\\", "\\\\").replace('"', '\\"')
-def primary_language(data: dict) -> Optional[str]:
+def primary_language(data: dict) -> str | None:
"""IMDb orders spokenLanguages most prominent first. Either level can come back null."""
spoken = data.get("spokenLanguages") or {}
langs = spoken.get("spokenLanguages") or []
return langs[0].get("id") if langs else None
-def title_to_result(node: dict, kind: str) -> Optional[MetadataResult]:
+def title_to_result(node: dict, kind: str) -> MetadataResult | None:
title = (node.get("titleText") or {}).get("text") or (node.get("originalTitleText") or {}).get("text")
if not title:
return None
@@ -66,7 +65,7 @@ class IMDBProvider(MetadataProvider):
def is_available(self) -> bool:
return True
- def graphql(self, operation: str, query: str) -> Optional[dict]:
+ def graphql(self, operation: str, query: str) -> dict | None:
"""Send a persisted query, and add it to the gateway with one POST if the gateway does not know its hash."""
extensions = {"persistedQuery": {"version": 1, "sha256Hash": hashlib.sha256(query.encode()).hexdigest()}}
# IMDb's GraphQL gateway decodes "+" literally, so these JSON params must carry no spaces
@@ -93,7 +92,7 @@ class IMDBProvider(MetadataProvider):
return None
return body.get("data")
- def search(self, title: str, year: Optional[int], kind: str) -> Optional[MetadataResult]:
+ def search(self, title: str, year: int | None, kind: str) -> MetadataResult | None:
self.log.debug("Searching IMDb for %r (%s, %s)", title, kind, year)
constraints = [f'titleTextConstraint: {{searchTerm: "{escape_graphql(title)}"}}']
@@ -106,8 +105,8 @@ class IMDBProvider(MetadataProvider):
constraints.append(f"titleTypeConstraint: {{anyTitleTypeIds: {json.dumps(types)}}}")
query = (
- "query UnshackleTitleSearch { advancedTitleSearch(first: 5, constraints: {%s}) "
- "{ edges { node { title { %s } } } } }" % (", ".join(constraints), TITLE_FIELDS)
+ f"query UnshackleTitleSearch {{ advancedTitleSearch(first: 5, constraints: {{{', '.join(constraints)}}}) "
+ f"{{ edges {{ node {{ title {{ {TITLE_FIELDS} }} }} }} }} }}"
)
data = self.graphql("UnshackleTitleSearch", query)
@@ -126,19 +125,19 @@ class IMDBProvider(MetadataProvider):
self.log.debug("IMDb -> %s (ID %s)", result.title, result.external_ids.imdb_id)
return result
- def get_by_id(self, provider_id: Union[int, str], kind: str) -> Optional[MetadataResult]:
+ def get_by_id(self, provider_id: int | str, kind: str) -> MetadataResult | None:
"""Fetch metadata by IMDB ID (e.g. 'tt1375666')."""
imdb_id = str(provider_id)
self.log.debug("Fetching IMDb title %s", imdb_id)
- query = 'query UnshackleTitle { title(id: "%s") { %s } }' % (escape_graphql(imdb_id), TITLE_FIELDS)
+ query = f'query UnshackleTitle {{ title(id: "{escape_graphql(imdb_id)}") {{ {TITLE_FIELDS} }} }}'
data = self.graphql("UnshackleTitle", query)
node = (data or {}).get("title")
if not node:
return None
return title_to_result(node, kind)
- def get_external_ids(self, provider_id: Union[int, str], kind: str) -> ExternalIds:
+ def get_external_ids(self, provider_id: int | str, kind: str) -> ExternalIds:
"""Return external IDs. For IMDB, the provider_id IS the IMDB ID."""
return ExternalIds(imdb_id=str(provider_id))
diff --git a/unshackle/core/providers/omdb.py b/unshackle/core/providers/omdb.py
index 032f7ff1..afc412e0 100644
--- a/unshackle/core/providers/omdb.py
+++ b/unshackle/core/providers/omdb.py
@@ -1,7 +1,6 @@
from __future__ import annotations
from difflib import SequenceMatcher
-from typing import Optional, Union
import requests
from langcodes import Language
@@ -15,7 +14,7 @@ KIND_TO_TYPE: dict[str, str] = {
}
-def primary_language(data: dict) -> Optional[str]:
+def primary_language(data: dict) -> str | None:
"""OMDb gives English language names, most prominent first, e.g. 'Korean, English'."""
name = (data.get("Language") or "").split(",")[0].strip()
if not name:
@@ -26,7 +25,7 @@ def primary_language(data: dict) -> Optional[str]:
return None
-def parse_year(value: Optional[str]) -> Optional[int]:
+def parse_year(value: str | None) -> int | None:
# OMDb years look like "2017", "2008–2013" or "2023–"
if value and len(value) >= 4 and value[:4].isdigit():
return int(value[:4])
@@ -48,7 +47,7 @@ class OMDBProvider(MetadataProvider):
def api_key(self) -> str:
return config.omdb_api_key
- def api_get(self, params: dict[str, str]) -> Optional[dict]:
+ def api_get(self, params: dict[str, str]) -> dict | None:
try:
r = self.session.get(self.BASE_URL, params={"apikey": self.api_key, **params}, timeout=30)
r.raise_for_status()
@@ -61,7 +60,7 @@ class OMDBProvider(MetadataProvider):
return None
return data
- def search(self, title: str, year: Optional[int], kind: str) -> Optional[MetadataResult]:
+ def search(self, title: str, year: int | None, kind: str) -> MetadataResult | None:
self.log.debug("Searching OMDb for %r (%s, %s)", title, kind, year)
params: dict[str, str] = {"s": title}
@@ -81,7 +80,7 @@ class OMDBProvider(MetadataProvider):
results = data.get("Search") or []
- best_match: Optional[dict] = None
+ best_match: dict | None = None
best_ratio = 0.0
for candidate in results:
name = candidate.get("Title") or ""
@@ -120,7 +119,7 @@ class OMDBProvider(MetadataProvider):
raw=detail or best_match,
)
- def get_by_id(self, provider_id: Union[int, str], kind: str) -> Optional[MetadataResult]:
+ def get_by_id(self, provider_id: int | str, kind: str) -> MetadataResult | None:
"""Fetch metadata by IMDb ID (e.g. 'tt1375666')."""
imdb_id = str(provider_id)
self.log.debug("Fetching OMDb title %s", imdb_id)
@@ -139,6 +138,6 @@ class OMDBProvider(MetadataProvider):
raw=data,
)
- def get_external_ids(self, provider_id: Union[int, str], kind: str) -> ExternalIds:
+ def get_external_ids(self, provider_id: int | str, kind: str) -> ExternalIds:
"""Return external IDs. For OMDb, the provider_id IS the IMDb ID."""
return ExternalIds(imdb_id=str(provider_id))
diff --git a/unshackle/core/providers/simkl.py b/unshackle/core/providers/simkl.py
index c6d9cdb7..5e771a00 100644
--- a/unshackle/core/providers/simkl.py
+++ b/unshackle/core/providers/simkl.py
@@ -1,7 +1,5 @@
from __future__ import annotations
-from typing import Optional, Union
-
import requests
from unshackle.core.config import config
@@ -18,7 +16,7 @@ class SimklProvider(MetadataProvider):
def is_available(self) -> bool:
return bool(config.simkl_client_id)
- def search(self, title: str, year: Optional[int], kind: str) -> Optional[MetadataResult]:
+ def search(self, title: str, year: int | None, kind: str) -> MetadataResult | None:
self.log.debug("Searching Simkl for %r (%s, %s)", title, kind, year)
filename = f"{title}"
@@ -47,13 +45,13 @@ class SimklProvider(MetadataProvider):
return self.parse_response(data, title, year, kind)
- def get_by_id(self, provider_id: Union[int, str], kind: str) -> Optional[MetadataResult]:
+ def get_by_id(self, provider_id: int | str, kind: str) -> MetadataResult | None:
return None # SIMKL has no direct ID lookup used here
- def get_external_ids(self, provider_id: Union[int, str], kind: str) -> ExternalIds:
+ def get_external_ids(self, provider_id: int | str, kind: str) -> ExternalIds:
return ExternalIds() # IDs come from search() response
- def find_by_imdb_id(self, imdb_id: str, kind: str) -> Optional[ExternalIds]:
+ def find_by_imdb_id(self, imdb_id: str, kind: str) -> ExternalIds | None:
"""Look up TMDB/TVDB IDs from an IMDB ID using SIMKL's /search/id and detail endpoints."""
self.log.debug("Looking up IMDB ID %s on SIMKL", imdb_id)
headers = {"simkl-api-key": config.simkl_client_id}
@@ -92,12 +90,12 @@ class SimklProvider(MetadataProvider):
return None
ids = detail.get("ids", {})
- tmdb_id: Optional[int] = None
+ tmdb_id: int | None = None
raw_tmdb = ids.get("tmdb")
if raw_tmdb:
tmdb_id = int(raw_tmdb)
- tvdb_id: Optional[int] = None
+ tvdb_id: int | None = None
raw_tvdb = ids.get("tvdb")
if raw_tvdb:
tvdb_id = int(raw_tvdb)
@@ -112,8 +110,8 @@ class SimklProvider(MetadataProvider):
)
def parse_response(
- self, data: dict, search_title: str, search_year: Optional[int], kind: str
- ) -> Optional[MetadataResult]:
+ self, data: dict, search_title: str, search_year: int | None, kind: str
+ ) -> MetadataResult | None:
"""Parse a SIMKL response into a MetadataResult."""
if data.get("type") == "episode" and "show" in data:
info = data["show"]
@@ -138,7 +136,7 @@ class SimklProvider(MetadataProvider):
return None
ids = info.get("ids", {})
- tmdb_id: Optional[int] = None
+ tmdb_id: int | None = None
if content_type == "tv":
raw_tmdb = ids.get("tmdbtv")
else:
@@ -146,7 +144,7 @@ class SimklProvider(MetadataProvider):
if raw_tmdb:
tmdb_id = int(raw_tmdb)
- tvdb_id: Optional[int] = None
+ tvdb_id: int | None = None
raw_tvdb = ids.get("tvdb")
if raw_tvdb:
tvdb_id = int(raw_tvdb)
diff --git a/unshackle/core/providers/tmdb.py b/unshackle/core/providers/tmdb.py
index 40ac6735..af5eea56 100644
--- a/unshackle/core/providers/tmdb.py
+++ b/unshackle/core/providers/tmdb.py
@@ -1,7 +1,6 @@
from __future__ import annotations
from difflib import SequenceMatcher
-from typing import Optional, Union
import requests
@@ -24,7 +23,7 @@ class TMDBProvider(MetadataProvider):
def api_key(self) -> str:
return config.tmdb_api_key
- def search(self, title: str, year: Optional[int], kind: str) -> Optional[MetadataResult]:
+ def search(self, title: str, year: int | None, kind: str) -> MetadataResult | None:
search_title = strip_year(title)
self.log.debug("Searching TMDB for %r (%s, %s)", search_title, kind, year)
@@ -44,8 +43,8 @@ class TMDBProvider(MetadataProvider):
return None
best_ratio = 0.0
- best_id: Optional[int] = None
- best_title: Optional[str] = None
+ best_id: int | None = None
+ best_title: str | None = None
for result in results:
candidates = [
result.get("title"),
@@ -95,7 +94,7 @@ class TMDBProvider(MetadataProvider):
raw={"detail": detail or {}, "external_ids": ext_raw or {}},
)
- def get_by_id(self, provider_id: Union[int, str], kind: str) -> Optional[MetadataResult]:
+ def get_by_id(self, provider_id: int | str, kind: str) -> MetadataResult | None:
detail = self.fetch_detail(int(provider_id), kind)
if not detail:
return None
@@ -114,7 +113,7 @@ class TMDBProvider(MetadataProvider):
raw=detail,
)
- def get_external_ids(self, provider_id: Union[int, str], kind: str) -> ExternalIds:
+ def get_external_ids(self, provider_id: int | str, kind: str) -> ExternalIds:
raw = self.fetch_external_ids_raw(int(provider_id), kind)
if not raw:
return ExternalIds(tmdb_id=int(provider_id), tmdb_kind=kind)
@@ -125,7 +124,7 @@ class TMDBProvider(MetadataProvider):
tvdb_id=raw.get("tvdb_id"),
)
- def find_by_imdb_id(self, imdb_id: str, kind: str) -> Optional[ExternalIds]:
+ def find_by_imdb_id(self, imdb_id: str, kind: str) -> ExternalIds | None:
"""Look up TMDB/TVDB IDs from an IMDB ID using TMDB's /find endpoint.
When the requested kind has no results, unshackle tries the other kind, so the
@@ -176,7 +175,7 @@ class TMDBProvider(MetadataProvider):
tvdb_id=ext_raw.get("tvdb_id") if ext_raw else None,
)
- def fetch_detail(self, tmdb_id: int, kind: str) -> Optional[dict]:
+ def fetch_detail(self, tmdb_id: int, kind: str) -> dict | None:
try:
r = self.session.get(
f"{self.BASE_URL}/{kind}/{tmdb_id}",
@@ -189,7 +188,7 @@ class TMDBProvider(MetadataProvider):
self.log.debug("Failed to fetch TMDB detail: %s", exc)
return None
- def fetch_external_ids_raw(self, tmdb_id: int, kind: str) -> Optional[dict]:
+ def fetch_external_ids_raw(self, tmdb_id: int, kind: str) -> dict | None:
try:
r = self.session.get(
f"{self.BASE_URL}/{kind}/{tmdb_id}/external_ids",
diff --git a/unshackle/core/providers/tvdb.py b/unshackle/core/providers/tvdb.py
index 9b775d8a..c32ada56 100644
--- a/unshackle/core/providers/tvdb.py
+++ b/unshackle/core/providers/tvdb.py
@@ -2,7 +2,7 @@ from __future__ import annotations
from collections.abc import Collection
from difflib import SequenceMatcher
-from typing import Any, Optional, Union
+from typing import Any
import requests
@@ -10,7 +10,7 @@ from unshackle.core.config import config
from unshackle.core.providers._base import ExternalIds, MetadataProvider, MetadataResult, clean, strip_year
-def primary_language(data: dict) -> Optional[str]:
+def primary_language(data: dict) -> str | None:
"""Search results spell the field primary_language, the extended record originalLanguage."""
return data.get("primary_language") or data.get("originalLanguage") or None
@@ -23,17 +23,17 @@ SEASON_TYPES: tuple[str, ...] = ("official", "dvd", "absolute", "alternate", "re
AIRED_ORDER = "official"
# cached per-process; providers are re-instantiated per lookup
-_token: Optional[str] = None
+_token: str | None = None
-def parse_int(value: Optional[str]) -> Optional[int]:
+def parse_int(value: str | None) -> int | None:
try:
return int(value) # type: ignore[arg-type]
except (TypeError, ValueError):
return None
-def ids_from_remote(remote_ids: Optional[list], tvdb_id: Optional[int]) -> ExternalIds:
+def ids_from_remote(remote_ids: list | None, tvdb_id: int | None) -> ExternalIds:
"""Assemble ExternalIds from a TVDB remote_ids/remoteIds list."""
ext = ExternalIds(tvdb_id=tvdb_id)
for entry in remote_ids or []:
@@ -46,12 +46,10 @@ def ids_from_remote(remote_ids: Optional[list], tvdb_id: Optional[int]) -> Exter
return ext
-def pick_match(
- results: list[dict], search_title: str, year: Optional[int]
-) -> tuple[Optional[dict], Optional[str], float]:
+def pick_match(results: list[dict], search_title: str, year: int | None) -> tuple[dict | None, str | None, float]:
"""The result whose title matches best, ignoring any whose year is more than a year out."""
- best: Optional[dict] = None
- best_title: Optional[str] = None
+ best: dict | None = None
+ best_title: str | None = None
best_ratio = 0.0
for result in results:
result_year = parse_int(result.get("year"))
@@ -81,7 +79,7 @@ class TVDBProvider(MetadataProvider):
def is_available(self) -> bool:
return bool(config.tvdb_api_key)
- def login(self) -> Optional[str]:
+ def login(self) -> str | None:
global _token
payload: dict[str, str] = {"apikey": config.tvdb_api_key}
if config.tvdb_pin:
@@ -95,7 +93,7 @@ class TVDBProvider(MetadataProvider):
_token = None
return _token
- def api_get(self, path: str, params: Optional[dict] = None) -> Any:
+ def api_get(self, path: str, params: dict | None = None) -> Any:
"""The `data` payload of a TVDB response: a dict for entities, a list for searches."""
global _token
token = _token or self.login()
@@ -122,7 +120,7 @@ class TVDBProvider(MetadataProvider):
return None
return None
- def search(self, title: str, year: Optional[int], kind: str) -> Optional[MetadataResult]:
+ def search(self, title: str, year: int | None, kind: str) -> MetadataResult | None:
search_title = strip_year(title)
self.log.debug("Searching TVDB for %r (%s, %s)", search_title, kind, year)
@@ -165,11 +163,11 @@ class TVDBProvider(MetadataProvider):
raw=best,
)
- def fetch_extended(self, tvdb_id: int, kind: str) -> Optional[dict]:
+ def fetch_extended(self, tvdb_id: int, kind: str) -> dict | None:
path = KIND_TO_PATH.get(kind, "series")
return self.api_get(f"/{path}/{tvdb_id}/extended", {"short": "true"})
- def get_by_id(self, provider_id: Union[int, str], kind: str) -> Optional[MetadataResult]:
+ def get_by_id(self, provider_id: int | str, kind: str) -> MetadataResult | None:
tvdb_id = int(provider_id)
detail = self.fetch_extended(tvdb_id, kind)
if not detail:
@@ -189,7 +187,7 @@ class TVDBProvider(MetadataProvider):
raw=detail,
)
- def get_external_ids(self, provider_id: Union[int, str], kind: str) -> ExternalIds:
+ def get_external_ids(self, provider_id: int | str, kind: str) -> ExternalIds:
tvdb_id = int(provider_id)
detail = self.fetch_extended(tvdb_id, kind)
if not detail:
@@ -243,7 +241,7 @@ class TVDBProvider(MetadataProvider):
def get_order_map(
self, tvdb_id: int, order: str, source_order: str = AIRED_ORDER
- ) -> dict[tuple[int, int], tuple[int, int, Optional[str]]]:
+ ) -> dict[tuple[int, int], tuple[int, int, str | None]]:
"""Map (season, episode) in `source_order` to (season, episode, name) in `order`.
Every order lists the same episodes under the same TVDB episode ID, which is what
@@ -259,7 +257,7 @@ class TVDBProvider(MetadataProvider):
return {}
by_id = {ep.get("id"): ep for ep in target}
- mapping: dict[tuple[int, int], tuple[int, int, Optional[str]]] = {}
+ mapping: dict[tuple[int, int], tuple[int, int, str | None]] = {}
for ep in source:
match = by_id.get(ep.get("id"))
if not match:
@@ -273,7 +271,7 @@ class TVDBProvider(MetadataProvider):
self.log.debug("TVDB %s -> %s order: mapped %d/%d episodes", source_order, order, len(mapping), len(source))
return mapping
- def find_by_imdb_id(self, imdb_id: str, kind: str) -> Optional[ExternalIds]:
+ def find_by_imdb_id(self, imdb_id: str, kind: str) -> ExternalIds | None:
"""Get a TVDB ID from an IMDb ID through /search/remoteid."""
results = self.api_get(f"/search/remoteid/{imdb_id}")
if not results:
diff --git a/unshackle/core/proxies/asn.py b/unshackle/core/proxies/asn.py
index b5d406a9..adbede22 100644
--- a/unshackle/core/proxies/asn.py
+++ b/unshackle/core/proxies/asn.py
@@ -5,24 +5,24 @@ from __future__ import annotations
import ipaddress
import re
import socket
+from collections.abc import Iterable
from concurrent.futures import ThreadPoolExecutor
-from typing import Iterable, Optional
from unidecode import unidecode
WHOIS = ("whois.cymru.com", 43)
TIMEOUT = 3
NETWORKS: dict[str, str] = {}
-FAILED: Optional[str] = None
+FAILED: str | None = None
-def split_selector(query: str) -> tuple[str, Optional[str]]:
+def split_selector(query: str) -> tuple[str, str | None]:
"""Split "fr:paris@-datacamp" into the region query and the network selector after "@"."""
query, _, selector = query.partition("@")
return query, selector or None
-def mapped_query(region: str, value: object) -> Optional[str]:
+def mapped_query(region: str, value: object) -> str | None:
"""
Get the query that a server_map value stands for, or None for a plain server value.
@@ -102,7 +102,7 @@ def select(servers: dict[str, str], selector: str) -> list[str]:
def resolve_all(hostnames: Iterable[str]) -> dict[str, str]:
"""Resolve hostnames to an IPv4 address each, in parallel. A hostname that does not resolve is left out."""
- def resolve(hostname: str) -> Optional[str]:
+ def resolve(hostname: str) -> str | None:
try:
return socket.gethostbyname(hostname)
except OSError:
@@ -110,10 +110,10 @@ def resolve_all(hostnames: Iterable[str]) -> dict[str, str]:
hostnames = list(dict.fromkeys(hostnames))
with ThreadPoolExecutor(16) as pool:
- return {x: ip for x, ip in zip(hostnames, pool.map(resolve, hostnames)) if ip}
+ return {x: ip for x, ip in zip(hostnames, pool.map(resolve, hostnames), strict=True) if ip}
-def describe(hostname: str, ip: Optional[str] = None) -> str:
+def describe(hostname: str, ip: str | None = None) -> str:
"""Name a server with its IP and network, for the line that says which proxy is in use. This never raises."""
try:
ip = ip or socket.gethostbyname(hostname)
diff --git a/unshackle/core/proxies/basic.py b/unshackle/core/proxies/basic.py
index 7a39e300..0d78192f 100644
--- a/unshackle/core/proxies/basic.py
+++ b/unshackle/core/proxies/basic.py
@@ -1,6 +1,5 @@
import random
import re
-from typing import Optional, Union
from requests.utils import prepend_scheme_if_needed
from urllib3.util import parse_url
@@ -10,7 +9,7 @@ from unshackle.core.utils.redact import mask_proxy
class Basic(Proxy):
- def __init__(self, **countries: Union[str, list[str]]) -> None:
+ def __init__(self, **countries: str | list[str]) -> None:
"""Basic proxy provider that uses the proxies given in the configuration file."""
self.countries = {k.lower(): v for k, v in countries.items()}
@@ -20,7 +19,7 @@ class Basic(Proxy):
return f"{countries} Countr{['ies', 'y'][countries == 1]} ({servers} Server{['s', ''][servers == 1]})"
- def get_proxy(self, query: str) -> Optional[str]:
+ def get_proxy(self, query: str) -> str | None:
"""Get a proxy URI from the config. A query for a region or an entry number not in the config returns None."""
query = query.lower()
@@ -31,7 +30,7 @@ class Basic(Proxy):
country_code = match.group(1)
entry = match.group(2)
- servers: Optional[Union[str, list[str]]] = self.countries.get(country_code)
+ servers: str | list[str] | None = self.countries.get(country_code)
if not servers:
return None
diff --git a/unshackle/core/proxies/controld.py b/unshackle/core/proxies/controld.py
index e7275860..e0111234 100644
--- a/unshackle/core/proxies/controld.py
+++ b/unshackle/core/proxies/controld.py
@@ -10,7 +10,6 @@ import socketserver
import threading
import time
from functools import cached_property
-from typing import Optional
from urllib.parse import urlsplit
import requests
@@ -328,9 +327,9 @@ class ControlD(Proxy):
self,
*,
token: str,
- profile: Optional[str] = None,
- resolver: Optional[str] = None,
- profiles: Optional[list[dict]] = None,
+ profile: str | None = None,
+ resolver: str | None = None,
+ profiles: list[dict] | None = None,
max_profiles: int = 4,
) -> None:
"""
@@ -360,7 +359,7 @@ class ControlD(Proxy):
self.configured = {x["profile"]: resolver_id(x["resolver"]) for x in pairs}
self.max_profiles = max_profiles
self.resolvers = dict(self.configured)
- self.last_profile: Optional[str] = None
+ self.last_profile: str | None = None
@cached_property
def catalogue(self) -> list[dict]:
@@ -385,7 +384,7 @@ class ControlD(Proxy):
log.warning(f"Could not read Control D's locations: {e}")
return []
- def location(self, query: str) -> Optional[str]:
+ def location(self, query: str) -> str | None:
"""Get the identifier of a Control D proxy location for a country or location code."""
if not self.catalogue:
self.catalogue = self.get_locations()
@@ -470,7 +469,7 @@ class ControlD(Proxy):
log.info(f"Created profile {name} ({profile}) on the Control D account")
return profile
- def claim(self, query: str) -> Optional[str]:
+ def claim(self, query: str) -> str | None:
"""Point a profile at this region, unless one already is, and get its resolver ID. Hold STATE."""
location = self.location(query)
if not location:
@@ -492,13 +491,13 @@ class ControlD(Proxy):
self.last_profile = profile
return resolver
- def get_proxy(self, query: str) -> Optional[str]:
+ def get_proxy(self, query: str) -> str | None:
"""Get the local HTTP proxy URI that resolves through Control D for this region."""
with STATE:
resolver = self.claim(query.lower())
return forwarder(resolver).uri if resolver else None
- def last_connection_display(self) -> Optional[str]:
+ def last_connection_display(self) -> str | None:
"""Name the location of the last claim, with the resolver ID masked, in place of the loopback URI."""
location = LOCATIONS.get(self.last_profile or "")
if not location:
@@ -507,7 +506,7 @@ class ControlD(Proxy):
label = f"{location} - {city}" if city else location
return f"({label}): {self.resolvers[self.last_profile][:4]}{REDACTED}@dns.controld.com"
- def get_remote_proxy(self, query: str) -> Optional[str]:
+ def get_remote_proxy(self, query: str) -> str | None:
"""Get the `controld://` proxy URI for this region, for a server on another machine."""
with STATE:
resolver = self.claim(query.lower())
diff --git a/unshackle/core/proxies/expressvpn.py b/unshackle/core/proxies/expressvpn.py
index 592293bb..c61e8a44 100644
--- a/unshackle/core/proxies/expressvpn.py
+++ b/unshackle/core/proxies/expressvpn.py
@@ -9,7 +9,7 @@ import re
import sys
import time
from pathlib import Path
-from typing import Any, Optional
+from typing import Any
import requests
@@ -45,13 +45,13 @@ class ExpressVPN(Proxy):
def __init__(
self,
- region_map: Optional[dict[str, str]] = None,
- server_map: Optional[dict[str, str]] = None,
- refresh_token: Optional[str] = None,
- access_token: Optional[str] = None,
- connection_token: Optional[str] = None,
- account_json: Optional[str] = None,
- cache_path: Optional[str] = None,
+ region_map: dict[str, str] | None = None,
+ server_map: dict[str, str] | None = None,
+ refresh_token: str | None = None,
+ access_token: str | None = None,
+ connection_token: str | None = None,
+ account_json: str | None = None,
+ cache_path: str | None = None,
timeout: float = 10.0,
enable: bool = False,
) -> None:
@@ -81,13 +81,13 @@ class ExpressVPN(Proxy):
self.timeout = timeout
self.enable = enable
- self.tokens: Optional[dict] = None
- self.srt: Optional[str] = None
- self.locations: Optional[list[dict]] = None
- self.last_name: Optional[str] = None
- self.last_index: Optional[int] = None
- self.last_total: Optional[int] = None
- self.last_host: Optional[str] = None
+ self.tokens: dict | None = None
+ self.srt: str | None = None
+ self.locations: list[dict] | None = None
+ self.last_name: str | None = None
+ self.last_index: int | None = None
+ self.last_total: int | None = None
+ self.last_host: str | None = None
self.cache_path = Path(cache_path).expanduser() if cache_path else self.default_cache_path()
@@ -120,7 +120,7 @@ class ExpressVPN(Proxy):
or self.load_cache()
)
- def get_proxy(self, query: str) -> Optional[str]:
+ def get_proxy(self, query: str) -> str | None:
endpoint = self.resolve_endpoint(query.strip().lower())
if not endpoint:
return None
@@ -133,7 +133,7 @@ class ExpressVPN(Proxy):
log.debug("ExpressVPN proxy ready: %s", self.last_connection_display() or endpoint)
return f"https://cat:{connection_token}@{endpoint}:443"
- def last_connection_display(self) -> Optional[str]:
+ def last_connection_display(self) -> str | None:
if not self.last_name or not self.last_host:
return None
parts = [self.last_name]
@@ -141,7 +141,7 @@ class ExpressVPN(Proxy):
parts.append(f"#{self.last_index} of {self.last_total}")
return f"({', '.join(parts)}): {self.last_host.replace('.expressprovider.com', '')}"
- def resolve_endpoint(self, query: str) -> Optional[str]:
+ def resolve_endpoint(self, query: str) -> str | None:
self.last_name = self.last_index = self.last_total = self.last_host = None
query = self.server_map.get(query) or query
@@ -168,7 +168,7 @@ class ExpressVPN(Proxy):
return None
return self.pick_endpoint(endpoints, server_num)
- def parse_query(self, query: str) -> tuple[Optional[str], Optional[str], Optional[int]]:
+ def parse_query(self, query: str) -> tuple[str | None, str | None, int | None]:
"""Parse "us", "us-ny", "us-ny-2"/"us-ny2" into (country, city, server number)."""
server_num = None
num_match = re.match(r"^(.+?)[-]?(\d+)$", query)
@@ -185,7 +185,7 @@ class ExpressVPN(Proxy):
# not a country[-city] pattern; caller falls back to slug resolution
return None, None, None
- def resolve_location(self, country_code: str, city_query: Optional[str] = None) -> Optional[dict]:
+ def resolve_location(self, country_code: str, city_query: str | None = None) -> dict | None:
pool = [x for x in self.get_locations() if str(x.get("country_code") or "").lower() == country_code]
if not pool:
log.warning("ExpressVPN: no locations found for country '%s'", country_code.upper())
@@ -194,7 +194,7 @@ class ExpressVPN(Proxy):
return random.choice(pool)
return self.match_city(pool, city_query)
- def match_city(self, locations: list[dict], city_query: str) -> Optional[dict]:
+ def match_city(self, locations: list[dict], city_query: str) -> dict | None:
"""Find the city that matches the query by abbreviation ("ny"), exact slug, slug prefix, then substring."""
city_query = city_query.strip().lower()
abbrev, exact, prefix, substring = [], [], [], []
@@ -220,7 +220,7 @@ class ExpressVPN(Proxy):
log.debug("ExpressVPN: city '%s' matched %d locations", city_query, len(candidates))
return candidates[0]
- def resolve_slug(self, query: str) -> Optional[dict]:
+ def resolve_slug(self, query: str) -> dict | None:
for loc in self.get_locations():
name = str(loc.get("name") or "").lower()
keys = (str(loc.get("id") or "").lower(), name, str(loc.get("country_code") or "").lower(), slugify(name))
@@ -228,7 +228,7 @@ class ExpressVPN(Proxy):
return loc
return None
- def pick_endpoint(self, endpoints: list[dict], server_num: Optional[int] = None) -> Optional[str]:
+ def pick_endpoint(self, endpoints: list[dict], server_num: int | None = None) -> str | None:
hosts = [str(x.get("host") or "").lower() for x in endpoints if x.get("host")]
if not hosts:
return None
@@ -328,7 +328,7 @@ class ExpressVPN(Proxy):
self.tokens = {k: v for k, v in tokens.items() if v}
return self.tokens
- def refresh_access_token(self, refresh_token: str) -> Optional[dict]:
+ def refresh_access_token(self, refresh_token: str) -> dict | None:
response = self.request(
"POST",
f"{self.AUTH_BASE}/token",
@@ -341,7 +341,7 @@ class ExpressVPN(Proxy):
return None
return response.json()
- def device_login(self) -> Optional[dict]:
+ def device_login(self) -> dict | None:
"""One-time interactive bootstrap through the OAuth 2.0 device authorization grant (RFC 8628)."""
response = self.request(
"POST",
@@ -387,7 +387,7 @@ class ExpressVPN(Proxy):
log.error("ExpressVPN: device authorization timed out before approval")
return None
- def get_srt(self) -> Optional[str]:
+ def get_srt(self) -> str | None:
if self.srt and not jwt_expired(self.srt):
return self.srt
@@ -413,7 +413,7 @@ class ExpressVPN(Proxy):
self.save_cache(tokens)
return srt
- def get_connection_token(self) -> Optional[str]:
+ def get_connection_token(self) -> str | None:
tokens = self.get_tokens()
connection_token = tokens.get("connection_token")
if connection_token and not jwt_expired(connection_token):
@@ -434,7 +434,7 @@ class ExpressVPN(Proxy):
self.save_cache(tokens)
return connection_token
- def select_srt(self, receipts: list[dict], subscription_id: Optional[str]) -> Optional[str]:
+ def select_srt(self, receipts: list[dict], subscription_id: str | None) -> str | None:
for receipt in receipts:
srt = receipt.get("srt")
if "xv.vpn" in jwt_payload(srt).get("entitlements", {}):
@@ -496,7 +496,7 @@ def slugify(value: str) -> str:
return re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-")
-def jwt_payload(token: Optional[str]) -> dict:
+def jwt_payload(token: str | None) -> dict:
if not token:
return {}
try:
@@ -509,7 +509,7 @@ def jwt_payload(token: Optional[str]) -> dict:
return {}
-def jwt_expired(token: Optional[str]) -> bool:
+def jwt_expired(token: str | None) -> bool:
"""Treat tokens without an exp claim (proprietary SRT/connection tokens) as non-expiring."""
if not token:
return True
diff --git a/unshackle/core/proxies/gluetun.py b/unshackle/core/proxies/gluetun.py
index 92f0939c..a3b33517 100644
--- a/unshackle/core/proxies/gluetun.py
+++ b/unshackle/core/proxies/gluetun.py
@@ -7,7 +7,7 @@ import subprocess
import tempfile
import threading
import time
-from typing import Any, Optional
+from typing import Any
import requests
@@ -162,12 +162,12 @@ class Gluetun(Proxy):
def __init__(
self,
- providers: Optional[dict] = None,
+ providers: dict | None = None,
base_port: int = 8888,
auto_cleanup: bool = True,
container_prefix: str = "unshackle-gluetun",
- auth_user: Optional[str] = None,
- auth_password: Optional[str] = None,
+ auth_user: str | None = None,
+ auth_password: str | None = None,
verify_ip: bool = True,
**kwargs: Any,
) -> None:
@@ -231,7 +231,7 @@ class Gluetun(Proxy):
provider_count = len(self.providers)
return f"Gluetun ({provider_count} provider{['s', ''][provider_count == 1]})"
- def get_proxy(self, query: str) -> Optional[str]:
+ def get_proxy(self, query: str) -> str | None:
"""
Get an HTTP proxy URI for a Gluetun VPN connection.
@@ -366,7 +366,7 @@ class Gluetun(Proxy):
self.remove_container(container_name)
if query_key in self.active_containers:
del self.active_containers[query_key]
- raise coded(RuntimeError(f"Failed to create Gluetun container: {e}"), APIErrorCode.INVALID_PROXY)
+ raise coded(RuntimeError(f"Failed to create Gluetun container: {e}"), APIErrorCode.INVALID_PROXY) from e
def cleanup(self) -> None:
"""Stop and remove all managed Gluetun containers."""
@@ -408,7 +408,7 @@ class Gluetun(Proxy):
success=True,
)
- def get_connection_info(self, query: str) -> Optional[dict]:
+ def get_connection_info(self, query: str) -> dict | None:
"""
Get connection info for a proxy query.
@@ -590,7 +590,7 @@ class Gluetun(Proxy):
log.error(f"Docker pull failed: {result.stderr}")
return False
except subprocess.TimeoutExpired:
- raise RuntimeError(f"Timed out pulling Docker image '{image}'")
+ raise RuntimeError(f"Timed out pulling Docker image '{image}'") from None
def create_container(
self,
@@ -598,9 +598,9 @@ class Gluetun(Proxy):
port: int,
provider_name: str,
provider_config: dict,
- country: Optional[str] = None,
- city: Optional[str] = None,
- hostname: Optional[str] = None,
+ country: str | None = None,
+ city: str | None = None,
+ hostname: str | None = None,
) -> None:
"""
Make and start a Gluetun Docker container.
@@ -766,7 +766,7 @@ class Gluetun(Proxy):
success=False,
duration_ms=(time.time() - start_time) * 1000,
)
- raise RuntimeError("Docker run command timed out")
+ raise RuntimeError("Docker run command timed out") from None
if result.returncode != 0:
error_msg = result.stderr or "unknown error"
@@ -850,7 +850,7 @@ class Gluetun(Proxy):
except (subprocess.TimeoutExpired, FileNotFoundError):
return False
- def get_existing_container_info(self, container_name: str) -> Optional[dict]:
+ def get_existing_container_info(self, container_name: str) -> dict | None:
"""
Find whether a container exists in Docker, and get its info.
@@ -1038,7 +1038,7 @@ class Gluetun(Proxy):
)
return False
- def get_container_exit_info(self, container_name: str) -> Optional[dict]:
+ def get_container_exit_info(self, container_name: str) -> dict | None:
"""Get exit information for a stopped container."""
try:
result = subprocess.run(
diff --git a/unshackle/core/proxies/hola.py b/unshackle/core/proxies/hola.py
index f3ae958a..abba14bf 100644
--- a/unshackle/core/proxies/hola.py
+++ b/unshackle/core/proxies/hola.py
@@ -2,7 +2,6 @@ import random
import re
import subprocess
from functools import cached_property
-from typing import Optional
from unshackle.core import binaries
from unshackle.core.proxies.proxy import Proxy, cached_catalogue
@@ -14,7 +13,7 @@ class Hola(Proxy):
Proxy provider that uses Hola's direct connections through the hola-proxy binary.
"""
if not binaries.HolaProxy:
- raise EnvironmentError("hola-proxy executable not found but is required for the Hola proxy provider.")
+ raise OSError("hola-proxy executable not found but is required for the Hola proxy provider.")
self.binary = binaries.HolaProxy
@cached_property
@@ -27,7 +26,7 @@ class Hola(Proxy):
return f"{countries} Countr{['ies', 'y'][countries == 1]}"
- def get_proxy(self, query: str) -> Optional[str]:
+ def get_proxy(self, query: str) -> str | None:
"""
Get an HTTP proxy URI for a Datacenter ('direct') or Residential ('lum') Hola server.
diff --git a/unshackle/core/proxies/nordvpn.py b/unshackle/core/proxies/nordvpn.py
index 169c5ad9..d5fdd893 100644
--- a/unshackle/core/proxies/nordvpn.py
+++ b/unshackle/core/proxies/nordvpn.py
@@ -2,7 +2,6 @@ import json
import random
import re
from functools import cached_property
-from typing import Optional, Union
import requests
@@ -13,7 +12,7 @@ from unshackle.core.utilities import COUNTRY_CODE_ALIASES
class NordVPN(Proxy):
- def __init__(self, username: str, password: str, server_map: Optional[dict[str, Union[int, str]]] = None) -> None:
+ def __init__(self, username: str, password: str, server_map: dict[str, int | str] | None = None) -> None:
"""
Proxy provider that uses NordVPN Service Credentials.
@@ -36,7 +35,7 @@ class NordVPN(Proxy):
self.username = username
self.password = password
self.server_map = server_map or {}
- self.last_hostname: Optional[str] = None
+ self.last_hostname: str | None = None
@cached_property
def countries(self) -> list[dict]:
@@ -49,7 +48,7 @@ class NordVPN(Proxy):
return f"{countries} Countr{['ies', 'y'][countries == 1]} ({servers} Server{['s', ''][servers == 1]})"
- def get_proxy(self, query: str) -> Optional[str]:
+ def get_proxy(self, query: str) -> str | None:
"""
Get an HTTP(SSL) proxy URI for a NordVPN server.
@@ -133,11 +132,11 @@ class NordVPN(Proxy):
self.last_hostname = hostname
return f"https://{self.username}:{self.password}@{hostname}:89"
- def last_connection_display(self) -> Optional[str]:
+ def last_connection_display(self) -> str | None:
"""Name the last server with its IP and network, so a blocked network can be excluded with '@-'."""
return describe(self.last_hostname) if self.last_hostname else None
- def get_country(self, by_id: Optional[int] = None, by_code: Optional[str] = None) -> Optional[dict]:
+ def get_country(self, by_id: int | None = None, by_code: str | None = None) -> dict | None:
"""Find a Country and its metadata."""
if all(x is None for x in (by_id, by_code)):
raise ValueError("At least one search query must be made.")
@@ -168,12 +167,10 @@ class NordVPN(Proxy):
try:
return res.json()
except json.JSONDecodeError:
- raise ValueError("Could not decode list of NordVPN servers, not JSON data.")
+ raise ValueError("Could not decode list of NordVPN servers, not JSON data.") from None
@staticmethod
- def get_recommended_servers(
- country_id: int, city_id: Optional[int] = None, limit: Optional[int] = None
- ) -> list[dict]:
+ def get_recommended_servers(country_id: int, city_id: int | None = None, limit: int | None = None) -> list[dict]:
"""
Get the list of recommended Servers for a Country, or for one of its cities.
@@ -191,7 +188,7 @@ class NordVPN(Proxy):
try:
return res.json()
except json.JSONDecodeError:
- raise ValueError("Could not decode list of NordVPN countries, not JSON data.")
+ raise ValueError("Could not decode list of NordVPN countries, not JSON data.") from None
@staticmethod
@cached_catalogue
@@ -204,4 +201,4 @@ class NordVPN(Proxy):
try:
return res.json()
except json.JSONDecodeError:
- raise ValueError("Could not decode list of NordVPN countries, not JSON data.")
+ raise ValueError("Could not decode list of NordVPN countries, not JSON data.") from None
diff --git a/unshackle/core/proxies/proton.py b/unshackle/core/proxies/proton.py
index cdc6aede..2755c6b0 100644
--- a/unshackle/core/proxies/proton.py
+++ b/unshackle/core/proxies/proton.py
@@ -8,7 +8,6 @@ import re
import sys
import time
from pathlib import Path
-from typing import Optional
from urllib.parse import quote
import requests
@@ -58,9 +57,9 @@ class ProtonVPN(Proxy):
def __init__(
self,
- server_map: Optional[dict[str, str]] = None,
- cookie_path: Optional[str] = None,
- cache_path: Optional[str] = None,
+ server_map: dict[str, str] | None = None,
+ cookie_path: str | None = None,
+ cache_path: str | None = None,
timeout: float = 10.0,
enable: bool = False,
) -> None:
@@ -69,14 +68,14 @@ class ProtonVPN(Proxy):
self.enable = enable
self.api_base = self.API_BASE
- self.uid: Optional[str] = None
- self.access_token: Optional[str] = None
- self.refresh_token: Optional[str] = None
- self.logicals: Optional[list[dict]] = None
- self.max_tier: Optional[int] = None
- self.last_name: Optional[str] = None
- self.last_city: Optional[str] = None
- self.last_host: Optional[str] = None
+ self.uid: str | None = None
+ self.access_token: str | None = None
+ self.refresh_token: str | None = None
+ self.logicals: list[dict] | None = None
+ self.max_tier: int | None = None
+ self.last_name: str | None = None
+ self.last_city: str | None = None
+ self.last_host: str | None = None
self.cookie_path = Path(cookie_path).expanduser() if cookie_path else self.default_cookie_path()
self.cache_path = Path(cache_path).expanduser() if cache_path else self.default_cache_path()
@@ -97,7 +96,7 @@ class ProtonVPN(Proxy):
f"{countries} Countr{'ies' if countries != 1 else 'y'} ({len(servers)} Server{'s' if servers != 1 else ''})"
)
- def get_proxy(self, query: str) -> Optional[str]:
+ def get_proxy(self, query: str) -> str | None:
self.ensure_session()
server = self.resolve_server(query.strip().lower())
if not server:
@@ -113,13 +112,13 @@ class ProtonVPN(Proxy):
user, pwd = (quote(c, safe="") for c in creds)
return f"https://{user}:{pwd}@{host}:{port}"
- def last_connection_display(self) -> Optional[str]:
+ def last_connection_display(self) -> str | None:
if not self.last_name or not self.last_host:
return None
label = f"{self.last_name} - {self.last_city}" if self.last_city else self.last_name
return f"({label}): {self.last_host.replace('.protonvpn.net', '')}"
- def resolve_server(self, query: str) -> Optional[dict]:
+ def resolve_server(self, query: str) -> dict | None:
self.last_name = self.last_city = self.last_host = None
query = self.server_map.get(query, query)
country, city, server_num = self.parse_query(query)
@@ -149,7 +148,7 @@ class ProtonVPN(Proxy):
return None
return self.select(pool, server_num)
- def parse_query(self, query: str) -> tuple[Optional[str], Optional[str], Optional[int]]:
+ def parse_query(self, query: str) -> tuple[str | None, str | None, int | None]:
"""Parse "us", "us12"/"us-12"/"us#12" (server #12), and "us:ny" (city)."""
city = None
if ":" in query:
@@ -180,7 +179,7 @@ class ProtonVPN(Proxy):
substring.append(s)
return exact or prefix or substring
- def select(self, pool: list[dict], server_num: Optional[int]) -> dict:
+ def select(self, pool: list[dict], server_num: int | None) -> dict:
if server_num is not None:
matches = [s for s in pool if server_no(s) == server_num]
if matches:
@@ -218,7 +217,7 @@ class ProtonVPN(Proxy):
vpn = (response.json().get("VPN") or {}) if response is not None else {}
return vpn if "MaxTier" in vpn else {}
- def get_browser_token(self) -> Optional[tuple[str, str]]:
+ def get_browser_token(self) -> tuple[str, str] | None:
response = self.api("GET", f"/vpn/v1/browser/token?Duration={self.TOKEN_DURATION}")
if response is None:
return None
@@ -228,7 +227,7 @@ class ProtonVPN(Proxy):
log.error("Proton: browser/token response missing credentials")
return None
- def api(self, method: str, path: str) -> Optional[requests.Response]:
+ def api(self, method: str, path: str) -> requests.Response | None:
"""Call the Proton API, and refresh the login session one time on a 401."""
if not self.access_token:
self.load_session()
@@ -450,7 +449,7 @@ def slugify(value: str) -> str:
return re.sub(r"[^a-z0-9]+", "-", value.lower()).strip("-")
-def server_no(server: dict) -> Optional[int]:
+def server_no(server: dict) -> int | None:
"""Proton's server number from the logical name, e.g. "US#231" -> 231, "US-CO#21" -> 21."""
match = re.search(r"#(\d+)", str(server.get("Name") or ""))
return int(match.group(1)) if match else None
diff --git a/unshackle/core/proxies/proxy.py b/unshackle/core/proxies/proxy.py
index abcaee47..11dca90a 100644
--- a/unshackle/core/proxies/proxy.py
+++ b/unshackle/core/proxies/proxy.py
@@ -1,7 +1,8 @@
import functools
import time
from abc import abstractmethod
-from typing import Any, Callable, Optional, TypeVar
+from collections.abc import Callable
+from typing import Any, TypeVar
CATALOGUE_TTL = 600.0
CATALOGUES: dict[str, tuple[float, Any]] = {}
@@ -47,7 +48,7 @@ class Proxy:
return f"{countries} Countr{['ies', 'y'][countries == 1]} ({servers} Server{['s', ''][servers == 1]})"
@abstractmethod
- def get_proxy(self, query: str) -> Optional[str]:
+ def get_proxy(self, query: str) -> str | None:
"""
Get a proxy URI from the proxy provider.
diff --git a/unshackle/core/proxies/resolve.py b/unshackle/core/proxies/resolve.py
index f776062a..5c9d608f 100644
--- a/unshackle/core/proxies/resolve.py
+++ b/unshackle/core/proxies/resolve.py
@@ -6,7 +6,7 @@ import ipaddress
import json
import logging
import re
-from typing import Any, List, Optional
+from typing import Any
from urllib.parse import urlparse
import click
@@ -33,11 +33,11 @@ class Unavailable(Proxy):
def __repr__(self) -> str:
return f"failed to load ({self.error})"
- def get_proxy(self, query: str) -> Optional[str]:
+ def get_proxy(self, query: str) -> str | None:
return None
-def find_provider(proxy_providers: List[Any], name: str, hint: str = "") -> Any:
+def find_provider(proxy_providers: list[Any], name: str, hint: str = "") -> Any:
"""
Find a proxy provider by its class name, case-insensitive.
@@ -58,7 +58,7 @@ def find_provider(proxy_providers: List[Any], name: str, hint: str = "") -> Any:
raise coded(ValueError(f"{message}. {hint}" if hint else message), APIErrorCode.INVALID_PROXY)
-def load_proxy_providers(exclude: tuple[str, ...] = (), raise_errors: bool = False, quiet: bool = False) -> List[Any]:
+def load_proxy_providers(exclude: tuple[str, ...] = (), raise_errors: bool = False, quiet: bool = False) -> list[Any]:
"""
Build the proxy providers set in config: Basic first, then config key order, Control D last.
@@ -124,7 +124,7 @@ def load_proxy_providers(exclude: tuple[str, ...] = (), raise_errors: bool = Fal
return proxy_providers
-def initialize_proxy_providers(raise_errors: bool = False, quiet: bool = False) -> List[Any]:
+def initialize_proxy_providers(raise_errors: bool = False, quiet: bool = False) -> list[Any]:
"""
Load the proxy providers for the REST API and the remote service client.
@@ -140,7 +140,7 @@ def initialize_proxy_providers(raise_errors: bool = False, quiet: bool = False)
CITY_HINT = "A city query needs a proxy provider prefix, for example nordvpn:us:seattle."
-def split_proxy_query(proxy: str, proxy_providers: List[Any]) -> tuple[Optional[str], str]:
+def split_proxy_query(proxy: str, proxy_providers: list[Any]) -> tuple[str | None, str]:
"""
Split a proxy value into the proxy provider that its prefix names and the query for it.
@@ -156,7 +156,7 @@ def split_proxy_query(proxy: str, proxy_providers: List[Any]) -> tuple[Optional[
return name, query
-def pick_proxy(proxy_providers: List[Any], query: str, provider_name: Optional[str] = None) -> tuple[Any, str]:
+def pick_proxy(proxy_providers: list[Any], query: str, provider_name: str | None = None) -> tuple[Any, str]:
"""
Get a proxy provider and its proxy URI: from the named one, or else from the first one that answers.
@@ -247,7 +247,7 @@ def describe_explicit_proxy(uri: str) -> str:
return f"Using explicit Proxy: {mask_proxy(uri)}"
-def resolve_proxy(proxy: str, proxy_providers: List[Any]) -> Optional[str]:
+def resolve_proxy(proxy: str, proxy_providers: list[Any]) -> str | None:
"""Change a proxy parameter to a real proxy URI.
Accepts:
diff --git a/unshackle/core/proxies/surfsharkvpn.py b/unshackle/core/proxies/surfsharkvpn.py
index 61b770ee..314e6691 100644
--- a/unshackle/core/proxies/surfsharkvpn.py
+++ b/unshackle/core/proxies/surfsharkvpn.py
@@ -7,7 +7,6 @@ import socket
import ssl
import threading
from functools import cache, cached_property, partial
-from typing import Optional
import certifi
import requests
@@ -26,7 +25,7 @@ CONNECT_TIMEOUT = 30
CHUNK = 65536
TLS = ssl.create_default_context(cafile=certifi.where()) # the same CA bundle as requests
PINS: dict[tuple[str, str], int] = {}
-LOOP: Optional[asyncio.AbstractEventLoop] = None
+LOOP: asyncio.AbstractEventLoop | None = None
STATE = threading.Lock()
@@ -84,7 +83,7 @@ def pinned(ip: str, hostname: str) -> int:
class SurfsharkVPN(Proxy):
- def __init__(self, username: str, password: str, server_map: Optional[dict[str, str]] = None) -> None:
+ def __init__(self, username: str, password: str, server_map: dict[str, str] | None = None) -> None:
"""
Proxy provider that uses SurfsharkVPN Service Credentials.
@@ -122,7 +121,7 @@ class SurfsharkVPN(Proxy):
country, sep, city = str(region).lower().partition(":")
self.server_map[COUNTRY_CODE_ALIASES.get(country, country) + sep + city] = server
- self.last_server: Optional[tuple[str, str]] = None
+ self.last_server: tuple[str, str] | None = None
@cached_property
def countries(self) -> list[dict]:
@@ -135,7 +134,7 @@ class SurfsharkVPN(Proxy):
return f"{countries} Countr{['ies', 'y'][countries == 1]} ({servers} Server{['s', ''][servers == 1]})"
- def get_proxy(self, query: str) -> Optional[str]:
+ def get_proxy(self, query: str) -> str | None:
"""
Get an HTTP(SSL) proxy URI for a SurfsharkVPN server.
@@ -186,7 +185,7 @@ class SurfsharkVPN(Proxy):
self.last_server = (hostname, ip)
return f"http://{self.username}:{self.password}@127.0.0.1:{pinned(ip, hostname)}"
- def last_connection_display(self) -> Optional[str]:
+ def last_connection_display(self) -> str | None:
"""Name the pinned server with its IP and network, so it can be pinned again or excluded with '@-'."""
return describe(*self.last_server) if self.last_server else None
@@ -230,7 +229,7 @@ class SurfsharkVPN(Proxy):
server = server.lower()
return server if server.endswith(".surfshark.com") else f"{server}.prod.surfshark.com"
- def get_city_servers(self, servers: list[dict], city: Optional[str] = None) -> list[dict]:
+ def get_city_servers(self, servers: list[dict], city: str | None = None) -> list[dict]:
"""
Get a country's servers, optionally filtered by city.
@@ -266,4 +265,4 @@ class SurfsharkVPN(Proxy):
try:
return res.json()
except json.JSONDecodeError:
- raise ValueError("Could not decode list of SurfsharkVPN countries, not JSON data.")
+ raise ValueError("Could not decode list of SurfsharkVPN countries, not JSON data.") from None
diff --git a/unshackle/core/proxies/windscribevpn.py b/unshackle/core/proxies/windscribevpn.py
index 1aa9f0fe..b6bb17ed 100644
--- a/unshackle/core/proxies/windscribevpn.py
+++ b/unshackle/core/proxies/windscribevpn.py
@@ -1,8 +1,8 @@
import json
import random
import re
+from collections.abc import Iterator
from functools import cached_property
-from typing import Iterator, Optional
import requests
@@ -11,7 +11,7 @@ from unshackle.core.proxies.proxy import Proxy, cached_catalogue
class WindscribeVPN(Proxy):
- def __init__(self, username: str, password: str, server_map: Optional[dict[str, str]] = None) -> None:
+ def __init__(self, username: str, password: str, server_map: dict[str, str] | None = None) -> None:
"""
Proxy provider that uses WindscribeVPN Service Credentials.
@@ -32,7 +32,7 @@ class WindscribeVPN(Proxy):
self.username = username
self.password = password
self.server_map = server_map or {}
- self.last_hostname: Optional[str] = None
+ self.last_hostname: str | None = None
@cached_property
def countries(self) -> list[dict]:
@@ -45,7 +45,7 @@ class WindscribeVPN(Proxy):
return f"{countries} Countr{['ies', 'y'][countries == 1]} ({servers} Server{['s', ''][servers == 1]})"
- def get_proxy(self, query: str) -> Optional[str]:
+ def get_proxy(self, query: str) -> str | None:
"""
Get an HTTPS proxy URI for a WindscribeVPN server.
@@ -70,7 +70,7 @@ class WindscribeVPN(Proxy):
if selector:
if not re.fullmatch(r"[a-z]+", query):
raise ValueError(f"'{query}' is already one WindscribeVPN server, so it takes no '@' network selector.")
- hostname: Optional[str] = self.get_random_server(query, city, selector)
+ hostname: str | None = self.get_random_server(query, city, selector)
elif mapping := self.server_map.get(server_map_key) or self.server_map.get(query):
if mapped := mapped_query(server_map_key, mapping):
return self.get_proxy(mapped)
@@ -92,7 +92,7 @@ class WindscribeVPN(Proxy):
hostname = self.last_hostname = hostname.split(":")[0]
return f"https://{self.username}:{self.password}@{hostname}:443"
- def last_connection_display(self) -> Optional[str]:
+ def last_connection_display(self) -> str | None:
"""Name the last server with its IP and network, so a blocked network can be excluded with '@-'."""
return describe(self.last_hostname) if self.last_hostname else None
@@ -104,7 +104,7 @@ class WindscribeVPN(Proxy):
if host.get("hostname"):
yield host["hostname"]
- def get_specific_server(self, country_code: str, server_num: str) -> Optional[str]:
+ def get_specific_server(self, country_code: str, server_num: str) -> str | None:
"""
Find a server by country code and number, e.g. "sg007" -> "sg-007.totallyacdn.com".
@@ -123,9 +123,7 @@ class WindscribeVPN(Proxy):
return hostname
return None
- def get_random_server(
- self, country_code: str, city: Optional[str] = None, selector: Optional[str] = None
- ) -> Optional[str]:
+ def get_random_server(self, country_code: str, city: str | None = None, selector: str | None = None) -> str | None:
"""
Get a random server hostname for a country, optionally filtered by city.
@@ -185,4 +183,4 @@ class WindscribeVPN(Proxy):
data = res.json()
return data.get("data", [])
except json.JSONDecodeError:
- raise ValueError("Could not decode list of WindscribeVPN locations, not JSON data.")
+ raise ValueError("Could not decode list of WindscribeVPN locations, not JSON data.") from None
diff --git a/unshackle/core/remote_channel.py b/unshackle/core/remote_channel.py
index 14513e8f..b4af9455 100644
--- a/unshackle/core/remote_channel.py
+++ b/unshackle/core/remote_channel.py
@@ -14,8 +14,10 @@ import json
import logging
import time
from collections import deque
+from collections.abc import Callable, Iterator
+from contextlib import AbstractContextManager
from threading import Event, Lock, Thread
-from typing import TYPE_CHECKING, Any, Callable, ContextManager, Dict, Iterator, Optional, Union, cast
+from typing import TYPE_CHECKING, Any, cast
import aiohttp
import requests
@@ -68,7 +70,7 @@ class ServerMessages:
self.recent_logs: deque[str] = deque(maxlen=3)
self.log_lock = Lock()
self.cdm_lock = Lock()
- self.cdm_sessions: Dict[str, bytes] = {}
+ self.cdm_sessions: dict[str, bytes] = {}
def route(self, route: str) -> str:
return route.format(session_id=self.service._session_id)
@@ -87,7 +89,7 @@ class ServerMessages:
self.recent_logs.append(message.strip())
self.log_seq = seq
- def answer_cdm(self, call: Dict[str, Any]) -> Dict[str, Any]:
+ def answer_cdm(self, call: dict[str, Any]) -> dict[str, Any]:
"""Run one of the server's CDM calls on this machine's device; both adapters share its CDM sessions."""
from unshackle.core.cdm.client_relay import answer_cdm_call
@@ -151,7 +153,7 @@ class PollingChannel:
self.cdm_stop = Event()
self.paused: Callable[[], bool] = lambda: False
- def wait_auth(self, timeout: float = AUTH_TIMEOUT, step: Optional[Callable[[], bool]] = None) -> None:
+ def wait_auth(self, timeout: float = AUTH_TIMEOUT, step: Callable[[], bool] | None = None) -> None:
"""Poll the server until authentication completes, and answer its prompts and CDM calls.
``step`` replaces :meth:`auth_step` for an adapter that learns the login state another way.
@@ -248,7 +250,7 @@ class PollingChannel:
if last:
self.messages.close_cdm_sessions()
- def poll_cdm_calls(self, stop: Event, interval: Optional[float] = None) -> None:
+ def poll_cdm_calls(self, stop: Event, interval: float | None = None) -> None:
endpoint = self.messages.route(PROMPT_ROUTE)
while not stop.wait(CDM_POLL_INTERVAL if interval is None else interval):
if self.paused():
@@ -302,15 +304,15 @@ class WebSocketChannel:
self.connected = Event()
self.attempted = Event()
self.changed = Event()
- self.status: Optional[str] = None
+ self.status: str | None = None
self.error = ""
- self.failure: Optional[RemoteError] = None
+ self.failure: RemoteError | None = None
self.draining_now = False
- self.answers: Dict[str, Optional[ChannelAnswer]] = {} # None while this client still works on the ask
+ self.answers: dict[str, ChannelAnswer | None] = {} # None while this client still works on the ask
fallback.paused = self.connected.is_set
- self.ws: Optional[aiohttp.ClientWebSocketResponse] = None
- self.loop: Optional[asyncio.AbstractEventLoop] = None
- self.task: Optional[asyncio.Task[None]] = None
+ self.ws: aiohttp.ClientWebSocketResponse | None = None
+ self.loop: asyncio.AbstractEventLoop | None = None
+ self.task: asyncio.Task[None] | None = None
self.thread = Thread(
target=lambda: asyncio.run(self.run()), name=f"{self.service.service_tag}-channel", daemon=True
)
@@ -358,7 +360,7 @@ class WebSocketChannel:
if not self.attempted.is_set() or e.status in GONE_STATUSES:
return
backoff = max(backoff, retry_after(e) or 0)
- except (aiohttp.ClientError, asyncio.TimeoutError, OSError) as e:
+ except (TimeoutError, aiohttp.ClientError, OSError) as e:
log.debug(f"The session channel could not connect: {e!r}")
if not self.attempted.is_set():
return
@@ -385,7 +387,7 @@ class WebSocketChannel:
if isinstance(data, dict):
await self.receive(ws, data)
- async def receive(self, ws: aiohttp.ClientWebSocketResponse, data: Dict[str, Any]) -> None:
+ async def receive(self, ws: aiohttp.ClientWebSocketResponse, data: dict[str, Any]) -> None:
kind = data.get("type")
if kind == ChannelMessage.LOG:
self.messages.show_logs([cast(LogRecord, data)])
@@ -404,7 +406,7 @@ class WebSocketChannel:
elif kept := self.answers[ask_id]:
await ws.send_json(kept) # the server sends an ask again after a reconnect when its answer was lost
- def answer(self, data: Dict[str, Any]) -> None:
+ def answer(self, data: dict[str, Any]) -> None:
"""Answer one prompt or CDM call on this thread, so the channel keeps reading while the user types."""
cdm_call = data["type"] == ChannelMessage.CDM_CALL
answer = ChannelAnswer(type=ChannelMessage.ANSWER, id=data["id"], response="")
@@ -455,7 +457,7 @@ class WebSocketChannel:
if not self.connected.is_set():
self.fallback.keep_alive()
- def in_flight(self, endpoint: str) -> ContextManager[None]:
+ def in_flight(self, endpoint: str) -> AbstractContextManager[None]:
"""The fallback's CDM call poller, which polls only while the channel is down."""
return self.fallback.in_flight(endpoint)
@@ -475,7 +477,7 @@ class WebSocketChannel:
self.messages.close_cdm_sessions()
-Channel = Union[PollingChannel, WebSocketChannel]
+Channel = PollingChannel | WebSocketChannel
def open_channel(service: RemoteService) -> Channel:
diff --git a/unshackle/core/remote_protocol.py b/unshackle/core/remote_protocol.py
index 646bf517..5ebbe0a2 100644
--- a/unshackle/core/remote_protocol.py
+++ b/unshackle/core/remote_protocol.py
@@ -9,7 +9,7 @@ older peer.
from __future__ import annotations
from enum import Enum, StrEnum
-from typing import Any, NotRequired, Optional, TypedDict, TypeVar
+from typing import Any, NotRequired, TypedDict, TypeVar
HEALTH_ROUTE = "/api/health"
SERVICES_ROUTE = "/api/services"
@@ -109,7 +109,7 @@ class ClientInfo(TypedDict):
"""What a client tells the server about itself, for the server's logs."""
version: str
- code_hash: Optional[str]
+ code_hash: str | None
platform: str
argv: str
@@ -125,7 +125,7 @@ class SessionCreate(ClientLogin, total=False):
episode: Any
part: Any
wanted: Any
- proxy: Optional[str]
+ proxy: str | None
no_proxy: bool
client_region: str
proxy_region: str
@@ -153,7 +153,7 @@ class SessionCreated(TypedDict, total=False):
status: str
server_account: bool
server_cdm: bool
- server_cdm_max_height: Optional[int]
+ server_cdm_max_height: int | None
server_vault: bool
server_device: bool
@@ -168,7 +168,7 @@ class TracksReply(TypedDict, total=False):
session_headers: dict[str, str]
session_cookies: dict[str, str]
session_cookie_jar: list[dict[str, Any]]
- server_cdm: Optional[bool]
+ server_cdm: bool | None
server_cdm_type: str
sample_decrypt_tracks: list[str]
@@ -180,7 +180,7 @@ class SegmentFilterRequest(TypedDict):
class SegmentFilterReply(TypedDict):
"""The segment URIs to skip; None when the track has no segment filter."""
- unwanted: Optional[list[str]]
+ unwanted: list[str] | None
class LicenseRequest(TypedDict, total=False):
@@ -203,7 +203,7 @@ class LicenseReply(TypedDict, total=False):
track gets no content keys: ``capped_tracks`` holds its refusal details, ``reason`` and ``max_height``.
"""
- license: Optional[str]
+ license: str | None
keys: dict[str, Any]
vault_keys: list[str]
clear_tracks: list[str]
@@ -226,7 +226,7 @@ class PromptReply(TypedDict, total=False):
"""The login state of a remote session, and the prompt or CDM call that waits for the client."""
status: str
- prompt: Optional[str]
+ prompt: str | None
cdm_call: dict[str, Any]
error: str
diff --git a/unshackle/core/remote_service.py b/unshackle/core/remote_service.py
index d7ed62a1..18473d1e 100644
--- a/unshackle/core/remote_service.py
+++ b/unshackle/core/remote_service.py
@@ -18,20 +18,14 @@ import re
import shlex
import sys
import time
+from collections.abc import Callable, Iterable, Iterator, Mapping
from http.cookiejar import CookieJar
from threading import Lock, local
from typing import (
TYPE_CHECKING,
Any,
- Callable,
- Dict,
- Iterable,
- Iterator,
- Mapping,
- Optional,
Protocol,
TypeVar,
- Union,
cast,
)
from urllib.parse import urlencode, urlsplit
@@ -171,7 +165,7 @@ def quiet() -> Iterator[None]:
_mute.quiet = before
-def redact_secrets(text: str, data: Optional[Mapping[str, Any]] = None) -> str:
+def redact_secrets(text: str, data: Mapping[str, Any] | None = None) -> str:
"""Mask URL userinfo and any request-payload secrets before unshackle writes the text to the log."""
secrets = [v for k in SENSITIVE_DATA_KEYS if isinstance(v := (data or {}).get(k), str) and v]
return redact_text(text, secrets) or ""
@@ -227,8 +221,8 @@ class RemoteClient:
self,
server_url: str,
api_key: str,
- auth_headers: Optional[list[str]] = None,
- timeout: Optional[float] = None,
+ auth_headers: list[str] | None = None,
+ timeout: float | None = None,
) -> None:
self.server_url = server_url.rstrip("/")
self.timeout = timeout or 120
@@ -237,8 +231,8 @@ class RemoteClient:
self._auth_header_index = 0
self._auth_header_lock = Lock()
self._auth_header_found = False
- self._session: Optional[requests.Session] = None
- self.tunnel: Optional[TunnelClient] = None
+ self._session: requests.Session | None = None
+ self.tunnel: TunnelClient | None = None
self.no_channel = False # this server or a gateway in front of it refused the remote session channel
# wraps every request, so the service's CDM calls get answered while the server runs its code
self.in_flight: Callable[[str], contextlib.AbstractContextManager[Any]] = lambda _: contextlib.nullcontext()
@@ -272,16 +266,16 @@ class RemoteClient:
self,
method: str,
endpoint: str,
- data: Optional[Mapping[str, Any]] = None,
+ data: Mapping[str, Any] | None = None,
optional: bool = False,
expect: tuple[str, ...] = (),
- body: Optional[bytes] = None,
- ) -> Dict[str, Any]:
+ body: bytes | None = None,
+ ) -> dict[str, Any]:
"""Send one request and return its JSON body; an error outside ``expect`` exits, one inside it returns.
A raw ``body`` goes as ``application/octet-stream``, and a binary answer comes back under ``"body"``.
"""
- payload: Dict[str, Any] = (
+ payload: dict[str, Any] = (
{"json": data} if body is None else {"data": body, "headers": {"Content-Type": "application/octet-stream"}}
)
try:
@@ -301,7 +295,7 @@ class RemoteClient:
if resp.status_code < 400:
raise RemoteError(
f"The remote server answered {endpoint} with a body that is not JSON", ClientErrorKind.UNKNOWN
- )
+ ) from None
detail = {}
if not isinstance(detail, dict):
raise RemoteError(
@@ -369,7 +363,7 @@ class RemoteClient:
self._auth_header_found = True
return resp
- def probe(self, endpoint: str, background: bool = True) -> Dict[str, Any]:
+ def probe(self, endpoint: str, background: bool = True) -> dict[str, Any]:
"""GET a route with a short timeout: the JSON body, or an empty dict when the call fails. Never logs an error."""
try:
resp = self.send("get", endpoint, PROBE_TIMEOUT, background=background)
@@ -385,21 +379,21 @@ class RemoteClient:
ClientErrorKind.TIMEOUT,
)
- def post(self, endpoint: str, data: Mapping[str, Any], expect: tuple[str, ...] = ()) -> Dict[str, Any]:
+ def post(self, endpoint: str, data: Mapping[str, Any], expect: tuple[str, ...] = ()) -> dict[str, Any]:
return self.request("post", endpoint, data, expect=expect)
- def post_optional(self, endpoint: str, data: Mapping[str, Any]) -> Dict[str, Any]:
+ def post_optional(self, endpoint: str, data: Mapping[str, Any]) -> dict[str, Any]:
"""POST to an endpoint that an older server may not have. Empty dict when the route is missing."""
return self.request("post", endpoint, data, optional=True)
- def get(self, endpoint: str) -> Dict[str, Any]:
+ def get(self, endpoint: str) -> dict[str, Any]:
return self.request("get", endpoint)
- def get_optional(self, endpoint: str) -> Dict[str, Any]:
+ def get_optional(self, endpoint: str) -> dict[str, Any]:
"""GET an endpoint that an older server may not have. Empty dict when the route is missing."""
return self.request("get", endpoint, optional=True)
- def delete(self, endpoint: str) -> Dict[str, Any]:
+ def delete(self, endpoint: str) -> dict[str, Any]:
return self.request("delete", endpoint)
@@ -417,7 +411,7 @@ def sample_batches(samples: list[bytes]) -> Iterator[list[bytes]]:
yield batch
-def track_pssh(track: Any, drm_type: str, drm: Any = None) -> Optional[str]:
+def track_pssh(track: Any, drm_type: str, drm: Any = None) -> str | None:
"""The base64 PSSH of one DRM system's header: ``drm``'s own when it is of that system, else the track's first."""
for drm_obj in [drm, *(track.drm or [])]:
drm_class = drm_obj.__class__.__name__
@@ -428,7 +422,7 @@ def track_pssh(track: Any, drm_type: str, drm: Any = None) -> Optional[str]:
return None
-def apply_service_track_data(tracks: Tracks, data: Dict[str, Any]) -> None:
+def apply_service_track_data(tracks: Tracks, data: dict[str, Any]) -> None:
"""Overlay the service-set ``track.data`` the server sent.
Runs after the manifest re-parse so a service value wins over the parser's own for
@@ -509,7 +503,7 @@ def resolve_auth_headers(svc: dict, server_name: str) -> list[str]:
ANNOUNCED_SERVERS: set[str] = set()
-def resolve_server(server_name: Optional[str]) -> tuple[str, str, dict]:
+def resolve_server(server_name: str | None) -> tuple[str, str, dict]:
"""Find the server URL, the API key, and the per-service config in remote_services.
The per-service config carries the ``_auth_headers`` candidate list for RemoteClient.
@@ -546,24 +540,24 @@ def resolve_server(server_name: Optional[str]) -> tuple[str, str, dict]:
REMOTE_LIST_TTL = 300.0
REMOTE_LIST_FAILURE_TTL = 30.0
-_remote_lists: Dict[Optional[str], tuple[float, Optional[list[dict]]]] = {}
-_remote_list_locks: Dict[Optional[str], Lock] = {}
+_remote_lists: dict[str | None, tuple[float, list[dict] | None]] = {}
+_remote_list_locks: dict[str | None, Lock] = {}
-def remote_client(server_name: Optional[str]) -> RemoteClient:
+def remote_client(server_name: str | None) -> RemoteClient:
"""A RemoteClient for one ``remote_services`` server, with its auth headers and timeout."""
url, api_key, services_config = resolve_server(server_name)
return RemoteClient(url, api_key, services_config.get("_auth_headers"), services_config.get("_timeout"))
-def remote_service_list(server_name: Optional[str]) -> Optional[list[dict]]:
+def remote_service_list(server_name: str | None) -> list[dict] | None:
"""The services a ``remote_services`` server offers, cached for ``REMOTE_LIST_TTL``; None when it is unreachable.
A failure is cached for ``REMOTE_LIST_FAILURE_TTL``, so a server that is down does not stall every caller
for its timeout, and a blip does not hide its services for long. One caller fetches; the rest wait for it.
"""
- def cached() -> Optional[tuple[float, Optional[list[dict]]]]:
+ def cached() -> tuple[float, list[dict] | None] | None:
hit = _remote_lists.get(server_name)
ttl = REMOTE_LIST_FAILURE_TTL if hit and hit[1] is None else REMOTE_LIST_TTL
return hit if hit and time.monotonic() - hit[0] < ttl else None
@@ -573,7 +567,7 @@ def remote_service_list(server_name: Optional[str]) -> Optional[list[dict]]:
with _remote_list_locks.setdefault(server_name, Lock()):
if hit := cached():
return hit[1]
- services: Optional[list[dict]] = None
+ services: list[dict] | None = None
try:
with quiet():
services = remote_client(server_name).get(SERVICES_ROUTE).get("services") or []
@@ -588,7 +582,7 @@ def reset_remote_lists() -> None:
_remote_lists.clear()
-def find_remote_service(services: list[dict], name: str) -> Optional[dict]:
+def find_remote_service(services: list[dict], name: str) -> dict | None:
"""The remote service ``name`` means: a tag in any case first, then an alias, as local get_tag resolves one."""
lowered = name.lower()
return next((svc for svc in services if str(svc.get("tag", "")).lower() == lowered), None) or next(
@@ -596,7 +590,7 @@ def find_remote_service(services: list[dict], name: str) -> Optional[dict]:
)
-def remote_service_params(info: dict, data: Dict[str, Any]) -> Dict[str, Any]:
+def remote_service_params(info: dict, data: dict[str, Any]) -> dict[str, Any]:
"""The remote service's cli options in ``data``, read by ``service_options``."""
names = {p.get("name") for p in info.get("cli_params") or [] if p.get("kind") == "option"}
return {k: v for k, v in service_options(data, names).items() if v is not None and v is not False}
@@ -604,12 +598,12 @@ def remote_service_params(info: dict, data: Dict[str, Any]) -> Dict[str, Any]:
def make_remote_service(
ctx: click.Context,
- server_name: Optional[str],
+ server_name: str | None,
service_tag: str,
title_id: str,
- data: Dict[str, Any],
+ data: dict[str, Any],
apply_overrides: bool = True,
-) -> "RemoteService":
+) -> RemoteService:
"""A RemoteService for one ``remote_services`` server, set up the way ``dl --remote`` sets one up.
``apply_overrides`` False keeps the per-service ``remote_services..services`` overrides out of this
@@ -633,17 +627,17 @@ def make_remote_service(
return RemoteService(ctx, service_tag, title_id, url, api_key, services_config, service_params=params)
-def load_credentials_for_transport(service_tag: str, profile: Optional[str]) -> Optional[Dict[str, str]]:
+def load_credentials_for_transport(service_tag: str, profile: str | None) -> dict[str, str] | None:
credential = login.get_credentials(service_tag, profile)
if credential:
- result: Dict[str, str] = {"username": credential.username, "password": credential.password}
+ result: dict[str, str] = {"username": credential.username, "password": credential.password}
if credential.extra:
result["extra"] = credential.extra
return result
return None
-def load_cookies_for_transport(service_tag: str, profile: Optional[str]) -> Optional[str]:
+def load_cookies_for_transport(service_tag: str, profile: str | None) -> str | None:
import zlib
cookie_path = login.get_cookie_path(service_tag, profile)
@@ -652,7 +646,7 @@ def load_cookies_for_transport(service_tag: str, profile: Optional[str]) -> Opti
return None
-def resolve_proxy_arg(proxy_arg: Optional[str], providers: Optional[list] = None) -> Optional[str]:
+def resolve_proxy_arg(proxy_arg: str | None, providers: list | None = None) -> str | None:
if not proxy_arg:
return None
@@ -661,10 +655,10 @@ def resolve_proxy_arg(proxy_arg: Optional[str], providers: Optional[list] = None
try:
return resolve_proxy(proxy_arg, initialize_proxy_providers() if providers is None else providers)
except ValueError as e:
- raise click.ClickException(str(e))
+ raise click.ClickException(str(e)) from None
-def resolve_remote_proxy_arg(proxy_arg: str, providers: Optional[list] = None) -> Optional[str]:
+def resolve_remote_proxy_arg(proxy_arg: str, providers: list | None = None) -> str | None:
"""
Get the proxy URI to send to a server for a --proxy value.
@@ -689,7 +683,7 @@ def resolve_remote_proxy_arg(proxy_arg: str, providers: Optional[list] = None) -
return uri
return resolve_proxy(proxy_arg, [x for x in providers if not isinstance(x, ControlD)])
except ValueError as e:
- raise click.ClickException(str(e))
+ raise click.ClickException(str(e)) from None
def ws_headers(client: RemoteClient) -> dict[str, str]:
@@ -697,7 +691,7 @@ def ws_headers(client: RemoteClient) -> dict[str, str]:
return {k: str(v) for k, v in client.session.headers.items() if k.lower() != "connection"}
-def start_tunnel(client: RemoteClient, proxy: Optional[str] = None) -> TunnelClient:
+def start_tunnel(client: RemoteClient, proxy: str | None = None) -> TunnelClient:
"""Open a tunnel that sends the server's requests out through this machine's own connection, or through
``proxy`` from this machine.
@@ -722,12 +716,12 @@ def start_tunnel(client: RemoteClient, proxy: Optional[str] = None) -> TunnelCli
elif tunnel.at_limit and time.monotonic() < slot_deadline:
wait_retry_after(TUNNEL_SLOT_POLL, "Every tunnel of this API key is in use")
else:
- raise click.ClickException(f"--local-proxy could not open a tunnel to the server: {e}")
+ raise click.ClickException(f"--local-proxy could not open a tunnel to the server: {e}") from None
client.tunnel = tunnel
return tunnel
-def server_proxy_arg(params: Dict[str, Any]) -> str:
+def server_proxy_arg(params: dict[str, Any]) -> str:
"""The --proxy value to resolve for a server: the one typed when it resolved to a proxy on this machine."""
proxy = params["proxy"]
return (params.get("proxy_arg") or proxy) if is_loopback(proxy) else proxy
@@ -780,7 +774,7 @@ def cache_stem_is_relevant(
return not matched_foreign
-def cache_key_filter(service_tag: str, profile: Optional[str]) -> Callable[[str], bool]:
+def cache_key_filter(service_tag: str, profile: str | None) -> Callable[[str], bool]:
"""Return a check for the cache keys that belong to the active credential or profile.
The check runs :func:`cache_stem_is_relevant` on every path segment of a cache key,
@@ -822,7 +816,7 @@ class ServerKeySource(Protocol):
def licenses_locally(self, track: AnyTrack) -> bool:
"""True when this machine's own CDM licenses ``track`` instead of the server."""
- def license_track(self, track: AnyTrack, drm: Any, kid: Optional[UUID] = None) -> Optional[dict[UUID, str]]:
+ def license_track(self, track: AnyTrack, drm: Any, kid: UUID | None = None) -> dict[UUID, str] | None:
"""The content keys the server licenses for ``drm`` of ``track``, or None when it hands ``track`` to this machine's CDM.
Call it only for a track ``licenses_locally`` does not name; after None, it names the track. ``kid`` is
@@ -830,11 +824,11 @@ class ServerKeySource(Protocol):
raises ClickException.
"""
- def vault_source(self, kid: UUID, key: str) -> Optional[Vault]:
+ def vault_source(self, kid: UUID, key: str) -> Vault | None:
"""The server vault when it served ``key`` for ``kid``, else None. That content key must pass a decrypt check."""
@property
- def server_vault(self) -> Optional["ServerVault"]:
+ def server_vault(self) -> ServerVault | None:
"""The server's vaults, which take the content keys a decrypt proved, or None."""
@@ -849,20 +843,20 @@ class ServerVault(Vault):
report_now = True
- def __init__(self, service: "RemoteService") -> None:
+ def __init__(self, service: RemoteService) -> None:
super().__init__("server_cdm", no_push=True)
self.service = service
- def get_key(self, kid: Union[UUID, str], service: str) -> Optional[str]:
+ def get_key(self, kid: UUID | str, service: str) -> str | None:
return None
def get_keys(self, service: str) -> Iterator[tuple[str, str]]:
return iter(())
- def add_key(self, service: str, kid: Union[UUID, str], key: str) -> bool:
+ def add_key(self, service: str, kid: UUID | str, key: str) -> bool:
return False
- def add_keys(self, service: str, kid_keys: dict[Union[UUID, str], str], track: Optional[AnyTrack] = None) -> int:
+ def add_keys(self, service: str, kid_keys: dict[UUID | str, str], track: AnyTrack | None = None) -> int:
"""Post the pairs of ``track`` the server neither served nor accepted; always 0, as it does not say what it stored.
It runs on the vault writer thread and is silent: it drops a failed post and logs nothing. The wait is
@@ -884,7 +878,7 @@ class ServerVault(Vault):
def get_services(self) -> Iterator[str]:
return iter(())
- def flag_bad_key(self, service: str, kid: Union[UUID, str], key: str, source: str) -> None:
+ def flag_bad_key(self, service: str, kid: UUID | str, key: str, source: str) -> None:
self.service.report_bad_key(UUID(str(kid)), key)
@@ -902,7 +896,7 @@ class RemoteService:
ANIME: bool = False
DAILY: bool = False
server_cdm_type: str = "widevine"
- channel: Optional[Channel] = None
+ channel: Channel | None = None
def __init__(
self,
@@ -912,7 +906,7 @@ class RemoteService:
server_url: str,
api_key: str,
services_config: dict,
- service_params: Optional[Dict[str, Any]] = None,
+ service_params: dict[str, Any] | None = None,
) -> None:
self.__class__.__name__ = service_tag
console.print(Padding(Rule(f"[rule.text]Service: {service_tag} (Remote)"), (1, 2)))
@@ -925,28 +919,28 @@ class RemoteService:
self.ctx = ctx
self._service_params = service_params or {}
self.log = logging.getLogger(service_tag)
- self.credential: Optional[Credential] = None
- self.current_region: Optional[str] = None
+ self.credential: Credential | None = None
+ self.current_region: str | None = None
self.title_cache = None
- self._titles: Optional[Titles_T] = None
- self._tracks_by_title: Dict[str, Tracks] = {}
- self._chapters_by_title: Dict[str, list] = {}
- self._session_id: Optional[str] = None
+ self._titles: Titles_T | None = None
+ self._tracks_by_title: dict[str, Tracks] = {}
+ self._chapters_by_title: dict[str, list] = {}
+ self._session_id: str | None = None
self.client_licensed: set[str] = set() # track ids this machine's device licenses by challenge relay
- self.deferred_refusals: Dict[str, str] = {}
- self.server_vault_keys: Dict[UUID, str] = {}
+ self.deferred_refusals: dict[str, str] = {}
+ self.server_vault_keys: dict[UUID, str] = {}
self.served_keys: set[tuple[UUID, str]] = set()
self.server_vault = ServerVault(self)
- self._segment_filters: Dict[str, Callable[[Any], bool]] = {}
+ self._segment_filters: dict[str, Callable[[Any], bool]] = {}
self._sample_decrypt_tracks: set[str] = set()
self._input_bridge: Any = None # a serve relaying for a REST client sets one, as it does for a Service
# what a login waiting on the user (a pair code, an approval link) last showed; None otherwise
- self.auth_notice: Optional[str] = None
+ self.auth_notice: str | None = None
self._reopen_lock = Lock()
- self._current_title: Optional[Title_T] = None
+ self._current_title: Title_T | None = None
# client title and track id -> the id a reopened session gave the same title or track
- self._title_alias: Dict[str, str] = {}
- self._track_alias: Dict[str, str] = {}
+ self._title_alias: dict[str, str] = {}
+ self._track_alias: dict[str, str] = {}
self._session = requests.Session()
self._session.headers.update(config.headers)
@@ -970,7 +964,7 @@ class RemoteService:
self._server_vault = False
self._server_device = False
self._local_vaults_only = False
- self._server_accounts: Optional[dict] = services_config.get("_server_accounts")
+ self._server_accounts: dict | None = services_config.get("_server_accounts")
self._anonymous_search = bool(services_config.get("_anonymous_search"))
# read before apply_service_config merges the server's values into the same section
own = ci_get(config.services, service_tag) or {}
@@ -1017,7 +1011,7 @@ class RemoteService:
"""Search on the server, which logs in to the service itself with the login material sent here."""
params = self.ctx.parent.params if self.ctx.parent else {}
profile = params.get("profile")
- data: Dict[str, Any] = {"service": self.service_tag, "query": self.title_id}
+ data: dict[str, Any] = {"service": self.service_tag, "query": self.title_id}
if profile:
data["profile"] = profile
if not self._anonymous_search:
@@ -1041,7 +1035,7 @@ class RemoteService:
result["id"], result["title"], result.get("description"), result.get("label"), result.get("url")
)
- def client_login(self, profile: Optional[str]) -> ClientLogin:
+ def client_login(self, profile: str | None) -> ClientLogin:
"""The credentials, cookies and cache to send, or nothing when the server manages the account."""
login = ClientLogin()
if self._server_accounts is not None:
@@ -1054,7 +1048,7 @@ class RemoteService:
login["cache"] = cache
return login
- def require_reachable_proxy(self, proxy: Optional[str]) -> None:
+ def require_reachable_proxy(self, proxy: str | None) -> None:
"""Refuse a proxy on this machine when the server is elsewhere: the server cannot reach it."""
if proxy and is_loopback(proxy) and not is_loopback(self.client.server_url):
raise click.ClickException("--remote cannot use a proxy on this machine without --local-proxy")
@@ -1074,7 +1068,7 @@ class RemoteService:
)
return f"tunnel:{tunnel.id}"
- def authenticate(self, cookies: Optional[CookieJar] = None, credential: Optional[Credential] = None) -> None:
+ def authenticate(self, cookies: CookieJar | None = None, credential: Credential | None = None) -> None:
self.credential = credential
profile = self.ctx.parent.params.get("profile") if self.ctx.parent else None
proxy = self.ctx.parent.params.get("proxy") if self.ctx.parent else None
@@ -1275,7 +1269,7 @@ class RemoteService:
"falling back to the local CDM"
)
- def adopt_session_cdm(self, server_cdm: bool, max_height: Optional[int]) -> None:
+ def adopt_session_cdm(self, server_cdm: bool, max_height: int | None) -> None:
"""Take the server's choice of who licenses this remote session, and say why when a cap made it.
A remote session on the server's lent device keeps the server-CDM flow: dl checks the local vaults, then asks the
@@ -1301,7 +1295,7 @@ class RemoteService:
message += "; pass a higher -q to license above it with your own device"
self.log.info(message)
- def session_call(self, call: Callable[[Optional[str]], T]) -> T:
+ def session_call(self, call: Callable[[str | None], T]) -> T:
"""Run ``call`` with the session id, and once more on a new session when the server lost the old one."""
session_id = self._session_id
if _mute.recovering:
@@ -1319,7 +1313,7 @@ class RemoteService:
raise lost
return call(self._session_id)
- def recover(self, session_id: Optional[str], kind: str) -> bool:
+ def recover(self, session_id: str | None, kind: str) -> bool:
"""Whether a call that failed with ``kind`` can run again, on the same session or on a new one.
The same session takes the call again only after a connect error, as a timed-out call may have run.
@@ -1451,7 +1445,7 @@ class RemoteService:
self._titles = Movies(titles_list)
return self._titles
- def get_titles_cached(self, title_id: Optional[str] = None) -> Titles_T:
+ def get_titles_cached(self, title_id: str | None = None) -> Titles_T:
"""Apply the client's local title_map to titles fetched from the remote server.
Lets users rename titles for remote services they do not have installed locally.
@@ -1513,11 +1507,11 @@ class RemoteService:
def decrypts_samples(self, track: AnyTrack) -> bool:
return self.server_track_id(track.id) in self._sample_decrypt_tracks
- def get_sample_decrypter(self, track: AnyTrack, entry: int) -> Union[bytes, cbcs.SampleDecrypter]:
+ def get_sample_decrypter(self, track: AnyTrack, entry: int) -> bytes | cbcs.SampleDecrypter:
"""Ask the server how `entry` decrypts. A decrypter sends the samples to the server in batches."""
- def samples(body: bytes) -> Dict[str, Any]:
- def call(sid: Optional[str]) -> Dict[str, Any]:
+ def samples(body: bytes) -> dict[str, Any]:
+ def call(sid: str | None) -> dict[str, Any]:
query = urlencode({"track_id": self.server_track_id(track.id), "entry": entry})
return self.client.request("post", SAMPLES_ROUTE.format(session_id=sid) + f"?{query}", body=body)
@@ -1589,7 +1583,7 @@ class RemoteService:
drm_type = cdm_system(self.local_cdm) or "widevine"
self.log.debug(f"Requesting server CDM keys (server_cdm_type={drm_type})")
- capped: Dict[str, Any] = {}
+ capped: dict[str, Any] = {}
try:
with console.status("Retrieving Remote License...", spinner="dots"):
resp = cast(
@@ -1655,7 +1649,7 @@ class RemoteService:
self.deferred_refusals[str(track.id)] = e.message
self.log.debug(f"{e.message}; trying the local vaults first")
- def license_locally(self, track: AnyTrack, refusal: Dict[str, Any]) -> None:
+ def license_locally(self, track: AnyTrack, refusal: dict[str, Any]) -> None:
"""Hand a track the server CDM refused to license live to this machine's own device.
dl then licenses it through the challenge relay. An HLS track with no DRM yet passes, as its
@@ -1714,11 +1708,11 @@ class RemoteService:
"""True when the server handed ``track`` to this machine's own CDM to license."""
return str(track.id) in self.client_licensed
- def vault_source(self, kid: UUID, key: str) -> Optional[Vault]:
+ def vault_source(self, kid: UUID, key: str) -> Vault | None:
"""The server vault when it served ``key`` for ``kid``, else None."""
return self.server_vault if self.server_vault_keys.get(kid) == key else None
- def note_vault_keys(self, keys: Dict[str, str], vault_kids: set[str]) -> None:
+ def note_vault_keys(self, keys: dict[str, str], vault_kids: set[str]) -> None:
"""Remember every served pair, and which of them a server vault supplied. ``served_keys`` also takes each pair the server accepted."""
for kid_hex, key in keys.items():
kid = UUID(hex=kid_hex)
@@ -1793,17 +1787,13 @@ class RemoteService:
raw = self._chapters_by_title.get(title_id, [])
return Chapters([Chapter(ch["timestamp"], ch.get("name")) for ch in raw])
- def get_widevine_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> Optional[Union[bytes, str]]:
+ def get_widevine_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | None:
return self.proxy_license(challenge, track, "widevine")
- def get_playready_license(
- self, *, challenge: bytes, title: Title_T, track: AnyTrack
- ) -> Optional[Union[bytes, str]]:
+ def get_playready_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | None:
return self.proxy_license(challenge, track, "playready")
- def get_clearkey_license(
- self, *, challenge: bytes, title: Title_T, track: AnyTrack
- ) -> Optional[Union[bytes, str, dict]]:
+ def get_clearkey_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | dict | None:
return None
def get_widevine_service_certificate(
@@ -1812,7 +1802,7 @@ class RemoteService:
challenge: bytes,
title: Title_T,
track: AnyTrack,
- ) -> Optional[Union[bytes, str]]:
+ ) -> bytes | str | None:
# a missing certificate is legal (services may not use one), so a failed fetch continues without one
resp = cast(
LicenseReply,
@@ -1830,7 +1820,7 @@ class RemoteService:
)
return base64.b64decode(certificate) if (certificate := resp.get("license")) else None
- def license_track(self, track: AnyTrack, drm: Any, kid: Optional[UUID] = None) -> Optional[dict[UUID, str]]:
+ def license_track(self, track: AnyTrack, drm: Any, kid: UUID | None = None) -> dict[UUID, str] | None:
"""The content keys the server CDM licenses for ``drm`` of ``track``, or None when the server hands it to this machine.
The request sends the header of ``drm`` when it is of a system the server licenses, as a playlist can name a
@@ -1872,7 +1862,7 @@ class RemoteService:
self.license_locally(track, resp.get("details") or {})
return None
- def proxy_license(self, challenge: Union[bytes, str], track: AnyTrack, drm_type: str) -> bytes:
+ def proxy_license(self, challenge: bytes | str, track: AnyTrack, drm_type: str) -> bytes:
"""Relay a licence challenge to the server. A failed relay raises ClickException, so dl's licence fallbacks see it."""
if isinstance(challenge, str):
challenge = challenge.encode("utf-8")
@@ -1930,7 +1920,7 @@ class RemoteService:
if self.client.tunnel:
self.client.tunnel.stop()
- def save_returned_cache(self, cache_data: Dict[str, str], profile: Optional[str] = None) -> None:
+ def save_returned_cache(self, cache_data: dict[str, str], profile: str | None = None) -> None:
"""Save cache files returned by the server to the local cache directory.
The server returns updated cache files (e.g. refreshed tokens) on
@@ -1980,7 +1970,7 @@ class RemoteService:
self.log.info(f"Saved {saved} cache file(s) from server")
- def load_cache_files(self, profile: Optional[str] = None) -> Dict[str, str]:
+ def load_cache_files(self, profile: str | None = None) -> dict[str, str]:
"""Collect the cache files to forward, and withhold other profiles' files.
The client cannot rely on the server to filter, so it sends only the files
@@ -2001,7 +1991,7 @@ class RemoteService:
return {}
relevant = cache_key_filter(self.service_tag, profile)
- files: Dict[str, str] = {}
+ files: dict[str, str] = {}
for f in sorted(cache_dir.rglob("*.json")):
key = f.relative_to(cache_dir).as_posix()[: -len(".json")]
if f.stem.startswith("titles_") or not safe_cache_key(key):
diff --git a/unshackle/core/run_plan.py b/unshackle/core/run_plan.py
index 5f24afb1..c6faf6ac 100644
--- a/unshackle/core/run_plan.py
+++ b/unshackle/core/run_plan.py
@@ -1,8 +1,9 @@
"""The dl front door: one checked run plan from a dl click parse or a REST API job, and what the run gave back."""
+from collections.abc import Collection, Mapping
from dataclasses import dataclass, field
from pathlib import Path
-from typing import Any, Collection, Mapping, Optional, Union
+from typing import Any
import click
from click.core import ParameterSource
@@ -39,7 +40,7 @@ class RunOutcome:
files: list[Path] = field(default_factory=list)
skipped_subtitles: list[Any] = field(default_factory=list)
- error: Optional[BaseException] = None
+ error: BaseException | None = None
@dataclass(frozen=True)
@@ -60,10 +61,10 @@ class RunPlan:
def validate_metadata_ids(
- tmdb_id: Optional[int],
- imdb_id: Optional[str],
- tvdb_id: Optional[int],
- anilist_id: Optional[Union[int, str]] = None,
+ tmdb_id: int | None,
+ imdb_id: str | None,
+ tvdb_id: int | None,
+ anilist_id: int | str | None = None,
) -> None:
"""Reject ID flags that conflict, or that no configured metadata provider could ever find.
@@ -95,7 +96,7 @@ def validate_metadata_ids(
raise PlanError(f"{flag} needs the {' or '.join(names)} provider, which your metadata_providers config leaves out.")
-def bitrate_range(value: Optional[str], flag: str, example: str) -> Optional[tuple[int, int]]:
+def bitrate_range(value: str | None, flag: str, example: str) -> tuple[int, int] | None:
"""A ``MIN-MAX`` bitrate range as (low, high), in either order."""
if not value:
return None
@@ -174,7 +175,7 @@ def check_options(params: Mapping[str, Any]) -> None:
raise PlanError("Unable to run hybrid mode: dovi_tool not found")
-def api_plan(params: Mapping[str, Any], client_keys: Optional[Collection[str]] = None) -> RunPlan:
+def api_plan(params: Mapping[str, Any], client_keys: Collection[str] | None = None) -> RunPlan:
"""The checked run plan of a REST API job from its parameters, by API name.
A value counts as typed on the command line when its API name is in ``client_keys`` (every parameter when None),
diff --git a/unshackle/core/search_result.py b/unshackle/core/search_result.py
index 1ffe6ca7..58786cd3 100644
--- a/unshackle/core/search_result.py
+++ b/unshackle/core/search_result.py
@@ -1,14 +1,11 @@
-from typing import Optional, Union
-
-
class SearchResult:
def __init__(
self,
- id_: Union[str, int],
+ id_: str | int,
title: str,
- description: Optional[str] = None,
- label: Optional[str] = None,
- url: Optional[str] = None,
+ description: str | None = None,
+ label: str | None = None,
+ url: str | None = None,
) -> None:
"""
A search result for any title type a service can give.
@@ -40,7 +37,7 @@ class SearchResult:
self.label = label
self.url = url
- def to_dict(self) -> dict[str, Union[str, int, None]]:
+ def to_dict(self) -> dict[str, str | int | None]:
"""The result as the REST API returns it."""
return {
"id": self.id,
diff --git a/unshackle/core/service.py b/unshackle/core/service.py
index e6eb8f2e..7f012a3b 100644
--- a/unshackle/core/service.py
+++ b/unshackle/core/service.py
@@ -1,11 +1,11 @@
import logging
import time
from abc import ABCMeta, abstractmethod
-from collections.abc import Callable, Generator
+from collections.abc import Callable, Generator, Sequence
from dataclasses import dataclass, field
from http.cookiejar import CookieJar
from pathlib import Path
-from typing import TYPE_CHECKING, Any, Optional, Sequence, TypeVar, Union
+from typing import TYPE_CHECKING, Any, TypeVar, Union
if TYPE_CHECKING:
from unshackle.core.api.input_bridge import InputBridge
@@ -132,7 +132,7 @@ class TrackRequest:
generate_dv: bool = False
-def sanitize_proxy_for_log(uri: Optional[str], mask_host: bool = False) -> Optional[str]:
+def sanitize_proxy_for_log(uri: str | None, mask_host: bool = False) -> str | None:
"""
Sanitise a proxy URI for logs by masking any embedded userinfo (username/password).
@@ -166,10 +166,10 @@ class Service(metaclass=ABCMeta):
DAILY: bool = False # catalog is daily/date-based. episodes are named by air date. Title.daily overrides per title.
ANONYMOUS_SEARCH: bool = False # search() needs no login; a search then skips cookies and authenticate().
# vault namespace override; when set, key vault read/write uses this tag instead of the service's own.
- VAULT_TAG: Optional[str] = None
+ VAULT_TAG: str | None = None
# Auth methods the service accepts ("cookies"/"credentials"); when None the REST /services
# endpoint infers them from authenticate().
- AUTH_METHODS: Optional[tuple[str, ...]] = None
+ AUTH_METHODS: tuple[str, ...] | None = None
# Config keys a remote client may supply for a session its own device licenses (a device identity
# such as an ESN); the server's own values for these keys are withheld from that session.
CLIENT_CONFIG: tuple[str, ...] = ()
@@ -193,9 +193,9 @@ class Service(metaclass=ABCMeta):
self.cache_dir = config.directories.cache / self.__class__.__name__
self.ctx = ctx
- self.credential: Optional[Credential] = None # Will be set in authenticate()
+ self.credential: Credential | None = None # Will be set in authenticate()
self.current_region = None # Will be set based on proxy/geolocation
- self._input_bridge: Optional[InputBridge] = None
+ self._input_bridge: InputBridge | None = None
# Set track request from CLI params - services can read/override in their __init__
vcodec = ctx.parent.params.get("vcodec") if ctx.parent else None
@@ -308,7 +308,7 @@ class Service(metaclass=ABCMeta):
run_proxy.watch(type(self), run_proxy.proxy_of(self.session))
@classmethod
- def is_region_allowed(cls, region: Optional[str]) -> bool:
+ def is_region_allowed(cls, region: str | None) -> bool:
"""True when an exit IP in `region` (two-letter region code, any case) can use the service.
An unknown region (None or empty) is allowed, because there is nothing to compare.
@@ -357,7 +357,7 @@ class Service(metaclass=ABCMeta):
held = {Tracks.signature(track) for track in all_tracks}
all_tracks.add([track for track in tracks if Tracks.signature(track) not in held], warn_only=True)
- codecs: Sequence[Optional[Video.Codec]] = self.track_request.codecs or [None]
+ codecs: Sequence[Video.Codec | None] = self.track_request.codecs or [None]
ranges = self.track_request.ranges or [Video.Range.SDR]
for range_val in ranges:
@@ -445,7 +445,7 @@ class Service(metaclass=ABCMeta):
"""
return []
- def authenticate(self, cookies: Optional[CookieJar] = None, credential: Optional[Credential] = None) -> None:
+ def authenticate(self, cookies: CookieJar | None = None, credential: Credential | None = None) -> None:
"""
Authenticate the Service with Cookies and/or Credentials (Email/Username and Password).
@@ -480,7 +480,7 @@ class Service(metaclass=ABCMeta):
return prompt_user(prompt)
def wait_for_approval(
- self, message: str, check: Callable[[], Optional[T]], timeout: float, interval: float = 3.0
+ self, message: str, check: Callable[[], T | None], timeout: float, interval: float = 3.0
) -> T:
"""Show ``message``, then call ``check`` until it returns a value.
@@ -518,7 +518,7 @@ class Service(metaclass=ABCMeta):
def get_widevine_service_certificate(
self, *, challenge: bytes, title: Title_T, track: AnyTrack
- ) -> Optional[Union[bytes, str]]:
+ ) -> bytes | str | None:
"""
Get the Widevine Service Certificate used for Privacy Mode.
@@ -531,7 +531,7 @@ class Service(metaclass=ABCMeta):
Decode the data, return as is to reduce unnecessary computations.
"""
- def get_widevine_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> Optional[Union[bytes, str]]:
+ def get_widevine_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | None:
"""
Get a Widevine License message by sending a License Request (challenge).
@@ -550,9 +550,7 @@ class Service(metaclass=ABCMeta):
Decode the data, return as is to reduce unnecessary computations.
"""
- def get_playready_license(
- self, *, challenge: bytes, title: Title_T, track: AnyTrack
- ) -> Optional[Union[bytes, str]]:
+ def get_playready_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | None:
"""
Get a PlayReady License message by sending a License Request (challenge).
@@ -576,9 +574,7 @@ class Service(metaclass=ABCMeta):
**declared_kwargs(self.get_widevine_license, {"challenge": challenge, "title": title, "track": track})
)
- def get_clearkey_license(
- self, *, challenge: bytes, title: Title_T, track: AnyTrack
- ) -> Optional[Union[bytes, str, dict]]:
+ def get_clearkey_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | dict | None:
"""
Get a W3C ClearKey License (JWK Set) by sending a License Request (challenge).
@@ -612,7 +608,7 @@ class Service(metaclass=ABCMeta):
This can be useful to store information on each title that you need later, like any sub-asset IDs, or such.
"""
- def get_titles_cached(self, title_id: Optional[str] = None) -> Titles_T:
+ def get_titles_cached(self, title_id: str | None = None) -> Titles_T:
"""
Cached wrapper around get_titles() to reduce redundant API calls.
@@ -749,7 +745,7 @@ class Service(metaclass=ABCMeta):
track: The downloaded Track object.
"""
- def on_track_decrypted(self, track: AnyTrack, drm: DRM_T, segment: Optional[m3u8.Segment] = None) -> None:
+ def on_track_decrypted(self, track: AnyTrack, drm: DRM_T, segment: m3u8.Segment | None = None) -> None:
"""
Called when a Track has finished decrypting.
diff --git a/unshackle/core/service_repo.py b/unshackle/core/service_repo.py
index e8a8cd9d..1ed7fb16 100644
--- a/unshackle/core/service_repo.py
+++ b/unshackle/core/service_repo.py
@@ -6,7 +6,6 @@ import shutil
import subprocess # nosec B404 - git is resolved via binaries.find, args are composed locally
import time
from pathlib import Path
-from typing import Optional
from unshackle.core import binaries
@@ -63,10 +62,10 @@ def is_repo_spec(value: object) -> bool:
return bool(SHORTHAND_RE.match(base)) and not Path(value).expanduser().exists()
-def parse_spec(spec: str) -> tuple[str, Optional[str], str]:
+def parse_spec(spec: str) -> tuple[str, str | None, str]:
"""Return (clone_url, branch, dest_name). This function honours `@branch` for http/shorthand, not for ssh."""
is_ssh = spec.startswith(("git@", "ssh://"))
- branch: Optional[str] = None
+ branch: str | None = None
url = spec
if not is_ssh and "@" in spec:
url, branch = spec.rsplit("@", 1)
@@ -96,7 +95,7 @@ def repos_base() -> Path:
return Config._Directories.namespace_dir / "services" / "_repos"
-def resolve_service_repo(spec: str, *, ttl: int = DEFAULT_TTL, force: bool = False) -> Optional[Path]:
+def resolve_service_repo(spec: str, *, ttl: int = DEFAULT_TTL, force: bool = False) -> Path | None:
"""Find the local clone dir of a repo spec.
First use clones it. Only a TTL-stale clone touches the network. With ``force=True``
@@ -116,7 +115,7 @@ def resolve_service_repo(spec: str, *, ttl: int = DEFAULT_TTL, force: bool = Fal
return dest
-def clone(url: str, branch: Optional[str], dest: Path, stamp: Path) -> Optional[Path]:
+def clone(url: str, branch: str | None, dest: Path, stamp: Path) -> Path | None:
if not binaries.Git:
log.error("git not found on PATH; cannot fetch service repo %s", url)
return None
@@ -151,7 +150,7 @@ def pull(dest: Path, stamp: Path) -> None:
write_stamp(stamp) # stamp regardless so a flaky remote can't trigger a fetch every run (force overrides)
-def refresh_repo(spec: str) -> tuple[Optional[Path], list[str]]:
+def refresh_repo(spec: str) -> tuple[Path | None, list[str]]:
"""Force-sync a repo to upstream and return (clone dir, git-style per-service change lines).
Used by the manual ``refresh-services`` command. Each line is one service tag with a status
@@ -173,7 +172,7 @@ def refresh_repo(spec: str) -> tuple[Optional[Path], list[str]]:
return dest, lines
-def head(dest: Path) -> Optional[str]:
+def head(dest: Path) -> str | None:
r = subprocess.run([str(binaries.Git), "-C", str(dest), "rev-parse", "HEAD"], capture_output=True) # nosec B603
return r.stdout.decode(errors="ignore").strip() if r.returncode == 0 else None
@@ -188,7 +187,7 @@ def local_dirty_services(dest: Path) -> list[str]:
return sorted({line.split("/")[0] for line in r.stdout.decode(errors="ignore").splitlines() if line})
-def changed_services(dest: Path, old: Optional[str], new: Optional[str]) -> list[str]:
+def changed_services(dest: Path, old: str | None, new: str | None) -> list[str]:
"""Summarise a HEAD old->new diff as one ``+TAG``/``~TAG``/``-TAG`` token per top-level service directory."""
if not old or not new or old == new:
return []
diff --git a/unshackle/core/services.py b/unshackle/core/services.py
index 589bb7ab..b640eb79 100644
--- a/unshackle/core/services.py
+++ b/unshackle/core/services.py
@@ -7,9 +7,10 @@ import re
import sys
import threading
import time
+from collections.abc import Iterable
from importlib.machinery import EXTENSION_SUFFIXES
from pathlib import Path
-from typing import Any, Iterable
+from typing import Any
import click
from click.core import ParameterSource
@@ -437,8 +438,8 @@ class Services(click.Group):
if not available_services:
raise click.ClickException(
f"There are no Services added yet, therefore the '{name}' Service could not be found."
- )
- raise click.ClickException(f"{e}, available: {', '.join(available_services)}")
+ ) from None
+ raise click.ClickException(f"{e}, available: {', '.join(available_services)}") from e
if hasattr(service, "cli"):
cli = service.cli
diff --git a/unshackle/core/session.py b/unshackle/core/session.py
index 42efc80b..1e50ecdc 100644
--- a/unshackle/core/session.py
+++ b/unshackle/core/session.py
@@ -11,10 +11,10 @@ import sys
import time
from collections.abc import Iterator, MutableMapping
from copy import copy
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from email.utils import parsedate_to_datetime
from http.cookiejar import Cookie, CookieJar
-from typing import Any, Optional, Union
+from typing import Any
from urllib.parse import urlencode, urlparse, urlunparse
import rnet
@@ -103,7 +103,7 @@ class RnetResponseHeaders(MutableMapping):
def __len__(self) -> int:
return self._map.keys_len()
- def get(self, key: str, default: Optional[str] = None) -> Optional[str]: # type: ignore[override]
+ def get(self, key: str, default: str | None = None) -> str | None: # type: ignore[override]
val = self._map.get(key)
if val is None:
return default
@@ -118,9 +118,9 @@ class RnetResponse:
def __init__(self, resp: Any) -> None:
self._resp = resp
- self._headers: Optional[RnetResponseHeaders] = None
- self._content: Optional[bytes] = None
- self._text: Optional[str] = None
+ self._headers: RnetResponseHeaders | None = None
+ self._content: bytes | None = None
+ self._text: str | None = None
self._streamed = False
@property
@@ -142,7 +142,7 @@ class RnetResponse:
return str(self._resp.url)
@property
- def content_length(self) -> Optional[int]:
+ def content_length(self) -> int | None:
return self._resp.content_length
@property
@@ -200,7 +200,7 @@ class RnetResponse:
response=self, # type: ignore[arg-type]
)
- def iter_content(self, chunk_size: Optional[int] = None) -> Iterator[bytes]:
+ def iter_content(self, chunk_size: int | None = None) -> Iterator[bytes]:
"""Re-chunk rnet's variable-size data into fixed-size pieces."""
self._streamed = True
if chunk_size is None or chunk_size <= 0:
@@ -243,7 +243,7 @@ def utf8_text(res: Response | RnetResponse) -> str:
class RnetSessionHeaders(CaseInsensitiveDict):
"""Dict-like headers that write to the rnet client through update()."""
- def __init__(self, session: Optional[RnetSession] = None) -> None:
+ def __init__(self, session: RnetSession | None = None) -> None:
self._session = session
self._client: Any = None
super().__init__()
@@ -296,7 +296,7 @@ class RnetCookieAdapter(MutableMapping):
answers a lookup by name.
"""
- def __init__(self, client: Any, session: Optional[RnetSession] = None) -> None:
+ def __init__(self, client: Any, session: RnetSession | None = None) -> None:
self._client = client
self._session = session
self._store: dict[tuple[str, str, str], Cookie] = {}
@@ -351,7 +351,7 @@ class RnetCookieAdapter(MutableMapping):
for cookie in self.snapshot():
self.push(cookie)
- def client_urls(self, domain: Optional[str] = None, name: Optional[str] = None) -> list[str]:
+ def client_urls(self, domain: str | None = None, name: str | None = None) -> list[str]:
"""URLs the rnet cookie jar could hold a cookie under.
rnet keys its jar by URL, removes a cookie only at its exact path, and cannot list the
@@ -368,7 +368,7 @@ class RnetCookieAdapter(MutableMapping):
paths = {c.path for c in cookies if c.path and c.path != "/" and (name is None or c.name == name)}
return sorted(hosts | {url + path for url in hosts for path in paths})
- def remove_cookie_on_client(self, name: str, domain: Optional[str] = None) -> None:
+ def remove_cookie_on_client(self, name: str, domain: str | None = None) -> None:
"""Drop a cookie from the rnet cookie jar; call it before the store forgets the cookie's paths.
The client is built with cookie_store=True, so a cookie the server set lives in that
@@ -394,12 +394,12 @@ class RnetCookieAdapter(MutableMapping):
parsed = urlparse(response.url)
host = parsed.hostname or ""
default_path = (parsed.path[: parsed.path.rfind("/")] or "/") if parsed.path.startswith("/") else "/"
- now = datetime.now(timezone.utc)
+ now = datetime.now(UTC)
for server_cookie in server_cookies:
path = server_cookie.path if (server_cookie.path or "").startswith("/") else default_path
expires, max_age = server_cookie.expires, server_cookie.max_age
if expires is not None and expires.tzinfo is None:
- expires = expires.replace(tzinfo=timezone.utc)
+ expires = expires.replace(tzinfo=UTC)
expired = (max_age is not None and max_age.total_seconds() <= 0) or (expires is not None and expires <= now)
for cookie in self.snapshot():
domain = cookie.domain or ""
@@ -440,8 +440,8 @@ class RnetCookieAdapter(MutableMapping):
self.add(create_cookie(name, str(value)))
def get( # type: ignore[override]
- self, name: str, default: Optional[str] = None, domain: Optional[str] = None, path: Optional[str] = None
- ) -> Optional[str]:
+ self, name: str, default: str | None = None, domain: str | None = None, path: str | None = None
+ ) -> str | None:
"""The latest value of *name*."""
for cookie in reversed(self.snapshot()):
if cookie.name == name and domain in (None, cookie.domain) and path in (None, cookie.path):
@@ -476,11 +476,11 @@ class RnetCookieAdapter(MutableMapping):
def __bool__(self) -> bool:
return bool(self._store)
- def get_dict(self, domain: Optional[str] = None, path: Optional[str] = None) -> dict[str, str]:
+ def get_dict(self, domain: str | None = None, path: str | None = None) -> dict[str, str]:
"""Return cookies as a plain dict (requests RequestsCookieJar compat), filtered by exact domain and path."""
return {c.name: c.value or "" for c in self.snapshot() if domain in (None, c.domain) and path in (None, c.path)}
- def clear(self, domain: Optional[str] = None, path: Optional[str] = None, name: Optional[str] = None) -> None:
+ def clear(self, domain: str | None = None, path: str | None = None, name: str | None = None) -> None:
"""Remove cookies (requests RequestsCookieJar compat).
- ``clear()`` removes all cookies.
@@ -524,7 +524,7 @@ class RnetProxyDict(dict):
Supports both lazy (pre-client) and live (post-client) proxy updates.
"""
- def __init__(self, session: "RnetSession") -> None:
+ def __init__(self, session: RnetSession) -> None:
super().__init__()
self._session = session
@@ -545,7 +545,7 @@ class RnetProxyDict(dict):
class MaxRetriesError(Exception):
- def __init__(self, message: str, cause: Optional[Exception] = None) -> None:
+ def __init__(self, message: str, cause: Exception | None = None) -> None:
super().__init__(message)
self.__cause__ = cause
@@ -595,9 +595,9 @@ class RnetSession:
max_retries: int = MAX_RETRIES,
backoff_factor: float = BACKOFF_FACTOR,
max_backoff: float = MAX_BACKOFF,
- status_forcelist: Optional[list[int]] = None,
- allowed_methods: Optional[set[str]] = None,
- catch_exceptions: Optional[tuple[type[Exception], ...]] = None,
+ status_forcelist: list[int] | None = None,
+ allowed_methods: set[str] | None = None,
+ catch_exceptions: tuple[type[Exception], ...] | None = None,
**session_kwargs: Any,
) -> None:
self.max_retries = max_retries
@@ -643,7 +643,7 @@ class RnetSession:
client_kwargs["danger_accept_invalid_certs"] = True
self._client_kwargs = dict(client_kwargs)
- self._client: Optional[rnet.BlockingClient] = None
+ self._client: rnet.BlockingClient | None = None
self._origins: set[str] = set()
self.headers = RnetSessionHeaders(self)
@@ -661,7 +661,7 @@ class RnetSession:
self.proxies.update({"all": proxy_url})
@property
- def impersonate_name(self) -> Optional[str]:
+ def impersonate_name(self) -> str | None:
"""Preset name (e.g. 'Chrome131') for rebuilding this HTTP session in another process.
rnet enums stringify as 'Impersonate.Chrome131'. Return the trailing name, or None
@@ -787,7 +787,7 @@ class RnetSession:
for origin, header in exported.items():
self.set_cookie_header(client, origin, header)
- def build_url(self, url: str, params: Optional[Any] = None) -> str:
+ def build_url(self, url: str, params: Any | None = None) -> str:
"""Encode params into the URL (rnet ignores the params kwarg).
Accepts the same shapes as requests: a mapping, a sequence of pairs, or a
@@ -807,19 +807,19 @@ class RnetSession:
query = parsed.query + separator + extra if parsed.query else extra
return urlunparse(parsed._replace(query=query))
- def get_sleep_time(self, response: Optional[RnetResponse], attempt: int) -> Optional[float]:
+ def get_sleep_time(self, response: RnetResponse | None, attempt: int) -> float | None:
if response:
retry_after = response.headers.get("Retry-After")
if retry_after:
- wait: Optional[float] = None
+ wait: float | None = None
try:
wait = float(retry_after)
except ValueError:
try:
retry_date = parsedate_to_datetime(retry_after)
if retry_date.tzinfo is None:
- retry_date = retry_date.replace(tzinfo=timezone.utc)
- wait = (retry_date - datetime.now(timezone.utc)).total_seconds()
+ retry_date = retry_date.replace(tzinfo=UTC)
+ wait = (retry_date - datetime.now(UTC)).total_seconds()
except Exception:
# parsedate_to_datetime itself raises ValueError on malformed dates
# (Python >= 3.10); an unusable header must not escape the retry loop
@@ -898,8 +898,8 @@ class RnetSession:
if method_upper not in self.allowed_methods:
return self.absorb_cookies(RnetResponse(client.request(rnet_method, url, **kwargs)))
- last_exception: Optional[Exception] = None
- response: Optional[RnetResponse] = None
+ last_exception: Exception | None = None
+ response: RnetResponse | None = None
for attempt in range(max_retries + 1):
try:
@@ -1002,11 +1002,11 @@ class RnetSession:
pass
-AnySession = Union[Session, RnetSession]
+AnySession = Session | RnetSession
def session(
- browser: Optional[str] = None,
+ browser: str | None = None,
**kwargs: Any,
) -> RnetSession:
"""
diff --git a/unshackle/core/temp.py b/unshackle/core/temp.py
index 655329a9..94ea75d2 100644
--- a/unshackle/core/temp.py
+++ b/unshackle/core/temp.py
@@ -7,9 +7,10 @@ import os
import shutil
import time
import uuid
+from collections.abc import Callable, Iterator
from contextlib import contextmanager
from pathlib import Path
-from typing import Callable, Iterator, Optional, ParamSpec, TypeVar
+from typing import ParamSpec, TypeVar
from filelock import FileLock, Timeout
@@ -69,7 +70,7 @@ def sweep_task_dirs(root: Path) -> None:
entry.unlink(missing_ok=True)
-def resume_stash() -> Optional[Path]:
+def resume_stash() -> Path | None:
"""The dir beside the task dirs that keeps a failed track's segments for the next run.
None outside a task dir: there config.directories.temp itself outlives the run.
@@ -132,7 +133,7 @@ def restore_segments(save_dir: Path) -> None:
@contextmanager
-def task_temp_dir(task_id: Optional[str] = None) -> Iterator[Path]:
+def task_temp_dir(task_id: str | None = None) -> Iterator[Path]:
"""Point config.directories.temp at a private dir for this task. Remove it on any exit."""
root = config.directories.temp
root.mkdir(parents=True, exist_ok=True)
diff --git a/unshackle/core/title_cacher.py b/unshackle/core/title_cacher.py
index afd126fb..dcd91104 100644
--- a/unshackle/core/title_cacher.py
+++ b/unshackle/core/title_cacher.py
@@ -2,8 +2,8 @@ from __future__ import annotations
import hashlib
import logging
+from collections.abc import Callable
from datetime import datetime, timedelta
-from typing import Callable, Optional
from unshackle.core.cacher import Cacher
from unshackle.core.config import config
@@ -29,9 +29,7 @@ class TitleCacher:
self.stats = {"hits": 0, "misses": 0, "fallbacks": 0}
self.no_cache = False
- def generate_cache_key(
- self, title_id: str, region: Optional[str] = None, account_hash: Optional[str] = None
- ) -> str:
+ def generate_cache_key(self, title_id: str, region: str | None = None, account_hash: str | None = None) -> str:
"""
Make a unique cache key for title data.
@@ -63,8 +61,8 @@ class TitleCacher:
self,
title_id: str,
fetch_function: Callable[[], Titles_T],
- region: Optional[str] = None,
- account_hash: Optional[str] = None,
+ region: str | None = None,
+ account_hash: str | None = None,
no_cache: bool = False,
reset_cache: bool = False,
) -> Titles_T:
@@ -168,10 +166,10 @@ class TitleCacher:
self,
provider_name: str,
title_id: str,
- kind: Optional[str] = None,
- region: Optional[str] = None,
- account_hash: Optional[str] = None,
- ) -> Optional[dict]:
+ kind: str | None = None,
+ region: str | None = None,
+ account_hash: str | None = None,
+ ) -> dict | None:
"""Get the cached data of any metadata provider."""
if not config.title_cache_enabled or self.no_cache:
return None
@@ -219,9 +217,9 @@ class TitleCacher:
provider_name: str,
title_id: str,
data: dict,
- kind: Optional[str] = None,
- region: Optional[str] = None,
- account_hash: Optional[str] = None,
+ kind: str | None = None,
+ region: str | None = None,
+ account_hash: str | None = None,
ttl_days: int = 7,
) -> None:
"""Cache the data of any metadata provider."""
@@ -266,7 +264,7 @@ class TitleCacher:
self.log.debug(f"Cached {provider_name} data for {title_id}")
-def get_account_hash(credential: Optional[Credential]) -> Optional[str]:
+def get_account_hash(credential: Credential | None) -> str | None:
"""
Make a hash for account identification.
diff --git a/unshackle/core/titles/__init__.py b/unshackle/core/titles/__init__.py
index 58304aaf..54bb8c24 100644
--- a/unshackle/core/titles/__init__.py
+++ b/unshackle/core/titles/__init__.py
@@ -1,11 +1,9 @@
-from typing import Union
-
from .episode import Episode, Series
from .movie import Movie, Movies
from .music import Album, Music, Song
-Title_T = Union[Movie, Episode, Song]
-Titles_T = Union[Movies, Series, Music, Album]
+Title_T = Movie | Episode | Song
+Titles_T = Movies | Series | Music | Album
def remap_titles(titles: Titles_T, title_map: dict) -> Titles_T:
diff --git a/unshackle/core/titles/availability.py b/unshackle/core/titles/availability.py
index c2277aa5..4ac35e0a 100644
--- a/unshackle/core/titles/availability.py
+++ b/unshackle/core/titles/availability.py
@@ -4,14 +4,14 @@ Keep this allowlist separate from title.data: that dict can contain credentials,
playback URLs and other private service state which must never cross the API.
"""
-from typing import Any, Dict, Optional
+from typing import Any
-def availability_metadata(value: Any) -> Optional[Dict[str, Any]]:
+def availability_metadata(value: Any) -> dict[str, Any] | None:
"""Return only well-typed display fields; absent metadata remains absent."""
if not isinstance(value, dict):
return None
- result: Dict[str, Any] = {}
+ result: dict[str, Any] = {}
if isinstance(value.get("paid"), bool):
result["paid"] = value["paid"]
access = value.get("access")
diff --git a/unshackle/core/titles/episode.py b/unshackle/core/titles/episode.py
index 2ab89763..85b115bb 100644
--- a/unshackle/core/titles/episode.py
+++ b/unshackle/core/titles/episode.py
@@ -1,8 +1,9 @@
import re
from abc import ABC
from collections import Counter
+from collections.abc import Collection, Iterable
from datetime import date, datetime
-from typing import Any, Collection, Iterable, Optional, Union
+from typing import Any
from langcodes import Language
from pymediainfo import MediaInfo
@@ -19,8 +20,8 @@ from unshackle.core.utils.template_formatter import TemplateFormatter, detect_sp
class Episode(Title):
# class-level defaults so Episodes restored from an older title cache read as part-less,
# without an absolute number and not as sport
- part: Optional[int] = None
- absolute: Optional[int] = None
+ part: int | None = None
+ absolute: int | None = None
sport: bool = False
def __init__(
@@ -28,16 +29,16 @@ class Episode(Title):
id_: Any,
service: type,
title: str,
- season: Union[int, str],
- number: Union[int, str],
- name: Optional[str] = None,
- year: Optional[Union[int, str]] = None,
- language: Optional[Union[str, Language]] = None,
- data: Optional[Any] = None,
- description: Optional[str] = None,
- air_date: Optional[Union[date, str]] = None,
- part: Optional[Union[int, str]] = None,
- absolute: Optional[Union[int, str]] = None,
+ season: int | str,
+ number: int | str,
+ name: str | None = None,
+ year: int | str | None = None,
+ language: str | Language | None = None,
+ data: Any | None = None,
+ description: str | None = None,
+ air_date: date | str | None = None,
+ part: int | str | None = None,
+ absolute: int | str | None = None,
sport: bool = False,
) -> None:
super().__init__(id_, service, language, data)
@@ -224,7 +225,7 @@ class Episode(Title):
def get_filename(self, media_info: MediaInfo, folder: bool = False, show_service: bool = True) -> str:
if folder:
sports = self.sport and bool(config.folder_templates.get("sports"))
- template: Optional[str] = config.get_folder_template("sports" if sports else "series")
+ template: str | None = config.get_folder_template("sports" if sports else "series")
if template:
# all parts of an episode land in the same season folder
context = self.build_template_context(media_info, show_service, include_part=False)
@@ -283,7 +284,7 @@ class Episode(Title):
class Series(SortedKeyList, ABC):
- def __init__(self, iterable: Optional[Iterable] = None) -> None:
+ def __init__(self, iterable: Iterable | None = None) -> None:
# part slots before year so existing ties still resolve by year
super().__init__(iterable, key=lambda x: (x.season, x.number, x.part or 0, x.year or 0))
diff --git a/unshackle/core/titles/movie.py b/unshackle/core/titles/movie.py
index df581fd0..62e26cf5 100644
--- a/unshackle/core/titles/movie.py
+++ b/unshackle/core/titles/movie.py
@@ -1,6 +1,7 @@
import re
from abc import ABC
-from typing import Any, Iterable, Optional, Union
+from collections.abc import Iterable
+from typing import Any
from langcodes import Language
from pymediainfo import MediaInfo
@@ -20,10 +21,10 @@ class Movie(Title):
id_: Any,
service: type,
name: str,
- year: Optional[Union[int, str]] = None,
- language: Optional[Union[str, Language]] = None,
- data: Optional[Any] = None,
- description: Optional[str] = None,
+ year: int | str | None = None,
+ language: str | Language | None = None,
+ data: Any | None = None,
+ description: str | None = None,
) -> None:
super().__init__(id_, service, language, data)
@@ -61,7 +62,7 @@ class Movie(Title):
def get_filename(self, media_info: MediaInfo, folder: bool = False, show_service: bool = True) -> str:
if folder:
- template: Optional[str] = config.get_folder_template("movies")
+ template: str | None = config.get_folder_template("movies")
if template:
context = self.build_template_context(media_info, show_service)
spacer = detect_spacer(template) # one style for the whole path
@@ -86,7 +87,7 @@ class Movie(Title):
class Movies(SortedKeyList, ABC):
- def __init__(self, iterable: Optional[Iterable] = None) -> None:
+ def __init__(self, iterable: Iterable | None = None) -> None:
super().__init__(iterable, key=lambda x: x.year or 0)
def __str__(self) -> str:
diff --git a/unshackle/core/titles/music.py b/unshackle/core/titles/music.py
index 0e1c6dd7..e99e9194 100644
--- a/unshackle/core/titles/music.py
+++ b/unshackle/core/titles/music.py
@@ -1,6 +1,7 @@
import re
from abc import ABC
-from typing import Any, Collection, Iterable, Optional, Union
+from collections.abc import Collection, Iterable
+from typing import Any
from langcodes import Language
from pymediainfo import MediaInfo
@@ -85,23 +86,23 @@ class Song(Title):
album: str,
track: int,
disc: int = 1,
- year: Optional[int] = None,
- language: Optional[Union[str, Language]] = None,
- data: Optional[Any] = None,
- album_artist: Optional[str] = None,
+ year: int | None = None,
+ language: str | Language | None = None,
+ data: Any | None = None,
+ album_artist: str | None = None,
release_type: str = "album",
- total_tracks: Optional[int] = None,
- total_discs: Optional[int] = None,
- genre: Optional[str] = None,
- explicit: Optional[bool] = None,
- isrc: Optional[str] = None,
- upc: Optional[str] = None,
- copyright: Optional[str] = None,
- label: Optional[str] = None,
- lyrics: Optional[str] = None,
- artwork_url: Optional[str] = None,
- synced_lyrics: Optional[str] = None,
- lyrics_suffix: Optional[str] = None,
+ total_tracks: int | None = None,
+ total_discs: int | None = None,
+ genre: str | None = None,
+ explicit: bool | None = None,
+ isrc: str | None = None,
+ upc: str | None = None,
+ copyright: str | None = None,
+ label: str | None = None,
+ lyrics: str | None = None,
+ artwork_url: str | None = None,
+ synced_lyrics: str | None = None,
+ lyrics_suffix: str | None = None,
) -> None:
"""`lyrics` is the plain text the tagger embeds.
@@ -275,17 +276,17 @@ class Music(SortedKeyList, ABC):
def __init__(
self,
- iterable: Optional[Iterable] = None,
+ iterable: Iterable | None = None,
kind: str = "album",
- title: Optional[str] = None,
- artist: Optional[str] = None,
- year: Optional[int] = None,
- total_tracks: Optional[int] = None,
- total_discs: Optional[int] = None,
- artwork_url: Optional[str] = None,
- total_duration: Optional[int] = None,
- owner: Optional[str] = None,
- description: Optional[str] = None,
+ title: str | None = None,
+ artist: str | None = None,
+ year: int | None = None,
+ total_tracks: int | None = None,
+ total_discs: int | None = None,
+ artwork_url: str | None = None,
+ total_duration: int | None = None,
+ owner: str | None = None,
+ description: str | None = None,
) -> None:
if not isinstance(kind, str):
raise TypeError(f"Expected kind to be a str, not {kind!r}")
diff --git a/unshackle/core/titles/title.py b/unshackle/core/titles/title.py
index dd736831..928f588a 100644
--- a/unshackle/core/titles/title.py
+++ b/unshackle/core/titles/title.py
@@ -1,7 +1,7 @@
from __future__ import annotations
from abc import abstractmethod
-from typing import Any, Optional, Union
+from typing import Any
from langcodes import Language
from pymediainfo import MediaInfo
@@ -17,7 +17,7 @@ from unshackle.core.tracks import Tracks, Video
from unshackle.core.utilities import spoken_language, standard_resolution
-def rename(name: Optional[str]) -> str:
+def rename(name: str | None) -> str:
"""Return the user's `codec_names` override for a filename label, read here so per-service overrides are covered."""
value = config.codec_names.get(name, name) if name else name
return "" if value is None else str(value)
@@ -25,7 +25,7 @@ def rename(name: Optional[str]) -> str:
class Title:
def __init__(
- self, id_: Any, service: type, language: Optional[Union[str, Language]] = None, data: Optional[Any] = None
+ self, id_: Any, service: type, language: str | Language | None = None, data: Any | None = None
) -> None:
"""
Media Title from a Service.
@@ -59,8 +59,8 @@ class Title:
self.service = service
self.language = language
self.data: Any = data
- self.anime: Optional[bool] = None
- self.daily: Optional[bool] = None
+ self.anime: bool | None = None
+ self.daily: bool | None = None
self.tracks = Tracks()
@@ -82,7 +82,7 @@ class Title:
primary_audio_track = next(
(
t
- for t, lang in zip(media_info.audio_tracks, spoken_audio)
+ for t, lang in zip(media_info.audio_tracks, spoken_audio, strict=True)
if original_lang_tag and lang == original_lang_tag
),
next(iter(media_info.audio_tracks), None),
diff --git a/unshackle/core/tracks/attachment.py b/unshackle/core/tracks/attachment.py
index 3279fd67..9fd96517 100644
--- a/unshackle/core/tracks/attachment.py
+++ b/unshackle/core/tracks/attachment.py
@@ -4,7 +4,6 @@ import mimetypes
import os
import re
from pathlib import Path
-from typing import Optional, Union
from urllib.parse import urlparse
from zlib import crc32
@@ -17,12 +16,12 @@ from unshackle.core.utils import run_proxy
class Attachment:
def __init__(
self,
- path: Union[Path, str, None] = None,
- url: Optional[str] = None,
- name: Optional[str] = None,
- mime_type: Optional[str] = None,
- description: Optional[str] = None,
- session: Optional[AnySession] = None,
+ path: Path | str | None = None,
+ url: str | None = None,
+ name: str | None = None,
+ mime_type: str | None = None,
+ description: str | None = None,
+ session: AnySession | None = None,
) -> None:
"""
Make a new Attachment.
@@ -47,7 +46,7 @@ class Attachment:
self.url = url
self.session = session
- self.file_name: Optional[str] = None
+ self.file_name: str | None = None
if url:
if not isinstance(url, str):
@@ -96,10 +95,10 @@ class Attachment:
def download(
self,
- session: Optional[AnySession] = None,
+ session: AnySession | None = None,
*,
no_proxy_download: bool = False,
- proxy_download: Optional[str] = None,
+ proxy_download: str | None = None,
) -> None:
"""Download a URL-backed attachment to the temp directory with the same retries as a track."""
if self.path is not None or not self.url or DOWNLOAD_LICENCE_ONLY.is_set():
@@ -135,7 +134,7 @@ class Attachment:
def __str__(self) -> str:
return " | ".join(filter(None, ["ATT", self.name, self.mime_type, self.description]))
- def to_dict(self) -> dict[str, Optional[str]]:
+ def to_dict(self) -> dict[str, str | None]:
"""The attachment in the export form; see ``wire.attachment_to_dict``."""
from unshackle.core.wire import attachment_to_dict
@@ -162,11 +161,11 @@ class Attachment:
def from_url(
cls,
url: str,
- name: Optional[str] = None,
- mime_type: Optional[str] = None,
- description: Optional[str] = None,
- session: Optional[AnySession] = None,
- ) -> "Attachment":
+ name: str | None = None,
+ mime_type: str | None = None,
+ description: str | None = None,
+ session: AnySession | None = None,
+ ) -> Attachment:
"""
Make an attachment from a URL.
diff --git a/unshackle/core/tracks/audio.py b/unshackle/core/tracks/audio.py
index 1a2eca48..a905c891 100644
--- a/unshackle/core/tracks/audio.py
+++ b/unshackle/core/tracks/audio.py
@@ -9,7 +9,7 @@ import subprocess
import time
from enum import Enum
from pathlib import Path
-from typing import Any, Optional, Union
+from typing import Any
from unshackle.core import binaries
from unshackle.core.tracks.track import (
@@ -101,7 +101,7 @@ class Audio(Track):
raise ValueError(f"The MIME '{mime}' is not a supported Audio Codec")
@staticmethod
- def from_ts(stream_type: int, registration: bytes) -> Optional[Audio.Codec]:
+ def from_ts(stream_type: int, registration: bytes) -> Audio.Codec | None:
"""The codec an MPEG-TS PMT entry names by its registration descriptor or ``stream_type``, else None."""
if registration in (b"AVSA", b"av3a"):
return Audio.Codec.AV3A
@@ -110,7 +110,7 @@ class Audio(Track):
)
@staticmethod
- def from_ffprobe(codec_name: str, profile: str = "") -> Optional[Audio.Codec]:
+ def from_ffprobe(codec_name: str, profile: str = "") -> Audio.Codec | None:
"""Map an FFprobe ``codec_name`` to a codec, or None for one core does not name."""
if codec_name.startswith("pcm_"):
return Audio.Codec.PCM
@@ -131,11 +131,11 @@ class Audio(Track):
def __init__(
self,
*args: Any,
- codec: Optional[Audio.Codec] = None,
- bitrate: Optional[Union[str, int, float]] = None,
- channels: Optional[Union[str, int, float]] = None,
- joc: Optional[int] = None,
- descriptive: Union[bool, int] = False,
+ codec: Audio.Codec | None = None,
+ bitrate: str | int | float | None = None,
+ channels: str | int | float | None = None,
+ joc: int | None = None,
+ descriptive: bool | int = False,
**kwargs: Any,
) -> None:
"""
@@ -174,12 +174,12 @@ class Audio(Track):
try:
self.bitrate = int(math.ceil(float(bitrate))) if bitrate else None
except (ValueError, TypeError) as e:
- raise ValueError(f"Expected bitrate to be a number or float, {e}")
+ raise ValueError(f"Expected bitrate to be a number or float, {e}") from None
try:
self.channels = self.parse_channels(channels) if channels else None
except (ValueError, NotImplementedError) as e:
- raise ValueError(f"Expected channels to be a number, float, or a string, {e}")
+ raise ValueError(f"Expected channels to be a number, float, or a string, {e}") from None
self.joc = joc
self.descriptive = bool(descriptive)
@@ -220,7 +220,7 @@ class Audio(Track):
)
@staticmethod
- def parse_channels(channels: Union[str, int, float]) -> Union[float, str]:
+ def parse_channels(channels: str | int | float) -> float | str:
"""
Converts a Channel string to a float representing the audio channel layout.
E.g. "3" -> "3.0", "2.1" -> "2.1", ".1" -> "0.1".
@@ -246,7 +246,7 @@ class Audio(Track):
return float(channels)
@staticmethod
- def dolby_channel_layout(mask: int) -> Union[float, str]:
+ def dolby_channel_layout(mask: int) -> float | str:
"""Channel layout of a Dolby DASH channel configuration mask, e.g. 0xF801 -> 5.1."""
counts = {"main": 0, "lfe": 0, "height": 0}
for bit, (count, kind) in enumerate(DOLBY_CHANNEL_BITS):
@@ -257,7 +257,7 @@ class Audio(Track):
return float(f"{counts['main']}.{counts['lfe']}")
@staticmethod
- def channels_from_count(count: Union[str, int, None]) -> Union[float, str, None]:
+ def channels_from_count(count: str | int | None) -> float | str | None:
"""
Channel layout for a bare number of channels, as HLS CHANNELS, Smooth Streaming and most DASH schemes give it.
@@ -269,7 +269,7 @@ class Audio(Track):
return COUNT_CHANNEL_LAYOUTS.get(int(count), float(count))
@staticmethod
- def channel_total(channels: Union[str, int, float]) -> float:
+ def channel_total(channels: str | int | float) -> float:
"""
Total number of channels in either channel form, so a caller can compare both.
@@ -315,7 +315,7 @@ class Audio(Track):
return {}
return stream
- def to_music_container(self, start: float = 0.0, duration: Optional[float] = None) -> None:
+ def to_music_container(self, start: float = 0.0, duration: float | None = None) -> None:
"""Remux the track into the container of the codec FFprobe reads from the file, cut to the sample window.
The declared codec is used only when FFprobe cannot read the file. Every failure raises and keeps the
@@ -343,7 +343,7 @@ class Audio(Track):
self.path = output
def ffmpeg_music_container(
- self, source: Path, stream: dict[str, Any], start: float, duration: Optional[float]
+ self, source: Path, stream: dict[str, Any], start: float, duration: float | None
) -> Path:
"""Remux with FFmpeg. FLAC is encoded, never copied: FFmpeg's FLAC muxer writes a real sample count
only from an encoder. Float PCM and PCM above 24 bits go to WAV: FLAC has no float samples, and FFmpeg
@@ -351,7 +351,7 @@ class Audio(Track):
widen to 32-bit float. DTS goes to Matroska, because FFmpeg writes it into
MP4 with an mp4a sample entry. Only AAC, ALAC and AC-3 take the ipod muxer (the M4A brand)."""
if not binaries.FFMPEG:
- raise EnvironmentError('FFmpeg executable "ffmpeg" was not found but is required for this call.')
+ raise OSError('FFmpeg executable "ffmpeg" was not found but is required for this call.')
sample_fmt = stream.get("sample_fmt")
lossless_pcm = (
@@ -403,10 +403,10 @@ class Audio(Track):
)
return output
- def mp4box_music_container(self, source: Path, start: float, duration: Optional[float]) -> Path:
+ def mp4box_music_container(self, source: Path, start: float, duration: float | None) -> Path:
"""Rewrite the track as an unfragmented .m4a with MP4Box, for the codecs FFmpeg cannot write into MP4."""
if not binaries.MP4Box:
- raise EnvironmentError(f"MP4Box (GPAC) not found, the {getattr(self.codec, 'value', None)} remux needs it")
+ raise OSError(f"MP4Box (GPAC) not found, the {getattr(self.codec, 'value', None)} remux needs it")
candidate = source.with_name(f"{source.stem}_init.mp4")
output = source.with_name(f"{source.stem}_music.m4a")
try:
@@ -439,7 +439,7 @@ class Audio(Track):
candidate.unlink(missing_ok=True)
return output
- def get_track_name(self) -> Optional[str]:
+ def get_track_name(self) -> str | None:
"""Return the base Track Name."""
track_name = super().get_track_name() or ""
flag = self.descriptive and "Descriptive"
@@ -463,7 +463,7 @@ FFPROBE_CODECS: dict[str, Audio.Codec] = {
"mpegh_3d_audio": Audio.Codec.MPEGH,
}
-COPY_CONTAINERS: dict[Optional[Audio.Codec], str] = {
+COPY_CONTAINERS: dict[Audio.Codec | None, str] = {
Audio.Codec.OPUS: ".opus",
Audio.Codec.OGG: ".ogg",
Audio.Codec.MP3: ".mp3",
diff --git a/unshackle/core/tracks/chapter.py b/unshackle/core/tracks/chapter.py
index ef24ebf9..59a6683b 100644
--- a/unshackle/core/tracks/chapter.py
+++ b/unshackle/core/tracks/chapter.py
@@ -1,14 +1,13 @@
from __future__ import annotations
import re
-from typing import Optional, Union
from zlib import crc32
TIMESTAMP_FORMAT = re.compile(r"^(?P\d{2}):(?P\d{2}):(?P\d{2})(?P.\d{3}|)$")
class Chapter:
- def __init__(self, timestamp: Union[str, int, float], name: Optional[str] = None) -> None:
+ def __init__(self, timestamp: str | int | float, name: str | None = None) -> None:
"""
Make a new Chapter with a Timestamp and optional name.
diff --git a/unshackle/core/tracks/chapters.py b/unshackle/core/tracks/chapters.py
index 78a42f8a..5eeb4dd6 100644
--- a/unshackle/core/tracks/chapters.py
+++ b/unshackle/core/tracks/chapters.py
@@ -4,8 +4,9 @@ import os
import re
import threading
from abc import ABC
+from collections.abc import Iterable
from pathlib import Path
-from typing import Any, Iterable, Optional, Union
+from typing import Any
from zlib import crc32
from sortedcontainers import SortedKeyList
@@ -17,7 +18,7 @@ OGM_SIMPLE_LINE_2_FORMAT = re.compile(r"^CHAPTER(?P\d+)NAME=(?P.*)
class Chapters(SortedKeyList, ABC):
- def __init__(self, iterable: Optional[Iterable[Chapter]] = None) -> None:
+ def __init__(self, iterable: Iterable[Chapter] | None = None) -> None:
super().__init__(key=lambda x: x.timestamp or 0)
for chapter in iterable or []:
self.add(chapter)
@@ -45,7 +46,7 @@ class Chapters(SortedKeyList, ABC):
chapters = []
- for line_1, line_2 in zip(lines[::2], lines[1::2]):
+ for line_1, line_2 in zip(lines[::2], lines[1::2], strict=False):
line_1_match = OGM_SIMPLE_LINE_1_FORMAT.match(line_1)
if not line_1_match:
raise SyntaxError(f"An unexpected syntax error occurred on: {line_1}")
@@ -69,7 +70,7 @@ class Chapters(SortedKeyList, ABC):
return cls(chapters)
@classmethod
- def load(cls, path: Union[Path, str]) -> Chapters:
+ def load(cls, path: Path | str) -> Chapters:
"""Load chapter data from a file."""
if isinstance(path, str):
path = Path(path)
@@ -107,7 +108,7 @@ class Chapters(SortedKeyList, ABC):
return "\n".join(chapters)
- def dump(self, path: Union[Path, str], *args: Any, **kwargs: Any) -> int:
+ def dump(self, path: Path | str, *args: Any, **kwargs: Any) -> int:
"""
Write chapter data in OGM-based Simple Chapter format to a file.
diff --git a/unshackle/core/tracks/dv_fixup.py b/unshackle/core/tracks/dv_fixup.py
index 75e1bc49..e116a2e0 100644
--- a/unshackle/core/tracks/dv_fixup.py
+++ b/unshackle/core/tracks/dv_fixup.py
@@ -15,7 +15,7 @@ from __future__ import annotations
import logging
from pathlib import Path
-from typing import TYPE_CHECKING, Optional
+from typing import TYPE_CHECKING
from rich.padding import Padding
from rich.rule import Rule
@@ -32,12 +32,12 @@ if TYPE_CHECKING:
class DVFixup:
"""Demux a DV-composite HEVC track to an elementary HEVC file so mkvmerge exposes DV."""
- def __init__(self, video: "Video") -> None:
+ def __init__(self, video: Video) -> None:
self.log = logging.getLogger("dv-fixup")
self.video = video
if not FFMPEG:
- raise EnvironmentError("ffmpeg is required for DV-composite fixup but was not found.")
+ raise OSError("ffmpeg is required for DV-composite fixup but was not found.")
if not video.path or not Path(video.path).exists():
raise ValueError(f"Video track {video.id} was not downloaded before DV fixup.")
@@ -84,7 +84,7 @@ class DVFixup:
return fixed_hevc
-def apply_dv_fixup(video: "Video", keep_source: bool = False) -> Optional[Path]:
+def apply_dv_fixup(video: Video, keep_source: bool = False) -> Path | None:
"""Do the DV fixup on `video` if flagged as DV-composite and set `video.path` to the result.
Deletes the source file. With `keep_source`, returns its path for the caller to delete.
diff --git a/unshackle/core/tracks/hybrid.py b/unshackle/core/tracks/hybrid.py
index b635795c..cf06be84 100644
--- a/unshackle/core/tracks/hybrid.py
+++ b/unshackle/core/tracks/hybrid.py
@@ -5,9 +5,11 @@ import re
import subprocess
import tempfile
from collections import Counter
+from collections.abc import Iterable
from concurrent import futures
+from itertools import pairwise
from pathlib import Path
-from typing import TYPE_CHECKING, Any, Iterable, Optional
+from typing import TYPE_CHECKING, Any
from rich.padding import Padding
from rich.rule import Rule
@@ -113,7 +115,7 @@ def measured_shots(frames: list[tuple[int, float, int, bool]]) -> list[dict]:
cuts.append(len(frames))
to_12_bit = 4095 / 65535
shots = []
- for start, end in zip(cuts, cuts[1:]):
+ for start, end in pairwise(cuts):
shot = frames[start:end]
level1 = {
"min_pq": round(min(f[0] for f in shot) * to_12_bit),
@@ -124,7 +126,7 @@ def measured_shots(frames: list[tuple[int, float, int, bool]]) -> list[dict]:
return shots
-def hdr10plus_mean_pq(values: dict[int, float], active_fraction: float = 1.0) -> Optional[float]:
+def hdr10plus_mean_pq(values: dict[int, float], active_fraction: float = 1.0) -> float | None:
"""Mean PQ code of the maxRGB distribution in one HDR10+ histogram, or None if a slot is missing.
Dolby Vision L1 avg is a mean of PQ-coded maxRGB over the active area. HDR10+ AverageMaxRGB is a
@@ -142,7 +144,7 @@ def hdr10plus_mean_pq(values: dict[int, float], active_fraction: float = 1.0) ->
low = 1.0 - active_fraction
area = 0.0
- for (x1, y1), (x2, y2) in zip(knots, knots[1:]):
+ for (x1, y1), (x2, y2) in pairwise(knots):
if x2 <= low:
continue
if x1 < low:
@@ -169,13 +171,13 @@ def hdr10plus_shots(metadata: dict, active_fraction: float = 1.0) -> list[dict]:
shots = []
fallbacks = 0
- for first_frame, length in zip(first_frames, summary["SceneFrameNumbers"]):
+ for first_frame, length in zip(first_frames, summary["SceneFrameNumbers"], strict=False):
start = first_frame - offset
luminance = scenes[start]["LuminanceParameters"]
distribution = luminance["LuminanceDistributions"]
values = {
index: value / 10
- for index, value in zip(distribution["DistributionIndex"], distribution["DistributionValues"])
+ for index, value in zip(distribution["DistributionIndex"], distribution["DistributionValues"], strict=False)
}
peaks = [value for index, value in values.items() if index != 10]
max_pq = nits_to_pq(max(peaks or [v / 10 for v in luminance["MaxScl"]]))
@@ -205,7 +207,7 @@ class NoHDR10PlusMetadata(ValueError):
class Hybrid:
- def __init__(self, videos: list["Video"], source: str, output_name: Optional[str] = None) -> None:
+ def __init__(self, videos: list["Video"], source: str, output_name: str | None = None) -> None:
self.log = logging.getLogger("hybrid")
"""
@@ -359,7 +361,7 @@ class Hybrid:
message=f"Failed extracting {type_} stream",
context={"type": type_, "input": str(save_path), "output": str(output), "error": str(e)},
)
- raise ValueError(f"Failed extracting {type_} stream")
+ raise ValueError(f"Failed extracting {type_} stream") from None
log_event(
"hybrid_extract_stream",
@@ -394,8 +396,10 @@ class Hybrid:
self.extract_rpu(video, untouched=True)
return
if "Invalid PPS index" in stderr_text:
- raise ValueError("Dolby Vision VideoTrack seems to be corrupt")
- raise ValueError(f"Failed extracting{' untouched ' if untouched else ' '}RPU from Dolby Vision stream")
+ raise ValueError("Dolby Vision VideoTrack seems to be corrupt") from None
+ raise ValueError(
+ f"Failed extracting{' untouched ' if untouched else ' '}RPU from Dolby Vision stream"
+ ) from None
log_event(
"hybrid_extract_rpu",
@@ -438,7 +442,7 @@ class Hybrid:
)
except RuntimeError as e:
log_event("hybrid_align", level="ERROR", message="Failed aligning the RPU", context={"error": str(e)})
- raise ValueError("Failed aligning the Dolby Vision RPU with the sample")
+ raise ValueError("Failed aligning the Dolby Vision RPU with the sample") from None
log_event("hybrid_align", level="DEBUG", message="Aligned the RPU", context={"frames": frames}, success=True)
self.rpu_file = "RPU_ALIGN.bin"
@@ -481,7 +485,7 @@ class Hybrid:
message="Failed editing RPU Level 5 values",
context={"error": str(e)},
)
- raise ValueError("Failed editing RPU Level 5 values")
+ raise ValueError("Failed editing RPU Level 5 values") from None
log_event(
"hybrid_level5",
@@ -492,7 +496,7 @@ class Hybrid:
)
self.rpu_file = "RPU_L5.bin"
- def detect_active_area(self, input_video: Path) -> Optional[tuple[tuple[int, int, int, int], float]]:
+ def detect_active_area(self, input_video: Path) -> tuple[tuple[int, int, int, int], float] | None:
"""The picture's crop as (left, top, right, bottom) and its share of the frame, or None.
None also when the picture is under 40% of the frame: cropdetect on dark samples can report a tiny
@@ -504,8 +508,7 @@ class Hybrid:
with console.status("Detecting active area (crop detection)...", spinner="dots"):
result_duration = subprocess.run(
[ffprobe_bin, "-v", "error", "-show_entries", "format=duration", "-of", "json", str(input_video)],
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
+ capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
@@ -546,8 +549,7 @@ class Hybrid:
"json",
str(input_video),
],
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
+ capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
@@ -569,7 +571,7 @@ class Hybrid:
sample_times = [duration * (i + 0.5) / 10 for i in range(10)]
- def sample_crop(t: float) -> Optional[tuple[int, int, int, int]]:
+ def sample_crop(t: float) -> tuple[int, int, int, int] | None:
result_cropdetect = subprocess.run(
[
ffmpeg_bin,
@@ -591,8 +593,7 @@ class Hybrid:
"null",
"-",
],
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
+ capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
@@ -641,8 +642,8 @@ class Hybrid:
@staticmethod
def sanitize_l6(
- max_mdl: Optional[int], min_mdl: Optional[int], max_cll: Optional[int], max_fall: Optional[int]
- ) -> tuple[Optional[int], Optional[int], Optional[int], Optional[int]]:
+ max_mdl: int | None, min_mdl: int | None, max_cll: int | None, max_fall: int | None
+ ) -> tuple[int | None, int | None, int | None, int | None]:
"""Clamp static L6 values to a valid relationship.
MaxCLL must not exceed the mastering-display peak (some HDR10+ sources ship
@@ -671,7 +672,7 @@ class Hybrid:
message="Failed reading RPU metadata for Level 6 values",
context={"error": str(e)},
)
- raise ValueError("Failed reading RPU metadata for Level 6 values")
+ raise ValueError("Failed reading RPU metadata for Level 6 values") from None
blocks = rpu_info.get("vdr_dm_data", {}).get("cmv29_metadata", {}).get("ext_metadata_blocks", [])
level6: dict[str, Any] = next((b["Level6"] for b in blocks if isinstance(b, dict) and "Level6" in b), {})
@@ -750,7 +751,7 @@ class Hybrid:
message="Failed editing RPU Level 6 values",
context={"error": str(e)},
)
- raise ValueError("Failed editing RPU Level 6 values")
+ raise ValueError("Failed editing RPU Level 6 values") from None
log_event(
"hybrid_level6",
@@ -785,7 +786,7 @@ class Hybrid:
message="Failed injecting Dolby Vision metadata into HDR10 stream",
context={"error": str(e)},
)
- raise ValueError("Failed injecting Dolby Vision metadata into HDR10 stream")
+ raise ValueError("Failed injecting Dolby Vision metadata into HDR10 stream") from None
log_event(
"hybrid_inject_rpu",
@@ -828,8 +829,8 @@ class Hybrid:
context={"error": str(e)},
)
if "dynamic metadata" in str(e):
- raise NoHDR10PlusMetadata("No HDR10+ metadata found in the stream")
- raise ValueError("Failed extracting HDR10+ metadata")
+ raise NoHDR10PlusMetadata("No HDR10+ metadata found in the stream") from None
+ raise ValueError("Failed extracting HDR10+ metadata") from None
file_size = os.path.getsize(config.directories.temp / self.hdr10plus_file)
if file_size == 0:
@@ -876,8 +877,7 @@ class Hybrid:
"json",
str(config.directories.temp / "HDR10.hevc"),
],
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
+ capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
@@ -965,7 +965,7 @@ class Hybrid:
message="Failed converting HDR10+ to Dolby Vision",
context={"error": str(e)},
)
- raise ValueError("Failed converting HDR10+ to Dolby Vision")
+ raise ValueError("Failed converting HDR10+ to Dolby Vision") from None
finally:
config_path.unlink(missing_ok=True)
hdr10plus_path.unlink(missing_ok=True)
@@ -985,7 +985,7 @@ class Hybrid:
self.log.info(f"Dolby Vision generated from HDR10+ metadata ({len(shots)} scenes, {mode})")
def measure_frames(
- self, input_video: Path, crop: Optional[tuple[int, int, int, int]]
+ self, input_video: Path, crop: tuple[int, int, int, int] | None
) -> tuple[list[tuple[int, float, int, bool]], float]:
"""Decode the whole video through MEASURE_GRAPH.
@@ -1085,8 +1085,7 @@ class Hybrid:
"default=nw=1",
str(stream),
],
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
+ capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
@@ -1119,7 +1118,7 @@ class Hybrid:
generator_config["l1_avg_pq_cm_version"] = "V40"
return generator_config
- def measure_dv(self, crop: Optional[tuple[int, int, int, int]] = None) -> None:
+ def measure_dv(self, crop: tuple[int, int, int, int] | None = None) -> None:
"""Generate a Dolby Vision RPU with L1 measured from the decoded video, one shot per scene cut.
It measures HDR10.hevc, the file that gets the RPU, so the shots count the same frames. The first
@@ -1148,7 +1147,7 @@ class Hybrid:
message="Failed generating Dolby Vision from the decoded video",
context={"error": str(e)},
)
- raise ValueError("Failed generating Dolby Vision from the decoded video")
+ raise ValueError("Failed generating Dolby Vision from the decoded video") from None
finally:
config_path.unlink(missing_ok=True)
diff --git a/unshackle/core/tracks/resume.py b/unshackle/core/tracks/resume.py
index 605a690b..445292aa 100644
--- a/unshackle/core/tracks/resume.py
+++ b/unshackle/core/tracks/resume.py
@@ -14,8 +14,8 @@ from __future__ import annotations
import hashlib
import json
+from collections.abc import Sequence
from pathlib import Path
-from typing import Optional, Sequence
from urllib.parse import urlsplit, urlunsplit
_VERSION = 1
@@ -26,7 +26,7 @@ def sidecar_path(save_dir: Path) -> Path:
return save_dir.with_name(save_dir.name + ".resume.json")
-def _strip_url(url: Optional[str]) -> str:
+def _strip_url(url: str | None) -> str:
"""Drop query and fragment: auth tokens rotate between runs and would make every digest unique."""
if not url:
return ""
@@ -35,8 +35,8 @@ def _strip_url(url: Optional[str]) -> str:
def fingerprint(
- manifest_url: Optional[str],
- segments: Sequence[tuple[str, Optional[str]]],
+ manifest_url: str | None,
+ segments: Sequence[tuple[str, str | None]],
extra: Sequence[str] = (),
) -> str:
"""Stable digest of a track's segmentation.
diff --git a/unshackle/core/tracks/selection.py b/unshackle/core/tracks/selection.py
index 0f4ca6b6..5492da10 100644
--- a/unshackle/core/tracks/selection.py
+++ b/unshackle/core/tracks/selection.py
@@ -4,8 +4,9 @@ from __future__ import annotations
import logging
import math
+from collections.abc import Sequence
from dataclasses import dataclass
-from typing import Any, Optional, Sequence, Union
+from typing import Any
from unshackle.core.console import console
from unshackle.core.constants import AnyTrack
@@ -74,20 +75,20 @@ class TrackSelection:
quality: list[int]
vcodec: list[Video.Codec]
acodec: list[Audio.Codec]
- vbitrate: Optional[int]
- abitrate: Optional[int]
- vbitrate_min: Optional[int]
- vbitrate_max: Optional[int]
- abitrate_min: Optional[int]
- abitrate_max: Optional[int]
+ vbitrate: int | None
+ abitrate: int | None
+ vbitrate_min: int | None
+ vbitrate_max: int | None
+ abitrate_min: int | None
+ abitrate_max: int | None
range_: list[Video.Range]
generated_dv_bases: list[Video.Range]
- channels: Optional[float]
+ channels: float | None
no_atmos: bool
lang: list[str]
- v_lang: Optional[list[str]]
- a_lang: Optional[list[str]]
- s_lang: Optional[list[str]]
+ v_lang: list[str] | None
+ a_lang: list[str] | None
+ s_lang: list[str] | None
video_excl: list[str]
audio_excl: list[str]
s_lang_excl: list[str]
@@ -114,7 +115,7 @@ class TrackSelection:
best_available: bool
generate_dv: bool
- def select(self, title: Title_T, subtitles_unsupported: bool) -> Union[Kept, Skip]:
+ def select(self, title: Title_T, subtitles_unsupported: bool) -> Kept | Skip:
"""Narrow title.tracks to the tracks the flags ask for, or return the reason to skip the title.
subtitles_unsupported is the service's NO_SUBTITLES read after get_tracks, which can set it. The
@@ -586,7 +587,7 @@ class TrackSelection:
# video carries no audio of its own to fall back on
return Skip(f"There's no {as_requested(processed_lang, a_orig_token) or 'orig'} Audio Track...")
- kept_tracks: list[Union[AnyTrack, Chapter, Attachment]] = []
+ kept_tracks: list[AnyTrack | Chapter | Attachment] = []
if keep_videos:
kept_tracks.extend(title.tracks.videos)
if keep_audio:
@@ -623,7 +624,7 @@ def select_best_audio(
target_langs: list[Any] = list(dict.fromkeys(t.language for t in audio))
else:
target_langs = languages
- codecs: list[Optional[Audio.Codec]] = list(acodec) if len(acodec) > 1 else [None]
+ codecs: list[Audio.Codec | None] = list(acodec) if len(acodec) > 1 else [None]
selected: list[Audio] = []
for language in target_langs:
@@ -674,7 +675,7 @@ def keep_generated_dv_bases(videos: Sequence[Video], bases: Sequence[Video.Range
return [v for v in videos if v.range != Video.Range.DV and (v.range not in HYBRID_BASE_RANGES or v.range in bases)]
-def hybrid_gate_failure(videos: Sequence[Video], generate_dv: bool) -> Optional[str]:
+def hybrid_gate_failure(videos: Sequence[Video], generate_dv: bool) -> str | None:
"""The message that stops HYBRID for these selected videos, or None when it can go on."""
if any(v.native_hybrid for v in videos):
return None
diff --git a/unshackle/core/tracks/subtitle.py b/unshackle/core/tracks/subtitle.py
index 0af9686b..3f0b2c69 100644
--- a/unshackle/core/tracks/subtitle.py
+++ b/unshackle/core/tracks/subtitle.py
@@ -5,11 +5,12 @@ import re
import subprocess
import time
from collections import defaultdict
+from collections.abc import Callable, Iterable, Sequence
from enum import Enum
from functools import partial
from io import BytesIO
from pathlib import Path
-from typing import TYPE_CHECKING, Any, Callable, Iterable, Optional, Sequence, Union
+from typing import TYPE_CHECKING, Any
import click
import pycaption
@@ -104,7 +105,7 @@ class Subtitle(Track):
def __init__(
self,
*args: Any,
- codec: Optional[Subtitle.Codec] = None,
+ codec: Subtitle.Codec | None = None,
cc: bool = False,
sdh: bool = False,
forced: bool = False,
@@ -192,12 +193,12 @@ class Subtitle(Track):
if self.forced and (self.cc or self.sdh):
raise ValueError("A text track cannot be CC/SDH as well as Forced.")
- self.ass_style: Optional[pysubs2.SSAStyle] = None
- self.ass_video_size: Optional[tuple[int, int]] = None
+ self.ass_style: pysubs2.SSAStyle | None = None
+ self.ass_video_size: tuple[int, int] | None = None
# TODO: Migrate to new event observer system
# Called after Track has been converted to another format
- self.OnConverted: Optional[Callable[[Subtitle.Codec], None]] = None
+ self.OnConverted: Callable[[Subtitle.Codec], None] | None = None
@property
def mux_language(self) -> Language:
@@ -223,7 +224,7 @@ class Subtitle(Track):
"""The subtitle type that the config names: "forced", "sdh" (CC counts as SDH) or "normal"."""
return "forced" if self.forced else "sdh" if (self.sdh or self.cc) else "normal"
- def get_track_name(self) -> Optional[str]:
+ def get_track_name(self) -> str | None:
"""Return the base Track Name."""
track_name = super().get_track_name() or ""
flag = self.cc and "CC" or self.sdh and "SDH" or self.forced and "Forced"
@@ -237,12 +238,12 @@ class Subtitle(Track):
self,
session: AnySession,
prepare_drm: partial,
- max_workers: Optional[int] = None,
- progress: Optional[partial] = None,
+ max_workers: int | None = None,
+ progress: partial | None = None,
*,
- cdm: Optional[object] = None,
+ cdm: object | None = None,
no_proxy_download: bool = False,
- proxy_download: Optional[str] = None,
+ proxy_download: str | None = None,
adaptive_workers: bool = False,
download_processes: int = 1,
) -> None:
@@ -376,7 +377,7 @@ class Subtitle(Track):
kept.append(caption)
@staticmethod
- def first_cue_start(caption_set: pycaption.CaptionSet) -> Optional[int]:
+ def first_cue_start(caption_set: pycaption.CaptionSet) -> int | None:
"""The start of the first cue, in microseconds, looking past empty languages; None with no cues."""
return next(
(c.start for language in caption_set.get_languages() for c in caption_set.get_captions(language)[:1]),
@@ -403,9 +404,9 @@ class Subtitle(Track):
origin = ism["segment_times"][0] * 1_000_000 // ism["timescale"]
relative = any(
(first := Subtitle.first_cue_start(fragment)) is not None and first < previous
- for previous, fragment in zip(starts, fragments[1:])
+ for previous, fragment in zip(starts, fragments[1:], strict=False)
)
- for start, fragment in zip(starts, fragments):
+ for start, fragment in zip(starts, fragments, strict=True):
shift = (start if relative else 0) - origin
for language in fragment.get_languages():
kept = captions[language]
@@ -828,7 +829,7 @@ class Subtitle(Track):
text = try_ensure_utf8(data).decode("utf8")
caption_set = pycaption.SRTReader().read(text)
elif codec == Subtitle.Codec.fTTML:
- caption_lists: dict[Optional[str], pycaption.CaptionList] = defaultdict(pycaption.CaptionList)
+ caption_lists: dict[str | None, pycaption.CaptionList] = defaultdict(pycaption.CaptionList)
for segment in (
Subtitle.parse(payload, Subtitle.Codec.TimedTextMarkupLang)
for payload in Subtitle.mdat_payloads(data)
@@ -873,7 +874,7 @@ class Subtitle(Track):
else:
raise ValueError(f'Unknown Subtitle format "{codec}"...')
except pycaption.exceptions.CaptionReadSyntaxError as e:
- raise SyntaxError(f'A syntax error has occurred when reading the "{codec}" subtitle: {e}')
+ raise SyntaxError(f'A syntax error has occurred when reading the "{codec}" subtitle: {e}') from e
except pycaption.exceptions.CaptionReadNoCaptions:
return pycaption.CaptionSet({"en": []})
@@ -924,7 +925,7 @@ class Subtitle(Track):
return "\n".join(sanitized_lines)
@staticmethod
- def space_webvtt_headers(data: Union[str, bytes]) -> str:
+ def space_webvtt_headers(data: str | bytes) -> str:
"""
Space out the WEBVTT Headers from Captions.
@@ -987,7 +988,7 @@ class Subtitle(Track):
caption_set.set_captions(lang, filtered_captions)
@staticmethod
- def merge_segmented_wvtt(data: bytes, period_start: float = 0.0) -> tuple[CaptionList, Optional[str]]:
+ def merge_segmented_wvtt(data: bytes, period_start: float = 0.0) -> tuple[CaptionList, str | None]:
"""
Convert Segmented DASH WebVTT cues into a pycaption Caption List.
Also returns an ISO 639-2 alpha-3 language tag if available.
@@ -1071,7 +1072,7 @@ class Subtitle(Track):
vttc_boxes = MP4.parse_stream(BytesIO(box.data))
current_time = base_time + period_start
- for sample, vttc_box in zip(samples, vttc_boxes):
+ for sample, vttc_box in zip(samples, vttc_boxes, strict=False):
duration = sample.sample_duration or default_duration
if sample.sample_composition_time_offsets:
current_time += sample.sample_composition_time_offsets
@@ -1084,7 +1085,7 @@ class Subtitle(Track):
# vtte is a vttc that's empty, skip
continue
- layout: Optional[Layout] = None
+ layout: Layout | None = None
nodes: list[CaptionNode] = []
for cue_box in vttc_box.children:
@@ -1117,7 +1118,7 @@ class Subtitle(Track):
return captions, language
def sample_slice(
- self, starts: Sequence[float], timescale: float = 1, window: Optional[tuple[int, int]] = None
+ self, starts: Sequence[float], timescale: float = 1, window: tuple[int, int] | None = None
) -> slice:
"""Return the segments of ``window`` plus one segment on each side.
@@ -1241,7 +1242,7 @@ class Subtitle(Track):
else:
raise
sub.save()
- except (IOError, OSError) as e:
+ except OSError as e:
if "is not valid subtitle file" in str(e):
log = logging.getLogger("Subtitle")
log.warning(f"Failed to strip SDH from {self.path.name}, keeping it as is: {e}")
@@ -1259,7 +1260,7 @@ class Subtitle(Track):
raise ValueError("You must download the subtitle track first.")
if not binaries.SubtitleEdit:
- raise EnvironmentError("SubtitleEdit executable not found...")
+ raise OSError("SubtitleEdit executable not found...")
from unshackle.core.tracks.subtitle_convert import SUBTITLE_EDIT_FORMATS, subtitleedit_args
diff --git a/unshackle/core/tracks/subtitle_convert.py b/unshackle/core/tracks/subtitle_convert.py
index 4721de45..fc205610 100644
--- a/unshackle/core/tracks/subtitle_convert.py
+++ b/unshackle/core/tracks/subtitle_convert.py
@@ -20,9 +20,10 @@ import math
import re
import subprocess
import time
+from collections.abc import Mapping
from itertools import pairwise
from pathlib import Path
-from typing import Any, Mapping, Optional, Protocol
+from typing import Any, Protocol
import pycaption
import pysubs2
@@ -79,7 +80,7 @@ def subtitleedit_args(
src: Path,
fmt: str,
*,
- output_folder: Optional[Path] = None,
+ output_folder: Path | None = None,
convert_colors: bool = False,
remove_hi: bool = False,
reverse_rtl: bool = False,
@@ -284,7 +285,7 @@ REGISTRY: list[SubtitleBackend] = [
]
-def resolve_backends(source: Codec, target: Codec, *, pin: Optional[str] = None) -> list[SubtitleBackend]:
+def resolve_backends(source: Codec, target: Codec, *, pin: str | None = None) -> list[SubtitleBackend]:
"""Available backends that can convert source->target, ordered by rank. A pinned backend goes first."""
available = [b for b in REGISTRY if b.is_available() and b.can_convert(source, target)]
if pin:
@@ -382,7 +383,7 @@ def build_ass_style(fields: Mapping[str, Any]) -> pysubs2.SSAStyle:
return style
-def style_substation(path: Path, style: pysubs2.SSAStyle, video_size: Optional[tuple[int, int]]) -> None:
+def style_substation(path: Path, style: pysubs2.SSAStyle, video_size: tuple[int, int] | None) -> None:
"""Give every style of a converted SSA/ASS file the look of ``style``.
A file with no PlayResY gets a 1080-line canvas in the shape of the video. A file with one keeps it, so positions
@@ -434,7 +435,7 @@ def finalize(sub: Subtitle, target: Codec, out: Path) -> Path:
return out
-def time_sorted_copy(src: Path) -> Optional[Path]:
+def time_sorted_copy(src: Path) -> Path | None:
"""
Copy an SSA/ASS file with its events in start-time order, or return None when it is already in order.
@@ -454,7 +455,7 @@ def time_sorted_copy(src: Path) -> Optional[Path]:
return copy
-def run_conversion(sub: Subtitle, target: Codec, *, pin: Optional[str] = None, forced: bool = False) -> Path:
+def run_conversion(sub: Subtitle, target: Codec, *, pin: str | None = None, forced: bool = False) -> Path:
"""
Convert ``sub`` to ``target`` using the best available backend, falling back through the
capability chain on failure.
@@ -484,7 +485,7 @@ def run_conversion(sub: Subtitle, target: Codec, *, pin: Optional[str] = None, f
out = src.with_suffix(f".{target.value.lower()}")
sorted_src = time_sorted_copy(src) if source in SUBSTATION and target not in SUBSTATION else None
- last_exc: Optional[Exception] = None
+ last_exc: Exception | None = None
try:
for backend in chain:
try:
diff --git a/unshackle/core/tracks/track.py b/unshackle/core/tracks/track.py
index 5dc84b7f..a8e0f315 100644
--- a/unshackle/core/tracks/track.py
+++ b/unshackle/core/tracks/track.py
@@ -8,12 +8,13 @@ import struct
import subprocess
from bisect import bisect_left, bisect_right
from collections import defaultdict
+from collections.abc import Callable, Iterable, Sequence
from copy import copy
from dataclasses import dataclass
from enum import Enum
from functools import partial
from pathlib import Path
-from typing import Any, Callable, Iterable, Optional, Sequence, Union
+from typing import Any
from uuid import UUID
from zlib import crc32
@@ -45,7 +46,7 @@ from unshackle.core.utilities import get_boxes, language_name, log_event, try_en
from unshackle.core.utils import run_proxy
from unshackle.core.utils.subprocess import ffprobe
-DRM_PREFERENCE_TYPES: dict[str, Union[type[Widevine], type[PlayReady]]] = {
+DRM_PREFERENCE_TYPES: dict[str, type[Widevine] | type[PlayReady]] = {
"wv": Widevine,
"widevine": Widevine,
"pr": PlayReady,
@@ -53,7 +54,7 @@ DRM_PREFERENCE_TYPES: dict[str, Union[type[Widevine], type[PlayReady]]] = {
}
-def direct_session(session: AnySession, proxy: Optional[str] = None) -> Session:
+def direct_session(session: AnySession, proxy: str | None = None) -> Session:
"""requests.Session with copied headers/cookies and no proxy, or only ``proxy`` when given."""
new = Session()
if proxy:
@@ -392,13 +393,13 @@ class DownloadContext:
save_path: Path
save_dir: Path
progress: partial
- session: Optional[AnySession] = None
- proxy: Optional[str] = None
- max_workers: Optional[int] = None
+ session: AnySession | None = None
+ proxy: str | None = None
+ max_workers: int | None = None
adaptive_workers: bool = False
download_processes: int = 1
- license_widevine: Optional[Callable] = None
- cdm: Optional[object] = None
+ license_widevine: Callable | None = None
+ cdm: object | None = None
def ensure_session(self) -> AnySession:
"""Return the HTTP session, or a new ``Session`` if none was set."""
@@ -421,22 +422,22 @@ class Track:
def __init__(
self,
- url: Union[str, list[str]],
- language: Union[Language, str],
+ url: str | list[str],
+ language: Language | str,
is_original_lang: bool = False,
descriptor: Descriptor = Descriptor.URL,
needs_repack: bool = False,
- name: Optional[str] = None,
- drm: Optional[Iterable[DRM_T]] = None,
- edition: Optional[str] = None,
- note: Optional[str] = None,
- session: Optional[AnySession] = None,
- downloader: Optional[Callable] = None,
- downloader_args: Optional[dict] = None,
- from_file: Optional[Path] = None,
- data: Optional[Union[dict, defaultdict]] = None,
- id_: Optional[str] = None,
- extra: Optional[Any] = None,
+ name: str | None = None,
+ drm: Iterable[DRM_T] | None = None,
+ edition: str | None = None,
+ note: str | None = None,
+ session: AnySession | None = None,
+ downloader: Callable | None = None,
+ downloader_args: dict | None = None,
+ from_file: Path | None = None,
+ data: dict | defaultdict | None = None,
+ id_: str | None = None,
+ extra: Any | None = None,
) -> None:
if not isinstance(url, (str, list)):
raise TypeError(f"Expected url to be a {str}, or list of {str}, not {type(url)}")
@@ -473,12 +474,12 @@ class Track:
try:
iter(drm)
except TypeError:
- raise TypeError(f"Expected drm to be an iterable, not {type(drm)}")
+ raise TypeError(f"Expected drm to be an iterable, not {type(drm)}") from None
if downloader is None:
downloader = requests
- self.path: Optional[Path] = None
+ self.path: Path | None = None
self.url = url
self.language = language
self.is_original_lang = is_original_lang
@@ -486,7 +487,7 @@ class Track:
self.needs_repack = needs_repack
self.name = name
self.drm = drm
- self._drm_preference: Optional[str] = None
+ self._drm_preference: str | None = None
self.edition: list[str] = [edition] if isinstance(edition, str) else (edition or [])
self.note = note
self.session = session
@@ -507,12 +508,12 @@ class Track:
self.id = id_
# TODO: Currently using OnFoo event naming, change to just segment_filter
- self.OnSegmentFilter: Optional[Callable] = None
+ self.OnSegmentFilter: Callable | None = None
self.sample_start: float = 0.0
- self.sample_bytes: Optional[tuple[bytes, str]] = None
+ self.sample_bytes: tuple[bytes, str] | None = None
def sample_slice(
- self, starts: Sequence[float], timescale: float = 1, window: Optional[tuple[int, int]] = None
+ self, starts: Sequence[float], timescale: float = 1, window: tuple[int, int] | None = None
) -> slice:
"""Return the slice of segments that hold ``window``, from the start time of each segment.
@@ -530,7 +531,7 @@ class Track:
self.sample_start = (starts[first] - starts[0]) / timescale
return slice(first, max(bisect_left(starts, high) + self.sample_tail, first + 1))
- def sample_byte_range(self, session: AnySession) -> Optional[tuple[bytes, str]]:
+ def sample_byte_range(self, session: AnySession) -> tuple[bytes, str] | None:
"""Find the bytes of a one-file track that hold the sample window.
Reads the start of the file for a ``sidx`` box. Returns the bytes before that box, which hold
@@ -593,7 +594,7 @@ class Track:
return self._language
@language.setter
- def language(self, value: Union[Language, str, None]) -> None:
+ def language(self, value: Language | str | None) -> None:
self._language = Language.get(value or "und")
@property
@@ -625,7 +626,7 @@ class Track:
return self._data
@data.setter
- def data(self, value: Union[dict, defaultdict]) -> None:
+ def data(self, value: dict | defaultdict) -> None:
if not isinstance(value, (dict, defaultdict)):
raise TypeError(f"Expected data to be a {dict} or {defaultdict}, not {type(value)}")
if isinstance(value, dict):
@@ -633,7 +634,7 @@ class Track:
self._data = value
@property
- def drm_preference(self) -> Optional[str]:
+ def drm_preference(self) -> str | None:
"""
DRM system this track must license with, one of the names in DRM_PREFERENCE_TYPES.
@@ -643,7 +644,7 @@ class Track:
return self._drm_preference
@drm_preference.setter
- def drm_preference(self, value: Optional[str]) -> None:
+ def drm_preference(self, value: str | None) -> None:
if value is None:
self._drm_preference = None
return
@@ -653,7 +654,7 @@ class Track:
)
self._drm_preference = value.lower()
- def add_init_drm(self, init_data: Optional[bytes], cdm: Optional[object]) -> None:
+ def add_init_drm(self, init_data: bytes | None, cdm: object | None) -> None:
"""Add the Widevine and PlayReady DRM that the init segment carries and the track does not have.
A track with a different DRM type stays as it is. The DRM system that agrees with the CDM comes first.
@@ -678,20 +679,20 @@ class Track:
else:
log.debug("No PlayReady or Widevine PSSH was found for this track, is it DRM free?")
- def prefers_playready(self, cdm: Optional[object]) -> bool:
+ def prefers_playready(self, cdm: object | None) -> bool:
"""Whether to try PlayReady before Widevine. The track's preference wins over the loaded CDM."""
if self._drm_preference:
return DRM_PREFERENCE_TYPES[self._drm_preference] is PlayReady
return is_playready_cdm(cdm)
- def pssh_order(self, cdm: Optional[object]) -> tuple[Union[type[Widevine], type[PlayReady]], ...]:
+ def pssh_order(self, cdm: object | None) -> tuple[type[Widevine] | type[PlayReady], ...]:
"""Widevine and PlayReady, in the order to look for their PSSH."""
return (PlayReady, Widevine) if self.prefers_playready(cdm) else (Widevine, PlayReady)
def drm_from_pssh(
self,
- cdm: Optional[object],
- read: Callable[[Union[type[Widevine], type[PlayReady]]], DRM_T],
+ cdm: object | None,
+ read: Callable[[type[Widevine] | type[PlayReady]], DRM_T],
log: logging.Logger,
) -> None:
"""Set drm to the first DRM that `read` finds a PSSH for, in pssh_order."""
@@ -708,12 +709,12 @@ class Track:
self,
session: AnySession,
prepare_drm: partial,
- max_workers: Optional[int] = None,
- progress: Optional[partial] = None,
+ max_workers: int | None = None,
+ progress: partial | None = None,
*,
- cdm: Optional[object] = None,
+ cdm: object | None = None,
no_proxy_download: bool = False,
- proxy_download: Optional[str] = None,
+ proxy_download: str | None = None,
adaptive_workers: bool = False,
download_processes: int = 1,
) -> None:
@@ -799,7 +800,7 @@ class Track:
cleanup()
try:
- manifest_parsers: dict[Track.Descriptor, Union[type[DASH], type[HLS], type[ISM]]] = {
+ manifest_parsers: dict[Track.Descriptor, type[DASH] | type[HLS] | type[ISM]] = {
self.Descriptor.HLS: HLS,
self.Descriptor.DASH: DASH,
self.Descriptor.ISM: ISM,
@@ -929,7 +930,7 @@ class Track:
if not DOWNLOAD_LICENCE_ONLY.is_set():
assert self.path is not None
if self.path.stat().st_size <= 3: # Empty UTF-8 BOM == 3 bytes
- raise IOError("Download failed, the downloaded file is empty.")
+ raise OSError("Download failed, the downloaded file is empty.")
events.emit(events.Types.TRACK_DOWNLOADED, track=self)
@@ -938,7 +939,7 @@ class Track:
self.path.unlink()
self.path = None
- def move(self, target: Union[Path, str]) -> Path:
+ def move(self, target: Path | str) -> Path:
"""
Move the Track's file from current location, to target location.
This will overwrite anything at the target path.
@@ -988,14 +989,14 @@ class Track:
name = language_name(Language.get(lang)) or lang
return self.with_original_label(name) or ""
- def get_track_name(self) -> Optional[str]:
+ def get_track_name(self) -> str | None:
"""Get the Track Name, or the name of its language when the service set none."""
name = self.name
if name is None and config.muxing.get("track_names") != "none":
name = language_name(self.mux_language)
return self.with_original_label(name)
- def with_original_label(self, name: Optional[str]) -> Optional[str]:
+ def with_original_label(self, name: str | None) -> str | None:
"""Add `muxing.original_label` to the name of a track in the title's original language,
unless the name already contains the label's words."""
label = config.muxing.get("original_label")
@@ -1007,7 +1008,7 @@ class Track:
return name
return f"{name} {label}" if name else label
- def get_drm_for_cdm(self, cdm: Optional[object]) -> Optional[DRM_T]:
+ def get_drm_for_cdm(self, cdm: object | None) -> DRM_T | None:
"""Return the DRM matching the provided CDM, if available."""
if not self.drm:
return None
@@ -1030,7 +1031,7 @@ class Track:
return next(iter(self.drm))
- def get_key_id(self, init_data: Optional[bytes] = None, *args: Any, **kwargs: Any) -> Optional[UUID]:
+ def get_key_id(self, init_data: bytes | None = None, *args: Any, **kwargs: Any) -> UUID | None:
"""
Probe the DRM encryption Key ID (KID) for this specific track.
@@ -1072,7 +1073,7 @@ class Track:
return tenc.key_ID
return None
- def load_drm_if_needed(self, service: Optional[Any] = None) -> bool:
+ def load_drm_if_needed(self, service: Any | None = None) -> bool:
"""
Load DRM information for this track if the parser deferred it.
@@ -1099,7 +1100,7 @@ class Track:
self.needs_drm_loading = False
return True
except Exception as e:
- raise ValueError(f"Failed to load DRM from service for track {self.id}: {e}")
+ raise ValueError(f"Failed to load DRM from service for track {self.id}: {e}") # noqa: B904
return self.load_drm_from_playlist()
@@ -1145,16 +1146,16 @@ class Track:
return True
except Exception as e:
- raise ValueError(f"Failed to load DRM from playlist for track {self.id}: {e}")
+ raise ValueError(f"Failed to load DRM from playlist for track {self.id}: {e}") # noqa: B904
return False
def get_init_segment(
self,
maximum_size: int = 20000,
- url: Optional[str] = None,
- byte_range: Optional[str] = None,
- session: Optional[AnySession] = None,
+ url: str | None = None,
+ byte_range: str | None = None,
+ session: AnySession | None = None,
) -> bytes:
"""
Get the Track's initial segment data.
@@ -1217,7 +1218,7 @@ class Track:
if range_test.status_code == 206:
byte_range = f"0-{content_length - 1}"
- init_data: Optional[bytes]
+ init_data: bytes | None
if byte_range:
res = session.get(url=url, headers={"Range": f"bytes={byte_range}"})
res.raise_for_status()
@@ -1237,7 +1238,7 @@ class Track:
return init_data
- def repackage(self, bsf_v: Optional[str] = None) -> bool:
+ def repackage(self, bsf_v: str | None = None) -> bool:
"""Remux the track with FFmpeg ``-c copy``.
A given ``bsf_v`` goes into the same pass as ``-bsf:v``, which normalises video VUI
@@ -1252,13 +1253,13 @@ class Track:
ffmpeg_bin = binaries.FFMPEG
if not ffmpeg_bin:
- raise EnvironmentError('FFmpeg executable "ffmpeg" was not found but is required for this call.')
+ raise OSError('FFmpeg executable "ffmpeg" was not found but is required for this call.')
original_path = self.path
output_path = original_path.with_stem(f"{original_path.stem}_repack")
- def ffmpeg(extra_args: Optional[list[str]] = None, bsf: Optional[str] = None) -> None:
- args: list[Union[str, Path]] = [
+ def ffmpeg(extra_args: list[str] | None = None, bsf: str | None = None) -> None:
+ args: list[str | Path] = [
ffmpeg_bin,
"-nostdin",
"-hide_banner",
@@ -1303,8 +1304,7 @@ class Track:
subprocess.run(
args,
check=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
+ capture_output=True,
)
log_event(
diff --git a/unshackle/core/tracks/tracks.py b/unshackle/core/tracks/tracks.py
index da934b14..c41adb13 100644
--- a/unshackle/core/tracks/tracks.py
+++ b/unshackle/core/tracks/tracks.py
@@ -8,10 +8,11 @@ import re
import subprocess
import threading
import time
+from collections.abc import Callable, Iterator, Sequence
from functools import partial
from itertools import product
from pathlib import Path
-from typing import Any, Callable, Iterator, Optional, Sequence, Union
+from typing import Any
from langcodes import Language
from rich.markup import escape
@@ -71,7 +72,7 @@ def video_rank(video: Video) -> tuple[int, bool, float, int]:
)
-def pick_video(candidates: list[Video], worst: bool) -> Optional[Video]:
+def pick_video(candidates: list[Video], worst: bool) -> Video | None:
"""The best candidate by ``video_rank``, or with ``worst`` the lowest bitrate of the lowest resolution.
``worst`` prefers 2D and counts a track with no bitrate or no size as the highest. A full tie goes to the
@@ -86,7 +87,7 @@ def pick_video(candidates: list[Video], worst: bool) -> Optional[Video]:
return max(candidates, key=video_rank, default=None)
-def video_language_groups(videos: list[Video], requests: Optional[list[str]], exact: bool) -> list[Optional[set[str]]]:
+def video_language_groups(videos: list[Video], requests: list[str] | None, exact: bool) -> list[set[str] | None]:
"""The tag sets to pick one video from each: one per request, or one per tag when ``requests`` is None.
A request that matches several regional tags (en-AU, en-GB) is one set, so it gives one video. With no
@@ -103,7 +104,7 @@ def select_videos(
qualities: Sequence[int],
ranges: Sequence[Video.Range],
codecs: Sequence[Video.Codec],
- requests: Optional[list[str]],
+ requests: list[str] | None,
exact: bool,
worst: bool,
) -> list[Video]:
@@ -158,9 +159,9 @@ def remux_vvc(source: Path) -> Path:
with video no player decodes, so the codec ID FFmpeg wrote is checked.
"""
if not binaries.FFMPEG:
- raise EnvironmentError('FFmpeg executable "ffmpeg" was not found but is required to mux H.266.')
+ raise OSError('FFmpeg executable "ffmpeg" was not found but is required to mux H.266.')
output = config.directories.temp / f"vvcmux_{source.stem}_{os.getpid()}_{threading.get_ident()}.mkv"
- cmd: list[Union[str, Path]] = [binaries.FFMPEG, "-nostdin", "-y", "-i", source, "-map", "0:v", "-map", "0:a?"]
+ cmd: list[str | Path] = [binaries.FFMPEG, "-nostdin", "-y", "-i", source, "-map", "0:v", "-map", "0:a?"]
cmd += ["-map_metadata", "-1", "-fflags", "+bitexact", "-c", "copy", output]
run_step(
cmd,
@@ -177,7 +178,7 @@ def remux_vvc(source: Path) -> Path:
return output
-def mp4_track_count(moov: Optional[bytes]) -> int:
+def mp4_track_count(moov: bytes | None) -> int:
"""How many tracks ``MP4Box -add`` takes from a file: each ``trak`` of its moov, or 1 for a file with none."""
return sum(1 for kind, _, _ in children(moov or b"", 8) if kind == b"trak") or 1
@@ -192,17 +193,15 @@ class Tracks:
def __init__(
self,
- *args: Union[
- Tracks, Sequence[Union[AnyTrack, Chapter, Chapters, Attachment]], Track, Chapter, Chapters, Attachment
- ],
- manifest_url: Optional[str] = None,
+ *args: Tracks | Sequence[AnyTrack | Chapter | Chapters | Attachment] | Track | Chapter | Chapters | Attachment,
+ manifest_url: str | None = None,
) -> None:
self.videos: list[Video] = []
self.audio: list[Audio] = []
self.subtitles: list[Subtitle] = []
self.chapters = Chapters()
self.attachments: list[Attachment] = []
- self.manifest_url: Optional[str] = manifest_url
+ self.manifest_url: str | None = manifest_url
if args:
self.add(args)
@@ -215,9 +214,7 @@ class Tracks:
def __add__(
self,
- other: Union[
- Tracks, Sequence[Union[AnyTrack, Chapter, Chapters, Attachment]], Track, Chapter, Chapters, Attachment
- ],
+ other: Tracks | Sequence[AnyTrack | Chapter | Chapters | Attachment] | Track | Chapter | Chapters | Attachment,
) -> Tracks:
self.add(other)
return self
@@ -341,7 +338,7 @@ class Tracks:
return tree, progress_callables
- def exists(self, by_id: Optional[str] = None, by_url: Optional[Union[str, list[str]]] = None) -> bool:
+ def exists(self, by_id: str | None = None, by_url: str | list[str] | None = None) -> bool:
"""Examine whether a track already exists, by various methods."""
if by_id:
return any(x.id == by_id for x in self)
@@ -351,14 +348,12 @@ class Tracks:
def add(
self,
- tracks: Union[
- Tracks,
- Sequence[Union[Tracks, Sequence[Any], Track, Chapter, Chapters, Attachment]],
- Track,
- Chapter,
- Chapters,
- Attachment,
- ],
+ tracks: Tracks
+ | Sequence[Tracks | Sequence[Any] | Track | Chapter | Chapters | Attachment]
+ | Track
+ | Chapter
+ | Chapters
+ | Attachment,
warn_only: bool = False,
) -> None:
"""Add a provided track to its appropriate array.
@@ -454,9 +449,7 @@ class Tracks:
best[variant(sub)] = min(best.get(variant(sub), rank[sub.codec]), rank[sub.codec])
self.subtitles = [s for s in self.subtitles if s.codec not in rank or rank[s.codec] == best[variant(s)]]
- def sort_videos(
- self, by_language: Optional[Sequence[Union[str, Language]]] = None, exact_match: bool = False
- ) -> None:
+ def sort_videos(self, by_language: Sequence[str | Language] | None = None, exact_match: bool = False) -> None:
"""Sort video tracks by standard resolution, 2D before 3D, then bitrate, and optionally language.
The standard resolution puts a 3840x1606 and a 3840x1610 crop in one 2160p group, ordered by bitrate.
@@ -478,8 +471,8 @@ class Tracks:
def sort_audio(
self,
- by_language: Optional[Sequence[Union[str, Language]]] = None,
- codec_priority: Optional[Sequence[str]] = None,
+ by_language: Sequence[str | Language] | None = None,
+ codec_priority: Sequence[str] | None = None,
exact_match: bool = False,
) -> None:
"""Sort audio tracks by bitrate, codec priority, Atmos, descriptive, and optionally language."""
@@ -507,9 +500,9 @@ class Tracks:
def sort_subtitles(
self,
- by_language: Optional[Sequence[Union[str, Language]]] = None,
- type_priority: Optional[Sequence[str]] = None,
- group_by: Optional[str] = None,
+ by_language: Sequence[str | Language] | None = None,
+ type_priority: Sequence[str] | None = None,
+ group_by: str | None = None,
exact_match: bool = False,
) -> None:
"""
@@ -730,7 +723,7 @@ class Tracks:
return original_tag(language, exact) if language else ""
@staticmethod
- def first_match_index(tracks: Sequence[AnyTrack], language: Optional[str]) -> Optional[int]:
+ def first_match_index(tracks: Sequence[AnyTrack], language: str | None) -> int | None:
"""The index of the first track that `language` asks for, matched against every track at once.
Matching the whole list lets the RFC 4647 string preference pick en-US over en.
@@ -743,10 +736,10 @@ class Tracks:
@staticmethod
def default_subtitle_index(
subtitles: Sequence[Subtitle],
- language: Optional[str],
+ language: str | None,
types: Sequence[str],
- audio_language: Optional[Language] = None,
- ) -> Optional[int]:
+ audio_language: Language | None = None,
+ ) -> int | None:
"""The index of the first subtitle of the first type in `types` that a track has.
`language` limits the choice to the tracks it asks for. With no `types`, or no track
@@ -775,9 +768,9 @@ class Tracks:
self,
title: str,
delete: bool = True,
- progress: Optional[partial] = None,
+ progress: partial | None = None,
skip_subtitles: bool = False,
- output_path: Optional[Path] = None,
+ output_path: Path | None = None,
) -> tuple[Path, int, list[str]]:
"""
Multiplex the Tracks into an MP4 Container with MP4Box.
@@ -954,11 +947,11 @@ class Tracks:
self,
title: str,
delete: bool = True,
- progress: Optional[partial] = None,
+ progress: partial | None = None,
audio_expected: bool = True,
- title_language: Optional[Language] = None,
+ title_language: Language | None = None,
skip_subtitles: bool = False,
- output_path: Optional[Path] = None,
+ output_path: Path | None = None,
) -> tuple[Path, int, list[str]]:
"""
Multiplex all the Tracks into a Matroska Container file.
@@ -1038,7 +1031,7 @@ class Tracks:
preferred_video_idx = self.first_match_index(self.videos, preferred_video_lang)
preferred_audio_idx = self.first_match_index(self.audio, preferred_audio_lang)
if preferred_audio_idx is not None:
- default_audio: Optional[Audio] = self.audio[preferred_audio_idx]
+ default_audio: Audio | None = self.audio[preferred_audio_idx]
else:
default_audio = next(
(at for at in self.audio if at.is_original_lang), self.audio[0] if self.audio else None
diff --git a/unshackle/core/tracks/video.py b/unshackle/core/tracks/video.py
index f30b36d6..ee17d1b2 100644
--- a/unshackle/core/tracks/video.py
+++ b/unshackle/core/tracks/video.py
@@ -9,7 +9,7 @@ import time
from enum import Enum
from fractions import Fraction
from pathlib import Path
-from typing import Any, Optional, Union
+from typing import Any
from langcodes import Language
@@ -199,7 +199,7 @@ class Video(Track):
return Video.Range.SDR
@staticmethod
- def from_m3u_range_tag(tag: str) -> Optional[Video.Range]:
+ def from_m3u_range_tag(tag: str) -> Video.Range | None:
tag = (tag or "").upper().replace('"', "").strip()
if not tag:
return None
@@ -219,14 +219,14 @@ class Video(Track):
def __init__(
self,
*args: Any,
- codec: Optional[Video.Codec] = None,
- range_: Optional[Video.Range] = None,
- bitrate: Optional[Union[str, int, float]] = None,
- width: Optional[int] = None,
- 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,
+ codec: Video.Codec | None = None,
+ range_: Video.Range | None = None,
+ bitrate: str | int | float | None = None,
+ width: int | None = None,
+ height: int | None = None,
+ fps: str | int | float | None = None,
+ scan_type: Video.ScanType | None = None,
+ closed_captions: list[dict[str, Any]] | None = None,
dv_compatible_bitstream: bool = False,
hdr10plus: bool = False,
hdr10_base: bool = False,
@@ -279,22 +279,24 @@ class Video(Track):
try:
self.bitrate = int(math.ceil(float(bitrate))) if bitrate else None
except (ValueError, TypeError) as e:
- raise ValueError(f"Expected bitrate to be a number or float, {e}")
+ raise ValueError(f"Expected bitrate to be a number or float, {e}") from None
try:
self.width = int(width or 0) or None
except ValueError as e:
- raise ValueError(f"Expected width to be a number, not {width!r}, {e}")
+ raise ValueError(f"Expected width to be a number, not {width!r}, {e}") from None
try:
self.height = int(height or 0) or None
except ValueError as e:
- raise ValueError(f"Expected height to be a number, not {height!r}, {e}")
+ raise ValueError(f"Expected height to be a number, not {height!r}, {e}") from None
try:
self.fps = (FPS.parse(str(fps)) or None) if fps else None
except Exception as e:
- raise ValueError("Expected fps to be a number, float, or a string as numerator/denominator form, " + str(e))
+ raise ValueError( # noqa: B904
+ "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 []
@@ -308,20 +310,18 @@ class Video(Track):
self.native_hybrid = False
@staticmethod
- def dv_fourccs(codecs: Optional[str]) -> set[str]:
+ def dv_fourccs(codecs: str | None) -> set[str]:
"""The Dolby Vision fourccs in a codecs list (comma or space separated, ``/brand`` suffixes allowed)."""
fourccs = {token.split("/")[0].split(".")[0] for token in re.split(r"[\s,]+", (codecs or "").lower())}
return fourccs & {"dva1", "dvav", "dvhe", "dvh1"}
@staticmethod
- def has_dv_codec(codecs: Optional[str]) -> bool:
+ def has_dv_codec(codecs: str | None) -> bool:
"""Whether a codecs list names a Dolby Vision codec."""
return bool(Video.dv_fourccs(codecs))
@staticmethod
- def is_stereo(
- codecs: Optional[str], supplemental_codecs: Optional[str] = None, video_layout: Optional[str] = None
- ) -> bool:
+ def is_stereo(codecs: str | None, supplemental_codecs: str | None = None, video_layout: str | None = None) -> bool:
"""Whether a track is stereoscopic 3D: the HLS REQ-VIDEO-LAYOUT names CH-STEREO, or a codec is DV profile 20."""
tokens = re.split(r"[\s,]+", f"{codecs or ''},{supplemental_codecs or ''}".lower())
return "CH-STEREO" in (video_layout or "").upper() or any(
@@ -329,9 +329,7 @@ class Video(Track):
)
@staticmethod
- def is_dv_composite(
- codec: Optional[Video.Codec], codecs: Optional[str], supplemental_codecs: Optional[str]
- ) -> bool:
+ def is_dv_composite(codec: Video.Codec | None, codecs: str | None, supplemental_codecs: str | None) -> bool:
"""Whether an HEVC track names DV only in its supplemental codecs: DV profile 8 on an HDR10, SDR or HLG base."""
return (
codec == Video.Codec.HEVC
@@ -404,7 +402,7 @@ class Video(Track):
)
if not binaries.FFMPEG:
- raise EnvironmentError('FFmpeg executable "ffmpeg" was not found but is required for this call.')
+ raise OSError('FFmpeg executable "ffmpeg" was not found but is required for this call.')
filter_key = {Video.Codec.AVC: "h264_metadata", Video.Codec.HEVC: "hevc_metadata"}[self.codec]
@@ -451,7 +449,7 @@ class Video(Track):
if self.stereo:
self.needs_repack = False
- def repackage(self, bsf_v: Optional[str] = None) -> bool:
+ def repackage(self, bsf_v: str | None = None) -> bool:
"""Remux with FFmpeg, except a 3D track: an FFmpeg remux rewrites its stereo and DV boxes."""
if self.stereo:
logging.getLogger("Video").warning(
@@ -460,7 +458,7 @@ class Video(Track):
return False
return super().repackage(bsf_v)
- def vui_bsf(self) -> Optional[str]:
+ def vui_bsf(self) -> str | None:
"""Return the ``-bsf:v`` value that rewrites SPS VUI colour metadata to match ``self.range``.
Returns None when a rewrite is not necessary or not safe: SDR/DV/HYBRID ranges, non-AVC/HEVC
@@ -528,7 +526,7 @@ class Video(Track):
assert self.path is not None # vui_bsf() returns None when path is unset
if not binaries.FFMPEG:
- raise EnvironmentError('FFmpeg executable "ffmpeg" was not found but is required for this call.')
+ raise OSError('FFmpeg executable "ffmpeg" was not found but is required for this call.')
original_path = self.path
output_path = original_path.with_stem(f"{original_path.stem}_vui")
@@ -587,7 +585,11 @@ class Video(Track):
return []
opts: dict[str, object] = dict(
- zip(("--colour-primaries", "--colour-transfer-characteristics", "--colour-matrix-coefficients"), codes)
+ zip(
+ ("--colour-primaries", "--colour-transfer-characteristics", "--colour-matrix-coefficients"),
+ codes,
+ strict=False,
+ )
)
for data in stream.get("side_data_list", []):
# ffprobe leaves out the fields a source does not carry, so a partial entry adds nothing
@@ -647,14 +649,14 @@ class Video(Track):
return stream
def ccextractor(
- self, track_id: Any, out_path: Union[Path, str], language: Language, original: bool = False
- ) -> Optional[Subtitle]:
+ self, track_id: Any, out_path: Path | str, language: Language, original: bool = False
+ ) -> Subtitle | None:
"""Return a TextTrack object representing CC track extracted by CCExtractor."""
if not self.path:
raise ValueError("You must download the track first.")
if not binaries.CCExtractor:
- raise EnvironmentError("ccextractor executable was not found.")
+ raise OSError("ccextractor executable was not found.")
out_path = Path(out_path)
ccextractor = binaries.CCExtractor
@@ -665,8 +667,7 @@ class Video(Track):
subprocess.run(
[ccextractor, "-trim", "-nobom", "-noru", "-ru1", "-o", out_path, video_path],
check=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
+ capture_output=True,
)
except subprocess.CalledProcessError as e:
out_path.unlink(missing_ok=True)
@@ -766,7 +767,7 @@ class Video(Track):
raise ValueError("Cannot clean a Track that has not been downloaded.")
if not binaries.FFMPEG:
- raise EnvironmentError('FFmpeg executable "ffmpeg" was not found but is required for this call.')
+ raise OSError('FFmpeg executable "ffmpeg" was not found but is required for this call.')
log = logging.getLogger("x264-clean")
log.info("Removing EIA-CC from Video Track with FFMPEG")
diff --git a/unshackle/core/tunnel.py b/unshackle/core/tunnel.py
index 7a61a233..3c8835e2 100644
--- a/unshackle/core/tunnel.py
+++ b/unshackle/core/tunnel.py
@@ -21,7 +21,7 @@ import socket
import ssl
import struct
import threading
-from typing import Any, Optional
+from typing import Any
from urllib.parse import unquote, urlsplit
import aiohttp
@@ -80,7 +80,7 @@ def frame(sid: int, kind: int, data: bytes = b"") -> bytes:
return HEADER.pack(sid, kind) + data
-def new_queue() -> asyncio.Queue[Optional[bytes]]:
+def new_queue() -> asyncio.Queue[bytes | None]:
return asyncio.Queue(maxsize=BACKLOG + 1) # the extra slot always takes the end marker
@@ -90,7 +90,7 @@ class Link:
def __init__(self, ws: Any) -> None:
self.ws = ws
self.lock = asyncio.Lock()
- self.streams: dict[int, asyncio.Queue[Optional[bytes]]] = {}
+ self.streams: dict[int, asyncio.Queue[bytes | None]] = {}
async def send(self, sid: int, kind: int, data: bytes = b"") -> None:
async with self.lock:
@@ -106,7 +106,7 @@ class Link:
finally:
await self.close_stream(sid) # the peer does not echo CLOSE, so this also ends our drain
- async def drain(self, q: asyncio.Queue[Optional[bytes]], writer: asyncio.StreamWriter) -> None:
+ async def drain(self, q: asyncio.Queue[bytes | None], writer: asyncio.StreamWriter) -> None:
"""Copy the bytes that the peer sends for one connection into a socket, then close the socket."""
try:
while (chunk := await q.get()) is not None:
@@ -144,29 +144,29 @@ class Link:
self.end(sid)
async def relay(
- self, sid: int, q: asyncio.Queue[Optional[bytes]], reader: asyncio.StreamReader, writer: asyncio.StreamWriter
+ self, sid: int, q: asyncio.Queue[bytes | None], reader: asyncio.StreamReader, writer: asyncio.StreamWriter
) -> None:
await asyncio.gather(self.pump(sid, reader), self.drain(q, writer))
-TUNNELS: dict[str, "Tunnel"] = {}
+TUNNELS: dict[str, Tunnel] = {}
class Tunnel:
"""The server side of one client's tunnel: a loopback SOCKS5 listener and the client's current link."""
- def __init__(self, owner: Optional[str], client: Optional[str] = None) -> None:
+ def __init__(self, owner: str | None, client: str | None = None) -> None:
self.id = secrets.token_urlsafe(16)
self.secret = secrets.token_urlsafe(24)
self.owner = owner
self.client = client
- self.link: Optional[Link] = None
+ self.link: Link | None = None
self.pending: dict[int, asyncio.Future[bool]] = {}
self.sids = itertools.count(1)
- self.listener: Optional[asyncio.Server] = None
- self.expiry: Optional[asyncio.TimerHandle] = None
+ self.listener: asyncio.Server | None = None
+ self.expiry: asyncio.TimerHandle | None = None
self.linked = asyncio.Event()
- self.closing: Optional[asyncio.Task[None]] = None
+ self.closing: asyncio.Task[None] | None = None
@property
def port(self) -> int:
@@ -216,12 +216,12 @@ class Tunnel:
fut.set_result(False)
link.end(sid)
- async def wait_link(self) -> Optional[Link]:
+ async def wait_link(self) -> Link | None:
"""The current link, waiting ``RELINK_WAIT`` seconds for a dropped one to come back."""
if not self.link:
try:
await asyncio.wait_for(self.linked.wait(), RELINK_WAIT)
- except asyncio.TimeoutError:
+ except TimeoutError:
pass
return self.link
@@ -275,7 +275,7 @@ class Tunnel:
try:
await link.send(sid, OPEN, port + host.encode())
ok = await asyncio.wait_for(fut, OPEN_TIMEOUT)
- except (asyncio.TimeoutError, asyncio.CancelledError, ConnectionError, RuntimeError):
+ except (TimeoutError, asyncio.CancelledError, ConnectionError, RuntimeError):
pass
if not ok:
self.pending.pop(sid, None)
@@ -311,7 +311,7 @@ class Tunnel:
self.closing = asyncio.ensure_future(self.close()) # held, so the loop cannot drop the task
-def tunnel_proxy(tunnel_id: str, owner: Optional[str]) -> Optional[str]:
+def tunnel_proxy(tunnel_id: str, owner: str | None) -> str | None:
"""The loopback proxy URI for the tunnel ``tunnel_id`` that the caller owns, or None."""
tunnel = TUNNELS.get(tunnel_id)
return tunnel.proxy_uri if tunnel and tunnel.owner == owner else None
@@ -322,7 +322,7 @@ async def close_tunnels(_: web.Application) -> None:
await tunnel.close()
-def parse_ip(address: str) -> Optional[ipaddress.IPv4Address | ipaddress.IPv6Address]:
+def parse_ip(address: str) -> ipaddress.IPv4Address | ipaddress.IPv6Address | None:
try:
return ipaddress.ip_address(address.partition("%")[0])
except ValueError:
@@ -373,7 +373,7 @@ async def connect_public(host: str, port: int) -> tuple[asyncio.StreamReader, as
for address in addresses:
try:
reader, writer = await asyncio.wait_for(asyncio.open_connection(address, port), 10)
- except (OSError, asyncio.TimeoutError) as e:
+ except (TimeoutError, OSError) as e:
error = OSError(str(e))
continue
if not dialled_itself(writer):
@@ -408,7 +408,7 @@ async def check_proxied_target(host: str, port: int) -> None:
infos = await asyncio.get_running_loop().getaddrinfo(host, port, type=socket.SOCK_STREAM)
except (OSError, UnicodeError):
if is_ip_literal(host):
- raise PermissionError(f"{host} is not a public address")
+ raise PermissionError(f"{host} is not a public address") from None
return
allowed_addresses(host, [str(info[4][0]) for info in infos])
@@ -488,14 +488,14 @@ async def socks5_handshake(
await reader.readexactly(length + 2)
-def parse_retry_after(value: Optional[str]) -> Optional[int]:
+def parse_retry_after(value: str | None) -> int | None:
"""Whole seconds, at least 1, from a delay-seconds Retry-After; None for an absent, HTTP-date or malformed one."""
if not value or len(value) > 9 or not (value.isascii() and value.isdigit()):
return None
return max(1, int(value))
-def retry_after(e: aiohttp.WSServerHandshakeError) -> Optional[int]:
+def retry_after(e: aiohttp.WSServerHandshakeError) -> int | None:
"""The Retry-After seconds of a rate-limit refusal, or None for any other refusal."""
return parse_retry_after(CIMultiDict(e.headers or {}).get("Retry-After")) if e.status == 429 else None
@@ -512,22 +512,22 @@ def refusal(e: aiohttp.WSServerHandshakeError) -> str:
class TunnelClient:
"""The client side: a background thread that keeps the tunnel's WebSocket open and dials for the server."""
- def __init__(self, server_url: str, headers: dict[str, str], proxy: Optional[str] = None) -> None:
+ def __init__(self, server_url: str, headers: dict[str, str], proxy: str | None = None) -> None:
self.url = server_url.rstrip("/") + ROUTE
self.headers = headers
self.proxy = proxy
self.proxy_failed = False
- self.id: Optional[str] = None
- self.error: Optional[BaseException] = None
- self.retry_after: Optional[int] = None
+ self.id: str | None = None
+ self.error: BaseException | None = None
+ self.retry_after: int | None = None
self.at_limit = False
self.lost = False
self.ready = threading.Event()
self.relays: set[asyncio.Task[None]] = set()
self.refused: set[str] = set()
self.thread = threading.Thread(target=lambda: asyncio.run(self.run()), name="tunnel", daemon=True)
- self.loop: Optional[asyncio.AbstractEventLoop] = None
- self.task: Optional[asyncio.Task[None]] = None
+ self.loop: asyncio.AbstractEventLoop | None = None
+ self.task: asyncio.Task[None] | None = None
def start(self, timeout: float = 20) -> str:
"""Open the tunnel and return its id."""
@@ -577,7 +577,7 @@ class TunnelClient:
log.warning(f"The server closed the tunnel (HTTP {e.status}), so its requests now fail")
self.ready.set()
return
- except (aiohttp.ClientError, asyncio.TimeoutError, ValueError, KeyError, TypeError) as e:
+ except (TimeoutError, aiohttp.ClientError, ValueError, KeyError, TypeError) as e:
self.error = e
if not self.id:
self.ready.set()
@@ -620,7 +620,7 @@ class TunnelClient:
log.warning(f"Tunnel refused {e}")
await link.close_stream(sid)
return
- except (OSError, ValueError, asyncio.TimeoutError) as e: # the idna codec raises ValueError on a bad hostname
+ except (TimeoutError, OSError, ValueError) as e: # the idna codec raises ValueError on a bad hostname
if self.proxy and not self.proxy_failed:
self.proxy_failed = True
log.warning(f"Tunnel dial through the proxy failed: {str(e) or 'timed out'}")
diff --git a/unshackle/core/update_checker.py b/unshackle/core/update_checker.py
index 1d43e85e..776f161d 100644
--- a/unshackle/core/update_checker.py
+++ b/unshackle/core/update_checker.py
@@ -3,7 +3,6 @@ from __future__ import annotations
import json
import time
from pathlib import Path
-from typing import Optional
import requests
@@ -47,7 +46,7 @@ class UpdateChecker:
return {}
try:
- with open(cache_file, "r") as f:
+ with open(cache_file) as f:
return json.load(f)
except (json.JSONDecodeError, OSError):
return {}
@@ -92,7 +91,7 @@ class UpdateChecker:
return False
@classmethod
- def fetch_latest_version(cls) -> Optional[str]:
+ def fetch_latest_version(cls) -> str | None:
"""
Fetch the latest version from GitHub API.
@@ -135,7 +134,7 @@ class UpdateChecker:
return (current_time - last_check) >= check_interval
@classmethod
- def update_cache(cls, latest_version: Optional[str] = None, current_version: Optional[str] = None) -> None:
+ def update_cache(cls, latest_version: str | None = None, current_version: str | None = None) -> None:
"""
Update the cache file with the current timestamp and version info.
@@ -184,7 +183,7 @@ class UpdateChecker:
current_parts.extend([0] * (max_length - len(current_parts)))
latest_parts.extend([0] * (max_length - len(latest_parts)))
- for current_part, latest_part in zip(current_parts, latest_parts):
+ for current_part, latest_part in zip(current_parts, latest_parts, strict=True):
if latest_part > current_part:
return True
elif latest_part < current_part:
@@ -195,7 +194,7 @@ class UpdateChecker:
return False
@classmethod
- def get_cached_update_info(cls, current_version: str) -> Optional[str]:
+ def get_cached_update_info(cls, current_version: str) -> str | None:
"""
Examine the cache for an update for the current version.
@@ -220,7 +219,7 @@ class UpdateChecker:
return None
@classmethod
- def check_for_updates_sync(cls, current_version: str, check_interval: Optional[int] = None) -> Optional[str]:
+ def check_for_updates_sync(cls, current_version: str, check_interval: int | None = None) -> str | None:
"""
Synchronous version of update check with rate limiting.
diff --git a/unshackle/core/utilities.py b/unshackle/core/utilities.py
index 34c74dd8..e03937ea 100644
--- a/unshackle/core/utilities.py
+++ b/unshackle/core/utilities.py
@@ -15,12 +15,13 @@ import traceback
import unicodedata
import zlib
from collections import defaultdict
-from datetime import datetime, timezone
+from collections.abc import Callable, Iterator, Mapping, Sequence
+from datetime import UTC, datetime
from fractions import Fraction
from functools import cache
from pathlib import Path
from types import ModuleType
-from typing import Any, Callable, Iterator, Mapping, Optional, Sequence, Union
+from typing import Any
from urllib.parse import ParseResult, urlparse
from uuid import uuid4
@@ -125,7 +126,7 @@ def import_module_by_path(path: Path) -> ModuleType:
RESOLUTION_TIERS = (4320, 2160, 1440, 1080, 720, 576, 540, 480, 360, 240)
-def standard_resolution(width: Optional[int], height: Optional[int]) -> Optional[int]:
+def standard_resolution(width: int | None, height: int | None) -> int | None:
"""The resolution a release name uses: the nearest standard height within 10%, from the short side or a 16:9 width.
A cropped 1920x800, a padded 1920x1088 and a 1080x1920 portrait picture are all 1080. A size with no
@@ -145,7 +146,7 @@ def standard_resolution(width: Optional[int], height: Optional[int]) -> Optional
return tier if abs(tier - equivalent) <= tier / 10 else round(equivalent)
-def sanitize_filename(filename: str, spacer: str = ".", unicode: Optional[bool] = None) -> str:
+def sanitize_filename(filename: str, spacer: str = ".", unicode: bool | None = None) -> str:
"""
Sanitise a string to be filename safe.
@@ -176,7 +177,7 @@ def sanitize_filename(filename: str, spacer: str = ".", unicode: Optional[bool]
return unicodedata.normalize("NFC", filename)
-def is_close_match(language: Union[str, Language], languages: Sequence[Union[str, Language, None]]) -> bool:
+def is_close_match(language: str | Language, languages: Sequence[str | Language | None]) -> bool:
"""Examine whether a language closely matches any of the given languages."""
languages = [x for x in languages if x]
if not languages:
@@ -184,7 +185,7 @@ def is_close_match(language: Union[str, Language], languages: Sequence[Union[str
return closest_match(language, list(map(str, languages)))[1] <= LANGUAGE_MAX_DISTANCE
-def valid_language(language: Any) -> Optional[str]:
+def valid_language(language: Any) -> str | None:
"""Return the language tag as text, or None when it is not a valid tag."""
if not language:
return None
@@ -234,7 +235,7 @@ def with_script(language: Language) -> Language:
return language.update_dict({"script": language.maximize().script}).simplify_script()
-def language_name(language: Language) -> Optional[str]:
+def language_name(language: Language) -> str | None:
"""
Return the name of a track language, or None for an unknown or private-use language.
@@ -272,7 +273,7 @@ def language_name(language: Language) -> Optional[str]:
return name[:1].upper() + name[1:] if full.script in ("Latn", "Cyrl", "Grek", "Armn") else name
-def is_exact_match(language: Union[str, Language], languages: Sequence[Union[str, Language, None]]) -> bool:
+def is_exact_match(language: str | Language, languages: Sequence[str | Language | None]) -> bool:
"""Examine whether a language exactly matches any of the given languages."""
languages = [x for x in languages if x]
if not languages:
@@ -280,7 +281,7 @@ def is_exact_match(language: Union[str, Language], languages: Sequence[Union[str
return closest_match(language, list(map(str, languages)))[1] <= LANGUAGE_EXACT_DISTANCE
-def partition_exclusions(tokens: Optional[Sequence[str]]) -> tuple[list[str], list[str]]:
+def partition_exclusions(tokens: Sequence[str] | None) -> tuple[list[str], list[str]]:
"""
Split selection tokens into wanted values and values excluded with a leading '-'.
@@ -315,7 +316,7 @@ def inherited_exclusions(own: Sequence[str], own_excl: Sequence[str], fallback_e
def matched_language_tags(
tokens: Sequence[str],
- available: Sequence[Union[str, Language, None]],
+ available: Sequence[str | Language | None],
exact: bool = False,
*,
every_variant: bool = False,
@@ -345,7 +346,7 @@ def plain_subtitle_tags(tokens: Sequence[str], subtitles: Sequence[Any], exact:
return tags | {str(lang) for lang in sdh if tags and matching_languages(lang, list(tags), exact=True)}
-def kind_only_conflict(params: Mapping[str, Any]) -> Optional[tuple[str, str]]:
+def kind_only_conflict(params: Mapping[str, Any]) -> tuple[str, str] | None:
"""
Return the first (kind-only flag, flag that drops its track type) pair that are both set.
@@ -401,7 +402,7 @@ def apply_original_language(title: Any, language: Language) -> None:
def find_missing_langs(
requested: Sequence[str],
- available: Sequence[Union[str, Language, None]],
+ available: Sequence[str | Language | None],
*,
exact: bool = False,
) -> list[str]:
@@ -412,8 +413,8 @@ def find_missing_langs(
def missing_required_langs(
required: Sequence[str],
- available: Sequence[Union[str, Language, None]],
- original: Optional[Union[str, Language]] = None,
+ available: Sequence[str | Language | None],
+ original: str | Language | None = None,
*,
exact: bool = False,
) -> list[str]:
@@ -427,14 +428,14 @@ def missing_required_langs(
return find_missing_langs(resolve_sort_langs(wanted, original, exact=exact), available, exact=exact)
-def as_requested(tokens: Sequence[str], orig_token: Optional[str]) -> str:
+def as_requested(tokens: Sequence[str], orig_token: str | None) -> str:
"""Return language tokens as the user wrote them, so 'orig' reads as 'orig' and not the language it resolved to."""
return ", ".join("orig" if tok == orig_token else tok for tok in tokens)
def matching_languages(
- language: Union[str, Language],
- available: Sequence[Union[str, Language, None]],
+ language: str | Language,
+ available: Sequence[str | Language | None],
exact: bool = False,
*,
every_variant: bool = False,
@@ -473,14 +474,12 @@ class ServiceTag(str):
"""
-def original_tag(language: Union[str, Language], exact: bool = False) -> str:
+def original_tag(language: str | Language, exact: bool = False) -> str:
"""The tag to match a service-supplied language with: a ServiceTag, or the plain tag in exact mode."""
return str(language) if exact else ServiceTag(str(language))
-def orig_token(
- requested: Sequence[str], language: Optional[Union[str, Language]], exact: bool = False
-) -> Optional[str]:
+def orig_token(requested: Sequence[str], language: str | Language | None, exact: bool = False) -> str | None:
"""The tag 'orig' resolved to, for as_requested. None when 'orig' did not resolve or the user also named that tag."""
if "orig" not in requested or not language:
return None
@@ -489,7 +488,7 @@ def orig_token(
def resolve_sort_langs(
- tokens: Sequence[str], original: Optional[Union[str, Language]] = None, *, exact: bool = False
+ tokens: Sequence[str], original: str | Language | None = None, *, exact: bool = False
) -> list[str]:
"""
Resolve language tokens for selection, exclusion and the Tracks.sort_* by_language argument.
@@ -574,7 +573,7 @@ def get_boxes(data: bytes, box_type: bytes, as_bytes: bool = False) -> Box: # t
offset = box_start + len(built)
- except IOError:
+ except OSError:
break
except ValidationError as e:
if box_type == b"tenc":
@@ -583,7 +582,7 @@ def get_boxes(data: bytes, box_type: bytes, as_bytes: bool = False) -> Box: # t
raise e
-def ap_case(text: str, keep_spaces: bool = False, stop_words: Optional[tuple[str, ...]] = None) -> str:
+def ap_case(text: str, keep_spaces: bool = False, stop_words: tuple[str, ...] | None = None) -> str:
"""
Convert a string to title case using AP/APA style.
Based on https://github.com/words/ap-style-title-case
@@ -641,7 +640,7 @@ COUNTRY_CODE_ALIASES = {
}
-def get_country_name(code: str) -> Optional[str]:
+def get_country_name(code: str) -> str | None:
"""
Convert a 2-letter country code to full country name.
@@ -670,7 +669,7 @@ def get_country_name(code: str) -> Optional[str]:
return None
-def get_country_code(name: str) -> Optional[str]:
+def get_country_code(name: str) -> str | None:
"""
Convert a country name to its 2-letter ISO 3166-1 alpha-2 code.
@@ -768,7 +767,7 @@ def get_free_port() -> int:
return s.getsockname()[1]
-def get_extension(value: Union[str, Path, ParseResult]) -> Optional[str]:
+def get_extension(value: str | Path | ParseResult) -> str | None:
"""
Get a URL or Path file extension/suffix.
@@ -788,7 +787,7 @@ def get_extension(value: Union[str, Path, ParseResult]) -> Optional[str]:
return None
-def extract_font_family(font_path: Path) -> Optional[str]:
+def extract_font_family(font_path: Path) -> str | None:
"""
Extract font family name from TTF/OTF file using fontTools.
@@ -953,7 +952,7 @@ FONT_ALIASES = {
}
-def find_case_insensitive(font_name: str, fonts: dict[str, Path]) -> Optional[Path]:
+def find_case_insensitive(font_name: str, fonts: dict[str, Path]) -> Path | None:
"""
Find a font by a case-insensitive name.
@@ -971,7 +970,7 @@ def find_case_insensitive(font_name: str, fonts: dict[str, Path]) -> Optional[Pa
return None
-def find_font_with_fallbacks(font_name: str, system_fonts: dict[str, Path]) -> Optional[Path]:
+def find_font_with_fallbacks(font_name: str, system_fonts: dict[str, Path]) -> Path | None:
"""
Find a font by name, with intelligent fallbacks.
@@ -1052,7 +1051,7 @@ def suggest_font_packages(missing_fonts: list[str]) -> dict[str, list[str]]:
needed_aliases.update(FONT_ALIASES[font])
# Map needed aliases to packages
- for package_name, package_info in FONT_PACKAGES.items():
+ for package_info in FONT_PACKAGES.values():
provided_fonts = package_info["fonts"]
matching_fonts = [f for f in provided_fonts if f in needed_aliases]
if matching_fonts:
@@ -1103,7 +1102,7 @@ class DebugLogger:
This makes it easy to parse, filter, and analyse logs programmatically.
"""
- def __init__(self, log_path: Optional[Path] = None, enabled: bool = False, log_keys: bool = False) -> None:
+ def __init__(self, log_path: Path | None = None, enabled: bool = False, log_keys: bool = False) -> None:
"""
Initialise the debug logger.
@@ -1148,13 +1147,13 @@ class DebugLogger:
level: str = "DEBUG",
operation: str = "",
message: str = "",
- context: Optional[dict[str, Any]] = None,
- service: Optional[str] = None,
- error: Optional[BaseException] = None,
- request: Optional[dict[str, Any]] = None,
- response: Optional[dict[str, Any]] = None,
- duration_ms: Optional[float] = None,
- success: Optional[bool] = None,
+ context: dict[str, Any] | None = None,
+ service: str | None = None,
+ error: BaseException | None = None,
+ request: dict[str, Any] | None = None,
+ response: dict[str, Any] | None = None,
+ duration_ms: float | None = None,
+ success: bool | None = None,
**kwargs: Any,
) -> None:
"""
@@ -1177,7 +1176,7 @@ class DebugLogger:
return
entry: dict[str, Any] = {
- "timestamp": datetime.now(timezone.utc).isoformat(),
+ "timestamp": datetime.now(UTC).isoformat(),
"session_id": self.session_id,
"level": level,
}
@@ -1300,7 +1299,7 @@ class DebugLogger:
operation: str,
operation_id: str,
success: bool = True,
- duration_ms: Optional[float] = None,
+ duration_ms: float | None = None,
**kwargs: Any,
) -> None:
"""
@@ -1397,10 +1396,10 @@ class DebugLogger:
# Global debug logger instance
-debug_logger: Optional[DebugLogger] = None
+debug_logger: DebugLogger | None = None
-def get_debug_logger() -> Optional[DebugLogger]:
+def get_debug_logger() -> DebugLogger | None:
"""Get the global debug logger instance."""
return debug_logger
@@ -1458,7 +1457,7 @@ def timed_operation(operation: str, *, level: str = "DEBUG", message: str = "",
)
-def init_debug_logger(log_path: Optional[Path] = None, enabled: bool = False, log_keys: bool = False) -> None:
+def init_debug_logger(log_path: Path | None = None, enabled: bool = False, log_keys: bool = False) -> None:
"""
Initialise the global debug logger.
diff --git a/unshackle/core/utils/bitrate.py b/unshackle/core/utils/bitrate.py
index 4409e2c6..93f47f9c 100644
--- a/unshackle/core/utils/bitrate.py
+++ b/unshackle/core/utils/bitrate.py
@@ -5,9 +5,10 @@ import logging
import subprocess
import time
from collections import OrderedDict, defaultdict
+from collections.abc import Callable, Hashable, Sequence
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Callable, Hashable, Optional, Sequence, Union, cast
+from typing import TYPE_CHECKING, cast
from urllib.parse import urljoin
from requests import Session
@@ -37,19 +38,19 @@ class Segment:
url: str
# The original byte-range string (e.g. "0-1023"), preserved as the segment's
# identity so distinct ranges of one file are never confused with each other.
- byte_range: Optional[str]
+ byte_range: str | None
# Size in bytes when derivable without a request (from a byte range); else None.
- known_size: Optional[int]
+ known_size: int | None
duration: float
def measure_real_bitrate(
- track: "Track",
- session: Union[Session, RnetSession],
+ track: Track,
+ session: Session | RnetSession,
*,
samples: int = 40,
log: logging.Logger,
-) -> Optional[int]:
+) -> int | None:
"""
Probe a track's actual media size to compute its real average bitrate.
@@ -117,7 +118,7 @@ def measure_real_bitrate(
def apply_real_bitrates(
tracks: list[TrackT],
- session: Union[Session, RnetSession],
+ session: Session | RnetSession,
*,
log: logging.Logger,
group_key: Callable[[TrackT], Hashable],
@@ -156,8 +157,8 @@ def apply_real_bitrates(
def probe_batch(
- tracks: Sequence["Track"],
- session: Union[Session, RnetSession],
+ tracks: Sequence[Track],
+ session: Session | RnetSession,
*,
log: logging.Logger,
workers: int,
@@ -166,7 +167,7 @@ def probe_batch(
if not tracks:
return
- def probe_one(track: "Track") -> tuple["Track", Optional[int]]:
+ def probe_one(track: Track) -> tuple[Track, int | None]:
return track, measure_real_bitrate(track, track.session or session, log=log)
with ThreadPoolExecutor(max_workers=min(workers, len(tracks))) as executor:
@@ -176,7 +177,7 @@ def probe_batch(
declared = getattr(track, "bitrate", None)
if declared and declared != measured:
log.debug(f"{track.id}: bitrate {declared // 1000} → {measured // 1000} kb/s (real)")
- setattr(track, "bitrate", measured)
+ track.bitrate = measured # type: ignore[attr-defined]
def dedupe(segments: list[Segment]) -> list[Segment]:
@@ -191,7 +192,7 @@ def dedupe(segments: list[Segment]) -> list[Segment]:
whose duration is the sum they cover. Distinct byte ranges of one file (different offsets) are
kept individual so their sizes still add up to the full track.
"""
- merged: OrderedDict[tuple[str, Optional[str]], Segment] = OrderedDict()
+ merged: OrderedDict[tuple[str, str | None], Segment] = OrderedDict()
for segment in segments:
key = (segment.url, segment.byte_range)
existing = merged.get(key)
@@ -212,7 +213,7 @@ def pick_samples(segments: list[Segment], samples: int) -> list[Segment]:
return [segments[i] for i in indices]
-def probe_size(segment: Segment, session: Union[Session, RnetSession]) -> Optional[int]:
+def probe_size(segment: Segment, session: Session | RnetSession) -> int | None:
"""Return a segment's byte size with a HEAD request, falling back to a ranged GET. Validates status."""
try:
res = session.head(segment.url, allow_redirects=True, timeout=PROBE_TIMEOUT)
@@ -240,7 +241,7 @@ def probe_size(segment: Segment, session: Union[Session, RnetSession]) -> Option
return None
-def range_size(byte_range: Optional[str]) -> Optional[int]:
+def range_size(byte_range: str | None) -> int | None:
"""Size in bytes of a ``start-end`` media range, inclusive."""
if not byte_range or "-" not in byte_range:
return None
@@ -255,8 +256,8 @@ def range_size(byte_range: Optional[str]) -> Optional[int]:
def uniform_segments(
- raw_segments: list[tuple[str, Optional[str]]],
- total_duration: Optional[float],
+ raw_segments: list[tuple[str, str | None]],
+ total_duration: float | None,
) -> list[Segment]:
"""
Assemble Segments giving each an equal share of the total duration.
@@ -273,7 +274,7 @@ def uniform_segments(
return [Segment(url, byte_range, range_size(byte_range), per_segment) for url, byte_range in raw_segments]
-def extract_dash(track: "Track", session: Union[Session, RnetSession]) -> list[Segment]:
+def extract_dash(track: Track, session: Session | RnetSession) -> list[Segment]:
from unshackle.core.manifests import DASH
data = track.data["dash"]
@@ -286,11 +287,11 @@ def extract_dash(track: "Track", session: Union[Session, RnetSession]) -> list[S
track_url = track.url if isinstance(track.url, str) else track.url[0]
periods = manifest.findall("Period")
- durations = dict(zip(map(id, periods), DASH.period_durations(manifest)))
+ durations = dict(zip(map(id, periods), DASH.period_durations(manifest), strict=True))
content_periods = [p for p in periods if DASH.is_content_period(p, filtered_period_ids)]
- raw_segments: list[tuple[str, Optional[str]]] = []
- kept: list[Optional[float]] = []
+ raw_segments: list[tuple[str, str | None]] = []
+ kept: list[float | None] = []
for period in content_periods:
# rep ids are only unique within an AdaptationSet, so resolve like DASH.download_track
if period is stored_period:
@@ -314,7 +315,7 @@ def extract_dash(track: "Track", session: Union[Session, RnetSession]) -> list[S
kept.append(durations[id(period)])
# the kept periods only, so filtered ad time does not lower the estimate
- total_duration: Optional[float] = sum(cast(list[float], kept)) if kept and None not in kept else None
+ total_duration: float | None = sum(cast(list[float], kept)) if kept and None not in kept else None
mpd_duration = manifest.get("mediaPresentationDuration")
if total_duration is None and mpd_duration:
total_duration = DASH.pt_to_sec(mpd_duration)
@@ -322,7 +323,7 @@ def extract_dash(track: "Track", session: Union[Session, RnetSession]) -> list[S
return uniform_segments(raw_segments, total_duration)
-def extract_hls(track: "Track", session: Union[Session, RnetSession]) -> list[Segment]:
+def extract_hls(track: Track, session: Session | RnetSession) -> list[Segment]:
import m3u8
playlist_url = track.url if isinstance(track.url, str) else track.url[0]
@@ -333,7 +334,7 @@ def extract_hls(track: "Track", session: Union[Session, RnetSession]) -> list[Se
for segment in playlist.segments:
url = urljoin(segment.base_uri or "", segment.uri)
byte_range = segment.byterange # "[@]"
- known_size: Optional[int] = None
+ known_size: int | None = None
if byte_range:
length = byte_range.split("@")[0].strip()
if length.isdigit():
@@ -343,7 +344,7 @@ def extract_hls(track: "Track", session: Union[Session, RnetSession]) -> list[Se
return out
-def extract_ism(track: "Track", session: Union[Session, RnetSession]) -> list[Segment]:
+def extract_ism(track: Track, session: Session | RnetSession) -> list[Segment]:
data = track.data["ism"]
segments: list[str] = data.get("segments") or []
manifest = data["manifest"]
@@ -355,13 +356,13 @@ def extract_ism(track: "Track", session: Union[Session, RnetSession]) -> list[Se
return uniform_segments([(url, None) for url in segments], total_duration)
-def extract_url(track: "Track", session: Union[Session, RnetSession], *, log: logging.Logger) -> list[Segment]:
+def extract_url(track: Track, session: Session | RnetSession, *, log: logging.Logger) -> list[Segment]:
"""Single-file track: one whole-file URL with the duration from leftover manifest data."""
url = track.url if isinstance(track.url, str) else (track.url[0] if track.url else None)
if not url:
return []
- duration: Optional[float] = None
+ duration: float | None = None
dash_data = track.data.get("dash")
if dash_data and dash_data.get("manifest") is not None:
from unshackle.core.manifests import DASH
@@ -388,7 +389,7 @@ def extract_url(track: "Track", session: Union[Session, RnetSession], *, log: lo
return [Segment(url, None, None, duration)]
-def ffprobe_duration(url: str, session: Union[Session, RnetSession], *, log: logging.Logger) -> Optional[float]:
+def ffprobe_duration(url: str, session: Session | RnetSession, *, log: logging.Logger) -> float | None:
"""
Read a single-file track's duration (seconds) without a manifest.
@@ -410,7 +411,7 @@ def ffprobe_duration(url: str, session: Union[Session, RnetSession], *, log: log
return duration
-def ranged_get(url: str, session: Union[Session, RnetSession], byte_range: str) -> Optional[bytes]:
+def ranged_get(url: str, session: Session | RnetSession, byte_range: str) -> bytes | None:
"""Fetch a byte range, only accepting a real 206 partial response (never a full 200 body)."""
try:
res = session.get(url, headers={"Range": byte_range}, timeout=PROBE_TIMEOUT)
@@ -422,7 +423,7 @@ def ranged_get(url: str, session: Union[Session, RnetSession], byte_range: str)
return None
-def probe_bytes_duration(data: Optional[bytes], log: logging.Logger) -> Optional[float]:
+def probe_bytes_duration(data: bytes | None, log: logging.Logger) -> float | None:
"""Pipe media bytes to FFprobe and return the container or track duration in seconds."""
if not data:
return None
@@ -432,8 +433,7 @@ def probe_bytes_duration(data: Optional[bytes], log: logging.Logger) -> Optional
result = subprocess.run(
[ffprobe_bin, "-v", "error", "-show_entries", "format=duration:stream=duration", "-of", "json", "pipe:"],
input=data,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
+ capture_output=True,
timeout=60,
)
log_tool_run(
diff --git a/unshackle/core/utils/click_types.py b/unshackle/core/utils/click_types.py
index ca08388e..2d8683f7 100644
--- a/unshackle/core/utils/click_types.py
+++ b/unshackle/core/utils/click_types.py
@@ -1,7 +1,8 @@
import re
+from collections.abc import Callable, Sequence
from datetime import date, timedelta
from enum import Enum
-from typing import Any, Callable, Optional, Sequence, Union
+from typing import Any
import click
from click.shell_completion import CompletionItem
@@ -35,7 +36,7 @@ class VideoCodecChoice(click.Choice):
super().__init__(list(self._name_to_codec), case_sensitive=False)
- def convert(self, value: Any, param: Optional[click.Parameter] = None, ctx: Optional[click.Context] = None) -> Any:
+ def convert(self, value: Any, param: click.Parameter | None = None, ctx: click.Context | None = None) -> Any:
if not value:
return None
if isinstance(value, self.codec_enum):
@@ -57,9 +58,7 @@ class MultipleVideoCodecChoice(VideoCodecChoice):
name = "multiple_video_codec_choice"
- def convert(
- self, value: Any, param: Optional[click.Parameter] = None, ctx: Optional[click.Context] = None
- ) -> list[Any]:
+ def convert(self, value: Any, param: click.Parameter | None = None, ctx: click.Context | None = None) -> list[Any]:
if not value:
return []
if isinstance(value, list):
@@ -136,8 +135,8 @@ class SubtitleCodecChoice(click.Choice):
super().__init__(choices, case_sensitive=False)
def convert(
- self, value: Any, param: Optional[click.Parameter] = None, ctx: Optional[click.Context] = None
- ) -> Union[Subtitle.Codec, str, None]:
+ self, value: Any, param: click.Parameter | None = None, ctx: click.Context | None = None
+ ) -> Subtitle.Codec | str | None:
if not value:
return None
@@ -164,9 +163,9 @@ class ContextData:
config: dict,
cdm: Any,
proxy_providers: list,
- profile: Optional[str] = None,
+ profile: str | None = None,
cdm_entry: bool = False,
- cdm_for: Optional[Callable[[str, Optional[int]], Any]] = None,
+ cdm_for: Callable[[str, int | None], Any] | None = None,
) -> None:
self.config = config
self.cdm = cdm
@@ -207,7 +206,7 @@ class SeasonRange(click.ParamType):
self.fail(f"Invalid range, a date range cannot span more than {self.MAX_DATE_SPAN} days: {token}")
return [(left + timedelta(days=i)).isoformat() for i in range(span)]
- def token_sides(self, match: re.Match) -> tuple[int, Optional[int], Optional[int]]:
+ def token_sides(self, match: re.Match) -> tuple[int, int | None, int | None]:
"""Read one side of a token as (season, episode, part), episode/part None when absent.
A music disc x track token shares this (season, episode, part) space, disc reading
@@ -325,7 +324,7 @@ class SeasonRange(click.ParamType):
PARSED_KEY = re.compile(r"^!?(0|[1-9]\d*)x(0|[1-9]\d*)(\.[1-9]\d?)?$")
def convert(
- self, value: Union[str, list], param: Optional[click.Parameter] = None, ctx: Optional[click.Context] = None
+ self, value: str | list, param: click.Parameter | None = None, ctx: click.Context | None = None
) -> list[str]:
"""Parse a comma or semicolon separated string, or a list of tokens; parsed keys such as ``!1x2.3`` pass."""
tokens = re.split(r"\s*[,;]\s*", value) if isinstance(value, str) else value
@@ -340,7 +339,7 @@ class LanguageRange(click.ParamType):
name = "lang_range"
def convert(
- self, value: Union[str, list], param: Optional[click.Parameter] = None, ctx: Optional[click.Context] = None
+ self, value: str | list, param: click.Parameter | None = None, ctx: click.Context | None = None
) -> list[str]:
if isinstance(value, list):
return value
@@ -354,9 +353,9 @@ class QualityList(click.ParamType):
def convert(
self,
- value: Union[str, int, Sequence[Union[str, int]]],
- param: Optional[click.Parameter] = None,
- ctx: Optional[click.Context] = None,
+ value: str | int | Sequence[str | int],
+ param: click.Parameter | None = None,
+ ctx: click.Context | None = None,
) -> list[int]:
if not value:
return []
@@ -406,7 +405,7 @@ class AudioCodecList(click.ParamType):
def get_metavar(self, *args: Any, **kwargs: Any) -> str:
return f"[{'|'.join(self.choices)}]"
- def convert(self, value: Any, param: Optional[click.Parameter] = None, ctx: Optional[click.Context] = None) -> list:
+ def convert(self, value: Any, param: click.Parameter | None = None, ctx: click.Context | None = None) -> list:
if not value:
return []
if isinstance(value, self.codec_enum):
@@ -455,9 +454,7 @@ class MultipleChoice(click.Choice):
def __repr__(self) -> str:
return f"MultipleChoice({list(self.choices)})"
- def convert(
- self, value: Any, param: Optional[click.Parameter] = None, ctx: Optional[click.Context] = None
- ) -> list[Any]:
+ def convert(self, value: Any, param: click.Parameter | None = None, ctx: click.Context | None = None) -> list[Any]:
if not value:
return []
if isinstance(value, str):
@@ -501,9 +498,7 @@ class SlowDelayRange(click.ParamType):
name = "delay_range"
- def convert(
- self, value: Any, param: Optional[click.Parameter], ctx: Optional[click.Context]
- ) -> Optional[tuple[int, int]]:
+ def convert(self, value: Any, param: click.Parameter | None, ctx: click.Context | None) -> tuple[int, int] | None:
if isinstance(value, tuple):
return value
if isinstance(value, bool):
@@ -529,9 +524,7 @@ class SampleRange(click.ParamType):
name = "sample_range"
- def convert(
- self, value: Any, param: Optional[click.Parameter], ctx: Optional[click.Context]
- ) -> Optional[tuple[int, int]]:
+ def convert(self, value: Any, param: click.Parameter | None, ctx: click.Context | None) -> tuple[int, int] | None:
if isinstance(value, bool):
return DEFAULT_SAMPLE if value else None
if isinstance(value, (list, tuple)) and len(value) == 2:
diff --git a/unshackle/core/utils/collections.py b/unshackle/core/utils/collections.py
index c1d66b2e..d2a2f680 100644
--- a/unshackle/core/utils/collections.py
+++ b/unshackle/core/utils/collections.py
@@ -1,5 +1,6 @@
import itertools
-from typing import Any, Iterable, Iterator, Sequence, Tuple, Type, Union
+from collections.abc import Iterable, Iterator, Sequence
+from typing import Any
def as_lists(*args: Any) -> Iterator[Any]:
@@ -19,7 +20,7 @@ def as_list(*args: Any) -> list:
return list(itertools.chain.from_iterable(as_lists(*args)))
-def flatten(items: Any, ignore_types: Union[Type, Tuple[Type, ...]] = str) -> Iterator:
+def flatten(items: Any, ignore_types: type | tuple[type, ...] = str) -> Iterator:
"""
Flattens items recursively.
diff --git a/unshackle/core/utils/dovi.py b/unshackle/core/utils/dovi.py
index 6f7918a6..8290713b 100644
--- a/unshackle/core/utils/dovi.py
+++ b/unshackle/core/utils/dovi.py
@@ -16,7 +16,6 @@ import json
import subprocess
import time
from pathlib import Path
-from typing import Optional, Union
from unshackle.core import binaries
from unshackle.core.utils.subprocess import log_tool_run, run_step
@@ -24,7 +23,7 @@ from unshackle.core.utils.subprocess import log_tool_run, run_step
def require_dovi_tool() -> str:
if not binaries.DoviTool:
- raise EnvironmentError("dovi_tool executable was not found but is required.")
+ raise OSError("dovi_tool executable was not found but is required.")
return str(binaries.DoviTool)
@@ -32,8 +31,8 @@ def extract_rpu(
source: Path,
output: Path,
*,
- mode: Optional[int] = 3,
- status: Optional[str] = "Extracting DV RPU...",
+ mode: int | None = 3,
+ status: str | None = "Extracting DV RPU...",
label: str = "dovi_tool extract-rpu",
) -> bytes:
"""Extract DV RPU NALs from a raw HEVC bitstream. `mode=None` skips the -m flag (untouched)."""
@@ -50,7 +49,7 @@ def inject_rpu(
rpu: Path,
output: Path,
*,
- status: Optional[str] = "Re-injecting DV RPU...",
+ status: str | None = "Re-injecting DV RPU...",
label: str = "dovi_tool inject-rpu",
) -> bytes:
"""Inject a DV RPU back into a raw HEVC bitstream, producing DV-signaled output."""
@@ -68,7 +67,7 @@ def editor(
json_spec: Path,
output: Path,
*,
- status: Optional[str] = "Editing DV RPU...",
+ status: str | None = "Editing DV RPU...",
label: str = "dovi_tool editor",
) -> bytes:
"""Apply a JSON edit spec to an RPU file."""
@@ -124,20 +123,20 @@ def info_frame(rpu: Path, frame: int = 0) -> dict:
try:
return json.loads(p.stdout[start:])
except json.JSONDecodeError as e:
- raise RuntimeError(f"dovi_tool info returned invalid JSON: {e}")
+ raise RuntimeError(f"dovi_tool info returned invalid JSON: {e}") from e
def generate(
config_json: Path,
output: Path,
*,
- hdr10plus_json: Optional[Path] = None,
- status: Optional[str] = "Generating DV RPU...",
+ hdr10plus_json: Path | None = None,
+ status: str | None = "Generating DV RPU...",
label: str = "dovi_tool generate",
) -> bytes:
"""Build a DV RPU from a dovi_tool generator config, and from hdr10plus_tool JSON when given."""
tool = require_dovi_tool()
- extra: list[Union[str, Path]] = ["--hdr10plus-json", hdr10plus_json] if hdr10plus_json else []
+ extra: list[str | Path] = ["--hdr10plus-json", hdr10plus_json] if hdr10plus_json else []
return run_step(
[tool, "generate", "-j", config_json, *extra, "-o", output],
status=status,
diff --git a/unshackle/core/utils/firefox_cookie_extractor.py b/unshackle/core/utils/firefox_cookie_extractor.py
index e70a7589..d7629a2e 100644
--- a/unshackle/core/utils/firefox_cookie_extractor.py
+++ b/unshackle/core/utils/firefox_cookie_extractor.py
@@ -10,7 +10,6 @@ import sqlite3
import tempfile
from http.cookiejar import Cookie, CookieJar
from pathlib import Path
-from typing import Dict, List, Optional
def get_firefox_root() -> Path:
@@ -49,7 +48,7 @@ def get_latest_profile_path(ff_root: Path) -> Path:
return max(valid_profiles, key=lambda p: (p / "cookies.sqlite").stat().st_mtime)
-def get_local_storage_data(profile_path: Path, hosts: List[str], tmp_dir_path: Path) -> Dict[str, str]:
+def get_local_storage_data(profile_path: Path, hosts: list[str], tmp_dir_path: Path) -> dict[str, str]:
"""
Extracts LocalStorage tokens from webappsstore.sqlite with strict origin matching.
Operates within a secure temporary directory.
@@ -83,7 +82,7 @@ def get_local_storage_data(profile_path: Path, hosts: List[str], tmp_dir_path: P
return extracted_storage
-def get_firefox_cookies(service_settings: dict) -> Optional[CookieJar]:
+def get_firefox_cookies(service_settings: dict) -> CookieJar | None:
"""
Extracts cookies and optionally localStorage from Firefox based on provided host patterns.
Implements security hardening and data consistency (it can copy the WAL log) as per PR review.
diff --git a/unshackle/core/utils/hdr10plus.py b/unshackle/core/utils/hdr10plus.py
index d02879e6..c3218935 100644
--- a/unshackle/core/utils/hdr10plus.py
+++ b/unshackle/core/utils/hdr10plus.py
@@ -2,8 +2,9 @@ from __future__ import annotations
import logging
import struct
+from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor
-from typing import TYPE_CHECKING, Callable, Optional, TypeVar, Union
+from typing import TYPE_CHECKING, TypeVar
from urllib.parse import urljoin
from requests import Session
@@ -39,7 +40,7 @@ def is_ts(data: bytes) -> bool:
return data[:1] == b"\x47" and (len(data) <= TS_PACKET or data[TS_PACKET : TS_PACKET + 1] == b"\x47")
-def ts_streams(data: bytes) -> Optional[list[tuple[int, bytes]]]:
+def ts_streams(data: bytes) -> list[tuple[int, bytes]] | None:
"""The ``stream_type`` and registration format identifier of each PMT entry, or None without a PMT."""
entries = ts_pmt(data)
return None if entries is None else [(stream_type, registration) for _, stream_type, registration in entries]
@@ -56,7 +57,7 @@ def ts_payload(packet: bytes) -> bytes:
return packet[5 + packet[4] if adaptation & 2 else 4 :] if adaptation & 1 else b""
-def ts_pmt(data: bytes) -> Optional[list[tuple[int, int, bytes]]]:
+def ts_pmt(data: bytes) -> list[tuple[int, int, bytes]] | None:
"""The PID, ``stream_type`` and registration format identifier of each PMT entry, or None without a PMT.
PAT program 0 names the network information table, so it is skipped. Lengths that run past the packet
@@ -101,7 +102,7 @@ def ts_pmt(data: bytes) -> Optional[list[tuple[int, int, bytes]]]:
return None
-def sei_number(rbsp: bytes, i: int) -> tuple[Optional[int], int]:
+def sei_number(rbsp: bytes, i: int) -> tuple[int | None, int]:
"""Read the SEI payload type or size that starts at ``i``: 0xFF bytes add 255 each. Returns (value, next)."""
value = 0
while i < len(rbsp) and rbsp[i] == 0xFF:
@@ -127,7 +128,7 @@ def sei_has_t35(nal: bytes, t35: bytes) -> bool:
return False
-def fragment_has_t35(data: bytes, t35: bytes) -> Optional[bool]:
+def fragment_has_t35(data: bytes, t35: bytes) -> bool | None:
"""Whether the first sample of an fMP4 fragment carries the T.35 SEI that ``t35`` starts, or None when the bytes
cannot tell. ``HDR10PLUS_T35`` finds HDR10+, ``CUVA_T35`` HDR Vivid.
@@ -156,7 +157,7 @@ def fragment_has_t35(data: bytes, t35: bytes) -> Optional[bool]:
return None
-def first_segment(track: "Track", session: Union[Session, RnetSession]) -> Optional[tuple[str, int]]:
+def first_segment(track: Track, session: Session | RnetSession) -> tuple[str, int] | None:
"""The URL and start offset of the track's first media segment, looked up without a full parse."""
from unshackle.core.manifests import DASH
from unshackle.core.tracks.track import Track
@@ -196,7 +197,7 @@ def first_segment(track: "Track", session: Union[Session, RnetSession]) -> Optio
return None
-def first_fragment(track: "Track", session: Union[Session, RnetSession]) -> Optional[bytes]:
+def first_fragment(track: Track, session: Session | RnetSession) -> bytes | None:
"""The first PROBE_BYTES of the track's first media fragment, or of its first segment when that is MPEG-TS."""
segment = first_segment(track, session)
if not segment:
@@ -222,12 +223,12 @@ def first_fragment(track: "Track", session: Union[Session, RnetSession]) -> Opti
def probe_dynamic_hdr(
- videos: list["Video"],
- session: Union[Session, RnetSession],
+ videos: list[Video],
+ session: Session | RnetSession,
*,
log: logging.Logger,
workers: int,
- on_start: Optional[Callable[[], None]] = None,
+ on_start: Callable[[], None] | None = None,
) -> None:
"""Relabel HEVC tracks by the dynamic HDR metadata of their first sample, and flag DV tracks with HDR10+.
@@ -254,7 +255,7 @@ def probe_dynamic_hdr(
if any(ladders) and on_start:
on_start()
- def proven(data: Optional[bytes]) -> Optional["Video.Range"]:
+ def proven(data: bytes | None) -> Video.Range | None:
if not data:
return None
if is_ts(data):
@@ -263,7 +264,7 @@ def probe_dynamic_hdr(
return Video.Range.VIVID
return Video.Range.HDR10P if fragment_has_t35(data, HDR10PLUS_T35) else None
- def probe(video: "Video") -> Optional["Video.Range"]:
+ def probe(video: Video) -> Video.Range | None:
"""The range the first segment proves (HDR10P or VIVID), else None."""
try:
found = proven(first_fragment(video, video.session or session))
@@ -273,10 +274,10 @@ def probe_dynamic_hdr(
log.debug(f"{video.id}: dynamic HDR probe {found}")
return found
- def probe_all(tracks: list["Video"]) -> dict[int, Optional["Video.Range"]]:
- return dict(zip(map(id, tracks), map_probes(probe, tracks, workers)))
+ def probe_all(tracks: list[Video]) -> dict[int, Video.Range | None]:
+ return dict(zip(map(id, tracks), map_probes(probe, tracks, workers), strict=True))
- plans: list[tuple[list["Video"], list["Video"], list["Video"]]] = []
+ plans: list[tuple[list[Video], list[Video], list[Video]]] = []
for candidates in ladders:
if len(candidates) <= 4 or len({(v.width, v.height) for v in candidates}) < len(candidates):
plans.append((candidates, candidates, []))
@@ -287,9 +288,11 @@ def probe_dynamic_hdr(
found = probe_all([v for _, samples, _ in plans for v in samples])
labels = [{found[id(s)] for s in samples} for _, samples, _ in plans]
found.update(
- probe_all([v for (_, _, rest), seen in zip(plans, labels) if any(seen) and len(seen) > 1 for v in rest])
+ probe_all(
+ [v for (_, _, rest), seen in zip(plans, labels, strict=True) if any(seen) and len(seen) > 1 for v in rest]
+ )
)
- for (candidates, _, _), seen in zip(plans, labels):
+ for (candidates, _, _), seen in zip(plans, labels, strict=True):
whole = next(iter(seen)) if len(seen) == 1 else None
for video in candidates:
label = found.get(id(video), whole)
@@ -300,7 +303,7 @@ def probe_dynamic_hdr(
def probe_audio_codecs(
- audio: list["Audio"], session: Union[Session, RnetSession], *, log: logging.Logger, workers: int
+ audio: list[Audio], session: Session | RnetSession, *, log: logging.Logger, workers: int
) -> None:
"""Name the codec of each audio track that has none from the PMT of its MPEG-TS first segment.
@@ -308,7 +311,7 @@ def probe_audio_codecs(
"""
from unshackle.core.tracks import Audio
- def probe(track: "Audio") -> None:
+ def probe(track: Audio) -> None:
try:
track_session = track.session or session
segment = first_segment(track, track_session)
@@ -328,12 +331,12 @@ def probe_audio_codecs(
def probed_tracks(
- service: "Service",
- title: "Title_T",
+ service: Service,
+ title: Title_T,
*,
- workers: Optional[int] = None,
- on_probe: Optional[Callable[[], None]] = None,
-) -> "Tracks":
+ workers: int | None = None,
+ on_probe: Callable[[], None] | None = None,
+) -> Tracks:
"""The title's tracks from ``service.get_tracks``, with HDR10+ and HDR Vivid found in HDR10 and HLG tracks.
Audio with no codec gets one from the MPEG-TS ``stream_type``. ``workers`` defaults to ``dl.workers`` from
diff --git a/unshackle/core/utils/ip_info.py b/unshackle/core/utils/ip_info.py
index 300b0c8b..d1f7444b 100644
--- a/unshackle/core/utils/ip_info.py
+++ b/unshackle/core/utils/ip_info.py
@@ -2,7 +2,8 @@ from __future__ import annotations
import logging
import time
-from typing import Any, Callable, Optional
+from collections.abc import Callable
+from typing import Any
import requests
@@ -20,7 +21,7 @@ REQUEST_TIMEOUT = 10
# verify_proxy_exit compares against the proxy exit IP.
GEO_CACHE_KEYS = ("ip", "country", "country_code")
-Fetcher = Callable[[requests.Session], Optional[dict]]
+Fetcher = Callable[[requests.Session], dict | None]
log = logging.getLogger("ip_info")
@@ -40,7 +41,7 @@ def normalize(
as_name: str = "",
continent_code: str = "",
timezone: str = "",
-) -> Optional[dict]:
+) -> dict | None:
"""Assemble the canonical IP-info dict, or None if no country code is present."""
code = country_code.strip()
if not code:
@@ -59,7 +60,7 @@ def normalize(
}
-def parse_ipinfo_lite(data: dict) -> Optional[dict]:
+def parse_ipinfo_lite(data: dict) -> dict | None:
asn = (data.get("asn") or "").strip()
as_name = (data.get("as_name") or "").strip()
return normalize(
@@ -72,7 +73,7 @@ def parse_ipinfo_lite(data: dict) -> Optional[dict]:
)
-def parse_ipinfo(data: dict) -> Optional[dict]:
+def parse_ipinfo(data: dict) -> dict | None:
return normalize(
country_code=data.get("country") or "",
ip=data.get("ip") or "",
@@ -83,7 +84,7 @@ def parse_ipinfo(data: dict) -> Optional[dict]:
)
-def parse_ip_api_in(data: dict) -> Optional[dict]:
+def parse_ip_api_in(data: dict) -> dict | None:
asn = (data.get("asn") or "").strip()
org_name = (data.get("organization") or "").strip()
return normalize(
@@ -99,7 +100,7 @@ def parse_ip_api_in(data: dict) -> Optional[dict]:
)
-def lookup_session(source: Optional[requests.Session]) -> requests.Session:
+def lookup_session(source: requests.Session | None) -> requests.Session:
"""
Assemble a plain, retry-free `requests` HTTP session for IP geolocation.
@@ -120,7 +121,7 @@ def lookup_session(source: Optional[requests.Session]) -> requests.Session:
return sess
-def json_or_raise(response: requests.Response) -> Optional[dict]:
+def json_or_raise(response: requests.Response) -> dict | None:
"""Raise RateLimited on 429, return parsed JSON on 200, else None."""
if response.status_code == 429:
raise RateLimited()
@@ -135,19 +136,19 @@ def json_or_raise(response: requests.Response) -> Optional[dict]:
def fetch_ipinfo_lite(token: str) -> Fetcher:
headers = {"Authorization": f"Bearer {token}"}
- def fetch(session: requests.Session) -> Optional[dict]:
+ def fetch(session: requests.Session) -> dict | None:
payload = json_or_raise(session.get("https://api.ipinfo.io/lite/me", headers=headers, timeout=REQUEST_TIMEOUT))
return parse_ipinfo_lite(payload) if payload else None
return fetch
-def fetch_ipinfo(session: requests.Session) -> Optional[dict]:
+def fetch_ipinfo(session: requests.Session) -> dict | None:
payload = json_or_raise(session.get("https://ipinfo.io/json", timeout=REQUEST_TIMEOUT))
return parse_ipinfo(payload) if payload else None
-def fetch_ip_api_in(session: requests.Session) -> Optional[dict]:
+def fetch_ip_api_in(session: requests.Session) -> dict | None:
"""ip-api.in has no /me endpoint, so get the IP from ipify first, then look it up."""
ip_resp = session.get("https://api.ipify.org", timeout=REQUEST_TIMEOUT)
if ip_resp.status_code == 429:
@@ -189,12 +190,12 @@ def load_provider_state(cacher: Cacher) -> dict[str, Any]:
def get_ip_info(
- session: Optional[requests.Session] = None,
+ session: requests.Session | None = None,
*,
cached: bool = False,
- errors: Optional[list[Exception]] = None,
+ errors: list[Exception] | None = None,
require: tuple[str, ...] = (),
-) -> Optional[dict]:
+) -> dict | None:
"""
Look up IP/geolocation info through ipinfo.io (Lite when `ipinfo_api_key` configured)
with fallback to ip-api.in.
diff --git a/unshackle/core/utils/language_tags.py b/unshackle/core/utils/language_tags.py
index 4f7678ae..68a0af4b 100644
--- a/unshackle/core/utils/language_tags.py
+++ b/unshackle/core/utils/language_tags.py
@@ -3,8 +3,10 @@
from __future__ import annotations
import logging
+from collections.abc import Mapping
from collections.abc import Mapping as MappingABC
-from typing import Any, Mapping, Optional, Sequence
+from collections.abc import Sequence
+from typing import Any
from langcodes import Language
@@ -27,7 +29,7 @@ def evaluate_language_tag(
rules: list[dict[str, Any]],
audio_languages: Sequence[Language],
subtitle_languages: Sequence[Language],
- states: Optional[Mapping[str, bool]] = None,
+ states: Mapping[str, bool] | None = None,
) -> str:
"""Evaluate language tag rules against selected tracks.
@@ -69,7 +71,7 @@ def rule_matches(
rule: dict[str, Any],
audio_languages: Sequence[Language],
subtitle_languages: Sequence[Language],
- states: Optional[Mapping[str, bool]] = None,
+ states: Mapping[str, bool] | None = None,
) -> bool:
"""Return True when every condition in the rule matches the tracks."""
unknown = [key for key in rule if key not in (*LANGUAGE_CONDITIONS, *STATE_CONDITIONS, "tag")]
diff --git a/unshackle/core/utils/post_scripts.py b/unshackle/core/utils/post_scripts.py
index ae9aae12..9a0c2dc6 100644
--- a/unshackle/core/utils/post_scripts.py
+++ b/unshackle/core/utils/post_scripts.py
@@ -19,9 +19,10 @@ import os
import re
import shlex
import subprocess
+from collections.abc import Iterator, Sequence
from pathlib import Path
from types import SimpleNamespace
-from typing import Any, Iterator, Optional, Sequence
+from typing import Any
from unshackle.core.config import config
from unshackle.core.console import console
@@ -75,7 +76,7 @@ def substitute(tokens: Sequence[str], context: dict[str, str]) -> list[str]:
return argv
-def _data_injected_flag(tokens: Sequence[str], argv: Sequence[str]) -> Optional[str]:
+def _data_injected_flag(tokens: Sequence[str], argv: Sequence[str]) -> str | None:
"""A token that only became a ``-flag`` after substitution.
Tokenizing before substituting stops a value becoming a *new* token, but a bare
@@ -84,7 +85,7 @@ def _data_injected_flag(tokens: Sequence[str], argv: Sequence[str]) -> Optional[
value, not the template. A literal flag like ``--opt={var}`` starts with ``-`` in the
template itself and is the user's own, so it is never flagged.
"""
- for template, token in zip(tokens, argv):
+ for template, token in zip(tokens, argv, strict=False):
if token.startswith("-") and not template.startswith("-"):
return token
return None
@@ -92,13 +93,13 @@ def _data_injected_flag(tokens: Sequence[str], argv: Sequence[str]) -> Optional[
def build_context(
title: Any,
- media_info: Optional[Any] = None,
+ media_info: Any | None = None,
*,
- filepath: Optional[Path] = None,
- folder: Optional[Path] = None,
+ filepath: Path | None = None,
+ folder: Path | None = None,
sidecars: Sequence[Path] = (),
service: str = "",
- ids: Optional[dict[str, Any]] = None,
+ ids: dict[str, Any] | None = None,
error: str = "",
) -> dict[str, str]:
"""Assemble the variable set for one output file.
diff --git a/unshackle/core/utils/redact.py b/unshackle/core/utils/redact.py
index 69af12e6..019872cc 100644
--- a/unshackle/core/utils/redact.py
+++ b/unshackle/core/utils/redact.py
@@ -5,8 +5,9 @@ from __future__ import annotations
import logging
import re
import sys
+from collections.abc import Iterable
from pathlib import Path
-from typing import Iterable, Optional, overload
+from typing import overload
from urllib.parse import urlsplit, urlunsplit
REDACTED = "***"
@@ -21,7 +22,7 @@ SENSITIVE_QUERY_PARAM_RE = re.compile(
)
-def redact_text(text: Optional[str], secrets: Iterable[str] = ()) -> Optional[str]:
+def redact_text(text: str | None, secrets: Iterable[str] = ()) -> str | None:
"""
Mask URL userinfo, secret-bearing query parameters, and any known secret
strings inside a free-text value before unshackle logs or serializes it.
@@ -120,7 +121,7 @@ def path_redaction_enabled() -> bool:
def redact_path(text: str) -> str: ...
@overload
def redact_path(text: None) -> None: ...
-def redact_path(text: Optional[str]) -> Optional[str]:
+def redact_path(text: str | None) -> str | None:
"""Replace local base-directory prefixes (install root, venv, home) in ``text`` with tokens.
Idempotent and cheap. It touches only the strings that contain a known base dir, so URLs
@@ -140,7 +141,7 @@ URL_RE = re.compile(r"https?://[^\s\"'<>\\]+", re.IGNORECASE)
EXT_RE = re.compile(r"^\.[A-Za-z0-9]{1,5}$")
-def collapse_url(match: "re.Match[str]") -> str:
+def collapse_url(match: re.Match[str]) -> str:
url = match.group(0)
try:
suffix = Path(urlsplit(url).path).suffix
@@ -151,7 +152,7 @@ def collapse_url(match: "re.Match[str]") -> str:
return f"redacted{suffix}"
-def redact_url(text: Optional[str]) -> Optional[str]:
+def redact_url(text: str | None) -> str | None:
"""Collapse every http(s) URL in ``text`` to ``redacted[.ext]``.
Hides media/CDN/manifest/segment/api locations (host + path + query) from shareable debug
@@ -163,12 +164,12 @@ def redact_url(text: Optional[str]) -> Optional[str]:
return URL_RE.sub(collapse_url, text)
-def redact_all(text: Optional[str]) -> Optional[str]:
+def redact_all(text: str | None) -> str | None:
"""Full redaction for logged strings: secrets, then URLs, then local path prefixes."""
return redact_path(redact_url(redact_text(text)))
-def redact_secrets(text: Optional[str]) -> Optional[str]:
+def redact_secrets(text: str | None) -> str | None:
"""Redact text that goes back to the caller: secrets and local path prefixes only.
URLs stay readable. The caller supplied the URL that failed, or already holds it, so a
diff --git a/unshackle/core/utils/run_proxy.py b/unshackle/core/utils/run_proxy.py
index 33f2a1ad..2d3404d3 100644
--- a/unshackle/core/utils/run_proxy.py
+++ b/unshackle/core/utils/run_proxy.py
@@ -13,7 +13,7 @@ import sys
import weakref
from dataclasses import dataclass, field
from types import FrameType
-from typing import Any, Optional
+from typing import Any
from urllib.parse import urlsplit
import requests
@@ -46,7 +46,7 @@ def pin(session: requests.Session) -> None:
session.trust_env = False
-def proxy_of(session: Any) -> Optional[str]:
+def proxy_of(session: Any) -> str | None:
proxies = getattr(session, "proxies", None) or {}
return proxies.get("all") or proxies.get("https") or proxies.get("http")
@@ -55,12 +55,12 @@ def hostname(uri: str) -> str:
return (urlsplit(uri).hostname or "").lower()
-def service_dir(cls: type) -> Optional[str]:
+def service_dir(cls: type) -> str | None:
file = getattr(sys.modules.get(cls.__module__), "__file__", None)
return os.path.dirname(file) + os.sep if file else None
-def watch(cls: type, proxy: Optional[str]) -> None:
+def watch(cls: type, proxy: str | None) -> None:
"""Watch the requests of the service class ``cls`` in a run with the proxy ``proxy``."""
global hook_installed
directory = service_dir(cls)
@@ -77,7 +77,7 @@ def watch(cls: type, proxy: Optional[str]) -> None:
hook_installed = True
-def find_service(frame: Optional[FrameType], through_core: bool) -> Optional[tuple[FrameType, Watch]]:
+def find_service(frame: FrameType | None, through_core: bool) -> tuple[FrameType, Watch] | None:
"""Return the innermost frame of watched service code and its watch.
Without ``through_core`` the walk ends at the first unshackle core frame: core sends some requests
@@ -96,7 +96,7 @@ def find_service(frame: Optional[FrameType], through_core: bool) -> Optional[tup
return None
-def instance_of(frame: Optional[FrameType], entry: Watch) -> Any:
+def instance_of(frame: FrameType | None, entry: Watch) -> Any:
"""The service instance nearest to ``frame``, which knows the proxy of its own run.
The walk goes on past helper functions of the service, which have no ``self``.
@@ -114,7 +114,7 @@ def instance_of(frame: Optional[FrameType], entry: Watch) -> Any:
return None
-def run_proxy_for(frame: Optional[FrameType]) -> Optional[str]:
+def run_proxy_for(frame: FrameType | None) -> str | None:
"""The proxy of the run of the service code that called into core at ``frame``.
A download thread has no service frame. With one watched service, as in a CLI run, its proxy applies.
@@ -182,7 +182,7 @@ def audit(event: str, args: tuple) -> None:
pass
-def check(host: Any, frame: Optional[FrameType]) -> None:
+def check(host: Any, frame: FrameType | None) -> None:
"""Warn when the innermost unshackle frame that sends a request to ``host`` is service code.
A method of a service instance knows the proxy of its own run, so a run with no proxy never warns.
diff --git a/unshackle/core/utils/service_params.py b/unshackle/core/utils/service_params.py
index 65bcbcc2..eb6958e3 100644
--- a/unshackle/core/utils/service_params.py
+++ b/unshackle/core/utils/service_params.py
@@ -1,4 +1,5 @@
-from typing import Any, Collection, Dict, Iterable
+from collections.abc import Collection, Iterable
+from typing import Any
import click
@@ -6,8 +7,8 @@ FLAT_DL_KEYS = frozenset({"title", "service", "title_id", "profile", "proxy", "n
def service_options(
- data: Dict[str, Any], names: Collection[str], flat_excluded: Iterable[str] = FLAT_DL_KEYS
-) -> Dict[str, Any]:
+ data: dict[str, Any], names: Collection[str], flat_excluded: Iterable[str] = FLAT_DL_KEYS
+) -> dict[str, Any]:
"""A request's service options named in ``names``: from its ``service_params`` object, else its flat keys.
With ``service_params`` present every flat key is a dl value, so it never fills a service option of the same name.
@@ -20,7 +21,7 @@ def service_options(
return {k: v for k, v in data.items() if k in names and k not in excluded}
-def cast_service_options(params: Iterable[click.Parameter], ctx: Any, options: Dict[str, Any]) -> Dict[str, Any]:
+def cast_service_options(params: Iterable[click.Parameter], ctx: Any, options: dict[str, Any]) -> dict[str, Any]:
"""``options`` with each value cast by the click parameter of the same name; raises ``click.BadParameter``.
A name that no parameter declares keeps its value. A JSON object, an array for a single-value text option
@@ -28,7 +29,7 @@ def cast_service_options(params: Iterable[click.Parameter], ctx: Any, options: D
``BadParameter`` for strings, so any other error of a JSON value becomes one too.
"""
by_name = {p.name: p for p in params if p.name}
- cast: Dict[str, Any] = {}
+ cast: dict[str, Any] = {}
for k, v in options.items():
param = by_name.get(k)
if param is None:
diff --git a/unshackle/core/utils/sslciphers.py b/unshackle/core/utils/sslciphers.py
index 583da32d..9cb1672d 100644
--- a/unshackle/core/utils/sslciphers.py
+++ b/unshackle/core/utils/sslciphers.py
@@ -1,5 +1,5 @@
import ssl
-from typing import Any, Optional
+from typing import Any
from requests.adapters import HTTPAdapter
@@ -46,7 +46,7 @@ class SSLCiphers(HTTPAdapter):
__attrs__ = [*HTTPAdapter.__attrs__, "_ssl_context"]
- def __init__(self, cipher_list: Optional[str] = None, security_level: int = 0, *args: Any, **kwargs: Any) -> None:
+ def __init__(self, cipher_list: str | None = None, security_level: int = 0, *args: Any, **kwargs: Any) -> None:
if cipher_list:
if not isinstance(cipher_list, str):
raise TypeError(f"Expected cipher_list to be a str, not {cipher_list!r}")
diff --git a/unshackle/core/utils/subprocess.py b/unshackle/core/utils/subprocess.py
index f4dbeb6e..da89d2b2 100644
--- a/unshackle/core/utils/subprocess.py
+++ b/unshackle/core/utils/subprocess.py
@@ -1,8 +1,8 @@
import json
import subprocess
import time
+from collections.abc import Sequence
from pathlib import Path
-from typing import Optional, Sequence, Union
from unshackle.core import binaries
from unshackle.core.console import console
@@ -11,10 +11,10 @@ from unshackle.core.utilities import get_debug_logger
def log_tool_run(
label: str,
- tool: Optional[str],
- returncode: Optional[int],
+ tool: str | None,
+ returncode: int | None,
*,
- duration_ms: Optional[float] = None,
+ duration_ms: float | None = None,
**context: object,
) -> None:
"""Send a structured ``tool_run`` debug-log entry for an external tool invocation.
@@ -59,7 +59,7 @@ FFMPEG_CHECK_TIMEOUT = 120
FFMPEG_CHECK_TAIL = 8 # seconds
-def ffmpeg_decodes(path: Path, start: Optional[float] = None, seconds: float = 3, video: Optional[bool] = None) -> bool:
+def ffmpeg_decodes(path: Path, start: float | None = None, seconds: float = 3, video: bool | None = None) -> bool:
"""Return True when FFmpeg decodes a window of the file without an error.
A wrong content key leaves the container intact and the samples as noise, which the
@@ -81,7 +81,7 @@ def ffmpeg_decodes(path: Path, start: Optional[float] = None, seconds: float = 3
does a check that does not finish in time.
"""
if not binaries.FFMPEG:
- raise EnvironmentError('FFmpeg executable "ffmpeg" not found but is required.')
+ raise OSError('FFmpeg executable "ffmpeg" not found but is required.')
ffmpeg = str(binaries.FFMPEG)
def decode(window: list[str], keyframes: bool) -> bool:
@@ -140,12 +140,12 @@ def ffmpeg_decodes(path: Path, start: Optional[float] = None, seconds: float = 3
return decode(["-t", str(seconds)], keyframes=False) and decode(tail, keyframes=False)
-def ffprobe(uri: Union[bytes, Path]) -> dict:
+def ffprobe(uri: bytes | Path) -> dict:
"""Use FFprobe on the provided data to get its track information (``-show_streams``)."""
if not binaries.FFProbe:
- raise EnvironmentError('FFProbe executable "ffprobe" not found but is required.')
+ raise OSError('FFProbe executable "ffprobe" not found but is required.')
- args: list[Union[str, Path]] = [binaries.FFProbe, "-v", "quiet", "-of", "json", "-show_streams"]
+ args: list[str | Path] = [binaries.FFProbe, "-v", "quiet", "-of", "json", "-show_streams"]
if isinstance(uri, Path):
args.extend(
["-f", "lavfi", "-i", "movie={}[out+subcc]".format(str(uri).replace("\\", "/").replace(":", "\\\\:"))]
@@ -182,12 +182,12 @@ def ffprobe(uri: Union[bytes, Path]) -> dict:
def run_step(
- args: Sequence[Union[str, Path]],
+ args: Sequence[str | Path],
*,
- status: Optional[str] = None,
- output: Optional[Path] = None,
+ status: str | None = None,
+ output: Path | None = None,
label: str = "subprocess step",
- timeout: Optional[float] = None,
+ timeout: float | None = None,
) -> bytes:
"""Operate a CLI step that writes to `output` (when provided). Returns stderr bytes.
@@ -203,9 +203,9 @@ def run_step(
try:
if status:
with console.status(status, spinner="dots"):
- p = subprocess.run(str_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
+ p = subprocess.run(str_args, capture_output=True, timeout=timeout)
else:
- p = subprocess.run(str_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
+ p = subprocess.run(str_args, capture_output=True, timeout=timeout)
except subprocess.TimeoutExpired:
if output is not None:
output.unlink(missing_ok=True)
diff --git a/unshackle/core/utils/tag_rules.py b/unshackle/core/utils/tag_rules.py
index 9f314933..e9bd5d01 100644
--- a/unshackle/core/utils/tag_rules.py
+++ b/unshackle/core/utils/tag_rules.py
@@ -5,8 +5,8 @@ from __future__ import annotations
import logging
import operator
import re
-from collections.abc import Mapping
-from typing import Any, Callable, Optional
+from collections.abc import Callable, Mapping
+from typing import Any
log = logging.getLogger(__name__)
@@ -23,7 +23,7 @@ ORDERING = (">=", "<=", ">", "<")
NUMBER = re.compile(r"\d+(?:\.\d+)?")
-def evaluate_tag_rules(rules: Any, context: dict[str, Any]) -> Optional[str]:
+def evaluate_tag_rules(rules: Any, context: dict[str, Any]) -> str | None:
"""Evaluate tag rules against a filename template context.
unshackle evaluates the rules in order. It returns the tag of the first rule
diff --git a/unshackle/core/utils/tags.py b/unshackle/core/utils/tags.py
index 40683589..93bf394f 100644
--- a/unshackle/core/utils/tags.py
+++ b/unshackle/core/utils/tags.py
@@ -5,7 +5,7 @@ import subprocess
import tempfile
import time
from pathlib import Path
-from typing import Any, Optional, Union
+from typing import Any
from xml.sax.saxutils import escape
from unshackle.core import binaries
@@ -87,10 +87,10 @@ def build_tags_from_ids(ids: ExternalIds, kind: str) -> dict[str, str]:
def tag_file(
path: Path,
title: Title,
- tmdb_id: Optional[int] = None,
- imdb_id: Optional[str] = None,
- tvdb_id: Optional[int] = None,
- anilist_id: Optional[Union[int, str]] = None,
+ tmdb_id: int | None = None,
+ imdb_id: str | None = None,
+ tvdb_id: int | None = None,
+ anilist_id: int | str | None = None,
anime: bool = False,
session: Any = None,
) -> None:
diff --git a/unshackle/core/utils/webvtt.py b/unshackle/core/utils/webvtt.py
index 75980941..5b75a750 100644
--- a/unshackle/core/utils/webvtt.py
+++ b/unshackle/core/utils/webvtt.py
@@ -1,5 +1,5 @@
import re
-from typing import Optional
+from itertools import pairwise
TIMESTAMP = r"(?:\d+:)?\d{2}:\d{2}\.\d{3}"
# Timing line: optional hours, verbatim settings tail.
@@ -17,7 +17,7 @@ def timestamp_ms(ts: str) -> int:
return ((hours * 60 + minutes) * 60 + seconds) * 1000 + int(ms)
-def merge_segmented_webvtt(vtt_raw: str, segment_durations: Optional[list[int]] = None, timescale: int = 1) -> str:
+def merge_segmented_webvtt(vtt_raw: str, segment_durations: list[int] | None = None, timescale: int = 1) -> str:
"""
Merge concatenated Segmented WebVTT documents into a single document.
@@ -39,7 +39,7 @@ def merge_segmented_webvtt(vtt_raw: str, segment_durations: Optional[list[int]]
# each kept cue: [start, end, settings, payload, normalized payload for dedupe]
cues: list[list[str]] = []
headers: list[str] = [] # unique STYLE/REGION blocks, first-seen order
- prev: Optional[list[str]] = None
+ prev: list[str] | None = None
prev_end_ms = 0
for block in re.split(r"\n[ \t]*\n", vtt_raw.replace("\r\n", "\n").replace("\r", "\n")):
@@ -114,15 +114,16 @@ def webvtt_block_offsets(texts: list[str], bounds_ms: list[int]) -> list[int]:
This assumes each block's MPEGTS is the first video PTS of the same block.
"""
offsets, offset = [], 0
- for text, start, end in zip(texts, bounds_ms, bounds_ms[1:]):
+ for text, (start, end) in zip(texts, pairwise(bounds_ms), strict=False):
cues = [(timestamp_ms(m[2]), timestamp_ms(m[4])) for m in CUE_TIMES.finditer(text)]
local = TIMESTAMP_MAP_LOCAL.search(text)
restart = start - (timestamp_ms(local[1]) if local else 0)
- def inside(shift: int) -> int:
- return sum(cue_start + shift < end and cue_end + shift > start for cue_start, cue_end in cues)
-
- if inside(restart) > inside(offset):
+ at_restart, at_offset = (
+ sum(cue_start + shift < end and cue_end + shift > start for cue_start, cue_end in cues)
+ for shift in (restart, offset)
+ )
+ if at_restart > at_offset:
offset = restart
offsets.append(offset)
return offsets
diff --git a/unshackle/core/utils/xml.py b/unshackle/core/utils/xml.py
index c5e033d8..5554be7f 100644
--- a/unshackle/core/utils/xml.py
+++ b/unshackle/core/utils/xml.py
@@ -1,10 +1,8 @@
-from typing import Union
-
from lxml import etree
from lxml.etree import ElementTree
-def load_xml(xml: Union[str, bytes]) -> ElementTree:
+def load_xml(xml: str | bytes) -> ElementTree:
"""Safely parse XML data to an ElementTree, without namespaces in tags.
The strip uses string operations, not etree.QName: on a 20 MB manifest the QName walk costs several times the parse.
diff --git a/unshackle/core/vault.py b/unshackle/core/vault.py
index cda12c83..b00cda10 100644
--- a/unshackle/core/vault.py
+++ b/unshackle/core/vault.py
@@ -1,5 +1,5 @@
from abc import ABCMeta, abstractmethod
-from typing import Iterator, Optional, Union
+from collections.abc import Iterator
from uuid import UUID
from requests import ConnectionError as RequestsConnectionError
@@ -23,7 +23,7 @@ class RateLimited(Exception):
UNREACHABLE = (RequestsConnectionError, Timeout, ConnectionError, TimeoutError)
-def is_null_key(key: Optional[str]) -> bool:
+def is_null_key(key: str | None) -> bool:
"""True for a blank or all-zero content key, the null key that no vault stores."""
return not key or key.count("0") == len(key)
@@ -66,7 +66,7 @@ class Vault(metaclass=ABCMeta):
return f"{self.name} {type(self).__name__}"
@abstractmethod
- def get_key(self, kid: Union[UUID, str], service: str) -> Optional[str]:
+ def get_key(self, kid: UUID | str, service: str) -> str | None:
"""
Get the content key from the Vault by KID (Key ID) and Service.
@@ -84,11 +84,11 @@ class Vault(metaclass=ABCMeta):
"""Get All Keys from Vault by Service."""
@abstractmethod
- def add_key(self, service: str, kid: Union[UUID, str], key: str) -> bool:
+ def add_key(self, service: str, kid: UUID | str, key: str) -> bool:
"""Add KID:KEY to the Vault."""
@abstractmethod
- def add_keys(self, service: str, kid_keys: dict[Union[UUID, str], str]) -> int:
+ def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int:
"""
Add Multiple Content Keys with Key IDs for Service to the Vault.
The Vault ignores pre-existing Content Keys.
@@ -104,14 +104,14 @@ class Vault(metaclass=ABCMeta):
get_key/get_keys/add_key/add_keys reaches the namespace it came from.
"""
- def is_bad_key(self, kid: Union[UUID, str], key: str) -> bool:
+ def is_bad_key(self, kid: UUID | str, key: str) -> bool:
"""Return True if this Vault has flagged the KID:KEY as wrong."""
return False
- def flag_bad_key(self, service: str, kid: Union[UUID, str], key: str, source: str) -> None:
+ def flag_bad_key(self, service: str, kid: UUID | str, key: str, source: str) -> None:
"""Remember a KID:KEY that failed decryption and where it came from."""
- def unflag_bad_key(self, kid: Union[UUID, str], key: str) -> None:
+ def unflag_bad_key(self, kid: UUID | str, key: str) -> None:
"""Forget a flagged KID:KEY, for example when a CDM licence confirmed it."""
diff --git a/unshackle/core/vaults.py b/unshackle/core/vaults.py
index e46e9056..6e63d0ce 100644
--- a/unshackle/core/vaults.py
+++ b/unshackle/core/vaults.py
@@ -1,9 +1,10 @@
import inspect
import logging
import time
+from collections.abc import Collection, Iterable, Iterator
from concurrent.futures import Future, ThreadPoolExecutor, as_completed
from functools import partial
-from typing import Any, Collection, Iterable, Iterator, Optional, Union
+from typing import Any
from uuid import UUID
from unshackle.core.config import config
@@ -22,15 +23,15 @@ MODULES = {path.stem: getattr(import_module_by_path(path), path.stem) for path i
class Vaults:
"""Keeps hold of Key Vaults with convenience functions, e.g. searching all vaults."""
- def __init__(self, service: Optional[str] = None) -> None:
+ def __init__(self, service: str | None = None) -> None:
self.service = service or ""
self.vaults: list[Vault] = []
- self.sources: dict[Union[UUID, str], tuple[str, Vault]] = {}
- self.flagged: set[tuple[Union[UUID, str], str]] = set()
- self.candidates: dict[Union[UUID, str], list[tuple[str, Vault]]] = {}
- self.warned: set[tuple[str, Union[UUID, str], str]] = set()
+ self.sources: dict[UUID | str, tuple[str, Vault]] = {}
+ self.flagged: set[tuple[UUID | str, str]] = set()
+ self.candidates: dict[UUID | str, list[tuple[str, Vault]]] = {}
+ self.warned: set[tuple[str, UUID | str, str]] = set()
self.unreachable: set[Vault] = set()
- self.unreported: dict[tuple[Union[UUID, str], str], Vault] = {}
+ self.unreported: dict[tuple[UUID | str, str], Vault] = {}
def __iter__(self) -> Iterator[Vault]:
return iter(self.vaults)
@@ -48,7 +49,7 @@ class Vaults:
kwargs["timeout"] = config.vault_timeout
self.vaults.append(module(**kwargs))
- def get_key(self, kid: Union[UUID, str]) -> tuple[Optional[str], Optional[Vault]]:
+ def get_key(self, kid: UUID | str) -> tuple[str | None, Vault | None]:
"""Get Key from the first Vault it can by KID (Key ID) and Service.
Local vaults go first, one at a time: a hit there costs nothing and skips the network.
@@ -85,7 +86,7 @@ class Vaults:
# ones already running still finish and land in candidates through the callback
pool.shutdown(wait=False, cancel_futures=True)
- def remember_candidate(self, kid: Union[UUID, str], vault: Vault, future: Future) -> None:
+ def remember_candidate(self, kid: UUID | str, vault: Vault, future: Future) -> None:
"""Keep a remote answer for a later retry. Cancelled or failed queries leave nothing."""
if future.cancelled() or future.exception():
return
@@ -93,11 +94,11 @@ class Vaults:
if key and (key, vault) not in self.candidates.setdefault(kid, []):
self.candidates[kid].append((key, vault))
- def is_flagged(self, kid: Union[UUID, str], key: str) -> bool:
+ def is_flagged(self, kid: UUID | str, key: str) -> bool:
"""True when a local vault has flagged the KID:KEY as wrong."""
return any(v.is_bad_key(kid, key) for v in self.vaults if v.local)
- def query_vault(self, vault: Vault, kid: Union[UUID, str]) -> Optional[str]:
+ def query_vault(self, vault: Vault, kid: UUID | str) -> str | None:
"""Ask one vault for a content key. A failure logs a warning and returns None.
A flagged pair counts as no content key, so no vault can serve one again.
@@ -138,7 +139,7 @@ class Vaults:
)
return key if found else None
- def flag_bad_key(self, kid: Union[UUID, str], key: str) -> None:
+ def flag_bad_key(self, kid: UUID | str, key: str) -> None:
"""Flag a KID:KEY in every local vault. A failed decode is no proof, so the remote vault that
served it hears of it from ``report_replaced``, or at once when it sets ``report_now``."""
self.flagged.add((kid, key))
@@ -153,7 +154,7 @@ class Vaults:
else:
self.unreported[kid, key] = source[1]
- def report_replaced(self, content_keys: dict[Union[UUID, str], str]) -> None:
+ def report_replaced(self, content_keys: dict[UUID | str, str]) -> None:
"""Tell each remote vault about its flagged pair once ``content_keys`` holds another key for the KID."""
live = self.live()
for (kid, key), vault in list(self.unreported.items()):
@@ -162,7 +163,7 @@ class Vaults:
if vault in live:
self.tell(vault, kid, key, vault.name)
- def tell(self, vault: Vault, kid: Union[UUID, str], key: str, source: str) -> None:
+ def tell(self, vault: Vault, kid: UUID | str, key: str, source: str) -> None:
"""Flag one pair in one vault; a failure is only a debug line."""
try:
vault.flag_bad_key(self.service, kid, key, source)
@@ -176,7 +177,7 @@ class Vaults:
self.unflag_bad_key(kid, content_keys[kid])
return cleared
- def unflag_bad_key(self, kid: Union[UUID, str], key: str) -> None:
+ def unflag_bad_key(self, kid: UUID | str, key: str) -> None:
"""Remove a flag from every Vault."""
self.flagged.discard((kid, key))
for vault in self.live():
@@ -185,7 +186,7 @@ class Vaults:
except Exception as e:
log.debug(f"Could not unflag {key} in Vault '{vault.name}': {e!r}")
- def add_key(self, kid: Union[UUID, str], key: str, excluding: Optional[Vault] = None) -> int:
+ def add_key(self, kid: UUID | str, key: str, excluding: Vault | None = None) -> int:
"""Add a KID:KEY to all Vaults, optionally with an exclusion.
This method pushes to all Vaults at the same time, so one unreachable Vault costs only its
@@ -197,7 +198,7 @@ class Vaults:
with ThreadPoolExecutor(len(vaults), thread_name_prefix="vault-push") as pool:
return sum(pool.map(lambda vault: self.push_key(vault, kid, key), vaults))
- def push_key(self, vault: Vault, kid: Union[UUID, str], key: str) -> int:
+ def push_key(self, vault: Vault, kid: UUID | str, key: str) -> int:
"""Push one Content Key to one Vault. Returns 1 if the Vault stored it, 0 otherwise."""
dl = get_debug_logger()
try:
@@ -214,7 +215,7 @@ class Vaults:
dl.log_vault_query(vault.name, "add_key", kid=str(kid), success=False, error=e)
return 0
- def add_keys(self, kid_keys: dict[Union[UUID, str], str]) -> int:
+ def add_keys(self, kid_keys: dict[UUID | str, str]) -> int:
"""
Add multiple KID:KEYs to all Vaults. The Vaults skip duplicate Content Keys.
This method absorbs and ignores the PermissionError a Vault raises when it cannot make Tables.
@@ -231,7 +232,7 @@ class Vaults:
with ThreadPoolExecutor(len(vaults), thread_name_prefix="vault-push") as pool:
return sum(pool.map(lambda vault: self.push_keys(vault, kid_keys), vaults))
- def push_keys(self, vault: Vault, kid_keys: dict[Union[UUID, str], str]) -> int:
+ def push_keys(self, vault: Vault, kid_keys: dict[UUID | str, str]) -> int:
"""Push Content Keys to one Vault. Returns 1 if the Vault accepted them, 0 on any failure."""
try:
vault.add_keys(self.service, kid_keys)
@@ -247,7 +248,7 @@ class Vaults:
"""The vaults this run still uses."""
return [vault for vault in self.vaults if vault not in self.unreachable]
- def held_locally(self, kid: Union[UUID, str], key: str) -> bool:
+ def held_locally(self, kid: UUID | str, key: str) -> bool:
"""True when a local vault already holds this KID:KEY."""
return any(self.query_vault(vault, kid) == key for vault in self.vaults if vault.local)
@@ -263,8 +264,8 @@ __all__ = ("Vaults", "load_config_vaults")
def load_config_vaults(
- service: Optional[str] = None,
- configs: Optional[Iterable[dict[str, Any]]] = None,
+ service: str | None = None,
+ configs: Iterable[dict[str, Any]] | None = None,
critical: Collection[str] = (),
) -> tuple[Vaults, dict[str, BaseException]]:
"""Load vault configs (the config's ``key_vaults`` by default) into one Vaults for a service.
diff --git a/unshackle/core/wire.py b/unshackle/core/wire.py
index 0fce9744..455b2204 100644
--- a/unshackle/core/wire.py
+++ b/unshackle/core/wire.py
@@ -18,7 +18,7 @@ import re
from datetime import date as date_
from enum import Enum
from pathlib import Path
-from typing import Any, Dict, List, Optional, Union
+from typing import Any
from uuid import UUID
import click
@@ -52,7 +52,7 @@ def enum_name(value: Any) -> str:
return value.name if hasattr(value, "name") else str(value)
-def enum_get(enum_cls: type[Enum], name: Optional[str], default: Any = None) -> Any:
+def enum_get(enum_cls: type[Enum], name: str | None, default: Any = None) -> Any:
"""Safely get an enum value by name."""
if not name:
return default
@@ -62,15 +62,15 @@ def enum_get(enum_cls: type[Enum], name: Optional[str], default: Any = None) ->
return default
-def descriptor_name(track: Any) -> Optional[str]:
+def descriptor_name(track: Any) -> str | None:
"""Manifest descriptor (HLS/DASH/URL) name for a track, or None."""
descriptor = getattr(track, "descriptor", None)
return enum_name(descriptor) if descriptor else None
-def episode_flags(title: Episode) -> Dict[str, Any]:
+def episode_flags(title: Episode) -> dict[str, Any]:
"""The optional Episode keys both forms write only when set, so the JSON of a title without them stays the same."""
- flags: Dict[str, Any] = {}
+ flags: dict[str, Any] = {}
if title.absolute is not None:
flags["absolute"] = title.absolute
if getattr(title, "daily", None) is not None:
@@ -80,7 +80,7 @@ def episode_flags(title: Episode) -> Dict[str, Any]:
return flags
-def serialize_title(title: Title_T) -> Dict[str, Any]:
+def serialize_title(title: Title_T) -> dict[str, Any]:
"""Convert a title object to JSON-serializable dict."""
title_language = str(title.language) if hasattr(title, "language") and title.language else None
# Optional display metadata a service may provide: a synopsis (title.description) and a
@@ -169,7 +169,7 @@ def title_to_meta(title: Title_T) -> dict[str, Any]:
return meta
-def episode_name(name: Optional[str], series_title: Optional[str]) -> Optional[str]:
+def episode_name(name: str | None, series_title: str | None) -> str | None:
"""Drop a placeholder episode name the way ``Episode.__init__`` does.
The server sends "Episode 04" for an unnamed episode, so the same filter has to run
@@ -195,7 +195,7 @@ def parse_air_date(value: Any) -> Any:
return value
-def apply_title_fields(title: Title_T, info: Dict[str, Any]) -> None:
+def apply_title_fields(title: Title_T, info: dict[str, Any]) -> None:
"""Copy the serialized metadata fields onto a local title.
A service can change its title inside ``get_tracks`` (a corrected original language,
@@ -240,7 +240,7 @@ def apply_title_fields(title: Title_T, info: Dict[str, Any]) -> None:
title.data = extra
-def build_title(info: Dict[str, Any], service_tag: str, fallback_id: str) -> Title_T:
+def build_title(info: dict[str, Any], service_tag: str, fallback_id: str) -> Title_T:
"""Rebuild a title from its REST form or its export form, under a stand-in class named for the service."""
svc_class = type(service_tag, (), {})
lang = Language.get(info["language"]) if info.get("language") else None
@@ -296,7 +296,7 @@ def build_title(info: Dict[str, Any], service_tag: str, fallback_id: str) -> Tit
return title
-def serialize_drm(drm_list: Any) -> Optional[List[Dict[str, Any]]]:
+def serialize_drm(drm_list: Any) -> list[dict[str, Any]] | None:
"""Serialise DRM objects to JSON-serializable list."""
if not drm_list:
return None
@@ -347,7 +347,7 @@ def serialize_drm(drm_list: Any) -> Optional[List[Dict[str, Any]]]:
return result if result else None
-def reconstruct_drm(drm_list: Optional[list]) -> list:
+def reconstruct_drm(drm_list: list | None) -> list:
"""Reconstruct DRM objects from the REST form."""
if not drm_list:
return []
@@ -369,7 +369,7 @@ def reconstruct_drm(drm_list: Optional[list]) -> list:
return result
-def pssh_drm(system: str, pssh_b64: str, kids: Optional[List[str]]) -> Union[Widevine, PlayReady]:
+def pssh_drm(system: str, pssh_b64: str, kids: list[str] | None) -> Widevine | PlayReady:
"""A Widevine or PlayReady DRM rebuilt from its base64 PSSH, as both forms carry it (system in lower case).
kids repeats the PSSH KIDs, so kids[0] is not the track's own KID; only a PSSH without KIDs needs it.
@@ -380,7 +380,7 @@ def pssh_drm(system: str, pssh_b64: str, kids: Optional[List[str]]) -> Union[Wid
return Widevine(pssh=wv_pssh, kid=kids[0] if kids and not wv_pssh.key_ids else None)
-def drm_to_dict(drm: Union[Widevine, PlayReady, ClearKeyCENC]) -> dict[str, Any]:
+def drm_to_dict(drm: Widevine | PlayReady | ClearKeyCENC) -> dict[str, Any]:
"""A DRM in the export form: its system, PSSH and KIDs.
The export keeps the content keys once at title level, not here.
@@ -406,7 +406,7 @@ def drm_to_dict(drm: Union[Widevine, PlayReady, ClearKeyCENC]) -> dict[str, Any]
}
-def drm_from_dict(data: dict[str, Any]) -> Union[Widevine, PlayReady, ClearKeyCENC]:
+def drm_from_dict(data: dict[str, Any]) -> Widevine | PlayReady | ClearKeyCENC:
"""Reconstruct a Widevine/PlayReady/ClearKeyCENC DRM instance from its export form.
Rebuilds the PSSH from the stored base64 (KIDs for ClearKey, which has no PSSH)
@@ -419,7 +419,7 @@ def drm_from_dict(data: dict[str, Any]) -> Union[Widevine, PlayReady, ClearKeyCE
content_keys = data.get("content_keys") or {}
if system == "ClearKeyCENC":
- drm: Union[Widevine, PlayReady, ClearKeyCENC] = ClearKeyCENC(kids=kids, laurl=data.get("laurl"))
+ drm: Widevine | PlayReady | ClearKeyCENC = ClearKeyCENC(kids=kids, laurl=data.get("laurl"))
elif not pssh_b64:
raise ValueError("Cannot reconstruct DRM without a stored PSSH.")
elif system in ("PlayReady", "Widevine"):
@@ -433,7 +433,7 @@ def drm_from_dict(data: dict[str, Any]) -> Union[Widevine, PlayReady, ClearKeyCE
return drm
-def serialize_track_data(track: Any) -> Optional[Dict[str, Any]]:
+def serialize_track_data(track: Any) -> dict[str, Any] | None:
"""The JSON-safe part of a service-set ``track.data``.
This drops the manifest parsers' own keys: the client rebuilds those from the
@@ -442,7 +442,7 @@ def serialize_track_data(track: Any) -> Optional[Dict[str, Any]]:
data = getattr(track, "data", None)
if not isinstance(data, dict):
return None
- safe: Dict[str, Any] = {}
+ safe: dict[str, Any] = {}
for key, value in data.items():
if key in MANIFEST_DATA_KEYS:
continue
@@ -454,7 +454,7 @@ def serialize_track_data(track: Any) -> Optional[Dict[str, Any]]:
return safe or None
-def serialize_track_common(track: Any) -> Dict[str, Any]:
+def serialize_track_common(track: Any) -> dict[str, Any]:
"""The Track fields every track type shares, a superset of ``Track.to_dict()``."""
return {
"id": str(track.id),
@@ -472,7 +472,7 @@ def serialize_track_common(track: Any) -> Dict[str, Any]:
}
-def serialize_tracks(tracks: Tracks, title: Any, include_url: bool = False) -> Dict[str, List[Dict[str, Any]]]:
+def serialize_tracks(tracks: Tracks, title: Any, include_url: bool = False) -> dict[str, list[dict[str, Any]]]:
"""The ``video``, ``audio`` and ``subtitles`` lists of a title's tracks, video and audio highest bitrate first."""
video_tracks = sorted(tracks.videos, key=lambda t: t.bitrate or 0, reverse=True)
audio_tracks = sorted(tracks.audio, key=lambda t: t.bitrate or 0, reverse=True)
@@ -486,7 +486,7 @@ def serialize_tracks(tracks: Tracks, title: Any, include_url: bool = False) -> D
}
-def original_audio_ids(tracks: List[Audio], title: Title_T) -> set:
+def original_audio_ids(tracks: list[Audio], title: Title_T) -> set:
"""Return the ids of the audio tracks 'orig' resolves to, empty when the title has no language.
This defers to Tracks.by_language through original_tag, as 'orig' does, so the flag agrees
@@ -498,7 +498,7 @@ def original_audio_ids(tracks: List[Audio], title: Title_T) -> set:
return {t.id for t in Tracks.by_language(tracks, [original_tag(language)])}
-def serialize_video_track(track: Video, include_url: bool = False) -> Dict[str, Any]:
+def serialize_video_track(track: Video, include_url: bool = False) -> dict[str, Any]:
"""Convert video track to JSON-serializable dict."""
codec_name = enum_name(track.codec)
codec_value = track.codec.value if track.codec else codec_name
@@ -529,7 +529,7 @@ def serialize_video_track(track: Video, include_url: bool = False) -> Dict[str,
return result
-def serialize_audio_track(track: Audio, include_url: bool = False, is_original: bool = False) -> Dict[str, Any]:
+def serialize_audio_track(track: Audio, include_url: bool = False, is_original: bool = False) -> dict[str, Any]:
"""Convert audio track to JSON-serializable dict.
Get is_original from original_audio_ids so the flag always agrees with the
@@ -556,7 +556,7 @@ def serialize_audio_track(track: Audio, include_url: bool = False, is_original:
return result
-def serialize_subtitle_track(track: Subtitle, include_url: bool = False) -> Dict[str, Any]:
+def serialize_subtitle_track(track: Subtitle, include_url: bool = False) -> dict[str, Any]:
"""Convert subtitle track to JSON-serializable dict."""
result = {
"id": str(track.id),
@@ -571,12 +571,12 @@ def serialize_subtitle_track(track: Subtitle, include_url: bool = False) -> Dict
return result
-def base_track_kwargs(data: Dict[str, Any]) -> Dict[str, Any]:
+def base_track_kwargs(data: dict[str, Any]) -> dict[str, Any]:
"""The Track constructor kwargs that both forms decode the same way."""
return {"name": data.get("name"), "edition": data.get("edition") or None, "id_": data.get("id")}
-def rest_track_kwargs(data: Dict[str, Any]) -> Dict[str, Any]:
+def rest_track_kwargs(data: dict[str, Any]) -> dict[str, Any]:
"""The shared Track constructor kwargs of the REST form.
An older server omits the newer keys, so each one falls back to the value a
@@ -609,7 +609,7 @@ def export_track_kwargs(data: dict[str, Any]) -> dict[str, Any]:
}
-def deserialize_bitrate(data: Dict[str, Any]) -> int:
+def deserialize_bitrate(data: dict[str, Any]) -> int:
"""Exact bits/s when the server sent it, otherwise the kb/s figure scaled back up."""
exact = data.get("bitrate_bps")
if exact:
@@ -617,7 +617,7 @@ def deserialize_bitrate(data: Dict[str, Any]) -> int:
return data["bitrate"] * 1000 if data.get("bitrate") else 0
-def deserialize_video(data: Dict[str, Any]) -> Video:
+def deserialize_video(data: dict[str, Any]) -> Video:
"""A video track from its REST form."""
return Video(
**rest_track_kwargs(data),
@@ -636,7 +636,7 @@ def deserialize_video(data: Dict[str, Any]) -> Video:
)
-def deserialize_audio(data: Dict[str, Any]) -> Audio:
+def deserialize_audio(data: dict[str, Any]) -> Audio:
"""An audio track from its REST form."""
joc = data.get("joc")
return Audio(
@@ -650,7 +650,7 @@ def deserialize_audio(data: Dict[str, Any]) -> Audio:
)
-def deserialize_subtitle(data: Dict[str, Any]) -> Subtitle:
+def deserialize_subtitle(data: dict[str, Any]) -> Subtitle:
"""A subtitle track from its REST form."""
return Subtitle(
**rest_track_kwargs(data),
@@ -661,7 +661,7 @@ def deserialize_subtitle(data: Dict[str, Any]) -> Subtitle:
)
-def build_tracks(data: Dict[str, Any]) -> Tracks:
+def build_tracks(data: dict[str, Any]) -> Tracks:
"""A title's tracks, their DRM and its attachments from the REST form."""
tracks = Tracks()
tracks.videos = [deserialize_video(v) for v in data.get("video", [])]
@@ -669,9 +669,9 @@ def build_tracks(data: Dict[str, Any]) -> Tracks:
tracks.subtitles = [deserialize_subtitle(s) for s in data.get("subtitles", [])]
for track_data, track_obj in [
- *zip(data.get("video", []), tracks.videos),
- *zip(data.get("audio", []), tracks.audio),
- *zip(data.get("subtitles", []), tracks.subtitles),
+ *zip(data.get("video", []), tracks.videos, strict=False),
+ *zip(data.get("audio", []), tracks.audio, strict=False),
+ *zip(data.get("subtitles", []), tracks.subtitles, strict=False),
]:
drm_objs = reconstruct_drm(track_data.get("drm"))
if drm_objs:
@@ -743,13 +743,13 @@ def track_to_dict(track: Track) -> dict[str, Any]:
return data
-def track_from_dict(data: dict[str, Any]) -> Union[Video, Audio, Subtitle]:
+def track_from_dict(data: dict[str, Any]) -> Video | Audio | Subtitle:
"""Reconstruct the correct Track subclass from its export form.
DRM is not reconstructed here: the import flow attaches the licensed DRM + content keys separately.
"""
track_type = data.get("type")
- kinds: dict[Optional[str], type[Track]] = {"Video": Video, "Audio": Audio, "Subtitle": Subtitle}
+ kinds: dict[str | None, type[Track]] = {"Video": Video, "Audio": Audio, "Subtitle": Subtitle}
kind = kinds.get(track_type)
if kind is None:
raise ValueError(f"Cannot reconstruct unsupported track type: {track_type!r}")
@@ -786,7 +786,7 @@ def track_from_dict(data: dict[str, Any]) -> Union[Video, Audio, Subtitle]:
)
-def attachment_to_dict(attachment: Attachment) -> Dict[str, Any]:
+def attachment_to_dict(attachment: Attachment) -> dict[str, Any]:
"""An attachment in the export form, which is also the REST form of a URL-backed attachment."""
return {
"url": attachment.url,
@@ -796,7 +796,7 @@ def attachment_to_dict(attachment: Attachment) -> Dict[str, Any]:
}
-def serialize_attachment(attachment: Any) -> Optional[Dict[str, Any]]:
+def serialize_attachment(attachment: Any) -> dict[str, Any] | None:
"""One attachment as JSON, with a path-only attachment carried as base64 file bytes.
A service can attach a file it already wrote to disk (a font, a poster). The client
@@ -830,7 +830,7 @@ def serialize_attachment(attachment: Any) -> Optional[Dict[str, Any]]:
return result
-def build_attachment(data: Dict[str, Any]) -> Optional[Attachment]:
+def build_attachment(data: dict[str, Any]) -> Attachment | None:
"""Rebuild one attachment. A path-only attachment arrives as base64, which this writes to temp."""
kwargs = {
"name": data.get("name"),
diff --git a/unshackle/services/EXAMPLE/__init__.py b/unshackle/services/EXAMPLE/__init__.py
index 9b04e291..a38afe70 100644
--- a/unshackle/services/EXAMPLE/__init__.py
+++ b/unshackle/services/EXAMPLE/__init__.py
@@ -7,7 +7,7 @@ import re
from collections.abc import Generator
from datetime import datetime
from http.cookiejar import CookieJar
-from typing import Any, Optional, Union
+from typing import Any
import click
from langcodes import Language
@@ -161,9 +161,9 @@ class EXAMPLE(Service):
self.track_request.ranges = [Video.Range.SDR]
if self.config is None:
- raise EnvironmentError("config.yaml is missing for this service.")
+ raise OSError("config.yaml is missing for this service.")
- def authenticate(self, cookies: Optional[CookieJar] = None, credential: Optional[Credential] = None) -> None:
+ def authenticate(self, cookies: CookieJar | None = None, credential: Credential | None = None) -> None:
# Loads the cookie jar into self.session and stores self.credential.
super().authenticate(cookies, credential)
@@ -187,7 +187,7 @@ class EXAMPLE(Service):
if cookies:
jwt_token = next((c.value for c in cookies if c.name == "streamco_token"), None)
if not jwt_token:
- raise EnvironmentError("Cookie 'streamco_token' not found in jar.")
+ raise OSError("Cookie 'streamco_token' not found in jar.")
payload = json.loads(base64.urlsafe_b64decode(jwt_token.split(".")[1] + "==").decode())
body = {"token": jwt_token, "profileId": payload.get("profileId")}
elif credential:
@@ -195,7 +195,7 @@ class EXAMPLE(Service):
otp = self.request_input("Enter the OTP sent to your device: ")
body = {"username": credential.username, "password": credential.password, "otp": otp}
else:
- raise EnvironmentError("Service requires either Cookies or Credentials.")
+ raise OSError("Service requires either Cookies or Credentials.")
token = self.session.post(url=self.config["endpoints"]["login"], data=body).json()
cache.set(data=token, expiration=token.get("expires_in"))
@@ -289,7 +289,7 @@ class EXAMPLE(Service):
# codec x range in the TrackRequest, handles HYBRID (HDR10 + DV merge), and -
# when --best-available is set - skips combos the service can't deliver.
def get_tracks(self, title: Title_T) -> Tracks:
- def fetch_variant(title: Title_T, codec: Optional[Video.Codec], range_: Video.Range) -> Tracks:
+ def fetch_variant(title: Title_T, codec: Video.Codec | None, range_: Video.Range) -> Tracks:
vcodec_str = "H265" if codec == Video.Codec.HEVC else "H264"
self.log.info(f" + Fetching {vcodec_str} {range_.name} manifest")
tracks = self.fetch_dash_manifest(title, vcodec=vcodec_str, range_=range_)
@@ -455,11 +455,11 @@ class EXAMPLE(Service):
unique.setdefault(chapter.timestamp, chapter)
return Chapters(sorted(unique.values(), key=lambda c: c.timestamp))
- def get_widevine_service_certificate(self, **_: Any) -> Optional[str]:
+ def get_widevine_service_certificate(self, **_: Any) -> str | None:
# Returning the service cert enables privacy-mode license requests.
return self.config.get("certificate")
- def get_widevine_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> Optional[Union[bytes, str]]:
+ def get_widevine_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | None:
# `track` is passed so you can use its per-segment PSSH if the service rotates keys.
license_url = self.license_data.get("url") or self.config["endpoints"].get("widevine_license")
if not license_url:
@@ -481,9 +481,7 @@ class EXAMPLE(Service):
except (ValueError, KeyError):
return response.content
- def get_playready_license(
- self, *, challenge: bytes, title: Title_T, track: AnyTrack
- ) -> Optional[Union[bytes, str]]:
+ def get_playready_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | None:
license_url = self.config["endpoints"].get("playready_license")
if not license_url:
raise ValueError("PlayReady license endpoint not configured")
@@ -495,9 +493,7 @@ class EXAMPLE(Service):
response.raise_for_status()
return response.content
- def get_clearkey_license(
- self, *, challenge: bytes, title: Title_T, track: AnyTrack
- ) -> Optional[Union[bytes, str, dict]]:
+ def get_clearkey_license(self, *, challenge: bytes, title: Title_T, track: AnyTrack) -> bytes | str | dict | None:
# DASH org.w3.clearkey: `challenge` is the W3C JSON license request; return the
# JWK Set response. Omit this method entirely when the manifest carries a Laurl:
# the framework then POSTs the challenge there with no service code at all.
diff --git a/unshackle/services/MUSIC_EXAMPLE/__init__.py b/unshackle/services/MUSIC_EXAMPLE/__init__.py
index 8b1256bc..e7e66ef4 100644
--- a/unshackle/services/MUSIC_EXAMPLE/__init__.py
+++ b/unshackle/services/MUSIC_EXAMPLE/__init__.py
@@ -4,7 +4,7 @@ import re
from collections.abc import Generator
from datetime import datetime
from http.cookiejar import CookieJar
-from typing import Any, Optional
+from typing import Any
import click
@@ -119,9 +119,9 @@ class MUSIC_EXAMPLE(Service):
# the framework applies to whatever get_tracks() returns.
if self.config is None:
- raise EnvironmentError("config.yaml is missing for this service.")
+ raise OSError("config.yaml is missing for this service.")
- def authenticate(self, cookies: Optional[CookieJar] = None, credential: Optional[Credential] = None) -> None:
+ def authenticate(self, cookies: CookieJar | None = None, credential: Credential | None = None) -> None:
# Loads the cookie jar into self.session and stores self.credential.
super().authenticate(cookies, credential)
@@ -135,7 +135,7 @@ class MUSIC_EXAMPLE(Service):
self.log.info(" + Using cached tokens")
else:
if not credential:
- raise EnvironmentError("Service requires Credentials.")
+ raise OSError("Service requires Credentials.")
token = self.session.post(
url=self.config["endpoints"]["login"],
data={"username": credential.username, "password": credential.password},
@@ -370,7 +370,7 @@ class MUSIC_EXAMPLE(Service):
},
)
- def get_lyrics(self, track: dict) -> Optional[str]:
+ def get_lyrics(self, track: dict) -> str | None:
response = self.session.get(
url=self.config["endpoints"]["lyrics"].format(track_id=track["id"]),
params={"token": self.token},
diff --git a/unshackle/utils/base58.py b/unshackle/utils/base58.py
index b6216585..55bb4fd8 100644
--- a/unshackle/utils/base58.py
+++ b/unshackle/utils/base58.py
@@ -5,9 +5,9 @@ Implementations of Base58 and Base58Check encodings that are compatible
with the bitcoin network.
"""
+from collections.abc import Mapping
from functools import lru_cache
from hashlib import sha256
-from typing import Mapping, Union
__version__ = "2.1.1"
@@ -19,7 +19,7 @@ XRP_ALPHABET = RIPPLE_ALPHABET
alphabet = BITCOIN_ALPHABET
-def scrub_input(v: Union[str, bytes]) -> bytes:
+def scrub_input(v: str | bytes) -> bytes:
if isinstance(v, str):
v = v.encode("ascii")
@@ -40,7 +40,7 @@ def b58encode_int(i: int, default_one: bool = True, alphabet: bytes = BITCOIN_AL
return string
-def b58encode(v: Union[str, bytes], alphabet: bytes = BITCOIN_ALPHABET) -> bytes:
+def b58encode(v: str | bytes, alphabet: bytes = BITCOIN_ALPHABET) -> bytes:
"""
Encode a string using Base58
"""
@@ -56,7 +56,7 @@ def b58encode(v: Union[str, bytes], alphabet: bytes = BITCOIN_ALPHABET) -> bytes
return alphabet[0:1] * (origlen - newlen) + result
-@lru_cache()
+@lru_cache
def get_base58_decode_map(alphabet: bytes, autofix: bool) -> Mapping[int, int]:
invmap = {char: index for index, char in enumerate(alphabet)}
@@ -71,7 +71,7 @@ def get_base58_decode_map(alphabet: bytes, autofix: bool) -> Mapping[int, int]:
return invmap
-def b58decode_int(v: Union[str, bytes], alphabet: bytes = BITCOIN_ALPHABET, *, autofix: bool = False) -> int:
+def b58decode_int(v: str | bytes, alphabet: bytes = BITCOIN_ALPHABET, *, autofix: bool = False) -> int:
"""
Decode a Base58 encoded string as an integer
"""
@@ -87,11 +87,11 @@ def b58decode_int(v: Union[str, bytes], alphabet: bytes = BITCOIN_ALPHABET, *, a
for char in v:
decimal = decimal * base + map[char]
except KeyError as e:
- raise ValueError("Invalid character {!r}".format(chr(e.args[0]))) from None
+ raise ValueError(f"Invalid character {chr(e.args[0])!r}") from None
return decimal
-def b58decode(v: Union[str, bytes], alphabet: bytes = BITCOIN_ALPHABET, *, autofix: bool = False) -> bytes:
+def b58decode(v: str | bytes, alphabet: bytes = BITCOIN_ALPHABET, *, autofix: bool = False) -> bytes:
"""
Decode a Base58 encoded string
"""
@@ -107,7 +107,7 @@ def b58decode(v: Union[str, bytes], alphabet: bytes = BITCOIN_ALPHABET, *, autof
return acc.to_bytes(origlen - newlen + (acc.bit_length() + 7) // 8, "big")
-def b58encode_check(v: Union[str, bytes], alphabet: bytes = BITCOIN_ALPHABET) -> bytes:
+def b58encode_check(v: str | bytes, alphabet: bytes = BITCOIN_ALPHABET) -> bytes:
"""
Encode a string using Base58 with a 4 character checksum
"""
@@ -117,7 +117,7 @@ def b58encode_check(v: Union[str, bytes], alphabet: bytes = BITCOIN_ALPHABET) ->
return b58encode(v + digest[:4], alphabet=alphabet)
-def b58decode_check(v: Union[str, bytes], alphabet: bytes = BITCOIN_ALPHABET, *, autofix: bool = False) -> bytes:
+def b58decode_check(v: str | bytes, alphabet: bytes = BITCOIN_ALPHABET, *, autofix: bool = False) -> bytes:
"""Decode and verify the checksum of a Base58 encoded string"""
result = b58decode(v, alphabet=alphabet, autofix=autofix)
diff --git a/unshackle/utils/base62.py b/unshackle/utils/base62.py
index 9e1707de..b6efac35 100644
--- a/unshackle/utils/base62.py
+++ b/unshackle/utils/base62.py
@@ -105,12 +105,12 @@ def value(ch: str, charset: str) -> int:
try:
return charset.index(ch)
except ValueError:
- raise ValueError("base62: Invalid character (%s)" % ch)
+ raise ValueError(f"base62: Invalid character ({ch})") from None
def check_type(value: object, expected_type: type) -> None:
"""Checks if the input is in an appropriate type."""
if not isinstance(value, expected_type):
- msg = "Expected {} object, not {}".format(expected_type, value.__class__.__name__)
+ msg = f"Expected {expected_type} object, not {value.__class__.__name__}"
raise TypeError(msg)
diff --git a/unshackle/vaults/API.py b/unshackle/vaults/API.py
index 3c2b3f64..471b6da7 100644
--- a/unshackle/vaults/API.py
+++ b/unshackle/vaults/API.py
@@ -1,4 +1,4 @@
-from typing import Iterator, Optional, Union
+from collections.abc import Iterator
from uuid import UUID
from requests import HTTPError, Response
@@ -15,7 +15,7 @@ class API(Vault):
uri: str,
token: str,
no_push: bool = False,
- headers: Optional[dict[str, str]] = None,
+ headers: dict[str, str] | None = None,
timeout: float = 10.0,
) -> None:
super().__init__(name, no_push)
@@ -27,7 +27,7 @@ class API(Vault):
if headers:
self.session.headers.update(headers)
- def get_key(self, kid: Union[UUID, str], service: str) -> Optional[str]:
+ def get_key(self, kid: UUID | str, service: str) -> str | None:
if isinstance(kid, UUID):
kid = kid.hex
@@ -96,8 +96,7 @@ class API(Vault):
if not isinstance(content_keys, dict):
raise ValueError(f"Expected {content_keys} to be {dict}, was {type(content_keys)}")
- for key_id, key in content_keys.items():
- yield key_id, key
+ yield from content_keys.items()
pages = int(data["pages"])
if pages <= page:
@@ -105,7 +104,7 @@ class API(Vault):
page += 1
- def add_key(self, service: str, kid: Union[UUID, str], key: str) -> bool:
+ def add_key(self, service: str, kid: UUID | str, key: str) -> bool:
if isinstance(kid, UUID):
kid = kid.hex
@@ -138,7 +137,7 @@ class API(Vault):
return added or updated
- def add_keys(self, service: str, kid_keys: dict[Union[UUID, str], str]) -> int:
+ def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int:
normalized_keys = {str(kid).replace("-", ""): key for kid, key in kid_keys.items()}
kid_list = list(normalized_keys.keys())
@@ -207,7 +206,7 @@ class API(Vault):
return total_added
- def flag_bad_key(self, service: str, kid: Union[UUID, str], key: str, source: str) -> None:
+ def flag_bad_key(self, service: str, kid: UUID | str, key: str, source: str) -> None:
"""Report a pair that failed to decrypt. The vault only accepts pairs it served."""
if self.no_push:
return
@@ -222,7 +221,7 @@ class API(Vault):
)
self._check(response, ignore=frozenset({1, 4}))
- def unflag_bad_key(self, kid: Union[UUID, str], key: str) -> None:
+ def unflag_bad_key(self, kid: UUID | str, key: str) -> None:
if self.no_push:
return
if isinstance(kid, UUID):
@@ -270,8 +269,7 @@ class API(Vault):
if not isinstance(service_list, list):
raise ValueError(f"Expected {service_list} to be {list}, was {type(service_list)}")
- for service in service_list:
- yield service
+ yield from service_list
class Exceptions:
diff --git a/unshackle/vaults/HTTP.py b/unshackle/vaults/HTTP.py
index 8059204d..063e37ab 100644
--- a/unshackle/vaults/HTTP.py
+++ b/unshackle/vaults/HTTP.py
@@ -1,6 +1,6 @@
import json
+from collections.abc import Iterator
from enum import Enum
-from typing import Iterator, Optional, Union
from uuid import UUID
from unshackle.core.vault import RateLimited, Vault, is_null_key, vault_session
@@ -26,9 +26,9 @@ class HTTP(Vault):
self,
name: str,
host: str,
- password: Optional[str] = None,
- api_key: Optional[str] = None,
- username: Optional[str] = None,
+ password: str | None = None,
+ api_key: str | None = None,
+ username: str | None = None,
api_mode: str = "query",
no_push: bool = False,
timeout: float = 10.0,
@@ -55,7 +55,7 @@ class HTTP(Vault):
self.username = username
self.api_mode = api_mode.lower()
self.batch_insert = True
- self.current_title: Optional[str] = None
+ self.current_title: str | None = None
self.session = vault_session(timeout)
self.api_session_id = None
@@ -69,7 +69,7 @@ class HTTP(Vault):
elif self.api_mode not in ["query", "json", "decrypt_labs"]:
raise ValueError("api_mode must be either 'query', 'json', or 'decrypt_labs'")
- def request(self, method: str, params: Optional[dict] = None) -> dict:
+ def request(self, method: str, params: dict | None = None) -> dict:
"""Make a request to the JSON API vault."""
if self.api_mode != "json":
raise ValueError("request method is only available in json mode")
@@ -103,7 +103,7 @@ class HTTP(Vault):
except json.JSONDecodeError:
if r.status_code == 404:
return {"status": "not_found"}
- raise ValueError(f"API returned an invalid response: {r.text}")
+ raise ValueError(f"API returned an invalid response: {r.text}") from None
if res.get("status_code") != 200:
raise ValueError(f"API returned an error: {res['status_code']} - {res['message']}")
@@ -113,7 +113,7 @@ class HTTP(Vault):
return res.get("message", res)
- def get_key(self, kid: Union[UUID, str], service: str) -> Optional[str]:
+ def get_key(self, kid: UUID | str, service: str) -> str | None:
if isinstance(kid, UUID):
kid = kid.hex
@@ -217,7 +217,7 @@ class HTTP(Vault):
for key_entry in data["keys"]:
yield key_entry["kid"], key_entry["key"]
- def add_key(self, service: str, kid: Union[UUID, str], key: str) -> bool:
+ def add_key(self, service: str, kid: UUID | str, key: str) -> bool:
if is_null_key(key):
raise ValueError("You cannot add a NULL Content Key to a Vault.")
@@ -263,11 +263,11 @@ class HTTP(Vault):
return data.get("status_code") == 200
- def add_keys(self, service: str, kid_keys: dict[Union[UUID, str], str]) -> int:
+ def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int:
if self.api_mode == "decrypt_labs":
return 0
- for kid, key in kid_keys.items():
+ for key in kid_keys.values():
if is_null_key(key):
raise ValueError("You cannot add a NULL Content Key to a Vault.")
@@ -366,9 +366,7 @@ class HTTP(Vault):
"""
self.current_title = title
- def insert_key_with_result(
- self, service: str, kid: Union[UUID, str], key: str, title: Optional[str] = None
- ) -> InsertResult:
+ def insert_key_with_result(self, service: str, kid: UUID | str, key: str, title: str | None = None) -> InsertResult:
"""
Insert a content key and return detailed result information.
This method provides more granular feedback than the standard add_key method.
diff --git a/unshackle/vaults/MySQL.py b/unshackle/vaults/MySQL.py
index 94384503..46a2e7bb 100644
--- a/unshackle/vaults/MySQL.py
+++ b/unshackle/vaults/MySQL.py
@@ -1,7 +1,8 @@
from __future__ import annotations
import threading
-from typing import Any, Iterator, Optional, Union
+from collections.abc import Iterator
+from typing import Any
from uuid import UUID
import pymysql
@@ -32,7 +33,7 @@ class MySQL(Vault):
if not self.has_permission("SELECT"):
raise PermissionError(f"MySQL vault {self.slug} has no SELECT permission.")
- def get_key(self, kid: Union[UUID, str], service: str) -> Optional[str]:
+ def get_key(self, kid: UUID | str, service: str) -> str | None:
if isinstance(kid, UUID):
kid = kid.hex
@@ -73,7 +74,7 @@ class MySQL(Vault):
finally:
cursor.close()
- def add_key(self, service: str, kid: Union[UUID, str], key: str) -> bool:
+ def add_key(self, service: str, kid: UUID | str, key: str) -> bool:
if is_null_key(key):
raise ValueError("You cannot add a NULL Content Key to a Vault.")
@@ -113,8 +114,8 @@ class MySQL(Vault):
return True
- def add_keys(self, service: str, kid_keys: dict[Union[UUID, str], str]) -> int:
- for kid, key in kid_keys.items():
+ def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int:
+ for key in kid_keys.values():
if is_null_key(key):
raise ValueError("You cannot add a NULL Content Key to a Vault.")
@@ -178,7 +179,7 @@ class MySQL(Vault):
finally:
cursor.close()
- def resolve_table(self, name: str) -> Optional[str]:
+ def resolve_table(self, name: str) -> str | None:
"""
Get the actual Table name matching `name` case-insensitively, if it exists.
@@ -266,7 +267,7 @@ class MySQL(Vault):
conn.commit()
cursor.close()
- def has_permission(self, operation: str, database: Optional[str] = None, table: Optional[str] = None) -> bool:
+ def has_permission(self, operation: str, database: str | None = None, table: str | None = None) -> bool:
"""Return True if the current connection has a specific permission."""
grants = [x for x in self.permissions if x[0] == ["*"] or operation.upper() in x[0]]
if grants and database:
diff --git a/unshackle/vaults/SQLite.py b/unshackle/vaults/SQLite.py
index 510a2421..d2143f6b 100644
--- a/unshackle/vaults/SQLite.py
+++ b/unshackle/vaults/SQLite.py
@@ -1,8 +1,8 @@
import sqlite3
import threading
+from collections.abc import Iterator
from pathlib import Path
from sqlite3 import Connection
-from typing import Iterator, Optional, Union
from uuid import UUID
from unshackle.core.vault import Vault, is_null_key
@@ -13,13 +13,13 @@ class SQLite(Vault):
local = True
- def __init__(self, name: str, path: Union[str, Path], no_push: bool = False) -> None:
+ def __init__(self, name: str, path: str | Path, no_push: bool = False) -> None:
super().__init__(name, no_push)
self.path = Path(path).expanduser()
# TODO: Use a DictCursor or such to get fetches as dict?
self.conn_factory = ConnectionFactory(self.path)
- def get_key(self, kid: Union[UUID, str], service: str) -> Optional[str]:
+ def get_key(self, kid: UUID | str, service: str) -> str | None:
if isinstance(kid, UUID):
kid = kid.hex
@@ -52,12 +52,11 @@ class SQLite(Vault):
try:
cursor.execute(f"SELECT `kid`, `key_` FROM `{table}` WHERE `key_`!=?", ("0" * 32,))
- for kid, key_ in cursor.fetchall():
- yield kid, key_
+ yield from cursor.fetchall()
finally:
cursor.close()
- def add_key(self, service: str, kid: Union[UUID, str], key: str) -> bool:
+ def add_key(self, service: str, kid: UUID | str, key: str) -> bool:
if is_null_key(key):
raise ValueError("You cannot add a NULL Content Key to a Vault.")
@@ -93,8 +92,8 @@ class SQLite(Vault):
return True
- def add_keys(self, service: str, kid_keys: dict[Union[UUID, str], str]) -> int:
- for kid, key in kid_keys.items():
+ def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int:
+ for key in kid_keys.values():
if is_null_key(key):
raise ValueError("You cannot add a NULL Content Key to a Vault.")
@@ -169,7 +168,7 @@ class SQLite(Vault):
finally:
cursor.close()
- def is_bad_key(self, kid: Union[UUID, str], key: str) -> bool:
+ def is_bad_key(self, kid: UUID | str, key: str) -> bool:
if isinstance(kid, UUID):
kid = kid.hex
self.create_bad_keys_table()
@@ -180,7 +179,7 @@ class SQLite(Vault):
finally:
cursor.close()
- def flag_bad_key(self, service: str, kid: Union[UUID, str], key: str, source: str) -> None:
+ def flag_bad_key(self, service: str, kid: UUID | str, key: str, source: str) -> None:
if isinstance(kid, UUID):
kid = kid.hex
self.create_bad_keys_table()
@@ -198,7 +197,7 @@ class SQLite(Vault):
conn.commit()
cursor.close()
- def unflag_bad_key(self, kid: Union[UUID, str], key: str) -> None:
+ def unflag_bad_key(self, kid: UUID | str, key: str) -> None:
if isinstance(kid, UUID):
kid = kid.hex
self.create_bad_keys_table()
@@ -235,7 +234,7 @@ class SQLite(Vault):
# set only after the commit: a parallel vault thread must not query a table still being made
self._bad_keys_ready = True
- def resolve_table(self, name: str) -> Optional[str]:
+ def resolve_table(self, name: str) -> str | None:
"""Get the actual Table name matching `name` case-insensitively, if it exists."""
conn = self.conn_factory.get()
cursor = conn.cursor()
@@ -285,7 +284,7 @@ class SQLite(Vault):
class ConnectionFactory:
- def __init__(self, path: Union[str, Path]) -> None:
+ def __init__(self, path: str | Path) -> None:
self._path = path
self._store = threading.local()