mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-27 03:15:08 +00:00
feat(service): pass a qr code with a login prompt or approval wait
This commit is contained in:
@@ -276,6 +276,22 @@ when the client deletes the remote session, so the loop does not continue on the
|
|||||||
server with no client. The message goes out as a log line, so a remote
|
server with no client. The message goes out as a log line, so a remote
|
||||||
session shows it. A REST download job shows it in its `notice` field until the wait ends.
|
session shows it. A REST download job shows it in its `notice` field until the wait ends.
|
||||||
|
|
||||||
|
For a login that the user scans with a phone, give the text of the QR code as `qr`. Both
|
||||||
|
`wait_for_approval` and `request_input` take it. The terminal that shows the message draws
|
||||||
|
the code under it, on the client for a remote session. Give the text that the login API puts in
|
||||||
|
the code, such as the login URL, not an image. Keep the URL or code in the message too: a
|
||||||
|
terminal that cannot draw the code, or a phone that cannot read it, still shows the text.
|
||||||
|
`EXAMPLE.scan_login` in `unshackle/services/EXAMPLE/` shows the whole flow.
|
||||||
|
|
||||||
|
```python
|
||||||
|
token = self.wait_for_approval(
|
||||||
|
f"Scan the code with the app, or open {login_url}",
|
||||||
|
check=lambda: self.poll_login(session_id),
|
||||||
|
timeout=expires_in,
|
||||||
|
qr=login_url,
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
The wait sees a cancel only between two `check` calls, so `check` must return within a few
|
The wait sees a cancel only between two `check` calls, so `check` must return within a few
|
||||||
seconds. A `check` that reads a socket keeps the socket open across calls and returns `None`
|
seconds. A `check` that reads a socket keeps the socket open across calls and returns `None`
|
||||||
after each short idle wait.
|
after each short idle wait.
|
||||||
|
|||||||
@@ -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.
|
- **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.
|
- **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.
|
- **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 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.
|
- **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`, its `qr` (the text of a QR code to scan, or null), 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"
|
!!! 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.
|
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.
|
||||||
@@ -589,7 +589,8 @@ Show download jobs, with optional filtering and sorting.
|
|||||||
"skipped_subtitles": [],
|
"skipped_subtitles": [],
|
||||||
"skipped_titles": [],
|
"skipped_titles": [],
|
||||||
"input_prompt": null,
|
"input_prompt": null,
|
||||||
"notice": null
|
"notice": null,
|
||||||
|
"qr": null
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -757,7 +758,8 @@ answer here.
|
|||||||
|
|
||||||
A job that waits for an approval on another device, such as a pair code login, shows the
|
A job that waits for an approval on another device, such as a pair code login, shows the
|
||||||
message in its `notice` field instead. A notice needs no answer: show it to the user and keep
|
message in its `notice` field instead. A notice needs no answer: show it to the user and keep
|
||||||
polling.
|
polling. When the login is a QR code to scan, the job also sets `qr` to the text of the code:
|
||||||
|
draw it as a QR code beside the prompt or notice.
|
||||||
|
|
||||||
=== "Request"
|
=== "Request"
|
||||||
|
|
||||||
|
|||||||
@@ -165,6 +165,7 @@ full detail:
|
|||||||
| `skipped_titles` | list | Titles that the run skipped because a requested track or language is missing, each `{title, reason}`. |
|
| `skipped_titles` | list | Titles that the run skipped because a requested track or language is missing, each `{title, reason}`. |
|
||||||
| `input_prompt` | string or `null` | The prompt the service waits on. Answer it with `POST /api/download/jobs/{job_id}/input`. |
|
| `input_prompt` | string or `null` | The prompt the service waits on. Answer it with `POST /api/download/jobs/{job_id}/input`. |
|
||||||
| `notice` | string or `null` | A message the service shows while it waits for an approval on another device, such as a pair code. It needs no answer. |
|
| `notice` | string or `null` | A message the service shows while it waits for an approval on another device, such as a pair code. It needs no answer. |
|
||||||
|
| `qr` | string or `null` | The text of a QR code that goes with `input_prompt` or `notice`, such as a login URL to scan with a phone. Draw it as a QR code. |
|
||||||
|
|
||||||
The full detail adds `started_time`, `completed_time`, `output_files`, the redacted
|
The full detail adds `started_time`, `completed_time`, `output_files`, the redacted
|
||||||
`parameters`, and, for failed jobs, `error_message`, `error_details`, and `error_code`.
|
`parameters`, and, for failed jobs, `error_message`, `error_details`, and `error_code`.
|
||||||
@@ -375,7 +376,8 @@ The job worker has no terminal. When a service asks the user for input, the job
|
|||||||
the prompt to `progress.json` as `input_prompt` and waits. The answer from
|
the prompt to `progress.json` as `input_prompt` and waits. The answer from
|
||||||
`POST /api/download/jobs/{job_id}/input` goes to the job worker on its stdin.
|
`POST /api/download/jobs/{job_id}/input` goes to the job worker on its stdin.
|
||||||
When a service waits for an approval on another device, the job worker writes the message as
|
When a service waits for an approval on another device, the job worker writes the message as
|
||||||
`notice` and sets it back to `null` when the wait ends.
|
`notice` and sets it back to `null` when the wait ends. A QR code to scan goes out as `qr`, and
|
||||||
|
the end of its prompt or notice sets it back to `null`.
|
||||||
|
|
||||||
Running each download out-of-process isolates the server from crashes, memory growth,
|
Running each download out-of-process isolates the server from crashes, memory growth,
|
||||||
and blocking work inside the download engine, and makes hard cancellation (killing the
|
and blocking work inside the download engine, and makes hard cancellation (killing the
|
||||||
|
|||||||
@@ -530,7 +530,7 @@ thread, an `InputBridge` pauses that thread and exposes the prompt to the HTTP
|
|||||||
layer.
|
layer.
|
||||||
|
|
||||||
- `AuthStatus` values: `authenticating`, `pending_input`, `authenticated`, `failed`.
|
- `AuthStatus` values: `authenticating`, `pending_input`, `authenticated`, `failed`.
|
||||||
- `InputBridge.request_input(prompt, timeout=600)` blocks the sync auth thread on a
|
- `InputBridge.request_input(prompt, timeout=600, qr=None)` blocks the sync auth thread on a
|
||||||
`threading.Event` until `submit_response()` or `cancel()` fires.
|
`threading.Event` until `submit_response()` or `cancel()` fires.
|
||||||
- A timeout raises `TimeoutError`. The remote session becomes `FAILED` when that error ends the login.
|
- A timeout raises `TimeoutError`. The remote session becomes `FAILED` when that error ends the login.
|
||||||
- A prompt after authentication (in `get_titles()`, `get_tracks()` or licensing) goes to
|
- A prompt after authentication (in `get_titles()`, `get_tracks()` or licensing) goes to
|
||||||
@@ -549,6 +549,7 @@ layer.
|
|||||||
{ "status": "authenticated" }
|
{ "status": "authenticated" }
|
||||||
{ "status": "authenticating" }
|
{ "status": "authenticating" }
|
||||||
{ "status": "pending_input", "prompt": "Enter code: " }
|
{ "status": "pending_input", "prompt": "Enter code: " }
|
||||||
|
{ "status": "pending_input", "prompt": "Scan the code, then press Enter", "qr": "https://login.example/scan" }
|
||||||
{ "status": "pending_input", "prompt": "...", "cdm_call": { "op": "challenge", "drm": "widevine", "init_data": "...", "license_type": "OFFLINE", "privacy_mode": true, "service_certificate": "..." } }
|
{ "status": "pending_input", "prompt": "...", "cdm_call": { "op": "challenge", "drm": "widevine", "init_data": "...", "license_type": "OFFLINE", "privacy_mode": true, "service_certificate": "..." } }
|
||||||
{ "status": "failed", "error": "...message..." }
|
{ "status": "failed", "error": "...message..." }
|
||||||
```
|
```
|
||||||
@@ -576,9 +577,9 @@ Each message is a JSON text frame with a `type` field:
|
|||||||
|
|
||||||
| `type` | From | Fields | Meaning |
|
| `type` | From | Fields | Meaning |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| `prompt` | server | `id`, `prompt` | The service asks the user for input |
|
| `prompt` | server | `id`, `prompt`, `qr` | The service asks the user for input; `qr`, when present, is the text of a QR code to draw with it |
|
||||||
| `cdm_call` | server | `id`, `call` | The service calls the client's CDM; `call` has the shape of the prompt route's `cdm_call` |
|
| `cdm_call` | server | `id`, `call` | The service calls the client's CDM; `call` has the shape of the prompt route's `cdm_call` |
|
||||||
| `log` | server | `seq`, `level`, `message`, `ts` | One record of the service log, with the same redaction as `GET /logs` |
|
| `log` | server | `seq`, `level`, `message`, `ts`, `qr` | One record of the service log, with the same redaction as `GET /logs`; `qr`, when present, is the text of a QR code to draw under the message |
|
||||||
| `status` | server | `status`, `error` | The login state, as the `status` of `GET /prompt` |
|
| `status` | server | `status`, `error` | The login state, as the `status` of `GET /prompt` |
|
||||||
| `drain` | server | `draining` | The operator started or stopped a drain before a restart |
|
| `drain` | server | `draining` | The operator started or stopped a drain before a restart |
|
||||||
| `answer` | client | `id`, `response`, `error` | The answer to the `prompt` or `cdm_call` with this `id`; `error` says why the client cannot answer a prompt, and the service stops at once |
|
| `answer` | client | `id`, `response`, `error` | The answer to the `prompt` or `cdm_call` with this `id`; `error` says why the client cannot answer a prompt, and the service stops at once |
|
||||||
|
|||||||
@@ -89,12 +89,13 @@ These are abstract. A service will not load unless it defines all three:
|
|||||||
- **DRM license hooks**: `get_widevine_service_certificate`, `get_widevine_license`,
|
- **DRM license hooks**: `get_widevine_service_certificate`, `get_widevine_license`,
|
||||||
`get_playready_license` (delegates to Widevine by default), and
|
`get_playready_license` (delegates to Widevine by default), and
|
||||||
`get_clearkey_license` (returns `None` by default). See [DRM hooks](#drm-hooks) below.
|
`get_clearkey_license` (returns `None` by default). See [DRM hooks](#drm-hooks) below.
|
||||||
- **`request_input(prompt)`**: prompts the user. It goes through the remote-dl input
|
- **`request_input(prompt, qr=None)`**: prompts the user. It goes through the remote-dl input
|
||||||
bridge, the REST download job relay, or the rich console.
|
bridge, the REST download job relay, or the rich console.
|
||||||
- **`wait_for_approval(message, check, timeout, interval=3.0)`**: shows a message, then
|
- **`wait_for_approval(message, check, timeout, interval=3.0, qr=None)`**: shows a message, then
|
||||||
calls `check` until it returns a value. Use it for a login that the user approves on
|
calls `check` until it returns a value. Use it for a login that the user approves on
|
||||||
another device, such as a pair code. A remote-dl session shows the message as a log
|
another device, such as a pair code. A remote-dl session shows the message as a log
|
||||||
line, and a REST download job shows it as the job's `notice`.
|
line, and a REST download job shows it as the job's `notice`. Both methods take `qr`, the
|
||||||
|
text of a QR code to scan, and the terminal or UI that shows the user the message draws it.
|
||||||
- **Event callbacks**: `on_segment_downloaded`, `on_track_downloaded`,
|
- **Event callbacks**: `on_segment_downloaded`, `on_track_downloaded`,
|
||||||
`on_track_decrypted`, `on_track_repacked`, `on_track_multiplex` let a service react to
|
`on_track_decrypted`, `on_track_repacked`, `on_track_multiplex` let a service react to
|
||||||
pipeline events.
|
pipeline events.
|
||||||
|
|||||||
@@ -66,6 +66,7 @@ dependencies = [
|
|||||||
"defusedxml>=0.7.1",
|
"defusedxml>=0.7.1",
|
||||||
"rich-click>=1.9.8",
|
"rich-click>=1.9.8",
|
||||||
"mediaexport @ git+https://github.com/unshackle-dl/mediaexport@main",
|
"mediaexport @ git+https://github.com/unshackle-dl/mediaexport@main",
|
||||||
|
"segno>=1.6.6,<2",
|
||||||
]
|
]
|
||||||
|
|
||||||
[project.urls]
|
[project.urls]
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import segno
|
||||||
|
|
||||||
|
from unshackle.core import console
|
||||||
|
from unshackle.core.console import qr_text, show_qr
|
||||||
|
|
||||||
|
TOP = {"\u2588": True, "\u2580": True, "\u2584": False, " ": False}
|
||||||
|
BOTTOM = {"\u2588": True, "\u2580": False, "\u2584": True, " ": False}
|
||||||
|
|
||||||
|
|
||||||
|
def test_each_line_holds_two_module_rows_of_the_code() -> None:
|
||||||
|
data = "https://login.example/scan?code=EXAMPLE"
|
||||||
|
rows = [[bool(v) for v in row] for row in segno.make_qr(data).matrix_iter(border=2)]
|
||||||
|
unpacked = []
|
||||||
|
for line in qr_text(data, indent=0).plain.splitlines():
|
||||||
|
unpacked += [[TOP[c] for c in line], [BOTTOM[c] for c in line]]
|
||||||
|
assert unpacked[: len(rows)] == rows
|
||||||
|
assert not any(cell for row in unpacked[len(rows) :] for cell in row)
|
||||||
|
|
||||||
|
|
||||||
|
def test_short_text_is_a_full_qr_code_not_a_micro_one() -> None:
|
||||||
|
assert len(qr_text("12345", indent=0).plain.splitlines()) * 2 >= 21 + 4
|
||||||
|
|
||||||
|
|
||||||
|
def test_text_longer_than_a_qr_code_holds_draws_nothing(monkeypatch) -> None:
|
||||||
|
printed: list = []
|
||||||
|
monkeypatch.setattr(console.console, "print", lambda *a, **k: printed.extend(a))
|
||||||
|
show_qr("\u20ac" * 1500)
|
||||||
|
assert printed == []
|
||||||
@@ -49,6 +49,18 @@ def test_logs_the_message_for_a_remote_session(caplog):
|
|||||||
assert "enter code" in caplog.messages
|
assert "enter code" in caplog.messages
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("remote", [False, True])
|
||||||
|
def test_draws_the_qr_code_here_only_without_a_remote_session(monkeypatch, caplog, remote):
|
||||||
|
drawn = []
|
||||||
|
monkeypatch.setattr("unshackle.core.service.show_qr", drawn.append)
|
||||||
|
with caplog.at_level(logging.INFO, logger="test"):
|
||||||
|
Service.wait_for_approval(
|
||||||
|
_service(InputBridge() if remote else None), "scan", lambda: "token", timeout=5, interval=0, qr="EXAMPLE"
|
||||||
|
)
|
||||||
|
assert drawn == ([] if remote else ["EXAMPLE"])
|
||||||
|
assert [getattr(r, "qr", None) for r in caplog.records] == ["EXAMPLE"]
|
||||||
|
|
||||||
|
|
||||||
def test_a_request_with_no_user_fails_at_once():
|
def test_a_request_with_no_user_fails_at_once():
|
||||||
calls = []
|
calls = []
|
||||||
with pytest.raises(RuntimeError, match="needs the user"):
|
with pytest.raises(RuntimeError, match="needs the user"):
|
||||||
@@ -74,7 +86,7 @@ def test_no_user_message_is_an_authentication_error():
|
|||||||
)
|
)
|
||||||
def test_shows_the_message_as_a_notice_and_clears_it(monkeypatch, check, expectation):
|
def test_shows_the_message_as_a_notice_and_clears_it(monkeypatch, check, expectation):
|
||||||
notices = []
|
notices = []
|
||||||
monkeypatch.setattr(console, "_notice_handler", notices.append)
|
monkeypatch.setattr(console, "_notice_handler", lambda message, qr: notices.append(message))
|
||||||
with expectation:
|
with expectation:
|
||||||
Service.wait_for_approval(_service(), "enter code", check, timeout=0.05, interval=0.01)
|
Service.wait_for_approval(_service(), "enter code", check, timeout=0.05, interval=0.01)
|
||||||
assert notices == ["enter code", None]
|
assert notices == ["enter code", None]
|
||||||
|
|||||||
@@ -346,16 +346,19 @@ def test_worker_relays_a_prompt_and_reads_the_answer(monkeypatch: pytest.MonkeyP
|
|||||||
def answer_on_prompt(update: dict) -> None:
|
def answer_on_prompt(update: dict) -> None:
|
||||||
"""Answer only once the prompt is out: the prompt discards answers that arrived before it."""
|
"""Answer only once the prompt is out: the prompt discards answers that arrived before it."""
|
||||||
updates.append(update)
|
updates.append(update)
|
||||||
if update["input_prompt"]:
|
if update.get("input_prompt"):
|
||||||
os.write(write_fd, (json.dumps("12\n34") + "\n").encode("utf-8"))
|
os.write(write_fd, (json.dumps("12\n34") + "\n").encode("utf-8"))
|
||||||
|
|
||||||
download_worker.relay_prompts(answer_on_prompt)
|
download_worker.relay_prompts(answer_on_prompt)
|
||||||
try:
|
try:
|
||||||
assert prompt_user("Enter PIN") == "12\n34"
|
assert prompt_user("Enter PIN", qr="https://login.example/scan") == "12\n34"
|
||||||
finally:
|
finally:
|
||||||
set_prompt_handler(None)
|
set_prompt_handler(None)
|
||||||
os.close(write_fd)
|
os.close(write_fd)
|
||||||
assert updates == [{"input_prompt": "Enter PIN"}, {"input_prompt": None}]
|
assert updates == [
|
||||||
|
{"input_prompt": "Enter PIN", "qr": "https://login.example/scan"},
|
||||||
|
{"input_prompt": None, "qr": None},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
def test_worker_relays_a_notice_as_progress(monkeypatch: pytest.MonkeyPatch) -> None:
|
def test_worker_relays_a_notice_as_progress(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
@@ -373,13 +376,16 @@ def test_worker_relays_a_notice_as_progress(monkeypatch: pytest.MonkeyPatch) ->
|
|||||||
|
|
||||||
download_worker.relay_prompts(updates.append)
|
download_worker.relay_prompts(updates.append)
|
||||||
try:
|
try:
|
||||||
show_notice("Enter pair code ABCD")
|
show_notice("Enter pair code ABCD", "https://login.example/pair")
|
||||||
show_notice(None)
|
show_notice(None)
|
||||||
finally:
|
finally:
|
||||||
set_prompt_handler(None)
|
set_prompt_handler(None)
|
||||||
set_notice_handler(None)
|
set_notice_handler(None)
|
||||||
os.close(write_fd)
|
os.close(write_fd)
|
||||||
assert updates == [{"notice": "Enter pair code ABCD"}, {"notice": None}]
|
assert updates == [
|
||||||
|
{"notice": "Enter pair code ABCD", "qr": "https://login.example/pair"},
|
||||||
|
{"notice": None, "qr": None},
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
def test_a_prompt_discards_an_answer_sent_before_it(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
def test_a_prompt_discards_an_answer_sent_before_it(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||||
@@ -530,7 +536,8 @@ async def test_a_notice_reaches_the_job_and_an_event_listener(
|
|||||||
# The prompt holds the worker open until the test has seen the notice.
|
# The prompt holds the worker open until the test has seen the notice.
|
||||||
source = FAKE_PROMPT_WORKER.replace("import prompt_user", "import prompt_user, show_notice").replace(
|
source = FAKE_PROMPT_WORKER.replace("import prompt_user", "import prompt_user, show_notice").replace(
|
||||||
'answers = [prompt_user("Enter OTP"), prompt_user("Enter OTP")]',
|
'answers = [prompt_user("Enter OTP"), prompt_user("Enter OTP")]',
|
||||||
'show_notice("Enter pair code ABCD")\nanswers = [prompt_user("Continue")]',
|
'show_notice("Enter pair code ABCD", "https://login.example/pair")\n'
|
||||||
|
'answers = [prompt_user("Continue", "https://login.example/pair")]',
|
||||||
)
|
)
|
||||||
assert source.count("show_notice") == 2, "FAKE_PROMPT_WORKER changed; update the replacements"
|
assert source.count("show_notice") == 2, "FAKE_PROMPT_WORKER changed; update the replacements"
|
||||||
worker.write_text(source, encoding="utf-8")
|
worker.write_text(source, encoding="utf-8")
|
||||||
@@ -550,12 +557,13 @@ async def test_a_notice_reaches_the_job_and_an_event_listener(
|
|||||||
if event and event["data"]["input_prompt"]:
|
if event and event["data"]["input_prompt"]:
|
||||||
assert event["data"]["notice"] == "Enter pair code ABCD"
|
assert event["data"]["notice"] == "Enter pair code ABCD"
|
||||||
assert job.to_dict()["notice"] == "Enter pair code ABCD"
|
assert job.to_dict()["notice"] == "Enter pair code ABCD"
|
||||||
|
assert event["data"]["qr"] == job.to_dict()["qr"] == "https://login.example/pair"
|
||||||
assert manager.submit_input(job, "ok") is True
|
assert manager.submit_input(job, "ok") is True
|
||||||
return
|
return
|
||||||
|
|
||||||
await asyncio.wait_for(answer_after_notice(), timeout=20)
|
await asyncio.wait_for(answer_after_notice(), timeout=20)
|
||||||
assert await asyncio.wait_for(run, timeout=20) == ["ok"]
|
assert await asyncio.wait_for(run, timeout=20) == ["ok"]
|
||||||
assert job.notice is None
|
assert job.notice is None and job.qr is None
|
||||||
|
|
||||||
|
|
||||||
async def test_input_handler_rejects_bad_requests(
|
async def test_input_handler_rejects_bad_requests(
|
||||||
|
|||||||
@@ -246,7 +246,20 @@ def test_relayed_server_logs_lose_their_control_characters(monkeypatch: pytest.M
|
|||||||
|
|
||||||
def test_a_relayed_login_prompt_loses_its_control_characters() -> None:
|
def test_a_relayed_login_prompt_loses_its_control_characters() -> None:
|
||||||
service = RemoteService.__new__(RemoteService)
|
service = RemoteService.__new__(RemoteService)
|
||||||
asked: list[str] = []
|
asked: list[tuple[str, str | None]] = []
|
||||||
service._input_bridge = SimpleNamespace(request_input=lambda prompt: asked.append(prompt) or "1234")
|
service._input_bridge = SimpleNamespace(request_input=lambda prompt, qr=None: asked.append((prompt, qr)) or "1234")
|
||||||
assert ServerMessages(service).ask_user("Code\x1b[2J:\n") == "1234"
|
assert ServerMessages(service).ask_user("Code\x1b[2J:\n", {"not": "text"}) == "1234"
|
||||||
assert asked == ["Code[2J:\n"]
|
assert asked == [("Code[2J:\n", None)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_relayed_qr_code_too_long_to_draw_still_logs_its_line(monkeypatch) -> None:
|
||||||
|
from unshackle.core import console
|
||||||
|
|
||||||
|
seen: list[str] = []
|
||||||
|
service = RemoteService.__new__(RemoteService)
|
||||||
|
service._input_bridge, service.auth_qr = None, None
|
||||||
|
service.log = SimpleNamespace(log=lambda level, message: seen.append(message))
|
||||||
|
monkeypatch.setattr(console.console, "print", lambda *a, **k: pytest.fail("nothing to draw"))
|
||||||
|
messages = ServerMessages(service)
|
||||||
|
messages.show_logs([{"seq": 1, "level": "INFO", "message": "Scan", "qr": "\u20ac" * 1500}])
|
||||||
|
assert seen == ["Scan"] and messages.log_seq == 1
|
||||||
|
|||||||
@@ -27,9 +27,11 @@ from unshackle.core.api.handlers import api_key_authentication
|
|||||||
from unshackle.core.api.routes import cors_middleware, no_5xx_middleware, setup_routes
|
from unshackle.core.api.routes import cors_middleware, no_5xx_middleware, setup_routes
|
||||||
from unshackle.core.cdm import client_relay
|
from unshackle.core.cdm import client_relay
|
||||||
from unshackle.core.config import config
|
from unshackle.core.config import config
|
||||||
|
from unshackle.core.console import console, qr_text
|
||||||
from unshackle.core.remote_channel import PollingChannel, WebSocketChannel
|
from unshackle.core.remote_channel import PollingChannel, WebSocketChannel
|
||||||
from unshackle.core.remote_protocol import CHANNEL_ROUTE, LOGS_ROUTE, PROMPT_ROUTE, SESSION_ROUTE, APIErrorCode
|
from unshackle.core.remote_protocol import CHANNEL_ROUTE, LOGS_ROUTE, PROMPT_ROUTE, SESSION_ROUTE, APIErrorCode
|
||||||
from unshackle.core.remote_service import RemoteError, RemoteService
|
from unshackle.core.remote_service import RemoteError, RemoteService
|
||||||
|
from unshackle.core.service import Service
|
||||||
from unshackle.core.titles.movie import Movie, Movies
|
from unshackle.core.titles.movie import Movie, Movies
|
||||||
from unshackle.core.tracks import Audio, Chapters, Tracks
|
from unshackle.core.tracks import Audio, Chapters, Tracks
|
||||||
from unshackle.core.tracks.track import Track
|
from unshackle.core.tracks.track import Track
|
||||||
@@ -174,7 +176,7 @@ def make_client(url: str, cdm: Any = None) -> RemoteService:
|
|||||||
parent.params = {"no_proxy": True}
|
parent.params = {"no_proxy": True}
|
||||||
ctx = click.Context(click.Command("EXAMPLE"), parent=parent, obj=obj)
|
ctx = click.Context(click.Command("EXAMPLE"), parent=parent, obj=obj)
|
||||||
service = RemoteService(ctx, "EXAMPLE", "example-1", url, KEY, {"_auth_headers": ["X-Api-Key", "X-Secret-Key"]})
|
service = RemoteService(ctx, "EXAMPLE", "example-1", url, KEY, {"_auth_headers": ["X-Api-Key", "X-Secret-Key"]})
|
||||||
service._input_bridge = SimpleNamespace(request_input=lambda prompt: CODE)
|
service._input_bridge = SimpleNamespace(request_input=lambda prompt, qr=None: CODE)
|
||||||
return service
|
return service
|
||||||
|
|
||||||
|
|
||||||
@@ -284,6 +286,65 @@ def test_a_remote_session_runs_end_to_end_over_http(
|
|||||||
assert [list(r) for reply in logs for r in reply["logs"]][:1] == [["seq", "level", "message", "ts"]]
|
assert [list(r) for reply in logs for r in reply["logs"]][:1] == [["seq", "level", "message", "ts"]]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("channel", ["socket", "polling"])
|
||||||
|
def test_a_qr_code_reaches_the_client_terminal_with_its_prompt(
|
||||||
|
server: SimpleNamespace, channel: str, monkeypatch: pytest.MonkeyPatch
|
||||||
|
) -> None:
|
||||||
|
payload = "https://login.example/scan?code=EXAMPLE"
|
||||||
|
if channel == "polling":
|
||||||
|
monkeypatch.setattr(WebSocketChannel, "open", lambda self, timeout=0: False)
|
||||||
|
|
||||||
|
def authenticate(self: StubService, cookies: Any, credential: Any) -> None:
|
||||||
|
if self._input_bridge.request_input("Scan the EXAMPLE code, then press Enter", qr=payload) != CODE:
|
||||||
|
raise ValueError("wrong code")
|
||||||
|
|
||||||
|
monkeypatch.setattr(StubService, "authenticate", authenticate)
|
||||||
|
printed: list[Any] = []
|
||||||
|
asked: list[str] = []
|
||||||
|
monkeypatch.setattr(console, "print", lambda *a, **k: printed.extend(a))
|
||||||
|
monkeypatch.setattr(console, "input", lambda prompt: asked.append(str(prompt)) or CODE)
|
||||||
|
service = make_client(server.url)
|
||||||
|
service._input_bridge = None
|
||||||
|
try:
|
||||||
|
service.authenticate()
|
||||||
|
assert isinstance(service.channel, WebSocketChannel if channel == "socket" else PollingChannel)
|
||||||
|
finally:
|
||||||
|
service.close()
|
||||||
|
assert [p.plain for p in printed if hasattr(p, "plain")] == [qr_text(payload).plain]
|
||||||
|
assert len(asked) == 1 and "Scan the EXAMPLE code" in asked[0]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("channel", ["socket", "polling"])
|
||||||
|
def test_a_qr_code_to_approve_reaches_the_client_with_its_log_line(
|
||||||
|
server: SimpleNamespace, channel: str, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch
|
||||||
|
) -> None:
|
||||||
|
caplog.set_level(logging.INFO)
|
||||||
|
payload = "https://login.example/approve?code=EXAMPLE"
|
||||||
|
if channel == "polling":
|
||||||
|
monkeypatch.setattr(WebSocketChannel, "open", lambda self, timeout=0: False)
|
||||||
|
printed: list[Any] = []
|
||||||
|
monkeypatch.setattr(console, "print", lambda *a, **k: printed.extend(a))
|
||||||
|
|
||||||
|
expected = qr_text(payload).plain
|
||||||
|
|
||||||
|
def drawn() -> bool | None:
|
||||||
|
return any(getattr(p, "plain", None) == expected for p in printed) or None
|
||||||
|
|
||||||
|
def authenticate(self: StubService, cookies: Any, credential: Any) -> None:
|
||||||
|
Service.wait_for_approval(self, "Scan the EXAMPLE code", drawn, 10, 0.01, payload)
|
||||||
|
|
||||||
|
monkeypatch.setattr(StubService, "authenticate", authenticate)
|
||||||
|
service = make_client(server.url)
|
||||||
|
service._input_bridge = None
|
||||||
|
try:
|
||||||
|
service.authenticate()
|
||||||
|
assert isinstance(service.channel, WebSocketChannel if channel == "socket" else PollingChannel)
|
||||||
|
finally:
|
||||||
|
service.close()
|
||||||
|
assert "Scan the EXAMPLE code" in example_messages(caplog)
|
||||||
|
assert [p.plain for p in printed if hasattr(p, "plain")] == [qr_text(payload).plain]
|
||||||
|
|
||||||
|
|
||||||
def test_the_session_channel_carries_what_the_server_starts(
|
def test_the_session_channel_carries_what_the_server_starts(
|
||||||
server: SimpleNamespace, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch
|
server: SimpleNamespace, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch
|
||||||
) -> None:
|
) -> None:
|
||||||
@@ -447,7 +508,7 @@ def test_a_cdm_call_made_while_the_channel_is_down_goes_through_polling(
|
|||||||
|
|
||||||
|
|
||||||
def test_a_prompt_the_client_cannot_answer_fails_the_login_at_once(server: SimpleNamespace) -> None:
|
def test_a_prompt_the_client_cannot_answer_fails_the_login_at_once(server: SimpleNamespace) -> None:
|
||||||
def refuse(prompt: str) -> str:
|
def refuse(prompt: str, qr: str | None = None) -> str:
|
||||||
raise RuntimeError("the EXAMPLE caller left")
|
raise RuntimeError("the EXAMPLE caller left")
|
||||||
|
|
||||||
service = make_client(server.url)
|
service = make_client(server.url)
|
||||||
|
|||||||
@@ -172,9 +172,9 @@ def test_session_transport_keys_are_the_create_body():
|
|||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
"shape,fields",
|
"shape,fields",
|
||||||
[
|
[
|
||||||
(protocol.ChannelPrompt, {"type", "id", "prompt"}),
|
(protocol.ChannelPrompt, {"type", "id", "prompt", "qr"}),
|
||||||
(protocol.ChannelCdmCall, {"type", "id", "call"}),
|
(protocol.ChannelCdmCall, {"type", "id", "call"}),
|
||||||
(protocol.ChannelLog, {"type", "seq", "level", "message", "ts"}),
|
(protocol.ChannelLog, {"type", "seq", "level", "message", "ts", "qr"}),
|
||||||
(protocol.ChannelStatus, {"type", "status", "error"}),
|
(protocol.ChannelStatus, {"type", "status", "error"}),
|
||||||
(protocol.ChannelDrain, {"type", "draining"}),
|
(protocol.ChannelDrain, {"type", "draining"}),
|
||||||
(protocol.ChannelAnswer, {"type", "id", "response", "error"}),
|
(protocol.ChannelAnswer, {"type", "id", "response", "error"}),
|
||||||
|
|||||||
@@ -216,7 +216,7 @@ def test_a_quiet_remote_login_shows_its_last_server_lines_as_a_notice(monkeypatc
|
|||||||
from unshackle.core import remote_channel
|
from unshackle.core import remote_channel
|
||||||
|
|
||||||
shown = []
|
shown = []
|
||||||
monkeypatch.setattr(remote_channel, "show_notice", shown.append)
|
monkeypatch.setattr(remote_channel, "show_notice", lambda message, qr=None: shown.append(message))
|
||||||
monkeypatch.setattr(remote_channel, "AUTH_POLL_INTERVAL", 0)
|
monkeypatch.setattr(remote_channel, "AUTH_POLL_INTERVAL", 0)
|
||||||
logs = iter([["+ IP Region: CA"], ["+ Open URL: https://example.test/start\n+ Enter pair code: 9835-2503"], []])
|
logs = iter([["+ IP Region: CA"], ["+ Open URL: https://example.test/start\n+ Enter pair code: 9835-2503"], []])
|
||||||
statuses = iter(["authenticating", "authenticating", "authenticating", "authenticated"])
|
statuses = iter(["authenticating", "authenticating", "authenticating", "authenticated"])
|
||||||
@@ -234,7 +234,7 @@ def test_a_quiet_remote_login_shows_its_last_server_lines_as_a_notice(monkeypatc
|
|||||||
|
|
||||||
remote = object.__new__(remote_service.RemoteService)
|
remote = object.__new__(remote_service.RemoteService)
|
||||||
remote.seq = 0
|
remote.seq = 0
|
||||||
remote.client, remote._session_id, remote.auth_notice = Client(), "sid", None
|
remote.client, remote._session_id, remote.auth_notice, remote.auth_qr = Client(), "sid", None, None
|
||||||
remote.log = logging.getLogger("test")
|
remote.log = logging.getLogger("test")
|
||||||
monkeypatch.setattr(remote_service.RemoteService, "local_cdm", None)
|
monkeypatch.setattr(remote_service.RemoteService, "local_cdm", None)
|
||||||
|
|
||||||
@@ -244,11 +244,31 @@ def test_a_quiet_remote_login_shows_its_last_server_lines_as_a_notice(monkeypatc
|
|||||||
assert remote.auth_notice is None
|
assert remote.auth_notice is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_relayed_login_keeps_its_qr_code_until_the_login_ends(monkeypatch):
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from unshackle.core import remote_channel
|
||||||
|
|
||||||
|
shown = []
|
||||||
|
monkeypatch.setattr(remote_channel, "show_notice", lambda message, qr=None: shown.append(message))
|
||||||
|
monkeypatch.setattr(remote_channel, "show_qr", lambda data: pytest.fail("a relaying serve has no terminal"))
|
||||||
|
monkeypatch.setattr(remote_service.RemoteService, "local_cdm", None)
|
||||||
|
remote = object.__new__(remote_service.RemoteService)
|
||||||
|
remote.auth_notice, remote.auth_qr, remote._input_bridge = None, None, object()
|
||||||
|
remote.log = logging.getLogger("test")
|
||||||
|
messages = remote_channel.ServerMessages(remote)
|
||||||
|
messages.show_logs([{"seq": 1, "level": "INFO", "message": "Scan the code", "qr": "https://login.example/scan"}])
|
||||||
|
assert remote.auth_qr == "https://login.example/scan"
|
||||||
|
messages.login_done()
|
||||||
|
assert remote.auth_qr is None and shown == [None]
|
||||||
|
|
||||||
|
|
||||||
async def test_a_remote_login_prompt_waits_for_its_owners_answer(monkeypatch):
|
async def test_a_remote_login_prompt_waits_for_its_owners_answer(monkeypatch):
|
||||||
import threading as th
|
import threading as th
|
||||||
|
|
||||||
class Remote:
|
class Remote:
|
||||||
auth_notice = None
|
auth_notice = None
|
||||||
|
auth_qr = None
|
||||||
|
|
||||||
login = handlers.RemoteLogin("owner", "srv", "OTHER", "show", Remote())
|
login = handlers.RemoteLogin("owner", "srv", "OTHER", "show", Remote())
|
||||||
monkeypatch.setattr(handlers, "_remote_logins", {login.id: login})
|
monkeypatch.setattr(handlers, "_remote_logins", {login.id: login})
|
||||||
@@ -256,13 +276,18 @@ async def test_a_remote_login_prompt_waits_for_its_owners_answer(monkeypatch):
|
|||||||
caller = {"key": "owner"}
|
caller = {"key": "owner"}
|
||||||
monkeypatch.setattr(handlers, "caller_key", lambda request: caller["key"])
|
monkeypatch.setattr(handlers, "caller_key", lambda request: caller["key"])
|
||||||
got = []
|
got = []
|
||||||
asker = th.Thread(target=lambda: got.append(login.bridge.request_input("Enter the code sent to your email")))
|
asker = th.Thread(
|
||||||
|
target=lambda: got.append(
|
||||||
|
login.bridge.request_input("Enter the code sent to your email", qr="https://login.example/scan")
|
||||||
|
)
|
||||||
|
)
|
||||||
asker.start()
|
asker.start()
|
||||||
while login.bridge.get_pending_prompt() is None:
|
while login.bridge.get_pending_prompt() is None:
|
||||||
await asyncio.sleep(0.01)
|
await asyncio.sleep(0.01)
|
||||||
|
|
||||||
listed = json.loads((await handlers.remote_logins_handler(None)).text)["logins"]
|
listed = json.loads((await handlers.remote_logins_handler(None)).text)["logins"]
|
||||||
assert listed[0]["prompt"] == "Enter the code sent to your email"
|
assert listed[0]["prompt"] == "Enter the code sent to your email"
|
||||||
|
assert listed[0]["qr"] == "https://login.example/scan"
|
||||||
|
|
||||||
caller["key"] = "someone-else"
|
caller["key"] = "someone-else"
|
||||||
assert json.loads((await handlers.remote_logins_handler(None)).text)["logins"] == []
|
assert json.loads((await handlers.remote_logins_handler(None)).text)["logins"] == []
|
||||||
|
|||||||
@@ -156,6 +156,8 @@ class DownloadJob:
|
|||||||
input_prompt: str | None = None
|
input_prompt: str | None = None
|
||||||
# Message a service shows through show_notice() while it waits for an approval; needs no answer.
|
# Message a service shows through show_notice() while it waits for an approval; needs no answer.
|
||||||
notice: str | None = None
|
notice: str | None = None
|
||||||
|
# Text of the QR code that goes with input_prompt or notice.
|
||||||
|
qr: str | None = None
|
||||||
|
|
||||||
# Subtitles skipped under skip_subtitle_errors (non-fatal). Each entry is a dl.SkippedSubtitle
|
# 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.
|
# dict (id / language / title) so a client can report which weren't available.
|
||||||
@@ -196,6 +198,7 @@ class DownloadJob:
|
|||||||
"skipped_titles": self.skipped_titles,
|
"skipped_titles": self.skipped_titles,
|
||||||
"input_prompt": self.input_prompt,
|
"input_prompt": self.input_prompt,
|
||||||
"notice": self.notice,
|
"notice": self.notice,
|
||||||
|
"qr": self.qr,
|
||||||
}
|
}
|
||||||
|
|
||||||
if include_full_details:
|
if include_full_details:
|
||||||
@@ -952,6 +955,8 @@ class DownloadQueueManager:
|
|||||||
job.input_prompt = progress_data["input_prompt"]
|
job.input_prompt = progress_data["input_prompt"]
|
||||||
if "notice" in progress_data:
|
if "notice" in progress_data:
|
||||||
job.notice = progress_data["notice"]
|
job.notice = progress_data["notice"]
|
||||||
|
if "qr" in progress_data:
|
||||||
|
job.qr = progress_data["qr"]
|
||||||
if progress_data.get("skipped_subtitles"):
|
if progress_data.get("skipped_subtitles"):
|
||||||
job.skipped_subtitles = progress_data["skipped_subtitles"]
|
job.skipped_subtitles = progress_data["skipped_subtitles"]
|
||||||
if progress_data.get("skipped_titles"):
|
if progress_data.get("skipped_titles"):
|
||||||
@@ -1045,6 +1050,7 @@ class DownloadQueueManager:
|
|||||||
self._download_processes.pop(job.job_id, None)
|
self._download_processes.pop(job.job_id, None)
|
||||||
job.input_prompt = None
|
job.input_prompt = None
|
||||||
job.notice = None
|
job.notice = None
|
||||||
|
job.qr = None
|
||||||
|
|
||||||
temp_paths = self._job_temp_files.pop(job.job_id, {})
|
temp_paths = self._job_temp_files.pop(job.job_id, {})
|
||||||
for path in temp_paths.values():
|
for path in temp_paths.values():
|
||||||
|
|||||||
@@ -68,6 +68,7 @@ def relay_prompts(progress_callback: Callable[[dict[str, Any]], None]) -> None:
|
|||||||
uses unbuffered stdin: a daemon thread blocked in ``sys.stdin.buffer`` aborts the interpreter at shutdown.
|
uses unbuffered stdin: a daemon thread blocked in ``sys.stdin.buffer`` aborts the interpreter at shutdown.
|
||||||
Prompts go out one at a time, and a prompt discards answers that arrived before it, such as a late
|
Prompts go out one at a time, and a prompt discards answers that arrived before it, such as a late
|
||||||
answer to a prompt that timed out. A show_notice() message goes out as ``notice`` progress and needs no answer.
|
answer to a prompt that timed out. A show_notice() message goes out as ``notice`` progress and needs no answer.
|
||||||
|
The QR code text of a prompt or notice goes out with it as ``qr``.
|
||||||
"""
|
"""
|
||||||
answers: queue.Queue[str] = queue.Queue()
|
answers: queue.Queue[str] = queue.Queue()
|
||||||
one_prompt = threading.Lock()
|
one_prompt = threading.Lock()
|
||||||
@@ -78,11 +79,11 @@ def relay_prompts(progress_callback: Callable[[dict[str, Any]], None]) -> None:
|
|||||||
|
|
||||||
threading.Thread(target=read_answers, name="prompt-answers", daemon=True).start()
|
threading.Thread(target=read_answers, name="prompt-answers", daemon=True).start()
|
||||||
|
|
||||||
def ask(prompt: str) -> str:
|
def ask(prompt: str, qr: str | None) -> str:
|
||||||
with one_prompt:
|
with one_prompt:
|
||||||
while not answers.empty():
|
while not answers.empty():
|
||||||
answers.get_nowait()
|
answers.get_nowait()
|
||||||
progress_callback({"input_prompt": prompt})
|
progress_callback({"input_prompt": prompt, "qr": qr})
|
||||||
try:
|
try:
|
||||||
return answers.get(timeout=AUTH_INPUT_TIMEOUT)
|
return answers.get(timeout=AUTH_INPUT_TIMEOUT)
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
@@ -92,10 +93,10 @@ def relay_prompts(progress_callback: Callable[[dict[str, Any]], None]) -> None:
|
|||||||
APIErrorCode.AUTH_FAILED,
|
APIErrorCode.AUTH_FAILED,
|
||||||
) from None
|
) from None
|
||||||
finally:
|
finally:
|
||||||
progress_callback({"input_prompt": None})
|
progress_callback({"input_prompt": None, "qr": None})
|
||||||
|
|
||||||
set_prompt_handler(ask)
|
set_prompt_handler(ask)
|
||||||
set_notice_handler(lambda message: progress_callback({"notice": message}))
|
set_notice_handler(lambda message, qr: progress_callback({"notice": message, "qr": qr}))
|
||||||
|
|
||||||
|
|
||||||
def apply_payload_speed_limit(payload: dict[str, Any]) -> None:
|
def apply_payload_speed_limit(payload: dict[str, Any]) -> None:
|
||||||
|
|||||||
@@ -479,20 +479,24 @@ _remote_logins: dict[str, RemoteLogin] = {}
|
|||||||
|
|
||||||
|
|
||||||
async def remote_logins_handler(request: web.Request) -> web.Response:
|
async def remote_logins_handler(request: web.Request) -> web.Response:
|
||||||
"""Answer the request for the caller's remote logins in progress, each with its prompt and notice."""
|
"""Answer the request for the caller's remote logins in progress, each with its prompt, notice and QR code."""
|
||||||
owner, admin = caller_key(request), request_policy(request).admin
|
owner, admin = caller_key(request), request_policy(request).admin
|
||||||
logins = [
|
logins = []
|
||||||
|
for entry in list(_remote_logins.values()):
|
||||||
|
if not (admin or entry.owner == owner):
|
||||||
|
continue
|
||||||
|
ask = entry.bridge.get_pending_ask()
|
||||||
|
logins.append(
|
||||||
{
|
{
|
||||||
"id": login.id,
|
"id": entry.id,
|
||||||
"remote": login.remote,
|
"remote": entry.remote,
|
||||||
"service": login.service,
|
"service": entry.service,
|
||||||
"title_id": login.title_id,
|
"title_id": entry.title_id,
|
||||||
"prompt": login.bridge.get_pending_prompt(),
|
"prompt": ask.prompt if ask else None,
|
||||||
"notice": login.instance.auth_notice,
|
"notice": entry.instance.auth_notice,
|
||||||
|
"qr": ask.qr if ask else entry.instance.auth_qr,
|
||||||
}
|
}
|
||||||
for login in list(_remote_logins.values())
|
)
|
||||||
if admin or login.owner == owner
|
|
||||||
]
|
|
||||||
return web.json_response({"logins": logins})
|
return web.json_response({"logins": logins})
|
||||||
|
|
||||||
|
|
||||||
@@ -3368,10 +3372,11 @@ async def session_prompt_get_handler(session_id: str, request: web.Request | Non
|
|||||||
if session.auth_status == AuthStatus.FAILED:
|
if session.auth_status == AuthStatus.FAILED:
|
||||||
return web.json_response(PromptReply(status=AuthStatus.FAILED, error=session.auth_error or "unknown error"))
|
return web.json_response(PromptReply(status=AuthStatus.FAILED, error=session.auth_error or "unknown error"))
|
||||||
|
|
||||||
if bridge:
|
if bridge and (ask := bridge.get_pending_ask()) and ask.prompt:
|
||||||
prompt = bridge.get_pending_prompt()
|
reply = PromptReply(status=AuthStatus.PENDING_INPUT, prompt=ask.prompt)
|
||||||
if prompt:
|
if ask.qr:
|
||||||
return web.json_response(PromptReply(status=AuthStatus.PENDING_INPUT, prompt=prompt))
|
reply["qr"] = ask.qr
|
||||||
|
return web.json_response(reply)
|
||||||
|
|
||||||
return web.json_response(PromptReply(status=AuthStatus.AUTHENTICATING))
|
return web.json_response(PromptReply(status=AuthStatus.AUTHENTICATING))
|
||||||
|
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ class Ask:
|
|||||||
id: str
|
id: str
|
||||||
prompt: str
|
prompt: str
|
||||||
cdm_call: dict[str, Any] | None = None
|
cdm_call: dict[str, Any] | None = None
|
||||||
|
qr: str | None = None
|
||||||
owner: str | None = None # CHANNEL or POLL: the path that carried the ask, and the only one that answers it
|
owner: str | None = None # CHANNEL or POLL: the path that carried the ask, and the only one that answers it
|
||||||
response: str | None = None
|
response: str | None = None
|
||||||
error: str | None = None # the client could not answer, and says why
|
error: str | None = None # the client could not answer, and says why
|
||||||
@@ -62,18 +63,18 @@ class InputBridge:
|
|||||||
_cancelled: bool = field(default=False, init=False, repr=False)
|
_cancelled: bool = field(default=False, init=False, repr=False)
|
||||||
_lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False)
|
_lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False)
|
||||||
|
|
||||||
def _open(self, prompt: str, cdm_call: dict[str, Any] | None = None) -> Ask:
|
def _open(self, prompt: str, cdm_call: dict[str, Any] | None = None, qr: str | None = None) -> Ask:
|
||||||
"""Register an ask and offer it to the attached channel; call it with the lock held."""
|
"""Register an ask and offer it to the attached channel; call it with the lock held."""
|
||||||
if self._cancelled:
|
if self._cancelled:
|
||||||
raise RuntimeError("Session was cancelled")
|
raise RuntimeError("Session was cancelled")
|
||||||
ask = Ask(uuid.uuid4().hex, prompt, cdm_call)
|
ask = Ask(uuid.uuid4().hex, prompt, cdm_call, qr)
|
||||||
if self.channel is not None and self.channel.offer(ask):
|
if self.channel is not None and self.channel.offer(ask):
|
||||||
ask.owner = CHANNEL
|
ask.owner = CHANNEL
|
||||||
ask.picked_up.set()
|
ask.picked_up.set()
|
||||||
self._asks[ask.id] = ask
|
self._asks[ask.id] = ask
|
||||||
return ask
|
return ask
|
||||||
|
|
||||||
def request_input(self, prompt: str, timeout: float = AUTH_INPUT_TIMEOUT) -> str:
|
def request_input(self, prompt: str, timeout: float = AUTH_INPUT_TIMEOUT, qr: str | None = None) -> str:
|
||||||
"""Block until the remote client submits a response for *prompt*.
|
"""Block until the remote client submits a response for *prompt*.
|
||||||
|
|
||||||
After authentication only an attached session channel can carry a prompt, as a polling client stops
|
After authentication only an attached session channel can carry a prompt, as a polling client stops
|
||||||
@@ -88,7 +89,7 @@ class InputBridge:
|
|||||||
if self._cancelled:
|
if self._cancelled:
|
||||||
raise RuntimeError("Session was cancelled")
|
raise RuntimeError("Session was cancelled")
|
||||||
raise RuntimeError(f"Remote mode cannot relay a prompt after authentication: {prompt}")
|
raise RuntimeError(f"Remote mode cannot relay a prompt after authentication: {prompt}")
|
||||||
ask = self._open(prompt)
|
ask = self._open(prompt, qr=qr)
|
||||||
try:
|
try:
|
||||||
# cancel() and an answer both set the event, so a single wait returns on signal-or-cancel
|
# cancel() and an answer both set the event, so a single wait returns on signal-or-cancel
|
||||||
if not ask.answered.wait(timeout=timeout):
|
if not ask.answered.wait(timeout=timeout):
|
||||||
@@ -159,12 +160,16 @@ class InputBridge:
|
|||||||
|
|
||||||
def get_pending_prompt(self) -> str | None:
|
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."""
|
"""Return the prompt of the first ask the prompt routes can serve, and keep that ask on them."""
|
||||||
|
ask = self.get_pending_ask()
|
||||||
|
return ask.prompt if ask else None
|
||||||
|
|
||||||
|
def get_pending_ask(self) -> Ask | None:
|
||||||
|
"""Return the first ask the prompt routes can serve, and keep that ask on them."""
|
||||||
with self._lock:
|
with self._lock:
|
||||||
ask = next(iter(self._pollable()), None)
|
ask = next(iter(self._pollable()), None)
|
||||||
if ask is None:
|
if ask is not None:
|
||||||
return None
|
|
||||||
ask.owner = POLL
|
ask.owner = POLL
|
||||||
return ask.prompt
|
return ask
|
||||||
|
|
||||||
def submit_response(self, response: str) -> bool:
|
def submit_response(self, response: str) -> bool:
|
||||||
"""Answer the oldest ask that the prompt routes served, else the oldest one they can serve.
|
"""Answer the oldest ask that the prompt routes served, else the oldest one they can serve.
|
||||||
@@ -257,7 +262,7 @@ NO_USER_MESSAGE = "This login needs the user, and only a download job or a remot
|
|||||||
class NoUserBridge(InputBridge):
|
class NoUserBridge(InputBridge):
|
||||||
"""Bridge for a request with no channel to the user: a login step that needs the user fails at once."""
|
"""Bridge for a request with no channel to the user: a login step that needs the user fails at once."""
|
||||||
|
|
||||||
def request_input(self, prompt: str, timeout: float = AUTH_INPUT_TIMEOUT) -> str:
|
def request_input(self, prompt: str, timeout: float = AUTH_INPUT_TIMEOUT, qr: str | None = None) -> str:
|
||||||
raise coded(RuntimeError(NO_USER_MESSAGE), APIErrorCode.AUTH_FAILED)
|
raise coded(RuntimeError(NO_USER_MESSAGE), APIErrorCode.AUTH_FAILED)
|
||||||
|
|
||||||
def ensure_active(self) -> None:
|
def ensure_active(self) -> None:
|
||||||
|
|||||||
@@ -1576,7 +1576,8 @@ async def download_job_input(request: web.Request) -> web.Response:
|
|||||||
Submit the answer to the prompt a running job waits on (an OTP code, a PIN, a device-code
|
Submit the answer to the prompt a running job waits on (an OTP code, a PIN, a device-code
|
||||||
confirmation). The job shows the prompt in its `input_prompt` field and in its SSE `progress`
|
confirmation). The job shows the prompt in its `input_prompt` field and in its SSE `progress`
|
||||||
events. The job fails if nobody answers within the prompt timeout. A job that waits for an
|
events. The job fails if nobody answers within the prompt timeout. A job that waits for an
|
||||||
approval on another device shows the message in its `notice` field, which takes no answer.
|
approval on another device shows the message in its `notice` field, which takes no answer. A login
|
||||||
|
to scan with a phone also sets `qr` to the text of the QR code.
|
||||||
parameters:
|
parameters:
|
||||||
- name: job_id
|
- name: job_id
|
||||||
in: path
|
in: path
|
||||||
@@ -3436,6 +3437,10 @@ async def remote_logins(request: web.Request) -> web.Response:
|
|||||||
notice:
|
notice:
|
||||||
type: string
|
type: string
|
||||||
nullable: true
|
nullable: true
|
||||||
|
qr:
|
||||||
|
type: string
|
||||||
|
nullable: true
|
||||||
|
description: The text of a QR code to scan with the prompt or notice, or null
|
||||||
"""
|
"""
|
||||||
return await remote_logins_handler(request)
|
return await remote_logins_handler(request)
|
||||||
|
|
||||||
|
|||||||
@@ -153,7 +153,10 @@ def log_message(record: LogRecord) -> ChannelLog:
|
|||||||
def ask_message(ask: Ask) -> ChannelPrompt | ChannelCdmCall:
|
def ask_message(ask: Ask) -> ChannelPrompt | ChannelCdmCall:
|
||||||
if ask.cdm_call is not None:
|
if ask.cdm_call is not None:
|
||||||
return ChannelCdmCall(type=ChannelMessage.CDM_CALL, id=ask.id, call=ask.cdm_call)
|
return ChannelCdmCall(type=ChannelMessage.CDM_CALL, id=ask.id, call=ask.cdm_call)
|
||||||
return ChannelPrompt(type=ChannelMessage.PROMPT, id=ask.id, prompt=ask.prompt)
|
message = ChannelPrompt(type=ChannelMessage.PROMPT, id=ask.id, prompt=ask.prompt)
|
||||||
|
if ask.qr:
|
||||||
|
message["qr"] = ask.qr
|
||||||
|
return message
|
||||||
|
|
||||||
|
|
||||||
def receive(text: str, bridge: Any) -> None:
|
def receive(text: str, bridge: Any) -> None:
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ class SessionLogBuffer:
|
|||||||
self._lock = threading.Lock()
|
self._lock = threading.Lock()
|
||||||
self.listener: Callable[[LogRecord], None] | None = None
|
self.listener: Callable[[LogRecord], None] | None = None
|
||||||
|
|
||||||
def append(self, level: int, message: str) -> None:
|
def append(self, level: int, message: str, qr: str | None = None) -> None:
|
||||||
with self._lock:
|
with self._lock:
|
||||||
self._seq += 1
|
self._seq += 1
|
||||||
record = LogRecord(
|
record = LogRecord(
|
||||||
@@ -49,6 +49,8 @@ class SessionLogBuffer:
|
|||||||
message=sanitize_log(message)[:MAX_MESSAGE_LEN],
|
message=sanitize_log(message)[:MAX_MESSAGE_LEN],
|
||||||
ts=time.time(),
|
ts=time.time(),
|
||||||
)
|
)
|
||||||
|
if qr:
|
||||||
|
record["qr"] = qr
|
||||||
self._records.append(record)
|
self._records.append(record)
|
||||||
if self.listener is not None:
|
if self.listener is not None:
|
||||||
self.listener(record)
|
self.listener(record)
|
||||||
@@ -96,7 +98,8 @@ class SessionLogMirror(logging.LoggerAdapter):
|
|||||||
if isinstance(exc_info, tuple) and exc_info[1] is not None:
|
if isinstance(exc_info, tuple) and exc_info[1] is not None:
|
||||||
cause = "".join(traceback.format_exception_only(exc_info[0], exc_info[1])).strip()
|
cause = "".join(traceback.format_exception_only(exc_info[0], exc_info[1])).strip()
|
||||||
message = f"{message} | {cause}"
|
message = f"{message} | {cause}"
|
||||||
self.buffer.append(level, message)
|
qr = (kwargs.get("extra") or {}).get("qr")
|
||||||
|
self.buffer.append(level, message, qr if isinstance(qr, str) else None)
|
||||||
super().log(level, msg, *args, **kwargs)
|
super().log(level, msg, *args, **kwargs)
|
||||||
|
|
||||||
def process(self, msg: Any, kwargs: MutableMapping[str, Any]) -> tuple[Any, MutableMapping[str, Any]]:
|
def process(self, msg: Any, kwargs: MutableMapping[str, Any]) -> tuple[Any, MutableMapping[str, Any]]:
|
||||||
|
|||||||
+47
-10
@@ -514,38 +514,75 @@ def print_listing(renderable: RenderableType) -> None:
|
|||||||
console.print(Padding(renderable, (0, 5)))
|
console.print(Padding(renderable, (0, 5)))
|
||||||
|
|
||||||
|
|
||||||
_prompt_handler: Callable[[str], str] | None = None
|
_prompt_handler: Callable[[str, str | None], str] | None = None
|
||||||
|
|
||||||
|
|
||||||
def set_prompt_handler(handler: Callable[[str], str] | None) -> None:
|
def set_prompt_handler(handler: Callable[[str, str | None], str] | None) -> None:
|
||||||
"""Route every :func:`prompt_user` call to *handler*, for a process with no terminal to prompt on."""
|
"""Route every :func:`prompt_user` call to *handler*, for a process with no terminal to prompt on."""
|
||||||
global _prompt_handler
|
global _prompt_handler
|
||||||
_prompt_handler = handler
|
_prompt_handler = handler
|
||||||
|
|
||||||
|
|
||||||
def prompt_user(prompt: str) -> str:
|
def qr_text(data: str, indent: int = 5) -> Text:
|
||||||
"""Ask the user for input on the shared console, themed and indented like the rest of the output."""
|
"""Draw *data* as a QR code in half blocks, dark on light whatever the theme, so a phone camera reads it."""
|
||||||
|
import segno
|
||||||
|
|
||||||
|
rows = [list(row) for row in segno.make_qr(data).matrix_iter(border=2)]
|
||||||
|
if len(rows) % 2:
|
||||||
|
rows.append([False] * len(rows[0]))
|
||||||
|
blocks = {(True, True): "\u2588", (True, False): "\u2580", (False, True): "\u2584", (False, False): " "}
|
||||||
|
text = Text()
|
||||||
|
for top, bottom in zip(rows[::2], rows[1::2], strict=True):
|
||||||
|
text.append(" " * indent)
|
||||||
|
text.append("".join(blocks[bool(t), bool(b)] for t, b in zip(top, bottom, strict=True)), style="black on white")
|
||||||
|
text.append("\n")
|
||||||
|
return text
|
||||||
|
|
||||||
|
|
||||||
|
def show_qr(data: str) -> None:
|
||||||
|
"""Draw *data* as a QR code on the shared console, unless a prompt handler stands in for the terminal.
|
||||||
|
|
||||||
|
Text longer than a QR code holds draws nothing: the prompt or notice beside it still shows.
|
||||||
|
"""
|
||||||
|
from segno import DataOverflowError
|
||||||
|
|
||||||
if _prompt_handler is not None:
|
if _prompt_handler is not None:
|
||||||
return _prompt_handler(prompt)
|
return
|
||||||
|
try:
|
||||||
|
text = qr_text(data)
|
||||||
|
except DataOverflowError:
|
||||||
|
return
|
||||||
|
console.print(text, no_wrap=True, overflow="ignore", crop=False)
|
||||||
|
|
||||||
|
|
||||||
|
def prompt_user(prompt: str, qr: str | None = None) -> str:
|
||||||
|
"""Ask the user for input on the shared console, themed and indented like the rest of the output.
|
||||||
|
|
||||||
|
*qr* is drawn above the prompt as a QR code, for a login the user scans on a phone.
|
||||||
|
"""
|
||||||
|
if _prompt_handler is not None:
|
||||||
|
return _prompt_handler(prompt, qr)
|
||||||
|
if qr:
|
||||||
|
show_qr(qr)
|
||||||
indent = " " * 5
|
indent = " " * 5
|
||||||
body = Text(indent + prompt.rstrip("\n ").replace("\n", "\n" + indent), style="text")
|
body = Text(indent + prompt.rstrip("\n ").replace("\n", "\n" + indent), style="text")
|
||||||
body.append("\n" + indent + "> ", style="rule.text")
|
body.append("\n" + indent + "> ", style="rule.text")
|
||||||
return console.input(body)
|
return console.input(body)
|
||||||
|
|
||||||
|
|
||||||
_notice_handler: Callable[[str | None], None] | None = None
|
_notice_handler: Callable[[str | None, str | None], None] | None = None
|
||||||
|
|
||||||
|
|
||||||
def set_notice_handler(handler: Callable[[str | None], None] | None) -> None:
|
def set_notice_handler(handler: Callable[[str | None, str | None], None] | None) -> None:
|
||||||
"""Route every :func:`show_notice` call to *handler*, for a process whose log output no user reads."""
|
"""Route every :func:`show_notice` call to *handler*, for a process whose log output no user reads."""
|
||||||
global _notice_handler
|
global _notice_handler
|
||||||
_notice_handler = handler
|
_notice_handler = handler
|
||||||
|
|
||||||
|
|
||||||
def show_notice(message: str | None) -> None:
|
def show_notice(message: str | None, qr: str | None = None) -> None:
|
||||||
"""Give *message* to the notice handler, or None to clear it. Without a handler this does nothing."""
|
"""Give *message* and its QR code text to the notice handler, or None to clear it. Without a handler this does nothing."""
|
||||||
if _notice_handler is not None:
|
if _notice_handler is not None:
|
||||||
_notice_handler(message)
|
_notice_handler(message, qr)
|
||||||
|
|
||||||
|
|
||||||
__all__ = (
|
__all__ = (
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ import aiohttp
|
|||||||
import requests
|
import requests
|
||||||
from aiohttp import WSMsgType
|
from aiohttp import WSMsgType
|
||||||
|
|
||||||
from unshackle.core.console import prompt_user, show_notice
|
from unshackle.core.console import prompt_user, show_notice, show_qr
|
||||||
from unshackle.core.remote_protocol import (
|
from unshackle.core.remote_protocol import (
|
||||||
CHANNEL_ROUTE,
|
CHANNEL_ROUTE,
|
||||||
CHANNEL_SESSION_GONE,
|
CHANNEL_SESSION_GONE,
|
||||||
@@ -61,6 +61,11 @@ KEPT_ANSWERS = 64
|
|||||||
LEVELS = logging.getLevelNamesMapping()
|
LEVELS = logging.getLevelNamesMapping()
|
||||||
|
|
||||||
|
|
||||||
|
def server_qr(value: object) -> str | None:
|
||||||
|
"""The QR code text the server sent, or None when it is not text."""
|
||||||
|
return value if isinstance(value, str) and value else None
|
||||||
|
|
||||||
|
|
||||||
class ServerMessages:
|
class ServerMessages:
|
||||||
"""What this client does with each message the server starts, whichever adapter brought it."""
|
"""What this client does with each message the server starts, whichever adapter brought it."""
|
||||||
|
|
||||||
@@ -86,6 +91,10 @@ class ServerMessages:
|
|||||||
continue
|
continue
|
||||||
message = sanitize_log(record.get("message", ""), keep_lines=True)
|
message = sanitize_log(record.get("message", ""), keep_lines=True)
|
||||||
self.service.log.log(LEVELS.get(str(record.get("level", "INFO")), logging.INFO), message)
|
self.service.log.log(LEVELS.get(str(record.get("level", "INFO")), logging.INFO), message)
|
||||||
|
if qr := server_qr(record.get("qr")):
|
||||||
|
self.service.auth_qr = qr
|
||||||
|
if self.service._input_bridge is None:
|
||||||
|
show_qr(qr)
|
||||||
self.recent_logs.append(message.strip())
|
self.recent_logs.append(message.strip())
|
||||||
self.log_seq = seq
|
self.log_seq = seq
|
||||||
|
|
||||||
@@ -100,14 +109,15 @@ class ServerMessages:
|
|||||||
)
|
)
|
||||||
return answer
|
return answer
|
||||||
|
|
||||||
def ask_user(self, prompt: str) -> str:
|
def ask_user(self, prompt: str, qr: object = None) -> str:
|
||||||
"""Ask the user the server's prompt, with control characters stripped as the server text can hold any."""
|
"""Ask the user the server's prompt, with control characters stripped as the server text can hold any."""
|
||||||
from unshackle.core.api.sanitize import sanitize_log
|
from unshackle.core.api.sanitize import sanitize_log
|
||||||
|
|
||||||
prompt = sanitize_log(prompt, keep_lines=True)
|
prompt = sanitize_log(prompt, keep_lines=True)
|
||||||
|
code = server_qr(qr)
|
||||||
bridge = self.service._input_bridge
|
bridge = self.service._input_bridge
|
||||||
try:
|
try:
|
||||||
return str(bridge.request_input(prompt) if bridge else prompt_user(prompt))
|
return str(bridge.request_input(prompt, qr=code) if bridge else prompt_user(prompt, code))
|
||||||
except EOFError:
|
except EOFError:
|
||||||
raise RemoteError("Remote auth needs interactive input but stdin is closed", ClientErrorKind.AUTH) from None
|
raise RemoteError("Remote auth needs interactive input but stdin is closed", ClientErrorKind.AUTH) from None
|
||||||
|
|
||||||
@@ -117,7 +127,7 @@ class ServerMessages:
|
|||||||
notice = "\n".join(self.recent_logs)
|
notice = "\n".join(self.recent_logs)
|
||||||
if notice != self.service.auth_notice:
|
if notice != self.service.auth_notice:
|
||||||
self.service.auth_notice = notice
|
self.service.auth_notice = notice
|
||||||
show_notice(notice)
|
show_notice(notice, self.service.auth_qr)
|
||||||
|
|
||||||
def close_cdm_sessions(self) -> None:
|
def close_cdm_sessions(self) -> None:
|
||||||
"""Close the local CDM sessions that the server's calls opened; best effort."""
|
"""Close the local CDM sessions that the server's calls opened; best effort."""
|
||||||
@@ -130,8 +140,8 @@ class ServerMessages:
|
|||||||
|
|
||||||
def login_done(self) -> None:
|
def login_done(self) -> None:
|
||||||
self.close_cdm_sessions()
|
self.close_cdm_sessions()
|
||||||
if self.service.auth_notice is not None:
|
if self.service.auth_notice is not None or self.service.auth_qr is not None:
|
||||||
self.service.auth_notice = None
|
self.service.auth_notice = self.service.auth_qr = None
|
||||||
show_notice(None)
|
show_notice(None)
|
||||||
|
|
||||||
|
|
||||||
@@ -184,7 +194,7 @@ class PollingChannel:
|
|||||||
if status == AuthStatus.PENDING_INPUT and isinstance(resp.get("cdm_call"), dict):
|
if status == AuthStatus.PENDING_INPUT and isinstance(resp.get("cdm_call"), dict):
|
||||||
self.answer(json.dumps(self.messages.answer_cdm(resp["cdm_call"])))
|
self.answer(json.dumps(self.messages.answer_cdm(resp["cdm_call"])))
|
||||||
elif status == AuthStatus.PENDING_INPUT:
|
elif status == AuthStatus.PENDING_INPUT:
|
||||||
self.answer(self.messages.ask_user(resp.get("prompt") or "Enter input: "))
|
self.answer(self.messages.ask_user(resp.get("prompt") or "Enter input: ", resp.get("qr")))
|
||||||
else:
|
else:
|
||||||
time.sleep(AUTH_POLL_INTERVAL)
|
time.sleep(AUTH_POLL_INTERVAL)
|
||||||
return False
|
return False
|
||||||
@@ -414,7 +424,7 @@ class WebSocketChannel:
|
|||||||
if cdm_call:
|
if cdm_call:
|
||||||
answer["response"] = json.dumps(self.messages.answer_cdm(data.get("call") or {}))
|
answer["response"] = json.dumps(self.messages.answer_cdm(data.get("call") or {}))
|
||||||
else:
|
else:
|
||||||
answer["response"] = self.messages.ask_user(str(data.get("prompt") or "Enter input: "))
|
answer["response"] = self.messages.ask_user(str(data.get("prompt") or "Enter input: "), data.get("qr"))
|
||||||
except (Exception, RemoteError) as e: # an unanswered ask would hold the service thread until it times out
|
except (Exception, RemoteError) as e: # an unanswered ask would hold the service thread until it times out
|
||||||
if isinstance(e, RemoteError):
|
if isinstance(e, RemoteError):
|
||||||
self.failure = e
|
self.failure = e
|
||||||
|
|||||||
@@ -227,6 +227,7 @@ class PromptReply(TypedDict, total=False):
|
|||||||
|
|
||||||
status: str
|
status: str
|
||||||
prompt: str | None
|
prompt: str | None
|
||||||
|
qr: str
|
||||||
cdm_call: dict[str, Any]
|
cdm_call: dict[str, Any]
|
||||||
error: str
|
error: str
|
||||||
|
|
||||||
@@ -236,10 +237,13 @@ class PromptAnswer(TypedDict):
|
|||||||
|
|
||||||
|
|
||||||
class LogRecord(TypedDict):
|
class LogRecord(TypedDict):
|
||||||
|
"""One service log record; ``qr`` is the text of a QR code the client draws below the message."""
|
||||||
|
|
||||||
seq: int
|
seq: int
|
||||||
level: str
|
level: str
|
||||||
message: str
|
message: str
|
||||||
ts: float
|
ts: float
|
||||||
|
qr: NotRequired[str]
|
||||||
|
|
||||||
|
|
||||||
class LogsReply(TypedDict):
|
class LogsReply(TypedDict):
|
||||||
@@ -274,11 +278,12 @@ class ChannelMessage(StrEnum):
|
|||||||
|
|
||||||
|
|
||||||
class ChannelPrompt(TypedDict):
|
class ChannelPrompt(TypedDict):
|
||||||
"""A prompt for the user; the answer names its ``id``."""
|
"""A prompt for the user; the answer names its ``id``. ``qr`` is the text of a QR code to draw with it."""
|
||||||
|
|
||||||
type: str
|
type: str
|
||||||
id: str
|
id: str
|
||||||
prompt: str
|
prompt: str
|
||||||
|
qr: NotRequired[str]
|
||||||
|
|
||||||
|
|
||||||
class ChannelCdmCall(TypedDict):
|
class ChannelCdmCall(TypedDict):
|
||||||
|
|||||||
@@ -890,6 +890,7 @@ class RemoteService(TitleSource):
|
|||||||
self._input_bridge: Any = None # a serve relaying for a REST client sets one, as it does for a Service
|
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
|
# what a login waiting on the user (a pair code, an approval link) last showed; None otherwise
|
||||||
self.auth_notice: str | None = None
|
self.auth_notice: str | None = None
|
||||||
|
self.auth_qr: str | None = None
|
||||||
self._reopen_lock = Lock()
|
self._reopen_lock = Lock()
|
||||||
self._current_title: Title_T | None = None
|
self._current_title: Title_T | None = None
|
||||||
# client title and track id -> the id a reopened session gave the same title or track
|
# client title and track id -> the id a reopened session gave the same title or track
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ from rich.rule import Rule
|
|||||||
|
|
||||||
from unshackle.core.cacher import Cacher
|
from unshackle.core.cacher import Cacher
|
||||||
from unshackle.core.config import config
|
from unshackle.core.config import config
|
||||||
from unshackle.core.console import console, prompt_user, show_notice
|
from unshackle.core.console import console, prompt_user, show_notice, show_qr
|
||||||
from unshackle.core.credential import Credential
|
from unshackle.core.credential import Credential
|
||||||
from unshackle.core.launch import launch_keys
|
from unshackle.core.launch import launch_keys
|
||||||
from unshackle.core.proxies.basic import Basic
|
from unshackle.core.proxies.basic import Basic
|
||||||
@@ -467,19 +467,20 @@ class Service(TitleSource):
|
|||||||
# Store credential for cache key generation
|
# Store credential for cache key generation
|
||||||
self.credential = credential
|
self.credential = credential
|
||||||
|
|
||||||
def request_input(self, prompt: str) -> str:
|
def request_input(self, prompt: str, qr: str | None = None) -> str:
|
||||||
"""Request interactive input from the user.
|
"""Request interactive input from the user.
|
||||||
|
|
||||||
Locally, prompts through the shared rich console so the prompt renders alongside
|
Locally, prompts through the shared rich console so the prompt renders alongside
|
||||||
Live progress. A remote-dl session relays it through its :class:`InputBridge`, and a
|
Live progress. A remote-dl session relays it through its :class:`InputBridge`, and a
|
||||||
REST download job relays it through ``prompt_user`` to the job's ``input_prompt``.
|
REST download job relays it through ``prompt_user`` to the job's ``input_prompt``.
|
||||||
|
*qr* is the text of a QR code for the user to scan; the terminal that asks the user draws it.
|
||||||
"""
|
"""
|
||||||
if self._input_bridge is not None:
|
if self._input_bridge is not None:
|
||||||
return self._input_bridge.request_input(prompt)
|
return self._input_bridge.request_input(prompt, qr=qr)
|
||||||
return prompt_user(prompt)
|
return prompt_user(prompt, qr)
|
||||||
|
|
||||||
def wait_for_approval(
|
def wait_for_approval(
|
||||||
self, message: str, check: Callable[[], T | None], timeout: float, interval: float = 3.0
|
self, message: str, check: Callable[[], T | None], timeout: float, interval: float = 3.0, qr: str | None = None
|
||||||
) -> T:
|
) -> T:
|
||||||
"""Show ``message``, then call ``check`` until it returns a value.
|
"""Show ``message``, then call ``check`` until it returns a value.
|
||||||
|
|
||||||
@@ -487,9 +488,12 @@ class Service(TitleSource):
|
|||||||
``check`` returns None while the approval is pending, and must return within a few
|
``check`` returns None while the approval is pending, and must return within a few
|
||||||
seconds. Raises TimeoutError after ``timeout`` seconds, and RuntimeError when the
|
seconds. Raises TimeoutError after ``timeout`` seconds, and RuntimeError when the
|
||||||
remote session no longer exists. A REST download job shows ``message`` as its ``notice``.
|
remote session no longer exists. A REST download job shows ``message`` as its ``notice``.
|
||||||
|
*qr* is the text of a QR code for the user to scan; a remote client gets it with the log record of ``message``.
|
||||||
"""
|
"""
|
||||||
self.log.info(message)
|
self.log.info(message, extra={"qr": qr})
|
||||||
show_notice(message)
|
if qr and self._input_bridge is None:
|
||||||
|
show_qr(qr)
|
||||||
|
show_notice(message, qr)
|
||||||
deadline = time.monotonic() + timeout
|
deadline = time.monotonic() + timeout
|
||||||
try:
|
try:
|
||||||
while True:
|
while True:
|
||||||
|
|||||||
@@ -31,10 +31,10 @@ class EXAMPLE(Service):
|
|||||||
every framework feature in one place. Music is the one exception: it has its
|
every framework feature in one place. Music is the one exception: it has its
|
||||||
own reference service, MUSIC_EXAMPLE.
|
own reference service, MUSIC_EXAMPLE.
|
||||||
|
|
||||||
Version: 2.1.0
|
Version: 2.2.0
|
||||||
Author: sp4rk.y
|
Author: sp4rk.y
|
||||||
Date: 2026-08-23
|
Date: 2026-11-26
|
||||||
Authorization: Cookies + Credentials
|
Authorization: Cookies, Credentials or a QR code scanned in the app
|
||||||
Geofence: US, UK
|
Geofence: US, UK
|
||||||
Robustness:
|
Robustness:
|
||||||
Widevine:
|
Widevine:
|
||||||
@@ -53,6 +53,7 @@ class EXAMPLE(Service):
|
|||||||
Feature map (where to look):
|
Feature map (where to look):
|
||||||
__init__ TrackRequest read/override, CDM-aware codec gating
|
__init__ TrackRequest read/override, CDM-aware codec gating
|
||||||
authenticate cookies AND credentials, JWT decode, token cache+refresh
|
authenticate cookies AND credentials, JWT decode, token cache+refresh
|
||||||
|
scan_login QR code login: wait_for_approval(qr=...) hands the code to the client
|
||||||
search SearchResult generator
|
search SearchResult generator
|
||||||
get_titles Movies / Series + data passthrough
|
get_titles Movies / Series + data passthrough
|
||||||
get_tracks DASH variant fan-out (default) + HLS/ISM alternates
|
get_tracks DASH variant fan-out (default) + HLS/ISM alternates
|
||||||
@@ -195,14 +196,37 @@ class EXAMPLE(Service):
|
|||||||
otp = self.request_input("Enter the OTP sent to your device: ")
|
otp = self.request_input("Enter the OTP sent to your device: ")
|
||||||
body = {"username": credential.username, "password": credential.password, "otp": otp}
|
body = {"username": credential.username, "password": credential.password, "otp": otp}
|
||||||
else:
|
else:
|
||||||
raise OSError("Service requires either Cookies or Credentials.")
|
body = None
|
||||||
|
|
||||||
|
if body:
|
||||||
token = self.session.post(url=self.config["endpoints"]["login"], data=body).json()
|
token = self.session.post(url=self.config["endpoints"]["login"], data=body).json()
|
||||||
|
else:
|
||||||
|
token = self.scan_login()
|
||||||
cache.set(data=token, expiration=token.get("expires_in"))
|
cache.set(data=token, expiration=token.get("expires_in"))
|
||||||
|
|
||||||
self.token = cache.data["token"]
|
self.token = cache.data["token"]
|
||||||
self.user_id = cache.data.get("userId")
|
self.user_id = cache.data.get("userId")
|
||||||
|
|
||||||
|
def scan_login(self) -> dict[str, Any]:
|
||||||
|
"""Log in with a QR code the user scans in the app, for a run with no cookies or credentials."""
|
||||||
|
device = self.session.post(url=self.config["endpoints"]["device_code"]).json()
|
||||||
|
# Pass the QR code's TEXT as qr= (the URL the app encodes), never an image. The local
|
||||||
|
# terminal draws it, and over `serve` a --remote client or the REST job's UI draws it.
|
||||||
|
# Keep the URL and code in the message too, for a terminal that cannot draw the code.
|
||||||
|
# `request_input(prompt, qr=...)` takes the same argument when the user must type an answer.
|
||||||
|
return self.wait_for_approval(
|
||||||
|
f"Scan the QR code with the app, or open {device['verification_uri']} and enter {device['user_code']}",
|
||||||
|
check=lambda: self.poll_scan_login(device["device_code"]),
|
||||||
|
timeout=device.get("expires_in", 300),
|
||||||
|
interval=device.get("interval", 5),
|
||||||
|
qr=device["verification_uri_complete"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def poll_scan_login(self, device_code: str) -> dict[str, Any] | None:
|
||||||
|
"""The token once the user approves the scan, None while the approval is pending."""
|
||||||
|
res = self.session.post(url=self.config["endpoints"]["device_token"], data={"device_code": device_code})
|
||||||
|
return res.json() if res.ok else None
|
||||||
|
|
||||||
def search(self) -> Generator[SearchResult, None, None]:
|
def search(self) -> Generator[SearchResult, None, None]:
|
||||||
results = self.session.get(
|
results = self.session.get(
|
||||||
url=self.config["endpoints"]["search"],
|
url=self.config["endpoints"]["search"],
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
|
|
||||||
endpoints:
|
endpoints:
|
||||||
login: https://api.domain.com/v1/login
|
login: https://api.domain.com/v1/login
|
||||||
|
device_code: https://api.domain.com/v1/device/code # QR code login: start
|
||||||
|
device_token: https://api.domain.com/v1/device/token # QR code login: poll until approved
|
||||||
refresh: https://api.domain.com/v1/token/refresh
|
refresh: https://api.domain.com/v1/token/refresh
|
||||||
search: https://api.domain.com/v1/search
|
search: https://api.domain.com/v1/search
|
||||||
metadata: https://api.domain.com/v1/metadata/{title_id}.json
|
metadata: https://api.domain.com/v1/metadata/{title_id}.json
|
||||||
|
|||||||
@@ -2003,6 +2003,15 @@ wheels = [
|
|||||||
{ url = "https://files.pythonhosted.org/packages/dd/75/e90ab9aeece218a9fc5a5bc3ec97d0ee6bb3c4ff95869463c1de58e29a1c/ruff-0.15.21-py3-none-win_arm64.whl", hash = "sha256:6e83115d4b9377c1cbc13abf0e051f069fab0ef815ea0504a8a008cee24dd0a8", size = 11375265, upload-time = "2026-07-09T20:01:31.772Z" },
|
{ url = "https://files.pythonhosted.org/packages/dd/75/e90ab9aeece218a9fc5a5bc3ec97d0ee6bb3c4ff95869463c1de58e29a1c/ruff-0.15.21-py3-none-win_arm64.whl", hash = "sha256:6e83115d4b9377c1cbc13abf0e051f069fab0ef815ea0504a8a008cee24dd0a8", size = 11375265, upload-time = "2026-07-09T20:01:31.772Z" },
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "segno"
|
||||||
|
version = "1.6.6"
|
||||||
|
source = { registry = "https://pypi.org/simple" }
|
||||||
|
sdist = { url = "https://files.pythonhosted.org/packages/1c/2e/b396f750c53f570055bf5a9fc1ace09bed2dff013c73b7afec5702a581ba/segno-1.6.6.tar.gz", hash = "sha256:e60933afc4b52137d323a4434c8340e0ce1e58cec71439e46680d4db188f11b3", size = 1628586, upload-time = "2025-03-12T22:12:53.324Z" }
|
||||||
|
wheels = [
|
||||||
|
{ url = "https://files.pythonhosted.org/packages/d6/02/12c73fd423eb9577b97fc1924966b929eff7074ae6b2e15dd3d30cb9e4ae/segno-1.6.6-py3-none-any.whl", hash = "sha256:28c7d081ed0cf935e0411293a465efd4d500704072cdb039778a2ab8736190c7", size = 76503, upload-time = "2025-03-12T22:12:48.106Z" },
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "six"
|
name = "six"
|
||||||
version = "1.17.0"
|
version = "1.17.0"
|
||||||
@@ -2171,6 +2180,7 @@ dependencies = [
|
|||||||
{ name = "rlaphoenix-m3u8" },
|
{ name = "rlaphoenix-m3u8" },
|
||||||
{ name = "rnet" },
|
{ name = "rnet" },
|
||||||
{ name = "ruamel-yaml" },
|
{ name = "ruamel-yaml" },
|
||||||
|
{ name = "segno" },
|
||||||
{ name = "sortedcontainers" },
|
{ name = "sortedcontainers" },
|
||||||
{ name = "subby" },
|
{ name = "subby" },
|
||||||
{ name = "subtitle-filter" },
|
{ name = "subtitle-filter" },
|
||||||
@@ -2238,6 +2248,7 @@ requires-dist = [
|
|||||||
{ name = "rlaphoenix-m3u8", specifier = ">=3.4.0,<4" },
|
{ name = "rlaphoenix-m3u8", specifier = ">=3.4.0,<4" },
|
||||||
{ name = "rnet", specifier = ">=2.4.2" },
|
{ name = "rnet", specifier = ">=2.4.2" },
|
||||||
{ name = "ruamel-yaml", specifier = ">=0.18.6,<0.19" },
|
{ name = "ruamel-yaml", specifier = ">=0.18.6,<0.19" },
|
||||||
|
{ name = "segno", specifier = ">=1.6.6,<2" },
|
||||||
{ name = "sortedcontainers", specifier = ">=2.4.0,<3" },
|
{ name = "sortedcontainers", specifier = ">=2.4.0,<3" },
|
||||||
{ name = "subby", git = "https://github.com/vevv/subby.git?rev=a057280f31acd3a0ba5c6dc69eaefbb88aea974e" },
|
{ name = "subby", git = "https://github.com/vevv/subby.git?rev=a057280f31acd3a0ba5c6dc69eaefbb88aea974e" },
|
||||||
{ name = "subtitle-filter", specifier = ">=1.4.9,<2" },
|
{ name = "subtitle-filter", specifier = ">=1.4.9,<2" },
|
||||||
|
|||||||
Reference in New Issue
Block a user