feat(service): pass a qr code with a login prompt or approval wait

This commit is contained in:
imSp4rky
2026-11-26 13:27:50 -07:00
parent 251d1e779a
commit 291417db4e
28 changed files with 386 additions and 94 deletions
+6
View File
@@ -156,6 +156,8 @@ class DownloadJob:
input_prompt: str | None = None
# Message a service shows through show_notice() while it waits for an approval; needs no answer.
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
# dict (id / language / title) so a client can report which weren't available.
@@ -196,6 +198,7 @@ class DownloadJob:
"skipped_titles": self.skipped_titles,
"input_prompt": self.input_prompt,
"notice": self.notice,
"qr": self.qr,
}
if include_full_details:
@@ -952,6 +955,8 @@ class DownloadQueueManager:
job.input_prompt = progress_data["input_prompt"]
if "notice" in progress_data:
job.notice = progress_data["notice"]
if "qr" in progress_data:
job.qr = progress_data["qr"]
if progress_data.get("skipped_subtitles"):
job.skipped_subtitles = progress_data["skipped_subtitles"]
if progress_data.get("skipped_titles"):
@@ -1045,6 +1050,7 @@ class DownloadQueueManager:
self._download_processes.pop(job.job_id, None)
job.input_prompt = None
job.notice = None
job.qr = None
temp_paths = self._job_temp_files.pop(job.job_id, {})
for path in temp_paths.values():
+5 -4
View File
@@ -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.
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.
The QR code text of a prompt or notice goes out with it as ``qr``.
"""
answers: queue.Queue[str] = queue.Queue()
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()
def ask(prompt: str) -> str:
def ask(prompt: str, qr: str | None) -> str:
with one_prompt:
while not answers.empty():
answers.get_nowait()
progress_callback({"input_prompt": prompt})
progress_callback({"input_prompt": prompt, "qr": qr})
try:
return answers.get(timeout=AUTH_INPUT_TIMEOUT)
except queue.Empty:
@@ -92,10 +93,10 @@ def relay_prompts(progress_callback: Callable[[dict[str, Any]], None]) -> None:
APIErrorCode.AUTH_FAILED,
) from None
finally:
progress_callback({"input_prompt": None})
progress_callback({"input_prompt": None, "qr": None})
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:
+22 -17
View File
@@ -479,20 +479,24 @@ _remote_logins: dict[str, RemoteLogin] = {}
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
logins = [
{
"id": login.id,
"remote": login.remote,
"service": login.service,
"title_id": login.title_id,
"prompt": login.bridge.get_pending_prompt(),
"notice": login.instance.auth_notice,
}
for login in list(_remote_logins.values())
if admin or login.owner == owner
]
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": entry.id,
"remote": entry.remote,
"service": entry.service,
"title_id": entry.title_id,
"prompt": ask.prompt if ask else None,
"notice": entry.instance.auth_notice,
"qr": ask.qr if ask else entry.instance.auth_qr,
}
)
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:
return web.json_response(PromptReply(status=AuthStatus.FAILED, error=session.auth_error or "unknown error"))
if bridge:
prompt = bridge.get_pending_prompt()
if prompt:
return web.json_response(PromptReply(status=AuthStatus.PENDING_INPUT, prompt=prompt))
if bridge and (ask := bridge.get_pending_ask()) and ask.prompt:
reply = PromptReply(status=AuthStatus.PENDING_INPUT, prompt=ask.prompt)
if ask.qr:
reply["qr"] = ask.qr
return web.json_response(reply)
return web.json_response(PromptReply(status=AuthStatus.AUTHENTICATING))
+14 -9
View File
@@ -41,6 +41,7 @@ class Ask:
id: str
prompt: str
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
response: str | None = None
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)
_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."""
if self._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):
ask.owner = CHANNEL
ask.picked_up.set()
self._asks[ask.id] = 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*.
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:
raise RuntimeError("Session was cancelled")
raise RuntimeError(f"Remote mode cannot relay a prompt after authentication: {prompt}")
ask = self._open(prompt)
ask = self._open(prompt, qr=qr)
try:
# cancel() and an answer both set the event, so a single wait returns on signal-or-cancel
if not ask.answered.wait(timeout=timeout):
@@ -159,12 +160,16 @@ class InputBridge:
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."""
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:
ask = next(iter(self._pollable()), None)
if ask is None:
return None
ask.owner = POLL
return ask.prompt
if ask is not None:
ask.owner = POLL
return ask
def submit_response(self, response: str) -> bool:
"""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):
"""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)
def ensure_active(self) -> None:
+6 -1
View File
@@ -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
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
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:
- name: job_id
in: path
@@ -3436,6 +3437,10 @@ async def remote_logins(request: web.Request) -> web.Response:
notice:
type: string
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)
+4 -1
View File
@@ -153,7 +153,10 @@ def log_message(record: LogRecord) -> ChannelLog:
def ask_message(ask: Ask) -> ChannelPrompt | ChannelCdmCall:
if ask.cdm_call is not None:
return ChannelCdmCall(type=ChannelMessage.CDM_CALL, id=ask.id, call=ask.cdm_call)
return ChannelPrompt(type=ChannelMessage.PROMPT, id=ask.id, prompt=ask.prompt)
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:
+5 -2
View File
@@ -40,7 +40,7 @@ class SessionLogBuffer:
self._lock = threading.Lock()
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:
self._seq += 1
record = LogRecord(
@@ -49,6 +49,8 @@ class SessionLogBuffer:
message=sanitize_log(message)[:MAX_MESSAGE_LEN],
ts=time.time(),
)
if qr:
record["qr"] = qr
self._records.append(record)
if self.listener is not None:
self.listener(record)
@@ -96,7 +98,8 @@ class SessionLogMirror(logging.LoggerAdapter):
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()
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)
def process(self, msg: Any, kwargs: MutableMapping[str, Any]) -> tuple[Any, MutableMapping[str, Any]]: