forked from kenzuya/unshackle
feat(service): pass a qr code with a login prompt or approval wait
This commit is contained in:
@@ -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():
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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))
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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]]:
|
||||
|
||||
+47
-10
@@ -514,38 +514,75 @@ def print_listing(renderable: RenderableType) -> None:
|
||||
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."""
|
||||
global _prompt_handler
|
||||
_prompt_handler = handler
|
||||
|
||||
|
||||
def prompt_user(prompt: str) -> str:
|
||||
"""Ask the user for input on the shared console, themed and indented like the rest of the output."""
|
||||
def qr_text(data: str, indent: int = 5) -> Text:
|
||||
"""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:
|
||||
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
|
||||
body = Text(indent + prompt.rstrip("\n ").replace("\n", "\n" + indent), style="text")
|
||||
body.append("\n" + indent + "> ", style="rule.text")
|
||||
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."""
|
||||
global _notice_handler
|
||||
_notice_handler = handler
|
||||
|
||||
|
||||
def show_notice(message: str | None) -> None:
|
||||
"""Give *message* to the notice handler, or None to clear it. Without a handler this does nothing."""
|
||||
def show_notice(message: str | None, qr: str | None = None) -> None:
|
||||
"""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:
|
||||
_notice_handler(message)
|
||||
_notice_handler(message, qr)
|
||||
|
||||
|
||||
__all__ = (
|
||||
|
||||
@@ -23,7 +23,7 @@ import aiohttp
|
||||
import requests
|
||||
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 (
|
||||
CHANNEL_ROUTE,
|
||||
CHANNEL_SESSION_GONE,
|
||||
@@ -61,6 +61,11 @@ KEPT_ANSWERS = 64
|
||||
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:
|
||||
"""What this client does with each message the server starts, whichever adapter brought it."""
|
||||
|
||||
@@ -86,6 +91,10 @@ class ServerMessages:
|
||||
continue
|
||||
message = sanitize_log(record.get("message", ""), keep_lines=True)
|
||||
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.log_seq = seq
|
||||
|
||||
@@ -100,14 +109,15 @@ class ServerMessages:
|
||||
)
|
||||
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."""
|
||||
from unshackle.core.api.sanitize import sanitize_log
|
||||
|
||||
prompt = sanitize_log(prompt, keep_lines=True)
|
||||
code = server_qr(qr)
|
||||
bridge = self.service._input_bridge
|
||||
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:
|
||||
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)
|
||||
if notice != self.service.auth_notice:
|
||||
self.service.auth_notice = notice
|
||||
show_notice(notice)
|
||||
show_notice(notice, self.service.auth_qr)
|
||||
|
||||
def close_cdm_sessions(self) -> None:
|
||||
"""Close the local CDM sessions that the server's calls opened; best effort."""
|
||||
@@ -130,8 +140,8 @@ class ServerMessages:
|
||||
|
||||
def login_done(self) -> None:
|
||||
self.close_cdm_sessions()
|
||||
if self.service.auth_notice is not None:
|
||||
self.service.auth_notice = None
|
||||
if self.service.auth_notice is not None or self.service.auth_qr is not None:
|
||||
self.service.auth_notice = self.service.auth_qr = None
|
||||
show_notice(None)
|
||||
|
||||
|
||||
@@ -184,7 +194,7 @@ class PollingChannel:
|
||||
if status == AuthStatus.PENDING_INPUT and isinstance(resp.get("cdm_call"), dict):
|
||||
self.answer(json.dumps(self.messages.answer_cdm(resp["cdm_call"])))
|
||||
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:
|
||||
time.sleep(AUTH_POLL_INTERVAL)
|
||||
return False
|
||||
@@ -414,7 +424,7 @@ class WebSocketChannel:
|
||||
if cdm_call:
|
||||
answer["response"] = json.dumps(self.messages.answer_cdm(data.get("call") or {}))
|
||||
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
|
||||
if isinstance(e, RemoteError):
|
||||
self.failure = e
|
||||
|
||||
@@ -227,6 +227,7 @@ class PromptReply(TypedDict, total=False):
|
||||
|
||||
status: str
|
||||
prompt: str | None
|
||||
qr: str
|
||||
cdm_call: dict[str, Any]
|
||||
error: str
|
||||
|
||||
@@ -236,10 +237,13 @@ class PromptAnswer(TypedDict):
|
||||
|
||||
|
||||
class LogRecord(TypedDict):
|
||||
"""One service log record; ``qr`` is the text of a QR code the client draws below the message."""
|
||||
|
||||
seq: int
|
||||
level: str
|
||||
message: str
|
||||
ts: float
|
||||
qr: NotRequired[str]
|
||||
|
||||
|
||||
class LogsReply(TypedDict):
|
||||
@@ -274,11 +278,12 @@ class ChannelMessage(StrEnum):
|
||||
|
||||
|
||||
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
|
||||
id: str
|
||||
prompt: str
|
||||
qr: NotRequired[str]
|
||||
|
||||
|
||||
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
|
||||
# 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_qr: str | None = None
|
||||
self._reopen_lock = Lock()
|
||||
self._current_title: Title_T | None = None
|
||||
# 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.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.launch import launch_keys
|
||||
from unshackle.core.proxies.basic import Basic
|
||||
@@ -467,19 +467,20 @@ class Service(TitleSource):
|
||||
# Store credential for cache key generation
|
||||
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.
|
||||
|
||||
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
|
||||
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:
|
||||
return self._input_bridge.request_input(prompt)
|
||||
return prompt_user(prompt)
|
||||
return self._input_bridge.request_input(prompt, qr=qr)
|
||||
return prompt_user(prompt, qr)
|
||||
|
||||
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:
|
||||
"""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
|
||||
seconds. Raises TimeoutError after ``timeout`` seconds, and RuntimeError when the
|
||||
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)
|
||||
show_notice(message)
|
||||
self.log.info(message, extra={"qr": qr})
|
||||
if qr and self._input_bridge is None:
|
||||
show_qr(qr)
|
||||
show_notice(message, qr)
|
||||
deadline = time.monotonic() + timeout
|
||||
try:
|
||||
while True:
|
||||
|
||||
@@ -31,10 +31,10 @@ class EXAMPLE(Service):
|
||||
every framework feature in one place. Music is the one exception: it has its
|
||||
own reference service, MUSIC_EXAMPLE.
|
||||
|
||||
Version: 2.1.0
|
||||
Version: 2.2.0
|
||||
Author: sp4rk.y
|
||||
Date: 2026-08-23
|
||||
Authorization: Cookies + Credentials
|
||||
Date: 2026-11-26
|
||||
Authorization: Cookies, Credentials or a QR code scanned in the app
|
||||
Geofence: US, UK
|
||||
Robustness:
|
||||
Widevine:
|
||||
@@ -53,6 +53,7 @@ class EXAMPLE(Service):
|
||||
Feature map (where to look):
|
||||
__init__ TrackRequest read/override, CDM-aware codec gating
|
||||
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
|
||||
get_titles Movies / Series + data passthrough
|
||||
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: ")
|
||||
body = {"username": credential.username, "password": credential.password, "otp": otp}
|
||||
else:
|
||||
raise OSError("Service requires either Cookies or Credentials.")
|
||||
body = None
|
||||
|
||||
token = self.session.post(url=self.config["endpoints"]["login"], data=body).json()
|
||||
if body:
|
||||
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"))
|
||||
|
||||
self.token = cache.data["token"]
|
||||
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]:
|
||||
results = self.session.get(
|
||||
url=self.config["endpoints"]["search"],
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
|
||||
endpoints:
|
||||
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
|
||||
search: https://api.domain.com/v1/search
|
||||
metadata: https://api.domain.com/v1/metadata/{title_id}.json
|
||||
|
||||
Reference in New Issue
Block a user