forked from kenzuya/unshackle
refactor(api): build list, search and session services through one launch_served
This commit is contained in:
+154
-208
@@ -17,7 +17,7 @@ from dataclasses import dataclass, field
|
||||
from functools import partial
|
||||
from http.cookiejar import CookieJar
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
from typing import Any, Final, Literal, NamedTuple, Optional
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import click
|
||||
@@ -241,19 +241,19 @@ def instantiate_service(
|
||||
|
||||
|
||||
def server_login_material(
|
||||
data: dict[str, Any], normalized_service: str, account: str | None, profile: str | None
|
||||
data: dict[str, Any], normalized_service: str, account: str | None, profile: str | None, client_only: bool = False
|
||||
) -> tuple:
|
||||
"""(cookies, credential) for a list or search call.
|
||||
"""(cookies, credential) for a served service.
|
||||
|
||||
A lent account takes the server's files for that account. Otherwise the full-mode server,
|
||||
which the operator's own UI drives, uses its own profiles; a ``--remote-only`` server uses only
|
||||
what the client sent, the same rule as a remote session.
|
||||
A lent account takes the server's files for that account. Otherwise only what the client sent counts
|
||||
for a remote session (``client_only``) and on a ``--remote-only`` server; a full-mode list or search,
|
||||
which the operator's own UI drives, uses the server's own profiles.
|
||||
"""
|
||||
from unshackle.core.api.stats import stats
|
||||
|
||||
if account:
|
||||
return server_account_cookies(normalized_service, profile), login.get_credentials(normalized_service, profile)
|
||||
if stats.mode != "remote_only":
|
||||
if not client_only and stats.mode != "remote_only":
|
||||
return login.get_cookie_jar(normalized_service, profile), login.get_credentials(normalized_service, profile)
|
||||
return load_client_cookies(data.get("cookies")), client_credential(data)
|
||||
|
||||
@@ -768,52 +768,151 @@ def remote_search(data: dict[str, Any], server: str, query: str, request: web.Re
|
||||
return {"results": results, "count": len(results)}
|
||||
|
||||
|
||||
def setup_list_service(
|
||||
LIST: Final = "list"
|
||||
SEARCH: Final = "search"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SessionLaunch:
|
||||
"""What a remote session chose before its service is built: the session purpose of :func:`launch_served`."""
|
||||
|
||||
proxy: tuple[str | None, list]
|
||||
policy: KeyPolicy
|
||||
server_account: bool
|
||||
licensing: LicensingMode
|
||||
input_bridge: InputBridge
|
||||
cache_dir: str
|
||||
|
||||
|
||||
class Launched(NamedTuple):
|
||||
"""A served service, the login material it authenticates with, and the licensing of a remote session after the build."""
|
||||
|
||||
service: Any
|
||||
cookies: Any
|
||||
credential: Any
|
||||
licensing: LicensingMode | None = None
|
||||
|
||||
|
||||
def launch_served(
|
||||
purpose: Literal["list", "search"] | SessionLaunch,
|
||||
data: dict[str, Any],
|
||||
normalized_service: str,
|
||||
service: str,
|
||||
title: str,
|
||||
profile: str | None,
|
||||
title_id: str,
|
||||
request: web.Request | None = None,
|
||||
request_cache: RequestCache | None = None,
|
||||
) -> Any:
|
||||
"""Assemble and authenticate a service instance for list_titles / list_tracks.
|
||||
) -> Launched:
|
||||
"""Build the service that ``data`` asks for, for a list, a search or a remote session.
|
||||
|
||||
Runs the shared preamble: load yaml → get proxy → load CDM → assemble ctx →
|
||||
instantiate → authenticate. Raises APIError on proxy failure.
|
||||
The purpose picks the CDM rule, the login material, the cache and the transport keys. A list or search
|
||||
service comes back authenticated; a remote session authenticates later, when the client can answer its prompts.
|
||||
"""
|
||||
|
||||
session = purpose if isinstance(purpose, SessionLaunch) else None
|
||||
api_key = caller_key(request)
|
||||
policy = request_policy(request)
|
||||
service_config = policy.service_yaml(normalized_service)
|
||||
policy = session.policy if session else request_policy(request)
|
||||
server_config = service_config = policy.service_yaml(service)
|
||||
proxy_param, proxy_providers = session.proxy if session else resolve_handler_proxy(data, service, request)
|
||||
|
||||
proxy_param, proxy_providers = resolve_handler_proxy(data, normalized_service, request)
|
||||
if session:
|
||||
account = (profile or "default") if session.server_account else None
|
||||
else:
|
||||
account = resolve_server_account(policy, service, data.get("client_region"))
|
||||
if account:
|
||||
profile = None if account == "default" else account
|
||||
|
||||
account = resolve_server_account(policy, normalized_service, data.get("client_region"))
|
||||
if account:
|
||||
profile = None if account == "default" else account
|
||||
service_module = Services.load(service)
|
||||
key_config = policy.cdm_config()
|
||||
licensing = session.licensing if session else None
|
||||
client_identity = False
|
||||
cdm: Any
|
||||
if session and session.licensing.client_device:
|
||||
client_config = getattr(service_module, "CLIENT_CONFIG", ())
|
||||
if client_config:
|
||||
service_config, client_identity = client_config_overlay(
|
||||
server_config, client_config, data.get("service_config")
|
||||
)
|
||||
|
||||
service_module = Services.load(normalized_service)
|
||||
cdm_type = None if server_device_requested(service_module, data) else data.get("cdm_type")
|
||||
cdm = load_full_cdm(normalized_service, profile, cdm_type, policy.cdm_config())
|
||||
cookies, credential = server_login_material(data, normalized_service, account, profile)
|
||||
def lend_server_device() -> Any:
|
||||
"""The server's device, with the server's own config back in the dict the service holds as ``self.config``."""
|
||||
if service_config is not server_config:
|
||||
service_config.clear()
|
||||
service_config.update(server_config)
|
||||
return load_full_cdm(service, profile, None, key_config)
|
||||
|
||||
cdm = client_device_cdm(data, session.input_bridge, lend_server_device)
|
||||
else:
|
||||
if session is None:
|
||||
follows_client = not server_device_requested(service_module, data)
|
||||
elif session.licensing.server_cdm:
|
||||
follows_client = choose_cdm(key_config.cdm, service).both and not server_device_requested(
|
||||
service_module, data
|
||||
)
|
||||
else:
|
||||
follows_client = True
|
||||
cdm = load_full_cdm(service, profile, data.get("cdm_type") if follows_client else None, key_config)
|
||||
|
||||
anonymous = purpose == SEARCH and getattr(service_module, "ANONYMOUS_SEARCH", False)
|
||||
cookies, credential = (
|
||||
(None, None) if anonymous else server_login_material(data, service, account, profile, session is not None)
|
||||
)
|
||||
|
||||
keys: LaunchKeys = {"cookies_supplied": cookies is not None}
|
||||
if session:
|
||||
# A service with CLIENT_CONFIG reads client_device and client_identity: with client_identity it uses
|
||||
# only what the client sent, and without it the server's identity, whose keys then come only from a vault.
|
||||
keys["client_device"] = session.licensing.client_device
|
||||
keys["client_identity"] = client_identity
|
||||
parent_ctx = served_parent(
|
||||
ContextData(config=service_config, cdm=cdm, proxy_providers=proxy_providers, profile=profile),
|
||||
data,
|
||||
{"cookies_supplied": cookies is not None},
|
||||
keys,
|
||||
proxy_param,
|
||||
# Services key their token caches on this. A list or search leaves it out: it shares the server's
|
||||
# cache, where a session runs on a cache directory of its own.
|
||||
profile if session else None,
|
||||
SESSION_TRANSPORT_KEYS if session else frozenset(),
|
||||
)
|
||||
service_instance = instantiate_service(parent_ctx, service_module, title_id, data, LIST_HANDLER_TRANSPORT_KEYS)
|
||||
|
||||
if purpose == SEARCH:
|
||||
try:
|
||||
service_instance = instantiate_service(parent_ctx, service_module, title)
|
||||
except (ConnectionError, click.ClickException) as exc:
|
||||
raise categorize_exception(exc, {"service": service}) from exc
|
||||
except Exception as exc:
|
||||
raise APIError(
|
||||
APIErrorCode.SERVICE_ERROR, f"Failed to initialize service: {exc}", details={"service": service}
|
||||
) from exc
|
||||
else:
|
||||
transport_keys = SESSION_TRANSPORT_KEYS if session else LIST_HANDLER_TRANSPORT_KEYS
|
||||
service_instance = instantiate_service(parent_ctx, service_module, title, data, transport_keys)
|
||||
|
||||
if session:
|
||||
# the service asked for the server's device in __init__, so the session never licenses live
|
||||
stand_in = getattr(getattr(getattr(service_instance, "ctx", None), "obj", None), "cdm", None)
|
||||
if getattr(stand_in, "lent", False) is True:
|
||||
licensing = session.licensing.lent()
|
||||
|
||||
if account:
|
||||
account_tag = f"_accounts/{normalized_service}/{account}"
|
||||
service_instance.cache = keyed_cache(account_tag, service_instance, normalized_service, api_key, policy)
|
||||
account_tag = f"_accounts/{service}/{account}"
|
||||
service_instance.cache = keyed_cache(account_tag, service_instance, service, api_key, policy)
|
||||
elif session and licensing:
|
||||
service_instance.cache = keyed_cache(
|
||||
session.cache_dir,
|
||||
service_instance,
|
||||
service,
|
||||
api_key,
|
||||
policy,
|
||||
temporary=True,
|
||||
client_identity=licensing.client_identity,
|
||||
)
|
||||
elif request_cache is not None:
|
||||
client_login = cookies is not None or credential is not None
|
||||
request_cache.attach(service_instance, data, normalized_service, request, client_login, policy)
|
||||
service_instance._input_bridge = NoUserBridge()
|
||||
service_instance.authenticate(cookies, credential)
|
||||
return service_instance
|
||||
request_cache.attach(service_instance, data, service, request, client_login, policy)
|
||||
|
||||
service_instance._input_bridge = session.input_bridge if session else NoUserBridge()
|
||||
if not session and not anonymous:
|
||||
service_instance.authenticate(cookies, credential)
|
||||
return Launched(service_instance, cookies, credential, licensing)
|
||||
|
||||
|
||||
def run_service_search(
|
||||
@@ -823,63 +922,13 @@ def run_service_search(
|
||||
request: web.Request | None = None,
|
||||
request_cache: RequestCache | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Assemble and authenticate a service instance, then run its search.
|
||||
|
||||
The same preamble as :func:`setup_list_service`, without the service option extras,
|
||||
plus the search itself. Every step blocks on disk or network, so the caller runs the
|
||||
whole function in one worker thread and keeps the event loop free for other clients.
|
||||
"""Launch the service for a search and run it, in one worker thread, so the event loop stays free.
|
||||
|
||||
The server account check and its cache directory apply to an ``ANONYMOUS_SEARCH`` service too.
|
||||
"""
|
||||
|
||||
profile = client_profile(data)
|
||||
|
||||
api_key = caller_key(request)
|
||||
policy = request_policy(request)
|
||||
service_config = policy.service_yaml(normalized_service)
|
||||
proxy_param, proxy_providers = resolve_handler_proxy(data, normalized_service, request)
|
||||
|
||||
account = resolve_server_account(policy, normalized_service, data.get("client_region"))
|
||||
if account:
|
||||
profile = None if account == "default" else account
|
||||
|
||||
cdm = load_full_cdm(normalized_service, profile, data.get("cdm_type"), policy.cdm_config())
|
||||
service_module = Services.load(normalized_service)
|
||||
anonymous = getattr(service_module, "ANONYMOUS_SEARCH", False)
|
||||
cookies, credential = (
|
||||
(None, None) if anonymous else server_login_material(data, normalized_service, account, profile)
|
||||
)
|
||||
|
||||
parent_ctx = served_parent(
|
||||
ContextData(config=service_config, cdm=cdm, proxy_providers=proxy_providers, profile=profile),
|
||||
data,
|
||||
{"cookies_supplied": cookies is not None},
|
||||
proxy_param,
|
||||
)
|
||||
|
||||
from click import ClickException
|
||||
|
||||
try:
|
||||
service_instance = instantiate_service(parent_ctx, service_module, query)
|
||||
except (ConnectionError, ClickException) as exc:
|
||||
raise categorize_exception(exc, {"service": normalized_service}) from exc
|
||||
except Exception as exc:
|
||||
raise APIError(
|
||||
APIErrorCode.SERVICE_ERROR,
|
||||
f"Failed to initialize service: {exc}",
|
||||
details={"service": normalized_service},
|
||||
) from exc
|
||||
|
||||
if account:
|
||||
account_tag = f"_accounts/{normalized_service}/{account}"
|
||||
service_instance.cache = keyed_cache(account_tag, service_instance, normalized_service, api_key, policy)
|
||||
elif request_cache is not None:
|
||||
client_login = cookies is not None or credential is not None
|
||||
request_cache.attach(service_instance, data, normalized_service, request, client_login, policy)
|
||||
service_instance._input_bridge = NoUserBridge()
|
||||
if not anonymous:
|
||||
service_instance.authenticate(cookies, credential)
|
||||
|
||||
service_instance = launch_served(
|
||||
SEARCH, data, normalized_service, query, client_profile(data), request, request_cache
|
||||
).service
|
||||
results: list[dict[str, Any]] = []
|
||||
try:
|
||||
for result in service_instance.search():
|
||||
@@ -1376,9 +1425,10 @@ async def list_titles_handler(data: dict[str, Any], request: web.Request | None
|
||||
lease, titles = await leased_titles(data, server, info, profile, title_id, request, True)
|
||||
service_instance = lease.service
|
||||
else:
|
||||
service_instance = await asyncio.to_thread(
|
||||
setup_list_service, data, normalized_service, profile, title_id, request, request_cache
|
||||
launched = await asyncio.to_thread(
|
||||
launch_served, LIST, data, normalized_service, title_id, profile, request, request_cache
|
||||
)
|
||||
service_instance = launched.service
|
||||
titles = await asyncio.to_thread(service_instance.get_titles)
|
||||
|
||||
title_list = [serialize_title(t, service_instance) for t in listed_titles(titles)]
|
||||
@@ -1425,9 +1475,10 @@ async def list_tracks_handler(data: dict[str, Any], request: web.Request | None
|
||||
service_instance = lease.service
|
||||
call: Callable[..., Any] = partial(remote_call, lease)
|
||||
else:
|
||||
service_instance = await asyncio.to_thread(
|
||||
setup_list_service, data, normalized_service, profile, title_id, request, request_cache
|
||||
launched = await asyncio.to_thread(
|
||||
launch_served, LIST, data, normalized_service, title_id, profile, request, request_cache
|
||||
)
|
||||
service_instance = launched.service
|
||||
call = asyncio.to_thread
|
||||
titles = await call(service_instance.get_titles)
|
||||
|
||||
@@ -2722,86 +2773,6 @@ def client_device_cdm(
|
||||
)
|
||||
|
||||
|
||||
def create_service_instance(
|
||||
normalized_service: str,
|
||||
title_id: str,
|
||||
data: dict[str, Any],
|
||||
proxy_param: str | None,
|
||||
proxy_providers: list,
|
||||
profile: str | None,
|
||||
server_account: bool = False,
|
||||
server_cdm: bool = False,
|
||||
client_device: bool = False,
|
||||
input_bridge: InputBridge | None = None,
|
||||
policy: KeyPolicy | None = None,
|
||||
) -> Any:
|
||||
"""Make a service instance and resolve its credentials and cookies.
|
||||
|
||||
``policy`` is the calling API key's: its own ``cdm`` and ``service_config`` apply.
|
||||
|
||||
With ``client_device`` the service sees a stand-in for the client's device, which relays CDM calls
|
||||
through ``input_bridge`` when the client can answer them, and a config holding the client's own identity.
|
||||
|
||||
A service option in ``SERVER_DEVICE_OPTIONS`` gets the server's device whatever device the client has: from an
|
||||
entry with a device for both systems, the one the entry lists first.
|
||||
|
||||
With ``server_account`` the service takes the server's own credential and cookie file for
|
||||
``profile`` and drops anything the client sent. Otherwise only client-sent data counts: a
|
||||
client that sends nothing authenticates with nothing, because the server never lends its
|
||||
own accounts.
|
||||
"""
|
||||
policy = policy or KeyPolicy.of(None)
|
||||
server_config = service_config = policy.service_yaml(normalized_service)
|
||||
service_module = Services.load(normalized_service)
|
||||
key_config = policy.cdm_config()
|
||||
cdm: Any
|
||||
client_identity = False
|
||||
if client_device:
|
||||
client_config = getattr(service_module, "CLIENT_CONFIG", ())
|
||||
if client_config:
|
||||
service_config, client_identity = client_config_overlay(
|
||||
server_config, client_config, data.get("service_config")
|
||||
)
|
||||
|
||||
def lend_server_device() -> Any:
|
||||
"""The server's device, with the server's own config back in the dict the service holds as ``self.config``."""
|
||||
if service_config is not server_config:
|
||||
service_config.clear()
|
||||
service_config.update(server_config)
|
||||
return load_full_cdm(normalized_service, profile, None, key_config)
|
||||
|
||||
cdm = client_device_cdm(data, input_bridge, lend_server_device)
|
||||
else:
|
||||
follows_client = not server_cdm or (
|
||||
choose_cdm(key_config.cdm, normalized_service).both and not server_device_requested(service_module, data)
|
||||
)
|
||||
cdm = load_full_cdm(normalized_service, profile, data.get("cdm_type") if follows_client else None, key_config)
|
||||
|
||||
if server_account:
|
||||
cookies = server_account_cookies(normalized_service, profile)
|
||||
credential = login.get_credentials(normalized_service, profile)
|
||||
else:
|
||||
credential = client_credential(data)
|
||||
cookies = load_client_cookies(data.get("cookies"))
|
||||
|
||||
parent_ctx = served_parent(
|
||||
ContextData(config=service_config, cdm=cdm, proxy_providers=proxy_providers, profile=profile),
|
||||
data,
|
||||
# A service with CLIENT_CONFIG reads client_device and client_identity: with client_identity it uses
|
||||
# only what the client sent, and without it the server's identity, whose keys then come only from a vault.
|
||||
{"cookies_supplied": cookies is not None, "client_device": client_device, "client_identity": client_identity},
|
||||
proxy_param,
|
||||
# Services key their token caches on this. The list and search handlers leave it out: they
|
||||
# share the server's cache, where a session runs on a cache directory of its own.
|
||||
profile,
|
||||
SESSION_TRANSPORT_KEYS,
|
||||
)
|
||||
|
||||
service_instance = instantiate_service(parent_ctx, service_module, title_id, data, SESSION_TRANSPORT_KEYS)
|
||||
|
||||
return service_instance, cookies, credential
|
||||
|
||||
|
||||
async def session_create_handler(data: dict[str, Any], request: web.Request | None = None) -> web.Response:
|
||||
"""Answer the remote session creation: authenticate + get titles + get tracks + get chapters.
|
||||
|
||||
@@ -2838,7 +2809,6 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
|
||||
api_key = caller_key(request)
|
||||
policy = request_policy(request)
|
||||
session_cache_dir = f"_sessions/{api_key_namespace(request)}/{session_id}/{normalized_service}"
|
||||
session_cache_tag: str | None = session_cache_dir
|
||||
|
||||
server_account = server_account_for(policy, normalized_service)
|
||||
if server_account:
|
||||
@@ -2855,45 +2825,21 @@ async def session_create_handler(data: dict[str, Any], request: web.Request | No
|
||||
log_buffer = None if server_account else SessionLogBuffer()
|
||||
service_class_name = getattr(Services.load(normalized_service), "__name__", normalized_service)
|
||||
|
||||
def build_service() -> Any:
|
||||
with capture_service_logs(service_class_name, log_buffer):
|
||||
return create_service_instance(
|
||||
normalized_service,
|
||||
title_id,
|
||||
data,
|
||||
proxy_param,
|
||||
proxy_providers,
|
||||
profile,
|
||||
server_account=server_account,
|
||||
server_cdm=licensing.server_cdm,
|
||||
client_device=licensing.client_device,
|
||||
input_bridge=bridge,
|
||||
policy=policy,
|
||||
)
|
||||
|
||||
service_instance, cookies, credential = await asyncio.to_thread(build_service)
|
||||
if log_buffer:
|
||||
service_instance.log = SessionLogMirror(service_instance.log, log_buffer)
|
||||
|
||||
# the service asked for the server's device in __init__, so the session never licenses live
|
||||
stand_in = getattr(getattr(getattr(service_instance, "ctx", None), "obj", None), "cdm", None)
|
||||
if getattr(stand_in, "lent", False) is True:
|
||||
licensing = licensing.lent()
|
||||
cache_tag = f"_accounts/{normalized_service}/{profile or 'default'}" if server_account else session_cache_dir
|
||||
if server_account:
|
||||
session_cache_tag = None
|
||||
service_instance.cache = keyed_cache(
|
||||
cache_tag,
|
||||
service_instance,
|
||||
normalized_service,
|
||||
api_key,
|
||||
policy,
|
||||
temporary=not server_account,
|
||||
client_identity=licensing.client_identity,
|
||||
purpose = SessionLaunch(
|
||||
(proxy_param, proxy_providers), policy, server_account, licensing, bridge, session_cache_dir
|
||||
)
|
||||
|
||||
def build_service() -> Launched:
|
||||
with capture_service_logs(service_class_name, log_buffer):
|
||||
return launch_served(purpose, data, normalized_service, title_id, profile, request)
|
||||
|
||||
service_instance, cookies, credential, launched_licensing = await asyncio.to_thread(build_service)
|
||||
licensing = launched_licensing or licensing
|
||||
if log_buffer:
|
||||
service_instance.log = SessionLogMirror(service_instance.log, log_buffer)
|
||||
session_cache_tag = None if server_account else session_cache_dir
|
||||
|
||||
cache_data = data.get("cache", {})
|
||||
service_instance._input_bridge = bridge
|
||||
client = data.get("client")
|
||||
store = get_session_store()
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user