mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-26 19:05:13 +00:00
Compare commits
10
Commits
96c3840b82
...
1a7192380d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1a7192380d | ||
|
|
397ac2c7cb | ||
|
|
93ca8ab9c0 | ||
|
|
65c8e60a7a | ||
|
|
de9646dba2 | ||
|
|
99f0c269be | ||
|
|
e509db618e | ||
|
|
2bbb2d65b8 | ||
|
|
a58da3f5d3 | ||
|
|
67d3d4801f |
@@ -36,10 +36,15 @@ jobs:
|
||||
- name: Import order
|
||||
run: uv run isort --check-only unshackle tests --skip-glob "*/services/*"
|
||||
- name: Type check
|
||||
if: ${{ !cancelled() }}
|
||||
run: |
|
||||
out=$(uv run mypy unshackle) || true
|
||||
out=$(uv run mypy unshackle) || rc=$?
|
||||
echo "$out"
|
||||
echo "$out" | sed -nE 's/^([^:]+):([0-9]+): error: (.*)$/::warning file=\1,line=\2::\3/p'
|
||||
echo "$out" | sed -nE 's/^([^:]+):([0-9]+): error: (.*)$/::error file=\1,line=\2::\3/p'
|
||||
exit ${rc:-0}
|
||||
- name: Security lint
|
||||
if: ${{ !cancelled() }}
|
||||
run: uv run bandit -q -c pyproject.toml -r unshackle --severity-level medium --confidence-level medium
|
||||
|
||||
test:
|
||||
strategy:
|
||||
|
||||
+24
-19
@@ -8,25 +8,6 @@ repos:
|
||||
hooks:
|
||||
- id: conventional-pre-commit
|
||||
stages: [commit-msg]
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
rev: v0.15.12
|
||||
hooks:
|
||||
- id: ruff-check
|
||||
args: [--fix]
|
||||
- id: ruff-format
|
||||
- repo: https://github.com/pycqa/isort
|
||||
rev: 9.0.0a3
|
||||
hooks:
|
||||
- id: isort
|
||||
- repo: https://github.com/PyCQA/bandit
|
||||
rev: 1.9.4
|
||||
hooks:
|
||||
- id: bandit
|
||||
args:
|
||||
- -c=pyproject.toml
|
||||
- --severity-level=medium
|
||||
- --confidence-level=medium
|
||||
additional_dependencies: ['bandit[toml]']
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v6.0.0
|
||||
hooks:
|
||||
@@ -35,6 +16,30 @@ repos:
|
||||
args: [--markdown-linebreak-ext=md]
|
||||
- repo: local
|
||||
hooks:
|
||||
- id: ruff-check
|
||||
name: ruff check
|
||||
entry: uv run ruff check --fix
|
||||
language: system
|
||||
types: [python]
|
||||
require_serial: true
|
||||
- id: ruff-format
|
||||
name: ruff format
|
||||
entry: uv run ruff format
|
||||
language: system
|
||||
types: [python]
|
||||
require_serial: true
|
||||
- id: isort
|
||||
name: isort
|
||||
entry: uv run isort
|
||||
language: system
|
||||
types: [python]
|
||||
require_serial: true
|
||||
- id: bandit
|
||||
name: bandit
|
||||
entry: uv run bandit -q -c pyproject.toml --severity-level medium --confidence-level medium
|
||||
language: system
|
||||
types: [python]
|
||||
files: ^unshackle/
|
||||
- id: mypy
|
||||
name: mypy
|
||||
entry: uv run mypy unshackle
|
||||
|
||||
@@ -17,7 +17,7 @@ Start the server with [`unshackle serve`](../../guide/cli-reference.md). By defa
|
||||
- **CORS.** Every response carries permissive CORS headers, and the server answers `OPTIONS` preflight requests automatically.
|
||||
- **Compression.** JSON responses of 256 bytes or more are gzip-compressed when the client sends `Accept-Encoding: gzip`. A [slow response](#slow-responses) is not compressed.
|
||||
- **Service allowlist.** The effective allowlist for your API key filters the service-facing endpoints (the intersection of the global `serve.services` list and your per-key list). The server treats services you cannot use as unknown.
|
||||
- **Remote services.** A full-mode server can run a service through one of its own `remote_services` servers (see [Remote sessions](remote-sessions.md)). `GET /api/config` lists their names in `remote_services`, and `GET /api/services?remote=<name>` lists that server's services, each with `remote` set to the name. Add `"remote": "<name>"` to `POST /api/search`, `/api/list-titles`, `/api/list-tracks` or `/api/download`, and the server opens a remote session with its own key for that server: the remote logs in and resolves titles, tracks and licences, and a download still runs, decrypts and muxes here. The tag may be any case or an alias, and your allowlist applies to it. An unknown name is `400 INVALID_PARAMETERS`, a server that does not answer is `SERVICE_UNAVAILABLE`, and a tag it does not offer is `INVALID_SERVICE`. List calls for the same title, profile, proxy and service options share one remote session, which closes after 120 seconds unused. An optional `client_name` names your client on the remote server's dashboard as `serve (<client_name>)`. A relayed search opens no remote session. The server sends its own credentials, cookies and cache for the `profile` with the search. A service that searches with no login gets none of them. A `--remote-only` server does not relay. A remote login that waits on you (a pair code or URL to approve on another device) cannot answer through a list call, so poll `GET /api/remote/logins` alongside it: each entry carries the login's `notice`, and its `prompt` when it asks a question (an OTP), which you answer with `POST /api/remote/logins/{id}/input` and `{"response": "..."}`. A remote download job shows the same text as its own `notice`, and asks a question (an OTP) through `input_prompt` as a local job does.
|
||||
- **Remote services.** A full-mode server can run a service through one of its own `remote_services` servers (see [Remote sessions](remote-sessions.md)). `GET /api/config` lists their names in `remote_services`, and `GET /api/services?remote=<name>` lists that server's services, each with `remote` set to the name. Add `"remote": "<name>"` to `POST /api/search`, `/api/list-titles`, `/api/list-tracks` or `/api/download`, and the server opens a remote session with its own key for that server: the remote logs in and resolves titles, tracks and licences, and a download still runs, decrypts and muxes here. The tag may be any case or an alias, and your allowlist applies to it. An unknown name is `400 INVALID_PARAMETERS`, a server that does not answer is `SERVICE_UNAVAILABLE`, and a tag it does not offer is `INVALID_SERVICE`. List calls from the same API key for the same title, profile, proxy, client region and service options share one remote session, which closes after 120 seconds unused. An optional `client_name` names your client on the remote server's dashboard as `serve (<client_name>)`. A relayed search opens no remote session. The server sends its own credentials, cookies and cache for the `profile` with the search. A service that searches with no login gets none of them. A `--remote-only` server does not relay. A remote login that waits on you (a pair code or URL to approve on another device) cannot answer through a list call, so poll `GET /api/remote/logins` alongside it: each entry carries the login's `notice`, and its `prompt` when it asks a question (an OTP), which you answer with `POST /api/remote/logins/{id}/input` and `{"response": "..."}`. A remote download job shows the same text as its own `notice`, and asks a question (an OTP) through `input_prompt` as a local job does.
|
||||
|
||||
!!! warning "Error responses have two shapes"
|
||||
Structured application errors (raised inside a handler) return `{"status": "error", "error_code": "...", "message": "...", "timestamp": "..."}`. The authentication middleware, however, returns a **different** shape: `{"status": 401, "message": "..."}` with an integer `status` and no `error_code`. The same middleware answers `429` in that shape when an API key goes over its rate limit. Clients must accept both shapes. The [Error responses](#error-responses) section at the bottom of this page gives the full error model.
|
||||
@@ -151,7 +151,7 @@ For a service with `anonymous_search`, the server does not log in and ignores `c
|
||||
| `service` | string | yes | - | Service tag. |
|
||||
| `query` | string | yes | - | Search query. |
|
||||
| `profile` | string | no | `null` | Credential/cookie profile to use. |
|
||||
| `proxy` | string | no | `null` | Full proxy URI, a Control D resolver as `controld://<resolver>@dns.controld.com`, or a country code when the API key has `server_proxy`. |
|
||||
| `proxy` | string | no | `null` | Full proxy URI on a public host, a Control D resolver as `controld://<resolver>@dns.controld.com`, or a country code when the API key has `server_proxy`. |
|
||||
| `no_proxy` | boolean | no | `false` | Force-disable all proxy use. |
|
||||
| `credentials`, `cookies`, `cache` | - | no | `null` | Your own login material, on a `--remote-only` server only. See [Client cache on a remote-only server](#client-cache-on-a-remote-only-server). |
|
||||
|
||||
@@ -200,7 +200,7 @@ Get the list of titles behind a title ID, for example episodes or a movie, witho
|
||||
| `service` | string | yes | Service tag. |
|
||||
| `title_id` | string | yes | Title identifier. |
|
||||
| `profile` | string | no | Credential/cookie profile. |
|
||||
| `proxy` | string | no | Full proxy URI, a Control D resolver as `controld://<resolver>@dns.controld.com`, or a country code when the API key has `server_proxy`. |
|
||||
| `proxy` | string | no | Full proxy URI on a public host, a Control D resolver as `controld://<resolver>@dns.controld.com`, or a country code when the API key has `server_proxy`. |
|
||||
| `no_proxy` | boolean | no | Force-disable proxy. |
|
||||
| `cdm_type` | string | no | Preferred CDM type. |
|
||||
| `credentials`, `cookies`, `cache` | - | no | Your own login material, on a `--remote-only` server only. See [Client cache on a remote-only server](#client-cache-on-a-remote-only-server). |
|
||||
@@ -468,7 +468,7 @@ Make a download job. It requires `service` and `title_id`. Every other field is
|
||||
| `all_drm` | boolean | `false` | License each track with both Widevine and PlayReady. Needs a CDM for each DRM system. Key vaults are read first; `cdm_only: true` sends a challenge for each system. The server refuses it with `cdm`, which selects one device. |
|
||||
| `export` | boolean | `false` | Export manifest/keys/subs to JSON. |
|
||||
| `cdm_only` | boolean | `null` | Force CDM-only (`true`) or vault-only (`false`) key retrieval. |
|
||||
| `proxy` / `no_proxy` / `no_proxy_download` / `proxy_download` | string / bool / bool / string | `null` / `false` / `false` / `null` | Proxy controls. `proxy` and `proxy_download` must be full proxy URIs unless the API key has `server_proxy`. A Control D resolver, `controld://<resolver>@dns.controld.com`, counts as a full proxy URI: the server runs a forwarder for it. |
|
||||
| `proxy` / `no_proxy` / `no_proxy_download` / `proxy_download` | string / bool / bool / string | `null` / `false` / `false` / `null` | Proxy controls. `proxy` and `proxy_download` must be full proxy URIs on a public host unless the API key has `server_proxy`. A Control D resolver, `controld://<resolver>@dns.controld.com`, counts as a full proxy URI: the server runs a forwarder for it. |
|
||||
| `no_folder` / `no_source` / `no_mux` | boolean | `false` | Output/mux controls. |
|
||||
| `sample` | boolean/string | `null` | Download a short sample and write it with a `SAMPLE` tag on the filename in a `Sample` folder inside the output folder. `true` is 60 seconds from 2 minutes in; `"0-60"` is a window in seconds. |
|
||||
| `include_sample` | boolean | `false` | Download the full title, then also cut a 60 second sample from each muxed file into a `Sample` folder next to it. |
|
||||
@@ -492,9 +492,11 @@ Make a download job. It requires `service` and `title_id`. Every other field is
|
||||
|
||||
**Service options.** A service's own CLI options travel in the same body. Send them in a nested
|
||||
`service_params` object, or as flat top-level keys. When the body has `service_params`, the server
|
||||
reads service options only from it, and every flat key is a `dl` value. An option you leave out
|
||||
reads service options only from it, and every flat key is a `dl` value. Without it, a flat key that
|
||||
is also a `dl` option, such as `quality` or `lang`, stays a `dl` value. An option you leave out
|
||||
takes the default declared on the service's `cli` command, so the job matches the equivalent `dl`
|
||||
run. `profile` at the top level always means the credential
|
||||
run. The server checks each service option against that option's type, and a value it refuses gets
|
||||
`400 INVALID_PARAMETERS`. `profile` at the top level always means the credential
|
||||
profile, never a service's own `--profile` option.
|
||||
|
||||
=== "Request"
|
||||
@@ -973,7 +975,7 @@ Make a remote session for a service and title. Authentication runs asynchronousl
|
||||
|
||||
Service CLI options also travel in a nested `service_params` object. When the body has `service_params`, the server reads service options only from it, and a flat key with the same name stays a `dl` value. `profile` at the top level always means the credentials profile, never a service's own `--profile` option.
|
||||
|
||||
The `proxy` value must be a full proxy URI, unless the operator gives your API key `server_proxy` in the `serve.users` config. Without `server_proxy`, the server does not resolve country codes with its own proxy providers. It rejects the request with `INVALID_PROXY` when no `proxy` is set and the reported `client_region` differs from the server's region. A request that reports no `client_region` is not blocked. Pass `proxy` with your own proxy, or `no_proxy` to accept the server's own connection. With `server_proxy`, the server resolves a country code and picks a proxy for your `client_region` itself. A Control D resolver, `controld://<resolver>@dns.controld.com`, counts as a full proxy URI: the server runs a forwarder for it and needs no Control D configuration of its own.
|
||||
The `proxy` value must be a full proxy URI, unless the operator gives your API key `server_proxy` in the `serve.users` config. Without `server_proxy`, a proxy URI gets `INVALID_PROXY` when its host is not a public address or is not a plain host name or IP address. Without `server_proxy`, the server does not resolve country codes with its own proxy providers. It rejects the request with `INVALID_PROXY` when no `proxy` is set and the reported `client_region` differs from the server's region. A request that reports no `client_region` is not blocked. Pass `proxy` with your own proxy, or `no_proxy` to accept the server's own connection. With `server_proxy`, the server resolves a country code and picks a proxy for your `client_region` itself. A Control D resolver, `controld://<resolver>@dns.controld.com`, counts as a full proxy URI: the server runs a forwarder for it and needs no Control D configuration of its own.
|
||||
|
||||
=== "Response `200`"
|
||||
|
||||
|
||||
@@ -136,7 +136,7 @@ hood the client walks a remote session through its lifecycle.
|
||||
- Local **cookies**, compressed and base64-encoded
|
||||
- A resolved **proxy**, or, if you did not set one, your detected
|
||||
**client region**. A client that reports no region is not blocked. The
|
||||
proxy must be a full proxy URI unless the operator gives your API key
|
||||
proxy must be a full proxy URI on a public host unless the operator gives your API key
|
||||
`server_proxy`. Without `server_proxy` the server does not resolve country
|
||||
codes with its own proxy providers, and it rejects the remote session when
|
||||
it sits in a different region from the reported one, asking the client to
|
||||
|
||||
@@ -97,7 +97,7 @@ These are abstract. A service will not load unless it defines all three:
|
||||
line, and a REST download job shows it as the job's `notice`.
|
||||
- **Event callbacks**: `on_segment_downloaded`, `on_track_downloaded`,
|
||||
`on_track_decrypted`, `on_track_repacked`, `on_track_multiplex` let a service react to
|
||||
pipeline events (for example, MonaLisa decrypts each segment in `on_segment_downloaded`).
|
||||
pipeline events.
|
||||
- **`resolve_server_keys(title)`**: an escape hatch for services whose decryption keys are
|
||||
resolved server-side *ahead of* the normal per-track license flow. Unlike everything else
|
||||
here it is **not declared on the `Service` base class at all**: `dl.py` probes for it with
|
||||
|
||||
@@ -309,6 +309,12 @@ to let that API key send a country code or a `provider:country` value, and to le
|
||||
pick a proxy for the client's region and for a service geofence. The client reports its own
|
||||
region; a client that reports none is not blocked.
|
||||
|
||||
Without `server_proxy`, the server refuses a proxy URI whose host is not a public address:
|
||||
loopback, private, link-local and other special-purpose addresses, and `localhost`. This also
|
||||
applies to a server on a LAN, so a client proxy on that LAN needs `server_proxy` or an admin key.
|
||||
The server checks the proxy values the job uses, including a `proxy` default from the server's
|
||||
own config.
|
||||
|
||||
```yaml
|
||||
serve:
|
||||
api_secret: change-me
|
||||
|
||||
+1
-1
@@ -65,7 +65,6 @@ dependencies = [
|
||||
"language-data>=1.4.0",
|
||||
"wasmtime>=41.0.0",
|
||||
"rnet>=2.4.2",
|
||||
"bandit>=1.9.4",
|
||||
"jsonpath-ng>=1.8.0",
|
||||
"mutagen>=1.47.0,<2",
|
||||
"defusedxml>=0.7.1",
|
||||
@@ -95,6 +94,7 @@ dev = [
|
||||
"isort>=5.13.2,<8",
|
||||
"ruff>=0.15.12,<0.16",
|
||||
"types-pyyaml>=6.0,<7",
|
||||
"bandit>=1.9.4,<2",
|
||||
]
|
||||
test = [
|
||||
"pytest>=8.3.0,<9",
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
"""MonaLisa's external decrypt tool: a missing tool raises, and a failed run leaves the ciphertext untouched."""
|
||||
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from uuid import UUID
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.drm.monalisa import MonaLisa
|
||||
from unshackle.core.utils import subprocess as tool_runner
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def track(tmp_path: Path) -> Path:
|
||||
path = tmp_path / "track.mp4"
|
||||
path.write_bytes(b"cipher")
|
||||
return path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def make_drm(monkeypatch: pytest.MonkeyPatch):
|
||||
"""Build a MonaLisa with a known key; extract_keys needs a real device file, so it is skipped."""
|
||||
monkeypatch.setattr(MonaLisa, "extract_keys", lambda self: None)
|
||||
|
||||
def build(tool: Path) -> MonaLisa:
|
||||
drm = MonaLisa("ticket", Path("unused.mld"), tool)
|
||||
drm._kid = UUID(int=1)
|
||||
drm._key = "00" * 16
|
||||
return drm
|
||||
|
||||
return build
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tool(tmp_path: Path) -> Path:
|
||||
path = tmp_path / "decrypt-tool"
|
||||
path.write_bytes(b"")
|
||||
return path
|
||||
|
||||
|
||||
def fake_tool(monkeypatch: pytest.MonkeyPatch, output: bytes, returncode: int = 0, stderr: bytes = b"") -> None:
|
||||
"""Replace the tool run with one that writes `output` to the `-o` path."""
|
||||
|
||||
def run(cmd, **kwargs):
|
||||
Path(cmd[cmd.index("-o") + 1]).write_bytes(output)
|
||||
return subprocess.CompletedProcess(cmd, returncode, b"", stderr)
|
||||
|
||||
monkeypatch.setattr(tool_runner.subprocess, "run", run)
|
||||
|
||||
|
||||
def test_a_missing_tool_raises_and_keeps_the_file(make_drm, track: Path, tmp_path: Path) -> None:
|
||||
with pytest.raises(RuntimeError, match="tool"):
|
||||
make_drm(tmp_path / "absent").decrypt(track)
|
||||
assert track.read_bytes() == b"cipher"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("output", "returncode", "stderr"),
|
||||
[(b"partial", 1, b"bad key"), (b"", 0, b"")],
|
||||
ids=["non-zero exit", "empty output"],
|
||||
)
|
||||
def test_a_failed_run_keeps_the_ciphertext(
|
||||
make_drm, track: Path, tool: Path, monkeypatch: pytest.MonkeyPatch, output: bytes, returncode: int, stderr: bytes
|
||||
) -> None:
|
||||
fake_tool(monkeypatch, output, returncode, stderr)
|
||||
with pytest.raises(RuntimeError, match=f"failed: {stderr.decode()}"):
|
||||
make_drm(tool).decrypt(track)
|
||||
assert track.read_bytes() == b"cipher"
|
||||
assert not track.with_name("track_decrypted.mp4").exists()
|
||||
|
||||
|
||||
def test_a_timeout_keeps_the_ciphertext_and_hides_the_key(
|
||||
make_drm, track: Path, tool: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
def hang(cmd, **kwargs):
|
||||
raise subprocess.TimeoutExpired(cmd, kwargs.get("timeout"))
|
||||
|
||||
monkeypatch.setattr(tool_runner.subprocess, "run", hang)
|
||||
drm = make_drm(tool)
|
||||
with pytest.raises(RuntimeError, match="timed out") as raised:
|
||||
drm.decrypt(track)
|
||||
assert drm.key_pair not in str(raised.value)
|
||||
assert raised.value.__suppress_context__
|
||||
assert track.read_bytes() == b"cipher"
|
||||
|
||||
|
||||
def test_a_good_run_replaces_the_file_and_drops_the_temp_output(
|
||||
make_drm, track: Path, tool: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
fake_tool(monkeypatch, b"plain")
|
||||
make_drm(tool).decrypt(track)
|
||||
assert track.read_bytes() == b"plain"
|
||||
assert not track.with_name("track_decrypted.mp4").exists()
|
||||
@@ -0,0 +1,22 @@
|
||||
import pytest
|
||||
|
||||
from unshackle.core.music.renderer import MusicRenderer
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("label", "hires"),
|
||||
[
|
||||
("FLAC 24-bit/96kHz", True),
|
||||
("24-bit / 96 kHz", True),
|
||||
("FLAC 16-bit/88.2kHz", True),
|
||||
("96k", True),
|
||||
("FLAC 16-bit/44.1kHz", False),
|
||||
("Lossless", False),
|
||||
("256 kb/s AAC", False),
|
||||
("MP3 320 kb/s", False),
|
||||
("320kbps", False),
|
||||
("AAC 96 kbit/s", False),
|
||||
],
|
||||
)
|
||||
def test_is_hires_quality_reads_sample_rate_not_bitrate(label: str, hires: bool) -> None:
|
||||
assert MusicRenderer.is_hires_quality(label) is hires
|
||||
@@ -265,7 +265,10 @@ def test_retry_takes_the_next_parallel_answer_without_a_new_request(tmp_path: Pa
|
||||
assert fast.calls == 1 and slow.calls == 1
|
||||
|
||||
|
||||
def test_cdm_returning_the_flagged_key_clears_the_flag(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
@pytest.mark.parametrize("replace", [False, True])
|
||||
def test_cdm_returning_the_flagged_key_clears_the_flag(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, replace: bool
|
||||
) -> None:
|
||||
"""A decode failure on a key the CDM then confirms is a false positive: unflag, keep the file."""
|
||||
local = SQLite("local", tmp_path / "local.db")
|
||||
poisoned = Remote("poisoned", tmp_path / "poisoned.db")
|
||||
@@ -280,13 +283,67 @@ def test_cdm_returning_the_flagged_key_clears_the_flag(tmp_path: Path, monkeypat
|
||||
|
||||
def licence(drm: FakeDRM, track_kid: UUID) -> None:
|
||||
assert vaults.get_key(KID) == (None, None)
|
||||
drm.content_keys[KID] = BAD # the CDM answers with the same key
|
||||
if replace:
|
||||
drm.content_keys = {KID: BAD} # a CDM licence builds a new dict
|
||||
else:
|
||||
drm.content_keys[KID] = BAD # the CDM answers with the same key
|
||||
|
||||
cmd.decrypt_verified(drm, path, licence, KID)
|
||||
assert path.read_bytes() == b"plain:" + BAD.encode()
|
||||
assert not local.is_bad_key(KID, BAD)
|
||||
|
||||
|
||||
def test_a_replacement_key_in_a_new_dict_is_checked_and_stored(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
local = SQLite("local", tmp_path / "local.db")
|
||||
poisoned = Remote("poisoned", tmp_path / "poisoned.db")
|
||||
poisoned.add_key("SVC", KID, BAD)
|
||||
vaults = Vaults("SVC")
|
||||
vaults.vaults = [local, poisoned]
|
||||
assert vaults.get_key(KID) == (BAD, poisoned)
|
||||
cmd = make_cmd(monkeypatch, vaults)
|
||||
path = tmp_path / "video.mp4"
|
||||
path.write_bytes(b"cipher")
|
||||
drm = FakeDRM({KID: BAD})
|
||||
other = Remote("other", tmp_path / "other.db")
|
||||
other.add_key("SVC", KID, GOOD)
|
||||
|
||||
def licence(drm: FakeDRM, track_kid: UUID) -> None:
|
||||
vaults.vaults.append(other)
|
||||
drm.content_keys = {KID: vaults.get_key(KID)[0]}
|
||||
|
||||
cmd.decrypt_verified(drm, path, licence, KID)
|
||||
cmd.wait_vault_writes()
|
||||
assert path.read_bytes() == b"plain:" + GOOD.encode()
|
||||
assert local.get_key(KID, "SVC") == GOOD
|
||||
|
||||
|
||||
@pytest.mark.parametrize("replace", [True, False])
|
||||
def test_a_cdm_that_confirms_a_key_flagged_on_entry_clears_the_flag(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, replace: bool
|
||||
) -> None:
|
||||
"""Another track flagged the pair, then this track's CDM licence answers with the same key."""
|
||||
local = SQLite("local", tmp_path / "local.db")
|
||||
vaults = Vaults("SVC")
|
||||
vaults.vaults = [local]
|
||||
cmd = make_cmd(monkeypatch, vaults)
|
||||
vaults.flag_bad_key(KID, BAD)
|
||||
path = tmp_path / "video.mp4"
|
||||
path.write_bytes(b"cipher")
|
||||
drm = FakeDRM({KID: BAD})
|
||||
|
||||
def licence(drm: FakeDRM, track_kid: UUID) -> None:
|
||||
if replace:
|
||||
drm.content_keys = {KID: BAD}
|
||||
else:
|
||||
drm.content_keys[KID] = BAD
|
||||
|
||||
cmd.decrypt_verified(drm, path, licence, KID)
|
||||
cmd.wait_vault_writes()
|
||||
assert path.read_bytes() == b"plain:" + BAD.encode()
|
||||
assert not local.is_bad_key(KID, BAD)
|
||||
assert local.get_key(KID, "SVC") == BAD
|
||||
|
||||
|
||||
def test_a_licence_key_that_replaces_a_bad_local_pair_is_stored(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
|
||||
@@ -4,10 +4,12 @@ import asyncio
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
import click
|
||||
import pytest
|
||||
|
||||
from unshackle.core.api import download_manager as dm
|
||||
from unshackle.core.api import handlers
|
||||
from unshackle.core.api.errors import APIError, APIErrorCode
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
@@ -106,8 +108,6 @@ def test_client_sent_keys_without_stamp_counts_all_keys():
|
||||
|
||||
|
||||
def test_service_defaults_and_options_travel_nested(env, monkeypatch):
|
||||
import click
|
||||
|
||||
@click.command()
|
||||
@click.option("--profile", type=int, default=1)
|
||||
@click.option("--device", default="chrome")
|
||||
@@ -119,3 +119,40 @@ def test_service_defaults_and_options_travel_nested(env, monkeypatch):
|
||||
assert params["profile"] == "work"
|
||||
assert params["service_params"] == {"profile": 2, "device": "chrome"}
|
||||
assert env(body={"device": "tv"})["service_params"] == {"profile": 1, "device": "tv"}
|
||||
|
||||
|
||||
def use_cli(monkeypatch, *options):
|
||||
"""Make the loaded service declare ``options`` on its cli."""
|
||||
cli = click.Command("svc", params=list(options))
|
||||
monkeypatch.setattr(handlers.Services, "load", lambda service: SimpleNamespace(cli=cli))
|
||||
|
||||
|
||||
def test_a_service_option_its_type_refuses_is_a_400(env, monkeypatch):
|
||||
use_cli(monkeypatch, click.Option(["--episodes"], type=click.IntRange(1, 3), default=1))
|
||||
with pytest.raises(APIError) as exc_info:
|
||||
env(body={"service_params": {"episodes": 9}})
|
||||
assert exc_info.value.error_code == APIErrorCode.INVALID_PARAMETERS
|
||||
assert "episodes" in exc_info.value.message
|
||||
assert env(body={"service_params": {"episodes": "2"}})["service_params"]["episodes"] == "2"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("name", "value"),
|
||||
[("episodes", {"a": 1}), ("episodes", [1]), ("movie", 2), ("movie", [1]), ("device", {"a": 1}), ("device", [1])],
|
||||
)
|
||||
def test_a_json_shape_click_cannot_convert_is_a_400(env, monkeypatch, name, value):
|
||||
use_cli(
|
||||
monkeypatch,
|
||||
click.Option(["--episodes"], type=int),
|
||||
click.Option(["--movie"], is_flag=True),
|
||||
click.Option(["--device"]),
|
||||
)
|
||||
with pytest.raises(APIError) as exc_info:
|
||||
env(body={"service_params": {name: value}})
|
||||
assert exc_info.value.error_code == APIErrorCode.INVALID_PARAMETERS
|
||||
assert name in exc_info.value.message
|
||||
|
||||
|
||||
def test_a_flat_dl_key_never_fills_a_service_option_of_the_same_name(env, monkeypatch):
|
||||
use_cli(monkeypatch, click.Option(["--quality"], type=click.Choice(["SD", "HD"]), default="HD"))
|
||||
assert env(body={"quality": [1080]})["service_params"] == {"quality": "HD"}
|
||||
|
||||
@@ -268,6 +268,40 @@ def test_perform_download_passes_latest_episodes_to_dl_result(tmp_path: Path, mo
|
||||
assert exc.value.args[0]["latest_episodes"] == 3
|
||||
|
||||
|
||||
def test_perform_download_casts_service_options(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
import click
|
||||
|
||||
import unshackle.commands.dl as dl_module
|
||||
from unshackle.core.api import download_manager, handlers
|
||||
from unshackle.core.services import Services
|
||||
|
||||
class FakeDl:
|
||||
cli = click.Command("dl")
|
||||
|
||||
def __init__(self, ctx: click.Context, **kwargs: object) -> None:
|
||||
pass
|
||||
|
||||
class FakeService:
|
||||
cli = click.Command(
|
||||
"svc", params=[click.Option(["--episodes"], type=int), click.Option(["--tag"], multiple=True)]
|
||||
)
|
||||
|
||||
def __init__(self, ctx: click.Context, episodes: object = None, tag: object = ()) -> None:
|
||||
raise _CapturedCtx(episodes, tag)
|
||||
|
||||
monkeypatch.setattr(dl_module, "dl", FakeDl)
|
||||
monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path))
|
||||
monkeypatch.setattr(Services, "load", staticmethod(lambda s: FakeService))
|
||||
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
|
||||
|
||||
with pytest.raises(_CapturedCtx) as exc:
|
||||
download_manager.perform_download(
|
||||
"job-1", "EXAMPLE", "t1", {"service_params": {"episodes": "2", "tag": ["a", "b"]}}
|
||||
)
|
||||
|
||||
assert exc.value.args == (2, ("a", "b"))
|
||||
|
||||
|
||||
def test_worker_relays_a_prompt_and_reads_the_answer(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
import json
|
||||
import os
|
||||
|
||||
@@ -63,6 +63,11 @@ def test_region_match_no_proxy(monkeypatch):
|
||||
assert handlers.resolve_handler_proxy({"client_region": "ca"}, "EXAMPLE", request("plainkey")) == (None, [])
|
||||
|
||||
|
||||
def test_relayed_tag_not_installed_here_skips_the_local_geoblock(monkeypatch):
|
||||
patch_server_region(monkeypatch, "CA")
|
||||
assert handlers.resolve_handler_proxy({"client_region": "ca"}, "NOTHERE", request("plainkey")) == (None, [])
|
||||
|
||||
|
||||
def test_region_unknown_no_error(monkeypatch):
|
||||
patch_server_region(monkeypatch, None)
|
||||
assert handlers.resolve_handler_proxy({"client_region": "ca"}, "EXAMPLE", request("plainkey")) == (None, [])
|
||||
@@ -246,6 +251,13 @@ class TestDownloadGates:
|
||||
handlers.enforce_download_gates({"service": "EXAMPLE", "client_region": "gb"}, request("plainkey"))
|
||||
assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY
|
||||
|
||||
def test_download_proxy_on_local_network_refused(self):
|
||||
with pytest.raises(APIError) as exc_info:
|
||||
handlers.enforce_download_gates(
|
||||
{"service": "EXAMPLE", "proxy_download": "http://127.0.0.1:9"}, request("plainkey")
|
||||
)
|
||||
assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY
|
||||
|
||||
|
||||
class TestDownloadEnforcement:
|
||||
"""The server_proxy stamp survives from submission to the dl construction."""
|
||||
@@ -349,3 +361,57 @@ def test_session_create_builds_service_off_the_event_loop(monkeypatch):
|
||||
assert seen["thread"] != threading.get_ident()
|
||||
assert [r["message"] for r in seen["buffer"].since(0)] == ["checking proxy"]
|
||||
assert json.loads(response.body)["error_code"] == "INVALID_PROXY"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"proxy",
|
||||
[
|
||||
"http://127.0.0.1:8080",
|
||||
"http://localhost:3128",
|
||||
"socks5://user:pass@10.0.0.5:1080",
|
||||
"https://[::1]:8443",
|
||||
"http://169.254.169.254",
|
||||
"socks5h://192.168.1.1:1080",
|
||||
"http://198.18.0.1:8080",
|
||||
"http://[2002:7f00:1::]:8080",
|
||||
"http://foo.localhost:8080",
|
||||
"http://127.0.0.1:8080\\@example.com",
|
||||
"http://%31%32%37.0.0.1:8080",
|
||||
],
|
||||
)
|
||||
def test_local_proxy_uri_refused_without_server_proxy(proxy):
|
||||
with pytest.raises(APIError) as exc_info:
|
||||
handlers.resolve_handler_proxy({"proxy": proxy}, "EXAMPLE", request("plainkey"))
|
||||
assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY
|
||||
assert "pass" not in exc_info.value.message # credentials never echo back
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", ["proxykey", "adminkey"]) # adminkey has no serve.users entry
|
||||
def test_local_proxy_uri_allowed_with_server_proxy_or_admin(monkeypatch, key):
|
||||
monkeypatch.setattr(handlers, "initialize_proxy_providers", lambda: [])
|
||||
proxy, _ = handlers.resolve_handler_proxy({"proxy": "http://127.0.0.1:8080"}, "EXAMPLE", request(key))
|
||||
assert proxy == "http://127.0.0.1:8080"
|
||||
|
||||
|
||||
def test_hostname_resolving_to_a_private_address_refused(monkeypatch):
|
||||
monkeypatch.setattr(handlers.socket, "getaddrinfo", lambda host, port: [(2, 1, 6, "", ("10.0.0.7", 0))])
|
||||
with pytest.raises(APIError) as exc_info:
|
||||
handlers.resolve_handler_proxy({"proxy": "http://proxy.lan:3128"}, "EXAMPLE", request("plainkey"))
|
||||
assert exc_info.value.error_code == APIErrorCode.INVALID_PROXY
|
||||
|
||||
|
||||
def test_local_proxy_uri_ignored_under_no_proxy():
|
||||
handlers.resolve_handler_proxy({"proxy": "http://127.0.0.1:8080", "no_proxy": True}, "EXAMPLE", request("plainkey"))
|
||||
|
||||
|
||||
def test_server_built_loopback_proxies_pass_without_server_proxy(monkeypatch):
|
||||
"""The check reads the client's value, so the loopback URIs the server builds for tunnel: and controld:// pass."""
|
||||
monkeypatch.setattr(handlers, "tunnel_proxy", lambda tunnel_id, key: "http://u:p@127.0.0.1:5000")
|
||||
proxy, _ = handlers.resolve_handler_proxy({"proxy": "tunnel:abc"}, "EXAMPLE", request("plainkey"))
|
||||
assert proxy == "http://u:p@127.0.0.1:5000"
|
||||
|
||||
monkeypatch.setattr(handlers, "resolve_proxy", lambda proxy, providers: "http://127.0.0.1:5001")
|
||||
proxy, _ = handlers.resolve_handler_proxy(
|
||||
{"proxy": "controld://abc@dns.controld.com"}, "EXAMPLE", request("plainkey")
|
||||
)
|
||||
assert proxy == "http://127.0.0.1:5001"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import asyncio
|
||||
import json
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -43,8 +44,8 @@ def pool(monkeypatch):
|
||||
return logins
|
||||
|
||||
|
||||
def lease(data, **extra):
|
||||
return handlers.lease_remote_service({**data, **extra}, "srv", INFO, None, "show")
|
||||
def lease(data, request=None, **extra):
|
||||
return handlers.lease_remote_service({**data, **extra}, "srv", INFO, None, "show", request)
|
||||
|
||||
|
||||
DATA = {"service": "EXAMPLE", "title_id": "show", "remote": "srv"}
|
||||
@@ -81,6 +82,25 @@ async def test_only_options_that_reach_the_remote_split_the_pool(pool):
|
||||
assert a.service is c.service
|
||||
|
||||
|
||||
def keyed(key):
|
||||
return SimpleNamespace(headers={"X-Secret-Key": key})
|
||||
|
||||
|
||||
async def test_each_api_key_gets_its_own_pooled_session(pool):
|
||||
a = await lease(DATA, keyed("a"), proxy="us")
|
||||
again = await lease(DATA, keyed("a"), proxy="us")
|
||||
b = await lease(DATA, keyed("b"), proxy="us")
|
||||
assert a.service is again.service
|
||||
assert b.service is not a.service
|
||||
assert pool == ["show", "show"]
|
||||
|
||||
|
||||
async def test_client_region_splits_the_pool(pool):
|
||||
us = await lease(DATA, client_region="us")
|
||||
gb = await lease(DATA, client_region="gb")
|
||||
assert us.service is not gb.service
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def remote_config(monkeypatch):
|
||||
monkeypatch.setattr(config, "remote_services", {"srv": {"url": "https://srv", "api_key": "k"}})
|
||||
|
||||
@@ -675,3 +675,31 @@ def test_a_service_profile_option_travels_nested_and_keeps_the_credential_profil
|
||||
|
||||
def test_no_dl_params_when_the_ctx_has_no_selection() -> None:
|
||||
assert "dl_params" not in _sent_create_data({}, {})
|
||||
|
||||
|
||||
def test_resolve_manifest_data_keeps_the_periods_the_server_filtered() -> None:
|
||||
"""A service drops periods (a mid-roll ad) on the server only. The client must skip the
|
||||
same periods after it re-parses the manifest, or a remote download joins them back in."""
|
||||
from unshackle.core.api.handlers import extract_manifests
|
||||
from unshackle.core.manifests import DASH
|
||||
from unshackle.core.remote_service import resolve_manifest_data
|
||||
|
||||
periods = "".join(
|
||||
f"""<Period id="{pid}" duration="PT1S"><AdaptationSet contentType="video" mimeType="video/mp4" lang="en">
|
||||
<Representation id="v0" codecs="avc1.640028" bandwidth="1000000" width="1920" height="1080">
|
||||
<SegmentTemplate timescale="1" duration="1" startNumber="1" initialization="{pid}/i.mp4"
|
||||
media="{pid}/$Number$.m4s"/></Representation></AdaptationSet></Period>"""
|
||||
for pid in ("main1", "ad1", "main2")
|
||||
)
|
||||
mpd = f"""<?xml version="1.0"?><MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="static"
|
||||
mediaPresentationDuration="PT3S"><BaseURL>https://x/</BaseURL>{periods}</MPD>"""
|
||||
server = DASH.from_text(mpd, url="https://x/manifest.mpd").to_tracks(language="en")
|
||||
for track in server:
|
||||
track.data["dash"]["filtered_period_ids"] = ["ad1"]
|
||||
|
||||
remote = deserialize_video(serialize_video_track(server.videos[0]))
|
||||
tracks = build_tracks({"video": [], "audio": [], "subtitles": []})
|
||||
tracks.videos.append(remote)
|
||||
resolve_manifest_data(tracks, extract_manifests(server))
|
||||
|
||||
assert remote.data["dash"]["filtered_period_ids"] == ["ad1"]
|
||||
|
||||
@@ -351,6 +351,24 @@ def test_segmented_fvtt_parses_and_converts(tmp_path, monkeypatch):
|
||||
assert cue_count(out) == 2
|
||||
|
||||
|
||||
def with_mdhd_timescale(data: bytes, timescale: int) -> bytes:
|
||||
"""The fixture with its version-0 mdhd timescale replaced; sample times stay in the same units."""
|
||||
at = data.index(b"mdhd") + 16
|
||||
return data[:at] + struct.pack(">I", timescale) + data[at + 4 :]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("timescale", [1000, 2000, 90000])
|
||||
def test_segmented_fvtt_cue_times_follow_the_media_timescale(timescale):
|
||||
data = (FIXTURES / "segmented.wvtt.mp4").read_bytes()
|
||||
assert with_mdhd_timescale(data, 1000) == data # the helper's offset hits the fixture's timescale
|
||||
|
||||
captions, _ = Subtitle.merge_segmented_wvtt(with_mdhd_timescale(data, timescale))
|
||||
|
||||
# the fixture's cues span 1000-2000 and 3000-4000 media units
|
||||
times = [t for c in captions for t in (c.start, c.end)]
|
||||
assert times == pytest.approx([t * 1_000_000 / timescale for t in (1000, 2000, 3000, 4000)])
|
||||
|
||||
|
||||
def test_segmented_fttml_joins_a_cue_split_at_a_segment_boundary():
|
||||
data = build_stpp_mp4(
|
||||
ttml_fragment(("00:00:01.000", "00:00:02.000", "Carried")),
|
||||
@@ -449,17 +467,25 @@ def test_dash_fttml_cues_lose_the_presentation_time_offset(tmp_path, monkeypatch
|
||||
assert (caption.start, caption.end) == times
|
||||
|
||||
|
||||
def test_dash_fvtt_cues_lose_the_presentation_time_offset(tmp_path, monkeypatch):
|
||||
template = '<SegmentTemplate timescale="1000" presentationTimeOffset="1000" duration="2000"/>'
|
||||
data = (FIXTURES / "segmented.wvtt.mp4").read_bytes()
|
||||
@pytest.mark.parametrize("method", ["subby", "pycaption"])
|
||||
@pytest.mark.parametrize(
|
||||
"mdhd_timescale, pto, cues",
|
||||
[
|
||||
(1000, 1000, ("00:00:00.000 --> 00:00:01.000", "00:00:02.000 --> 00:00:03.000")),
|
||||
(2000, 500, ("00:00:00.000 --> 00:00:00.500", "00:00:01.000 --> 00:00:01.500")),
|
||||
],
|
||||
)
|
||||
def test_dash_fvtt_cues_lose_the_presentation_time_offset(tmp_path, monkeypatch, method, mdhd_timescale, pto, cues):
|
||||
template = f'<SegmentTemplate timescale="1000" presentationTimeOffset="{pto}" duration="2000"/>'
|
||||
data = with_mdhd_timescale((FIXTURES / "segmented.wvtt.mp4").read_bytes(), mdhd_timescale)
|
||||
sub = dash_subtitle(tmp_path, monkeypatch, Codec.fVTT, data, template)
|
||||
monkeypatch.setattr("unshackle.core.config.config.subtitle", {"conversion_method": method}, raising=False)
|
||||
|
||||
sub.download(None, None) # type: ignore[arg-type]
|
||||
|
||||
assert sub.codec == Codec.WebVTT
|
||||
text = sub.path.read_text("utf8")
|
||||
assert "00:00:00.000 --> 00:00:01.000" in text
|
||||
assert "00:00:02.000 --> 00:00:03.000" in text
|
||||
assert all(cue in text for cue in cues)
|
||||
|
||||
|
||||
def ttml_fragment(*cues: tuple[str, ...]) -> str:
|
||||
|
||||
+24
-23
@@ -4506,7 +4506,7 @@ class dl:
|
||||
With ``decrypt=False`` the downloader already decrypted the segments in place, so a
|
||||
failure can only flag and raise; the next run skips the flagged pair.
|
||||
"""
|
||||
keys = getattr(drm, "content_keys", None)
|
||||
keys: Any = getattr(drm, "content_keys", None)
|
||||
if keys is None:
|
||||
if decrypt:
|
||||
drm.decrypt(path)
|
||||
@@ -4522,25 +4522,39 @@ class dl:
|
||||
self.LICENSE_KEY_CACHE.pop(kid)
|
||||
return key
|
||||
|
||||
def relicense(dropped: set[UUID]) -> None:
|
||||
"""Licence again, then ask for each dropped KID that is still without a content key.
|
||||
def relicense(bad: dict[UUID, str], kids: dict[UUID, Vault]) -> None:
|
||||
"""Licence again for each dropped KID, then settle each dropped pair against the new key.
|
||||
|
||||
prepare_drm licenses only for a KID it is told to need, so without the second call a
|
||||
track that still holds other content keys would decrypt without the dropped one.
|
||||
track that still holds other content keys would decrypt without the dropped one. A
|
||||
licence can replace the DRM's dict, so ``keys`` is read from the DRM again afterwards.
|
||||
A licence key equal to the dropped one proves the decode check wrong and clears its flag.
|
||||
"""
|
||||
nonlocal keys
|
||||
if not licence:
|
||||
return
|
||||
licence(drm, track_kid=track_kid)
|
||||
for kid in sorted(dropped):
|
||||
# prepare_drm can replace the dict, so read it from the DRM each time
|
||||
for kid in sorted(bad):
|
||||
if kid != track_kid and kid not in getattr(drm, "content_keys", {}):
|
||||
licence(drm, track_kid=kid)
|
||||
keys = getattr(drm, "content_keys", keys)
|
||||
for kid, key in bad.items():
|
||||
new = keys.get(kid)
|
||||
if new is None:
|
||||
continue
|
||||
source = self.vaults.sources.get(kid)
|
||||
if source is None:
|
||||
if new == key:
|
||||
self.vaults.unflag_bad_key(kid, key)
|
||||
self.flush_vault_writes([partial(self.vaults.add_key, kid, key)])
|
||||
elif not self.vaults.held_locally(kid, new):
|
||||
self.flush_vault_writes([partial(self.vaults.add_key, kid, new)])
|
||||
elif new == key and kid in kids and source[1] is kids[kid]:
|
||||
raise ValueError(f"{key} from {kids[kid].name} was bad and no other source has the key")
|
||||
|
||||
known_bad = flagged_kids()
|
||||
if known_bad and licence:
|
||||
for kid in known_bad:
|
||||
drop(kid)
|
||||
relicense(set(known_bad))
|
||||
relicense({kid: drop(kid) for kid in known_bad}, {})
|
||||
|
||||
def vault_kids() -> dict[UUID, Vault]:
|
||||
"""The KIDs whose key on the track came from a vault, with that vault."""
|
||||
@@ -4625,20 +4639,7 @@ class dl:
|
||||
raise ValueError("The content key from the vault did not decrypt the track; run again")
|
||||
path.unlink()
|
||||
os.link(backup, path)
|
||||
relicense(set(bad))
|
||||
for kid, key in bad.items():
|
||||
new = keys.get(kid)
|
||||
if new is None:
|
||||
continue
|
||||
source = self.vaults.sources.get(kid)
|
||||
if source is None:
|
||||
if new == key:
|
||||
self.vaults.unflag_bad_key(kid, key)
|
||||
self.flush_vault_writes([partial(self.vaults.add_key, kid, key)])
|
||||
elif not self.vaults.held_locally(kid, new):
|
||||
self.flush_vault_writes([partial(self.vaults.add_key, kid, new)])
|
||||
elif new == key and kid in kids and source[1] is kids[kid]:
|
||||
raise ValueError(f"{key} from {kids[kid].name} was bad and no other source has the key")
|
||||
relicense(bad, kids)
|
||||
raise ValueError("No vault or CDM produced a content key that decrypts the track")
|
||||
finally:
|
||||
backup.unlink(missing_ok=True)
|
||||
|
||||
@@ -21,7 +21,7 @@ from unshackle.core.api.events import bus, publish_service_event
|
||||
from unshackle.core.api.sanitize import sanitize_log
|
||||
from unshackle.core.utils.click_types import AUDIO_CODEC_LIST, QUALITY_LIST, VIDEO_CODEC_LIST
|
||||
from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_all, redact_path, redact_text
|
||||
from unshackle.core.utils.service_params import service_options
|
||||
from unshackle.core.utils.service_params import cast_service_options, service_options
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from unshackle.core.service import Service
|
||||
@@ -579,7 +579,9 @@ def perform_download(
|
||||
if "title" in service_init_params:
|
||||
service_kwargs["title"] = title_id
|
||||
|
||||
service_kwargs.update(service_options(params, service_init_params.keys() - {"title"}))
|
||||
cli_params = getattr(getattr(service_module, "cli", None), "params", None) or []
|
||||
options = service_options(params, service_init_params.keys() - {"title"})
|
||||
service_kwargs.update(cast_service_options(cli_params, service_ctx, options))
|
||||
|
||||
for param_name, param_info in service_init_params.items():
|
||||
if param_name not in service_kwargs and param_name not in ["self", "ctx"]:
|
||||
|
||||
@@ -4,6 +4,7 @@ import enum
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
@@ -16,6 +17,7 @@ from functools import partial
|
||||
from http.cookiejar import CookieJar
|
||||
from pathlib import Path
|
||||
from typing import AbstractSet, Any, Callable, Dict, Iterable, List, Optional, Set, cast
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import click
|
||||
from aiohttp import web
|
||||
@@ -32,20 +34,29 @@ from unshackle.core.config import config, load_yaml
|
||||
from unshackle.core.constants import AUDIO_CODEC_MAP, DYNAMIC_RANGE_MAP, VIDEO_CODEC_MAP, AnyTrack
|
||||
from unshackle.core.drm import BlowfishStripe, cbcs
|
||||
from unshackle.core.providers.anilist import parse_anilist_ref
|
||||
from unshackle.core.proxies.resolve import initialize_proxy_providers, resolve_proxy
|
||||
from unshackle.core.proxies.resolve import initialize_proxy_providers, is_loopback, resolve_proxy
|
||||
from unshackle.core.services import Services
|
||||
from unshackle.core.session import RnetSession, utf8_text
|
||||
from unshackle.core.titles import Episode, Movie, Song, Title_T
|
||||
from unshackle.core.titles.music import SONG_FIELDS
|
||||
from unshackle.core.titles.title import rename
|
||||
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
|
||||
from unshackle.core.tunnel import HEARTBEAT, MAX_MESSAGE, MAX_TUNNELS, TUNNELS, Tunnel, tunnel_proxy
|
||||
from unshackle.core.tunnel import (
|
||||
HEARTBEAT,
|
||||
MAX_MESSAGE,
|
||||
MAX_TUNNELS,
|
||||
TUNNELS,
|
||||
Tunnel,
|
||||
is_ip_literal,
|
||||
is_public_ip,
|
||||
tunnel_proxy,
|
||||
)
|
||||
from unshackle.core.utilities import declared_kwargs, kind_only_conflict, original_tag
|
||||
from unshackle.core.utils.click_types import AUDIO_CODEC_LIST, QUALITY_LIST, SUBTITLE_CODEC, VIDEO_CODEC_LIST
|
||||
from unshackle.core.utils.collections import ci_get
|
||||
from unshackle.core.utils.hdr10plus import probed_tracks
|
||||
from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_all, redact_secrets, redact_text
|
||||
from unshackle.core.utils.service_params import service_options
|
||||
from unshackle.core.utils.service_params import FLAT_DL_KEYS, cast_service_options, service_options
|
||||
|
||||
log = logging.getLogger("api")
|
||||
|
||||
@@ -242,6 +253,17 @@ def build_parent_ctx(
|
||||
return parent
|
||||
|
||||
|
||||
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)
|
||||
except click.BadParameter as e:
|
||||
name = e.param.name if e.param and e.param.name else "?"
|
||||
raise APIError(
|
||||
APIErrorCode.INVALID_PARAMETERS, f"Invalid service option '{sanitize_log(name)}': {sanitize_log(e.message)}"
|
||||
) from e
|
||||
|
||||
|
||||
def instantiate_service(
|
||||
parent_ctx: Any,
|
||||
service_module: Any,
|
||||
@@ -255,22 +277,13 @@ def instantiate_service(
|
||||
goes through its option's type here: JSON or a remote client's str-typed stub can send "1" for an int.
|
||||
"""
|
||||
cli_params = getattr(getattr(service_module, "cli", None), "params", []) or []
|
||||
params_by_name = {p.name: p for p in cli_params if getattr(p, "name", None) and p.name != "title"}
|
||||
extras: Dict[str, Any] = {}
|
||||
if data:
|
||||
for k, v in service_options(data, params_by_name, transport_keys).items():
|
||||
try:
|
||||
extras[k] = params_by_name[k].type_cast_value(parent_ctx, v)
|
||||
except click.BadParameter as e:
|
||||
raise APIError(
|
||||
APIErrorCode.INVALID_PARAMETERS, f"Invalid service option '{sanitize_log(k)}': {e.message}"
|
||||
) from e
|
||||
if data.get("service_params") is None:
|
||||
for k in params_by_name.keys() & transport_keys & data.keys():
|
||||
if k not in ("service", "title_id", "proxy", "no_proxy") and data.get(k) is not None:
|
||||
log.warning(
|
||||
f"Ignoring flat '{sanitize_log(k)}' as a service option, send it under 'service_params'"
|
||||
)
|
||||
names = {p.name for p in cli_params if getattr(p, "name", None) and p.name != "title"}
|
||||
data = data or {}
|
||||
extras = cast_or_refuse(cli_params, parent_ctx, service_options(data, names, transport_keys))
|
||||
if data and data.get("service_params") is None:
|
||||
for k in names & transport_keys & data.keys():
|
||||
if k not in ("service", "title_id", "proxy", "no_proxy") and data.get(k) is not None:
|
||||
log.warning(f"Ignoring flat '{sanitize_log(k)}' as a service option, send it under 'service_params'")
|
||||
return parent_ctx.invoke(service_module.cli, title=title, **extras)
|
||||
|
||||
|
||||
@@ -587,7 +600,7 @@ class RemoteLease:
|
||||
Only the event loop touches the pool, so it needs no thread lock; blocking work runs in threads.
|
||||
"""
|
||||
|
||||
key: tuple
|
||||
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
|
||||
@@ -600,12 +613,24 @@ _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) -> tuple:
|
||||
"""What opens a remote session; requests that differ only in episode selection share one."""
|
||||
def remote_pool_key(
|
||||
data: Dict[str, Any], server: str, info: dict, profile: Optional[str], title_id: str, request: Optional[web.Request]
|
||||
) -> 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
|
||||
|
||||
options = json.dumps(remote_service_params(info, data), sort_keys=True, default=str)
|
||||
return (server, data["service"], title_id, profile, data.get("proxy"), bool(data.get("no_proxy")), options)
|
||||
return (
|
||||
caller_key(request),
|
||||
server,
|
||||
data["service"],
|
||||
title_id,
|
||||
profile,
|
||||
data.get("proxy"),
|
||||
data.get("client_region"),
|
||||
bool(data.get("no_proxy")),
|
||||
options,
|
||||
)
|
||||
|
||||
|
||||
def close_remote_services(services: List[Any]) -> None:
|
||||
@@ -661,7 +686,7 @@ async def lease_remote_service(
|
||||
global _remote_sweeper
|
||||
if _remote_sweeper is None or _remote_sweeper.done():
|
||||
_remote_sweeper = asyncio.get_running_loop().create_task(sweep_remote_pool())
|
||||
key = remote_pool_key(data, server, info, profile, title_id)
|
||||
key = remote_pool_key(data, server, info, profile, title_id, request)
|
||||
lease = _remote_pool.setdefault(key, RemoteLease(key))
|
||||
lease.busy += 1
|
||||
try:
|
||||
@@ -1543,6 +1568,7 @@ def extract_manifests(tracks: Tracks) -> List[Dict[str, Any]]:
|
||||
"type": "dash",
|
||||
"url": manifest_url,
|
||||
"data": base64.b64encode(compressed).decode("ascii"),
|
||||
"filtered_period_ids": list(track.data["dash"].get("filtered_period_ids") or []),
|
||||
}
|
||||
)
|
||||
elif track.data.get("ism") and track.data["ism"].get("manifest") is not None:
|
||||
@@ -2467,7 +2493,12 @@ async def download_handler(data: Dict[str, Any], request: Optional[web.Request]
|
||||
for param in cli_params
|
||||
if param.name and param.default is not None and not isinstance(param.default, enum.Enum)
|
||||
}
|
||||
service_params = {**defaults, **service_options(data, {param.name for param in cli_params})}
|
||||
# A flat dl key (quality, lang) stays a dl value, as in instantiate_service.
|
||||
sent = service_options(
|
||||
data, {param.name for param in cli_params}, FLAT_DL_KEYS | DEFAULT_DOWNLOAD_PARAMS.keys()
|
||||
)
|
||||
cast_or_refuse(cli_params, click.Context(click.Command(normalized_service)), sent)
|
||||
service_params = {**defaults, **sent}
|
||||
|
||||
filtered_params = {k: v for k, v in data.items() if k not in ["service", "title_id"]}
|
||||
# Overlay any dl-relevant keys from `serve:` config (e.g. downloads, workers) so the API
|
||||
@@ -4551,6 +4582,33 @@ async def get_validated_session(session_id: str, request: Optional[web.Request])
|
||||
return session
|
||||
|
||||
|
||||
def local_proxy_refusal(proxy: str) -> Optional[str]:
|
||||
"""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
|
||||
reads a backslash or a percent-escape in the authority differently from ``urlsplit``.
|
||||
"""
|
||||
if not re.match(r"^(https?://|socks)", proxy):
|
||||
return None
|
||||
try:
|
||||
host = urlsplit(proxy).hostname or ""
|
||||
except ValueError:
|
||||
host = ""
|
||||
literal = is_ip_literal(host)
|
||||
if "\\" in proxy or not (literal or re.fullmatch(r"[a-z0-9._-]+", host)):
|
||||
return "Proxy URI has no plain host name or IP address"
|
||||
if literal or is_loopback(proxy):
|
||||
addresses = {host}
|
||||
else:
|
||||
try:
|
||||
addresses = {str(info[4][0]) for info in socket.getaddrinfo(host, None)}
|
||||
except (socket.gaierror, UnicodeError):
|
||||
return None # an unresolvable proxy fails at connect time anyway
|
||||
if not all(is_public_ip(address) for address in addresses):
|
||||
return f"Proxy host {sanitize_log(host)} is not a public address"
|
||||
return None
|
||||
|
||||
|
||||
def resolve_handler_proxy(
|
||||
data: Dict[str, Any], normalized_service: str, request: Optional[web.Request] = None
|
||||
) -> tuple[Optional[str], list]:
|
||||
@@ -4582,6 +4640,11 @@ def resolve_handler_proxy(
|
||||
details={"service": normalized_service},
|
||||
)
|
||||
|
||||
if isinstance(proxy_param, str) and not no_proxy and not (allowed or is_admin(request)):
|
||||
refusal = local_proxy_refusal(proxy_param)
|
||||
if refusal:
|
||||
raise APIError(APIErrorCode.INVALID_PROXY, refusal, details={"service": normalized_service})
|
||||
|
||||
if isinstance(proxy_param, str) and proxy_param.startswith("tunnel:") and not no_proxy:
|
||||
proxy_param = tunnel_proxy(
|
||||
proxy_param.removeprefix("tunnel:"), request_secret_key(request) if request else None
|
||||
@@ -4630,7 +4693,9 @@ def resolve_handler_proxy(
|
||||
log.debug(f"Server region lookup failed: {e!r}")
|
||||
server_region = None
|
||||
|
||||
geoblock = getattr(Services.load(normalized_service), "GEOBLOCK", ()) or ()
|
||||
geoblock: Any = ()
|
||||
with suppress(KeyError): # a relayed tag need not be installed on this server
|
||||
geoblock = getattr(Services.load(normalized_service), "GEOBLOCK", ()) or ()
|
||||
if client_region.lower() in {x.lower() for x in geoblock}:
|
||||
raise APIError(
|
||||
APIErrorCode.GEOFENCE,
|
||||
|
||||
@@ -537,7 +537,7 @@ async def search(request: web.Request) -> web.Response:
|
||||
description: Profile to use for credentials and cookies (default - None)
|
||||
proxy:
|
||||
type: string
|
||||
description: Full proxy URI, a Control D resolver as controld://<resolver>@dns.controld.com, or a country code when the API key has server_proxy, or tunnel:<id> for a tunnel the same API key opened on /api/tunnel (default - None)
|
||||
description: Full proxy URI on a public host, a Control D resolver as controld://<resolver>@dns.controld.com, or a country code when the API key has server_proxy, or tunnel:<id> for a tunnel the same API key opened on /api/tunnel (default - None)
|
||||
no_proxy:
|
||||
type: boolean
|
||||
description: Force disable all proxy use (default - false)
|
||||
@@ -817,7 +817,7 @@ async def list_tracks(request: web.Request) -> web.Response:
|
||||
description: Specific episode/season, or song ("1-5", "2x3" for disc 2 track 3) (optional)
|
||||
proxy:
|
||||
type: string
|
||||
description: Full proxy URI, a Control D resolver as controld://<resolver>@dns.controld.com, or a country code when the API key has server_proxy (default - None)
|
||||
description: Full proxy URI on a public host, a Control D resolver as controld://<resolver>@dns.controld.com, or a country code when the API key has server_proxy (default - None)
|
||||
dl_params:
|
||||
type: object
|
||||
description: |
|
||||
@@ -1072,7 +1072,7 @@ async def download(request: web.Request) -> web.Response:
|
||||
description: CDM device name on the server to license with, overriding the cdm config mapping. Requires serve.cdm_overrides to allow it (default - None)
|
||||
proxy:
|
||||
type: string
|
||||
description: Full proxy URI, a Control D resolver as controld://<resolver>@dns.controld.com, or a country code when the API key has server_proxy (default - None)
|
||||
description: Full proxy URI on a public host, a Control D resolver as controld://<resolver>@dns.controld.com, or a country code when the API key has server_proxy (default - None)
|
||||
no_proxy:
|
||||
type: boolean
|
||||
description: Force disable all proxy use (default - false)
|
||||
|
||||
@@ -8,13 +8,12 @@ from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import logging
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional, Union
|
||||
from uuid import UUID
|
||||
|
||||
from unshackle.core.cdm.monalisa import MonaLisaCDM
|
||||
from unshackle.core.utils.subprocess import run_step
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
@@ -220,57 +219,22 @@ class MonaLisa:
|
||||
self._execute_decrypt(path, output_path)
|
||||
|
||||
def _execute_decrypt(self, path: Path, output_path: Optional[Path] = None) -> None:
|
||||
"""Execute external CLI tool via subprocess to decrypt the target file."""
|
||||
"""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}")
|
||||
|
||||
if not self._tool_path or not self._tool_path.exists():
|
||||
return
|
||||
raise RuntimeError(f"MonaLisa decryption tool missing: {self._tool_path or 'no tool_path given'}")
|
||||
|
||||
if not self.key or not self.kid:
|
||||
raise MonaLisa.Exceptions.KeyExtractionFailed("Missing content key for decryption.")
|
||||
|
||||
target_output = output_path or path
|
||||
temp_enc = path.with_name(f"{path.name}.temp_enc")
|
||||
|
||||
try:
|
||||
if path.exists():
|
||||
path.replace(temp_enc)
|
||||
else:
|
||||
raise FileNotFoundError(f"Target file disappeared: {path}")
|
||||
|
||||
cmd = [
|
||||
str(self._tool_path),
|
||||
"-i",
|
||||
str(temp_enc),
|
||||
"-o",
|
||||
str(target_output),
|
||||
"-k",
|
||||
self.key_pair,
|
||||
]
|
||||
|
||||
startupinfo = None
|
||||
if sys.platform == "win32":
|
||||
startupinfo = subprocess.STARTUPINFO()
|
||||
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
|
||||
|
||||
process = subprocess.run(
|
||||
cmd,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
startupinfo=startupinfo,
|
||||
timeout=60,
|
||||
)
|
||||
|
||||
if process.returncode != 0 or not target_output.exists():
|
||||
raise RuntimeError(f"MonaLisa decryption failed for {path.name}: {process.stderr or 'unknown error'}")
|
||||
|
||||
finally:
|
||||
if temp_enc.exists():
|
||||
try:
|
||||
temp_enc.unlink()
|
||||
except Exception:
|
||||
pass
|
||||
temp_out = target_output.with_stem(f"{target_output.stem}_decrypted")
|
||||
run_step(
|
||||
[self._tool_path, "-i", path, "-o", temp_out, "-k", self.key_pair],
|
||||
output=temp_out,
|
||||
label=f"MonaLisa decryption of {path.name}",
|
||||
timeout=60,
|
||||
)
|
||||
temp_out.replace(target_output)
|
||||
|
||||
@@ -285,6 +285,7 @@ class MusicRenderer:
|
||||
|
||||
@staticmethod
|
||||
def is_hires_quality(value: str) -> bool:
|
||||
"""Return True for a label above 16-bit or 48 kHz; a "k" before "b" is a bitrate ("256 kb/s"), not a rate."""
|
||||
lowered = value.lower()
|
||||
bit_depth = None
|
||||
sample_rate = None
|
||||
@@ -293,7 +294,7 @@ class MusicRenderer:
|
||||
if bit_match:
|
||||
bit_depth = int(bit_match.group("bits"))
|
||||
|
||||
sample_match = re.search(r"(?P<rate>\d+(?:\.\d+)?)\s*k(?:hz)?", lowered)
|
||||
sample_match = re.search(r"(?P<rate>\d+(?:\.\d+)?)\s*k(?!b)(?:hz)?", lowered)
|
||||
if sample_match:
|
||||
sample_rate = float(sample_match.group("rate"))
|
||||
|
||||
|
||||
@@ -556,7 +556,13 @@ def resolve_manifest_data(tracks: Tracks, manifests: list) -> None:
|
||||
|
||||
from unshackle.core.manifests import DASH
|
||||
|
||||
local_tracks = DASH(etree.fromstring(raw), m_url).to_tracks(language=fallback_lang)
|
||||
skip = manifest_info.get("filtered_period_ids") or []
|
||||
local_tracks = DASH(etree.fromstring(raw), m_url).to_tracks(
|
||||
language=fallback_lang, period_filter=(lambda p: p.get("id") in skip) if skip else None
|
||||
)
|
||||
if skip:
|
||||
for local_track in local_tracks:
|
||||
local_track.data["dash"]["filtered_period_ids"] = skip
|
||||
elif m_type == "ism":
|
||||
from lxml import etree
|
||||
|
||||
|
||||
@@ -1111,8 +1111,8 @@ class Subtitle(Track):
|
||||
|
||||
if nodes:
|
||||
caption = Caption(
|
||||
start=start_time * timescale, # as microseconds
|
||||
end=end_time * timescale,
|
||||
start=start_time * 1_000_000 / timescale,
|
||||
end=end_time * 1_000_000 / timescale,
|
||||
nodes=nodes,
|
||||
layout_info=layout,
|
||||
)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
from typing import Any, Collection, Dict, Iterable
|
||||
|
||||
import click
|
||||
|
||||
FLAT_DL_KEYS = frozenset({"title", "service", "title_id", "profile", "proxy", "no_proxy"})
|
||||
|
||||
|
||||
@@ -16,3 +18,25 @@ def service_options(
|
||||
return {k: v for k, v in nested.items() if k in names}
|
||||
excluded = set(flat_excluded)
|
||||
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]:
|
||||
"""``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, or an array for a single-value option,
|
||||
is refused before the cast, since click would stringify it.
|
||||
"""
|
||||
by_name = {p.name: p for p in params if p.name}
|
||||
cast: Dict[str, Any] = {}
|
||||
for k, v in options.items():
|
||||
param = by_name.get(k)
|
||||
if param is None:
|
||||
cast[k] = v
|
||||
continue
|
||||
if isinstance(v, dict) or (isinstance(v, list) and not param.multiple and param.nargs == 1):
|
||||
raise click.BadParameter("expected a single value, not a JSON object or array", ctx=ctx, param=param)
|
||||
try:
|
||||
cast[k] = param.type_cast_value(ctx, v)
|
||||
except (TypeError, ValueError, AttributeError) as e: # convert() only promises BadParameter for strings
|
||||
raise click.BadParameter(f"not a valid {param.type.name} value", ctx=ctx, param=param) from e
|
||||
return cast
|
||||
|
||||
@@ -187,22 +187,30 @@ def run_step(
|
||||
status: Optional[str] = None,
|
||||
output: Optional[Path] = None,
|
||||
label: str = "subprocess step",
|
||||
timeout: Optional[float] = None,
|
||||
) -> bytes:
|
||||
"""Operate a CLI step that writes to `output` (when provided). Returns stderr bytes.
|
||||
|
||||
Raises RuntimeError with the stderr tail when the process exits non-zero, or when
|
||||
you give `output` and it does not exist or is empty after the step.
|
||||
you give `output` and it does not exist or is empty after the step. A timeout also
|
||||
raises RuntimeError.
|
||||
"""
|
||||
if output is not None:
|
||||
output.unlink(missing_ok=True)
|
||||
|
||||
str_args = [str(a) for a in args]
|
||||
start = time.monotonic()
|
||||
if status:
|
||||
with console.status(status, spinner="dots"):
|
||||
p = subprocess.run(str_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
else:
|
||||
p = subprocess.run(str_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
try:
|
||||
if status:
|
||||
with console.status(status, spinner="dots"):
|
||||
p = subprocess.run(str_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
|
||||
else:
|
||||
p = subprocess.run(str_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
if output is not None:
|
||||
output.unlink(missing_ok=True)
|
||||
# from None: the TimeoutExpired text holds the whole command line, which can carry a content key
|
||||
raise RuntimeError(f"{label} timed out after {timeout}s") from None
|
||||
|
||||
stderr = p.stderr or b""
|
||||
bad_output = output is not None and (not output.exists() or output.stat().st_size == 0)
|
||||
|
||||
@@ -2176,7 +2176,6 @@ dependencies = [
|
||||
{ name = "aiohttp" },
|
||||
{ name = "aiohttp-swagger3" },
|
||||
{ name = "appdirs" },
|
||||
{ name = "bandit" },
|
||||
{ name = "brotli" },
|
||||
{ name = "chardet" },
|
||||
{ name = "click" },
|
||||
@@ -2222,6 +2221,7 @@ dependencies = [
|
||||
|
||||
[package.dev-dependencies]
|
||||
dev = [
|
||||
{ name = "bandit" },
|
||||
{ name = "isort" },
|
||||
{ name = "mypy" },
|
||||
{ name = "mypy-protobuf" },
|
||||
@@ -2247,7 +2247,6 @@ requires-dist = [
|
||||
{ name = "aiohttp", specifier = ">=3.14.0,<4" },
|
||||
{ name = "aiohttp-swagger3", specifier = ">=0.9.0,<1" },
|
||||
{ name = "appdirs", specifier = ">=1.4.4,<2" },
|
||||
{ name = "bandit", specifier = ">=1.9.4" },
|
||||
{ name = "brotli", specifier = ">=1.1.0,<2" },
|
||||
{ name = "chardet", specifier = ">=5.2.0,<6" },
|
||||
{ name = "click", specifier = ">=8.2,<9" },
|
||||
@@ -2293,6 +2292,7 @@ requires-dist = [
|
||||
|
||||
[package.metadata.requires-dev]
|
||||
dev = [
|
||||
{ name = "bandit", specifier = ">=1.9.4,<2" },
|
||||
{ name = "isort", specifier = ">=5.13.2,<8" },
|
||||
{ name = "mypy", specifier = ">=1.9.0,<2" },
|
||||
{ name = "mypy-protobuf", specifier = ">=3.6.0,<4" },
|
||||
|
||||
Reference in New Issue
Block a user