fix(core): load every service config through one launch-context function

This commit is contained in:
imSp4rky
2026-11-25 16:14:21 -07:00
parent fcda47d995
commit 7838226590
20 changed files with 139 additions and 82 deletions
+1 -1
View File
@@ -4,7 +4,7 @@
- **Type:** `dict` keyed by service tag  ·  **Default:** `{}` - **Type:** `dict` keyed by service tag  ·  **Default:** `{}`
Per-service configuration, keyed by the canonical service tag (for example `EXAMPLE1`, `EXAMPLE2`, Per-service configuration, keyed by the service tag in any case (for example `EXAMPLE1`, `EXAMPLE2`,
`EXAMPLE3`). unshackle reads several well-known sub-keys out of each service's block: `EXAMPLE3`). unshackle reads several well-known sub-keys out of each service's block:
- **`proxy_map`**: remaps the region query you passed to `-p/--proxy` for this service. - **`proxy_map`**: remaps the region query you passed to `-p/--proxy` for this service.
+1 -1
View File
@@ -59,7 +59,7 @@ def built_ctx(monkeypatch):
seen["ctx"] = parent_ctx seen["ctx"] = parent_ctx
return object() return object()
monkeypatch.setattr(handlers, "load_service_yaml", lambda service: {}) monkeypatch.setattr(handlers, "load_service_config", lambda service: {})
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None) monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
monkeypatch.setattr(handlers.Services, "load", lambda service: None) monkeypatch.setattr(handlers.Services, "load", lambda service: None)
monkeypatch.setattr(handlers, "instantiate_service", fake_instantiate) monkeypatch.setattr(handlers, "instantiate_service", fake_instantiate)
+1 -1
View File
@@ -832,7 +832,7 @@ def test_a_remote_session_puts_the_flag_in_the_service_ctx(monkeypatch: pytest.M
seen["ctx"] = parent_ctx seen["ctx"] = parent_ctx
return object() return object()
monkeypatch.setattr(handlers, "load_service_yaml", lambda service: {}) monkeypatch.setattr(handlers, "load_service_config", lambda service: {})
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None) monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
monkeypatch.setattr(handlers.Services, "load", lambda service: None) monkeypatch.setattr(handlers.Services, "load", lambda service: None)
monkeypatch.setattr(handlers, "instantiate_service", fake_instantiate) monkeypatch.setattr(handlers, "instantiate_service", fake_instantiate)
+1 -1
View File
@@ -62,7 +62,7 @@ def rest_handlers(monkeypatch: pytest.MonkeyPatch) -> tuple[Any, dict]:
seen["ctx"] = parent_ctx seen["ctx"] = parent_ctx
return SimpleNamespace(authenticate=lambda cookies, credential: None) return SimpleNamespace(authenticate=lambda cookies, credential: None)
monkeypatch.setattr(handlers, "load_service_yaml", lambda tag: {}) monkeypatch.setattr(handlers, "load_service_config", lambda tag: {})
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *a: (None, [])) monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *a: (None, []))
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None) monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
monkeypatch.setattr(handlers.Services, "load", lambda tag: SimpleNamespace()) monkeypatch.setattr(handlers.Services, "load", lambda tag: SimpleNamespace())
+61
View File
@@ -0,0 +1,61 @@
"""The service config that a Service starts with: its config.yaml, with the user's ``services.<TAG>`` block over it."""
from __future__ import annotations
from pathlib import Path
from typing import Callable
import click
import pytest
from tests.core.test_launch_context import cli_dl, cli_search
from unshackle.core import launch
from unshackle.core.config import config
pytestmark = pytest.mark.unit
@pytest.fixture
def service_dir(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:
from unshackle.core.services import Services
monkeypatch.setattr(Services, "get_path", staticmethod(lambda tag: tmp_path))
return tmp_path
def test_an_empty_config_yaml_takes_the_user_block(monkeypatch: pytest.MonkeyPatch, service_dir: Path) -> None:
(service_dir / config.filenames.config).write_text("")
monkeypatch.setattr(config, "services", {"EXAMPLE": {"region": "us"}})
assert launch.load_service_config("EXAMPLE") == {"region": "us"}
def test_a_user_block_matches_the_tag_in_any_case(monkeypatch: pytest.MonkeyPatch, service_dir: Path) -> None:
(service_dir / config.filenames.config).write_text("region: gb\nendpoints:\n api: a\n")
monkeypatch.setattr(config, "services", {"example": {"region": "us"}})
assert launch.load_service_config("EXAMPLE") == {"region": "us", "endpoints": {"api": "a"}}
def test_a_remote_service_gets_the_user_block_only(monkeypatch: pytest.MonkeyPatch, service_dir: Path) -> None:
(service_dir / config.filenames.config).write_text("region: gb\n")
monkeypatch.setattr(config, "services", {"EXAMPLE": {"profile": "a"}})
assert launch.load_service_config("EXAMPLE", local=False) == {"profile": "a"}
def test_each_caller_gets_its_own_copy(monkeypatch: pytest.MonkeyPatch, service_dir: Path) -> None:
(service_dir / config.filenames.config).write_text("endpoints:\n api: a\n")
monkeypatch.setattr(config, "services", {"EXAMPLE": {"hosts": ["h1"]}})
first = launch.load_service_config("EXAMPLE")
first["endpoints"]["api"] = "changed"
first["hosts"].append("h2")
assert launch.load_service_config("EXAMPLE") == {"endpoints": {"api": "a"}, "hosts": ["h1"]}
assert config.services == {"EXAMPLE": {"hosts": ["h1"]}}
@pytest.mark.parametrize("build", [cli_dl, cli_search], ids=["dl", "search"])
def test_the_cli_starts_a_service_with_an_empty_config_yaml_and_a_user_block(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, build: Callable[[pytest.MonkeyPatch, Path], click.Context]
) -> None:
(tmp_path / config.filenames.config).write_text("")
monkeypatch.setattr(config, "services", {"example": {"region": "us"}})
ctx = build(monkeypatch, tmp_path)
assert ctx.obj.config == {"region": "us"}
+1 -1
View File
@@ -58,7 +58,7 @@ def session_params(monkeypatch: pytest.MonkeyPatch, data: dict) -> dict:
seen["params"] = parent_ctx.params seen["params"] = parent_ctx.params
return object() return object()
monkeypatch.setattr(handlers, "load_service_yaml", lambda service: {}) monkeypatch.setattr(handlers, "load_service_config", lambda service: {})
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None) monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
monkeypatch.setattr(handlers.Services, "load", lambda service: None) monkeypatch.setattr(handlers.Services, "load", lambda service: None)
monkeypatch.setattr(handlers, "instantiate_service", fake_instantiate) monkeypatch.setattr(handlers, "instantiate_service", fake_instantiate)
+2 -2
View File
@@ -170,7 +170,7 @@ def test_a_relaying_client_gets_a_stand_in_with_its_device_facts(monkeypatch: py
class Declares: class Declares:
CLIENT_CONFIG = ("esn",) CLIENT_CONFIG = ("esn",)
monkeypatch.setattr(handlers, "load_service_yaml", lambda tag: {"esn": "SERVER"}) monkeypatch.setattr(handlers, "load_service_config", lambda tag: {"esn": "SERVER"})
monkeypatch.setattr( monkeypatch.setattr(
handlers, handlers,
"served_context", "served_context",
@@ -331,7 +331,7 @@ def test_a_lent_device_gives_the_service_the_server_config_back(monkeypatch: pyt
CLIENT_CONFIG = ("esn", "esn_map") CLIENT_CONFIG = ("esn", "esn_map")
monkeypatch.setattr( monkeypatch.setattr(
handlers, "load_service_yaml", lambda tag: {"esn": "SERVER", "esn_map": {7000: "s"}, "other": 1} handlers, "load_service_config", lambda tag: {"esn": "SERVER", "esn_map": {7000: "s"}, "other": 1}
) )
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: server_device) monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: server_device)
monkeypatch.setattr(handlers, "served_context", lambda obj, *a: built.update(cdm=obj.cdm, config=obj.config)) monkeypatch.setattr(handlers, "served_context", lambda obj, *a: built.update(cdm=obj.cdm, config=obj.config))
@@ -181,7 +181,7 @@ def test_setup_list_service_threads_request(monkeypatch):
def authenticate(self, cookies, credential): def authenticate(self, cookies, credential):
seen["authenticated"] = True seen["authenticated"] = True
monkeypatch.setattr(handlers, "load_service_yaml", lambda service: {}) monkeypatch.setattr(handlers, "load_service_config", lambda service: {})
monkeypatch.setattr(handlers, "resolve_handler_proxy", fake_resolve) monkeypatch.setattr(handlers, "resolve_handler_proxy", fake_resolve)
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None) monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
monkeypatch.setattr(handlers.Services, "load", lambda service: None) monkeypatch.setattr(handlers.Services, "load", lambda service: None)
@@ -199,7 +199,7 @@ def test_search_reports_failed_proxy_check_as_invalid_proxy(monkeypatch):
def failed_check(*args): def failed_check(*args):
raise ConnectionError("Proxy check failed: no IP lookup got through the proxy.") raise ConnectionError("Proxy check failed: no IP lookup got through the proxy.")
monkeypatch.setattr(handlers, "load_service_yaml", lambda service: {}) monkeypatch.setattr(handlers, "load_service_config", lambda service: {})
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: ("http://127.0.0.1:9", [])) monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: ("http://127.0.0.1:9", []))
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None) monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
monkeypatch.setattr(handlers.Services, "load", lambda service: None) monkeypatch.setattr(handlers.Services, "load", lambda service: None)
+2 -2
View File
@@ -44,7 +44,7 @@ def test_a_session_keeps_the_user_config_it_was_created_with(server, monkeypatch
def test_the_key_block_beats_the_server_config_and_profile_sections(server, monkeypatch): def test_the_key_block_beats_the_server_config_and_profile_sections(server, monkeypatch):
base = {"device_id": "server", "device_key": "server", "p1": {"device_id": "p1", "other": 1}, "urls": {"a": "b"}} base = {"device_id": "server", "device_key": "server", "p1": {"device_id": "p1", "other": 1}, "urls": {"a": "b"}}
monkeypatch.setattr(handlers, "load_service_yaml", lambda service: json.loads(json.dumps(base))) monkeypatch.setattr(handlers, "load_service_config", lambda service: json.loads(json.dumps(base)))
user = {"service_config": {"example": {"device_id": "key", "device_key": "key"}}} user = {"service_config": {"example": {"device_id": "key", "device_key": "key"}}}
merged = handlers.key_service_yaml("EXAMPLE", user) merged = handlers.key_service_yaml("EXAMPLE", user)
@@ -172,7 +172,7 @@ def test_a_reload_checks_key_devices_against_the_new_config(server, monkeypatch)
def test_a_block_value_reaches_only_plain_values_of_other_sections(server, monkeypatch): def test_a_block_value_reaches_only_plain_values_of_other_sections(server, monkeypatch):
base = {"p1": {"device_id": "p1", "headers": {"a": "b"}}, "device_key": "server"} base = {"p1": {"device_id": "p1", "headers": {"a": "b"}}, "device_key": "server"}
monkeypatch.setattr(handlers, "load_service_yaml", lambda service: json.loads(json.dumps(base))) monkeypatch.setattr(handlers, "load_service_config", lambda service: json.loads(json.dumps(base)))
block = {"device_id": "key", "headers": {"c": "d"}, "device_key": {"nested": 1}} block = {"device_id": "key", "headers": {"c": "d"}, "device_key": {"nested": 1}}
merged = handlers.key_service_yaml("EXAMPLE", {"service_config": {"EXAMPLE": block}}) merged = handlers.key_service_yaml("EXAMPLE", {"service_config": {"EXAMPLE": block}})
+1 -1
View File
@@ -59,7 +59,7 @@ def seen(tmp_path, monkeypatch):
monkeypatch.setattr(config.directories, "cache", tmp_path) monkeypatch.setattr(config.directories, "cache", tmp_path)
monkeypatch.setattr(stats, "mode", "remote_only") monkeypatch.setattr(stats, "mode", "remote_only")
monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: tag) monkeypatch.setattr(handlers, "validate_service", lambda tag, request=None: tag)
monkeypatch.setattr(handlers, "load_service_yaml", lambda service: {}) monkeypatch.setattr(handlers, "load_service_config", lambda service: {})
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, [])) monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *args: (None, []))
monkeypatch.setattr(handlers, "resolve_server_account", lambda *args: None) monkeypatch.setattr(handlers, "resolve_server_account", lambda *args: None)
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None) monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
+5 -5
View File
@@ -71,7 +71,7 @@ def test_single_account_always_same(accounts):
def test_client_managed_gets_nothing(monkeypatch, accounts): def test_client_managed_gets_nothing(monkeypatch, accounts):
monkeypatch.setattr(handlers, "load_service_yaml", lambda s: {}) monkeypatch.setattr(handlers, "load_service_config", lambda s: {})
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None) monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: object())) monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: object()))
monkeypatch.setattr(handlers, "instantiate_service", lambda *a: "svc") monkeypatch.setattr(handlers, "instantiate_service", lambda *a: "svc")
@@ -101,7 +101,7 @@ def test_rotation_per_region_pool(accounts):
def test_server_account_ignores_client_credentials(monkeypatch, accounts): def test_server_account_ignores_client_credentials(monkeypatch, accounts):
monkeypatch.setattr(handlers, "load_service_yaml", lambda s: {}) monkeypatch.setattr(handlers, "load_service_config", lambda s: {})
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None) monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: object())) monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: object()))
monkeypatch.setattr(handlers, "instantiate_service", lambda *a: "svc") monkeypatch.setattr(handlers, "instantiate_service", lambda *a: "svc")
@@ -125,7 +125,7 @@ def test_server_cdm_ignores_client_cdm_type(monkeypatch):
"""A server_cdm tier licenses with the server's own device, so the client's CDM type must """A server_cdm tier licenses with the server's own device, so the client's CDM type must
not swap it for a stub of the other DRM system.""" not swap it for a stub of the other DRM system."""
seen = [] seen = []
monkeypatch.setattr(handlers, "load_service_yaml", lambda s: {}) monkeypatch.setattr(handlers, "load_service_config", lambda s: {})
monkeypatch.setattr(handlers, "load_full_cdm", lambda s, p, t=None, app_config=None: seen.append(t)) monkeypatch.setattr(handlers, "load_full_cdm", lambda s, p, t=None, app_config=None: seen.append(t))
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: object())) monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: object()))
monkeypatch.setattr(handlers, "instantiate_service", lambda *a: "svc") monkeypatch.setattr(handlers, "instantiate_service", lambda *a: "svc")
@@ -155,7 +155,7 @@ def _lang_option_module():
def _create_with_real_ctx(monkeypatch, data): def _create_with_real_ctx(monkeypatch, data):
monkeypatch.setattr(handlers, "load_service_yaml", lambda s: {}) monkeypatch.setattr(handlers, "load_service_config", lambda s: {})
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None) monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: _lang_option_module())) monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: _lang_option_module()))
svc, _, _ = handlers.create_service_instance("OTHER", "t", data, None, [], None) svc, _, _ = handlers.create_service_instance("OTHER", "t", data, None, [], None)
@@ -230,7 +230,7 @@ def test_malformed_dl_params_are_ignored(monkeypatch, dl_params):
def test_profile_reaches_the_parent_ctx_params(monkeypatch): def test_profile_reaches_the_parent_ctx_params(monkeypatch):
monkeypatch.setattr(handlers, "load_service_yaml", lambda s: {}) monkeypatch.setattr(handlers, "load_service_config", lambda s: {})
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None) monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: _lang_option_module())) monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda s: _lang_option_module()))
svc, _, _ = handlers.create_service_instance("OTHER", "t", {}, None, [], "work") svc, _, _ = handlers.create_service_instance("OTHER", "t", {}, None, [], "work")
@@ -478,7 +478,7 @@ def test_a_client_device_session_builds_the_service_on_a_stub_of_that_device(mon
def no_server_device(*a, **k): def no_server_device(*a, **k):
raise AssertionError("a client-device session must not load the server's device") raise AssertionError("a client-device session must not load the server's device")
monkeypatch.setattr(handlers, "load_service_yaml", lambda tag: {}) monkeypatch.setattr(handlers, "load_service_config", lambda tag: {})
monkeypatch.setattr(handlers, "load_full_cdm", no_server_device) monkeypatch.setattr(handlers, "load_full_cdm", no_server_device)
monkeypatch.setattr(handlers, "served_context", lambda obj, *a: built.update(cdm=obj.cdm)) monkeypatch.setattr(handlers, "served_context", lambda obj, *a: built.update(cdm=obj.cdm))
monkeypatch.setattr(handlers.Services, "load", lambda tag: object) monkeypatch.setattr(handlers.Services, "load", lambda tag: object)
@@ -237,7 +237,7 @@ def test_the_server_device_follows_the_client_only_when_both_systems_are_mapped(
): ):
asked: list = [] asked: list = []
monkeypatch.setattr(handlers.config, "cdm", mapping, raising=False) monkeypatch.setattr(handlers.config, "cdm", mapping, raising=False)
monkeypatch.setattr(handlers, "load_service_yaml", lambda tag: {}) monkeypatch.setattr(handlers, "load_service_config", lambda tag: {})
monkeypatch.setattr( monkeypatch.setattr(
handlers, "load_full_cdm", lambda service, profile, cdm_type, app_config=None: asked.append(cdm_type) handlers, "load_full_cdm", lambda service, profile, cdm_type, app_config=None: asked.append(cdm_type)
) )
+4 -14
View File
@@ -35,7 +35,7 @@ from rich.table import Table
from unshackle.core import __version__, binaries, login, providers from unshackle.core import __version__, binaries, login, providers
from unshackle.core.cdm.choice import choose_cdm from unshackle.core.cdm.choice import choose_cdm
from unshackle.core.cdm.detect import cdm_system, cdm_type_stub, is_playready_cdm, is_remote_cdm from unshackle.core.cdm.detect import cdm_system, cdm_type_stub, is_playready_cdm, is_remote_cdm
from unshackle.core.config import cdm_entry_names_device, config, load_yaml, resolve_cdm_name, resolve_decryption from unshackle.core.config import cdm_entry_names_device, config, resolve_cdm_name, resolve_decryption
from unshackle.core.console import SyncLive, console, listing_panel, print_listing from unshackle.core.console import SyncLive, console, listing_panel, print_listing
from unshackle.core.constants import ( from unshackle.core.constants import (
DEFAULT_SAMPLE, DEFAULT_SAMPLE,
@@ -62,7 +62,7 @@ from unshackle.core.drm import (
from unshackle.core.drm.key_resolution import ContentKeyResolver from unshackle.core.drm.key_resolution import ContentKeyResolver
from unshackle.core.events import events from unshackle.core.events import events
from unshackle.core.export_name import ExportNamer, move_export, plural, season_episodes, title_label from unshackle.core.export_name import ExportNamer, move_export, plural, season_episodes, title_label
from unshackle.core.launch import LaunchKeys, launch from unshackle.core.launch import LaunchKeys, launch, load_service_config
from unshackle.core.manifests.snapshot import capture from unshackle.core.manifests.snapshot import capture
from unshackle.core.mux_step import mux_title from unshackle.core.mux_step import mux_title
from unshackle.core.placement import SAMPLE_DIR, Placement, sample_name from unshackle.core.placement import SAMPLE_DIR, Placement, sample_name
@@ -1343,12 +1343,8 @@ class dl:
self.is_remote = bool(ctx.params.get("remote")) self.is_remote = bool(ctx.params.get("remote"))
with console.status("Loading Service Config...", spinner="dots"): with console.status("Loading Service Config...", spinner="dots"):
self.service_config = {} self.service_config = load_service_config(self.service, local=not self.is_remote)
if not self.is_remote: if not self.is_remote:
try:
service_config_path = Services.get_path(self.service) / config.filenames.config
if service_config_path.exists():
self.service_config = load_yaml(service_config_path)
self.log.info("Service Config loaded") self.log.info("Service Config loaded")
# log key names only: the full config carries service certificates, # log key names only: the full config carries service certificates,
# device fingerprints and endpoints that bloat the log and may be sensitive # device fingerprints and endpoints that bloat the log and may be sensitive
@@ -1356,14 +1352,8 @@ class dl:
"load_service_config", "load_service_config",
level="DEBUG", level="DEBUG",
service=self.service, service=self.service,
context={ context={"config_keys": sorted(map(str, self.service_config))},
"config_path": str(service_config_path),
"config_keys": sorted(self.service_config or []),
},
) )
except KeyError:
pass
merge_dict(ci_get(config.services, self.service), self.service_config)
service_config = ci_get(config.services, self.service, {}) service_config = ci_get(config.services, self.service, {})
if service_config: if service_config:
+3 -9
View File
@@ -11,10 +11,9 @@ from rich.rule import Rule
from rich.tree import Tree from rich.tree import Tree
from unshackle.core import login from unshackle.core import login
from unshackle.core.config import config, load_yaml
from unshackle.core.console import console from unshackle.core.console import console
from unshackle.core.constants import context_settings from unshackle.core.constants import context_settings
from unshackle.core.launch import LaunchKeys, launch from unshackle.core.launch import LaunchKeys, launch, load_service_config
from unshackle.core.proxies.proxy import Proxy from unshackle.core.proxies.proxy import Proxy
from unshackle.core.proxies.resolve import ( from unshackle.core.proxies.resolve import (
REGION, REGION,
@@ -28,7 +27,6 @@ from unshackle.core.proxies.resolve import (
from unshackle.core.service import Service from unshackle.core.service import Service
from unshackle.core.services import Services from unshackle.core.services import Services
from unshackle.core.utils.click_types import ContextData from unshackle.core.utils.click_types import ContextData
from unshackle.core.utils.collections import ci_get, merge_dict
@click.command( @click.command(
@@ -86,14 +84,10 @@ def search(
if profile: if profile:
log.info(f"Using profile: '{profile}'") log.info(f"Using profile: '{profile}'")
service_config: dict = {}
if not remote:
with console.status("Loading Service Config...", spinner="dots"): with console.status("Loading Service Config...", spinner="dots"):
service_config_path = Services.get_path(service) / config.filenames.config service_config = load_service_config(service, local=not remote)
if service_config_path.exists(): if not remote:
service_config = load_yaml(service_config_path)
log.info("Service Config loaded") log.info("Service Config loaded")
merge_dict(ci_get(config.services, service), service_config)
if ctx.params.get("local_proxy"): if ctx.params.get("local_proxy"):
require_alone_local_proxy(ctx) require_alone_local_proxy(ctx)
+4 -26
View File
@@ -37,7 +37,7 @@ from unshackle.core.cacher import Cacher
from unshackle.core.cdm.choice import choose_cdm, drm_system from unshackle.core.cdm.choice import choose_cdm, drm_system
from unshackle.core.cdm.detect import cdm_system, cdm_type_stub from unshackle.core.cdm.detect import cdm_system, cdm_type_stub
from unshackle.core.cdm.loader import device_system from unshackle.core.cdm.loader import device_system
from unshackle.core.config import config, load_yaml from unshackle.core.config import config
from unshackle.core.dl_options import ( from unshackle.core.dl_options import (
DEFAULT_DOWNLOAD_PARAMS, DEFAULT_DOWNLOAD_PARAMS,
DL_OPTION_API_NAMES, DL_OPTION_API_NAMES,
@@ -45,7 +45,7 @@ from unshackle.core.dl_options import (
forwarded_dl_params, forwarded_dl_params,
) )
from unshackle.core.drm import BlowfishStripe, cbcs, is_null_key, real_kids from unshackle.core.drm import BlowfishStripe, cbcs, is_null_key, real_kids
from unshackle.core.launch import served_context from unshackle.core.launch import load_service_config, served_context
from unshackle.core.manifests.snapshot import capture from unshackle.core.manifests.snapshot import capture
from unshackle.core.providers.anilist import parse_anilist_ref from unshackle.core.providers.anilist import parse_anilist_ref
from unshackle.core.proxies.resolve import initialize_proxy_providers, is_loopback, resolve_proxy from unshackle.core.proxies.resolve import initialize_proxy_providers, is_loopback, resolve_proxy
@@ -155,28 +155,6 @@ def load_full_cdm(
return resolve_server_cdm(service, profile, cdm_type, app_config) return resolve_server_cdm(service, profile, cdm_type, app_config)
SERVICE_YAML: Dict[Path, tuple[int, dict]] = {}
def load_service_yaml(normalized_service: str) -> dict:
"""Load a service's config.yaml and merge it with the global override block.
The parsed file is kept until its mtime changes; each caller gets its own copy to change.
"""
service_config_path = Services.get_path(normalized_service) / config.filenames.config
try:
mtime = service_config_path.stat().st_mtime_ns
except OSError:
service_config: dict = {}
else:
hit = SERVICE_YAML.get(service_config_path)
if not hit or hit[0] != mtime:
hit = SERVICE_YAML[service_config_path] = (mtime, load_yaml(service_config_path) or {})
service_config = copy.deepcopy(hit[1])
merge_dict(config.services.get(normalized_service) or {}, service_config)
return service_config
def cast_or_refuse(params: Iterable[click.Parameter], ctx: Any, options: Dict[str, Any]) -> Dict[str, Any]: def cast_or_refuse(params: Iterable[click.Parameter], ctx: Any, options: Dict[str, Any]) -> Dict[str, Any]:
"""``cast_service_options``, with a refused value as ``400 INVALID_PARAMETERS``.""" """``cast_service_options``, with a refused value as ``400 INVALID_PARAMETERS``."""
try: try:
@@ -952,12 +930,12 @@ def key_owns_identity(user_config: Optional[Dict[str, Any]], service: str) -> bo
def key_service_yaml(normalized_service: str, user_config: Optional[Dict[str, Any]]) -> dict: def key_service_yaml(normalized_service: str, user_config: Optional[Dict[str, Any]]) -> dict:
""":func:`load_service_yaml` with the API key's own block merged over it. """:func:`load_service_config` with the API key's own block merged over it.
A top-level section that sets one of the block's plain values (a profile section with its own identity) takes A top-level section that sets one of the block's plain values (a profile section with its own identity) takes
the key's value too, so a client cannot pick the server's identity back through the profile it names. the key's value too, so a client cannot pick the server's identity back through the profile it names.
""" """
service_config = load_service_yaml(normalized_service) service_config = load_service_config(normalized_service)
block = key_service_config(user_config, normalized_service) block = key_service_config(user_config, normalized_service)
if block: if block:
merge_dict(copy.deepcopy(block), service_config) merge_dict(copy.deepcopy(block), service_config)
+2 -1
View File
@@ -26,6 +26,7 @@ from unshackle.core.tracks import Audio, Chapter, Chapters, Subtitle, Tracks, Vi
from unshackle.core.tracks.attachment import Attachment from unshackle.core.tracks.attachment import Attachment
from unshackle.core.tracks.track import Track from unshackle.core.tracks.track import Track
from unshackle.core.utils import run_proxy from unshackle.core.utils import run_proxy
from unshackle.core.utils.collections import ci_get
from unshackle.core.wire import build_title, drm_from_dict, track_from_dict from unshackle.core.wire import build_title, drm_from_dict, track_from_dict
log = logging.getLogger("import") log = logging.getLogger("import")
@@ -386,7 +387,7 @@ class ImportService:
def get_titles_cached(self, title_id: Optional[str] = None) -> Titles_T: def get_titles_cached(self, title_id: Optional[str] = None) -> Titles_T:
"""Apply the service's title_map to titles reconstructed from the export sidecar.""" """Apply the service's title_map to titles reconstructed from the export sidecar."""
title_map = (config.services.get(self.service_tag) or {}).get("title_map") or {} title_map = (ci_get(config.services, self.service_tag) or {}).get("title_map") or {}
return remap_titles(self.get_titles(), title_map) return remap_titles(self.get_titles(), title_map)
def get_tracks(self, title: Title_T) -> Tracks: def get_tracks(self, title: Title_T) -> Tracks:
+32
View File
@@ -1,10 +1,14 @@
"""The launch context of a Service: ``ctx.obj`` and the launch keys in ``ctx.parent.params``.""" """The launch context of a Service: ``ctx.obj`` and the launch keys in ``ctx.parent.params``."""
import copy
from pathlib import Path
from typing import Any, Dict, Optional, TypedDict, cast from typing import Any, Dict, Optional, TypedDict, cast
import click import click
from unshackle.core.config import config, load_yaml
from unshackle.core.utils.click_types import ContextData from unshackle.core.utils.click_types import ContextData
from unshackle.core.utils.collections import ci_get, merge_dict
class LaunchKeys(TypedDict, total=False): class LaunchKeys(TypedDict, total=False):
@@ -46,6 +50,34 @@ def served_context(obj: ContextData, params: Dict[str, Any], keys: LaunchKeys) -
return ctx return ctx
SERVICE_YAML: Dict[Path, tuple[tuple[int, int], dict]] = {}
def load_service_config(tag: str, local: bool = True) -> dict:
"""The service's ``config.yaml`` with the user's ``services.<TAG>`` block merged over it.
*local* False leaves out the file, for a service that runs on a remote server. The parsed file is kept
until its mtime or size changes; each caller gets its own copy to change.
"""
from unshackle.core.services import Services
service_config: dict = {}
if local:
try:
path = Services.get_path(tag) / config.filenames.config
stat = path.stat()
except (KeyError, FileNotFoundError):
pass
else:
stamp = (stat.st_mtime_ns, stat.st_size)
hit = SERVICE_YAML.get(path)
if not hit or hit[0] != stamp:
hit = SERVICE_YAML[path] = (stamp, load_yaml(path) or {})
service_config = copy.deepcopy(hit[1])
merge_dict(copy.deepcopy(ci_get(config.services, tag) or {}), service_config)
return service_config
def launch_keys(ctx: click.Context) -> LaunchKeys: def launch_keys(ctx: click.Context) -> LaunchKeys:
"""The launch keys that a service context reads from its parent, or none without a parent.""" """The launch keys that a service context reads from its parent, or none without a parent."""
return cast(LaunchKeys, ctx.parent.params) if ctx.parent else {} return cast(LaunchKeys, ctx.parent.params) if ctx.parent else {}
+3 -3
View File
@@ -973,7 +973,7 @@ class RemoteService:
self._server_accounts: Optional[dict] = services_config.get("_server_accounts") self._server_accounts: Optional[dict] = services_config.get("_server_accounts")
self._anonymous_search = bool(services_config.get("_anonymous_search")) self._anonymous_search = bool(services_config.get("_anonymous_search"))
# read before apply_service_config merges the server's values into the same section # read before apply_service_config merges the server's values into the same section
own = config.services.get(service_tag) or {} own = ci_get(config.services, service_tag) or {}
self._client_config = {k: own[k] for k in services_config.get("_client_config") or [] if k in own} self._client_config = {k: own[k] for k in services_config.get("_client_config") or [] if k in own}
self.apply_service_config(svc_config) self.apply_service_config(svc_config)
@@ -997,7 +997,7 @@ class RemoteService:
extra = {k: v for k, v in svc_config.items() if k not in config_maps} extra = {k: v for k, v in svc_config.items() if k not in config_maps}
if extra: if extra:
existing = config.services.get(self.service_tag, {}) existing = ci_get(config.services, self.service_tag) or {}
for key, value in extra.items(): for key, value in extra.items():
if key in existing and isinstance(existing[key], dict) and isinstance(value, dict): if key in existing and isinstance(existing[key], dict) and isinstance(value, dict):
existing[key].update(value) existing[key].update(value)
@@ -1457,7 +1457,7 @@ class RemoteService:
Lets users rename titles for remote services they do not have installed locally. Lets users rename titles for remote services they do not have installed locally.
The server sends raw titles. The client's own ``services.<TAG>.title_map`` wins. The server sends raw titles. The client's own ``services.<TAG>.title_map`` wins.
""" """
title_map = (config.services.get(self.service_tag) or {}).get("title_map") or {} title_map = (ci_get(config.services, self.service_tag) or {}).get("title_map") or {}
return remap_titles(self.get_titles(), title_map) return remap_titles(self.get_titles(), title_map)
def get_tracks(self, title: Title_T) -> Tracks: def get_tracks(self, title: Title_T) -> Tracks:
+2 -1
View File
@@ -45,6 +45,7 @@ from unshackle.core.tracks import Chapters, Tracks
from unshackle.core.tracks.video import Video from unshackle.core.tracks.video import Video
from unshackle.core.utilities import declared_kwargs from unshackle.core.utilities import declared_kwargs
from unshackle.core.utils import run_proxy from unshackle.core.utils import run_proxy
from unshackle.core.utils.collections import ci_get
from unshackle.core.utils.ip_info import get_ip_info, verify_proxy_exit from unshackle.core.utils.ip_info import get_ip_info, verify_proxy_exit
from unshackle.core.utils.redact import mask_proxy from unshackle.core.utils.redact import mask_proxy
@@ -216,7 +217,7 @@ class Service(metaclass=ABCMeta):
proxy_provider_name = keys.get("proxy_provider") proxy_provider_name = keys.get("proxy_provider")
service_name = self.__class__.__name__ service_name = self.__class__.__name__
service_config_dict = config.services.get(service_name, {}) service_config_dict = ci_get(config.services, service_name) or {}
proxy_map = service_config_dict.get("proxy_map", {}) proxy_map = service_config_dict.get("proxy_map", {})
if proxy_map and proxy_query: if proxy_map and proxy_query: