diff --git a/docs/reference/configuration/services.md b/docs/reference/configuration/services.md index 7e15c38e..ad4f9d72 100644 --- a/docs/reference/configuration/services.md +++ b/docs/reference/configuration/services.md @@ -4,7 +4,7 @@ - **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: - **`proxy_map`**: remaps the region query you passed to `-p/--proxy` for this service. diff --git a/tests/core/test_client_cookies_flag.py b/tests/core/test_client_cookies_flag.py index 82b2142d..4ee7828d 100644 --- a/tests/core/test_client_cookies_flag.py +++ b/tests/core/test_client_cookies_flag.py @@ -59,7 +59,7 @@ def built_ctx(monkeypatch): seen["ctx"] = parent_ctx 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.Services, "load", lambda service: None) monkeypatch.setattr(handlers, "instantiate_service", fake_instantiate) diff --git a/tests/core/test_hybrid_hdr10plus.py b/tests/core/test_hybrid_hdr10plus.py index 6c5e63c9..3586f7d6 100644 --- a/tests/core/test_hybrid_hdr10plus.py +++ b/tests/core/test_hybrid_hdr10plus.py @@ -832,7 +832,7 @@ def test_a_remote_session_puts_the_flag_in_the_service_ctx(monkeypatch: pytest.M seen["ctx"] = parent_ctx 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.Services, "load", lambda service: None) monkeypatch.setattr(handlers, "instantiate_service", fake_instantiate) diff --git a/tests/core/test_launch_context.py b/tests/core/test_launch_context.py index 05cba0cc..7c1a1509 100644 --- a/tests/core/test_launch_context.py +++ b/tests/core/test_launch_context.py @@ -62,7 +62,7 @@ def rest_handlers(monkeypatch: pytest.MonkeyPatch) -> tuple[Any, dict]: seen["ctx"] = parent_ctx 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, "load_full_cdm", lambda *a: None) monkeypatch.setattr(handlers.Services, "load", lambda tag: SimpleNamespace()) diff --git a/tests/core/test_service_config.py b/tests/core/test_service_config.py new file mode 100644 index 00000000..4020e982 --- /dev/null +++ b/tests/core/test_service_config.py @@ -0,0 +1,61 @@ +"""The service config that a Service starts with: its config.yaml, with the user's ``services.`` 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"} diff --git a/tests/remote/unit/test_api_quality_param.py b/tests/remote/unit/test_api_quality_param.py index 71b96d94..567a4570 100644 --- a/tests/remote/unit/test_api_quality_param.py +++ b/tests/remote/unit/test_api_quality_param.py @@ -58,7 +58,7 @@ def session_params(monkeypatch: pytest.MonkeyPatch, data: dict) -> dict: seen["params"] = parent_ctx.params 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.Services, "load", lambda service: None) monkeypatch.setattr(handlers, "instantiate_service", fake_instantiate) diff --git a/tests/remote/unit/test_client_device_cdm.py b/tests/remote/unit/test_client_device_cdm.py index 3f3a4a78..84b767cb 100644 --- a/tests/remote/unit/test_client_device_cdm.py +++ b/tests/remote/unit/test_client_device_cdm.py @@ -170,7 +170,7 @@ def test_a_relaying_client_gets_a_stand_in_with_its_device_facts(monkeypatch: py class Declares: 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( handlers, "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") 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, "served_context", lambda obj, *a: built.update(cdm=obj.cdm, config=obj.config)) diff --git a/tests/remote/unit/test_handler_proxy_policy.py b/tests/remote/unit/test_handler_proxy_policy.py index f56a88ea..62d3b222 100644 --- a/tests/remote/unit/test_handler_proxy_policy.py +++ b/tests/remote/unit/test_handler_proxy_policy.py @@ -181,7 +181,7 @@ def test_setup_list_service_threads_request(monkeypatch): def authenticate(self, cookies, credential): 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, "load_full_cdm", lambda *args: 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): 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, "load_full_cdm", lambda *args: None) monkeypatch.setattr(handlers.Services, "load", lambda service: None) diff --git a/tests/remote/unit/test_key_identity.py b/tests/remote/unit/test_key_identity.py index 60499603..060899b0 100644 --- a/tests/remote/unit/test_key_identity.py +++ b/tests/remote/unit/test_key_identity.py @@ -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): 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"}}} 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): 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}} merged = handlers.key_service_yaml("EXAMPLE", {"service_config": {"EXAMPLE": block}}) diff --git a/tests/remote/unit/test_request_cache.py b/tests/remote/unit/test_request_cache.py index cad3eba4..31edebb3 100644 --- a/tests/remote/unit/test_request_cache.py +++ b/tests/remote/unit/test_request_cache.py @@ -59,7 +59,7 @@ def seen(tmp_path, monkeypatch): monkeypatch.setattr(config.directories, "cache", tmp_path) monkeypatch.setattr(stats, "mode", "remote_only") 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_server_account", lambda *args: None) monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None) diff --git a/tests/remote/unit/test_server_accounts.py b/tests/remote/unit/test_server_accounts.py index b335d847..1514c858 100644 --- a/tests/remote/unit/test_server_accounts.py +++ b/tests/remote/unit/test_server_accounts.py @@ -71,7 +71,7 @@ def test_single_account_always_same(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.Services, "load", staticmethod(lambda s: object())) 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): - 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.Services, "load", staticmethod(lambda s: object())) 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 not swap it for a stub of the other DRM system.""" 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.Services, "load", staticmethod(lambda s: object())) monkeypatch.setattr(handlers, "instantiate_service", lambda *a: "svc") @@ -155,7 +155,7 @@ def _lang_option_module(): 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.Services, "load", staticmethod(lambda s: _lang_option_module())) 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): - 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.Services, "load", staticmethod(lambda s: _lang_option_module())) svc, _, _ = handlers.create_service_instance("OTHER", "t", {}, None, [], "work") diff --git a/tests/remote/unit/test_server_cdm_max_height.py b/tests/remote/unit/test_server_cdm_max_height.py index 9a49f283..de23ba24 100644 --- a/tests/remote/unit/test_server_cdm_max_height.py +++ b/tests/remote/unit/test_server_cdm_max_height.py @@ -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): 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, "served_context", lambda obj, *a: built.update(cdm=obj.cdm)) monkeypatch.setattr(handlers.Services, "load", lambda tag: object) diff --git a/tests/remote/unit/test_server_cdm_type_override.py b/tests/remote/unit/test_server_cdm_type_override.py index c80024ac..4314db45 100644 --- a/tests/remote/unit/test_server_cdm_type_override.py +++ b/tests/remote/unit/test_server_cdm_type_override.py @@ -237,7 +237,7 @@ def test_the_server_device_follows_the_client_only_when_both_systems_are_mapped( ): asked: list = [] 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( handlers, "load_full_cdm", lambda service, profile, cdm_type, app_config=None: asked.append(cdm_type) ) diff --git a/unshackle/commands/dl.py b/unshackle/commands/dl.py index 46f2a496..4d76f2c6 100644 --- a/unshackle/commands/dl.py +++ b/unshackle/commands/dl.py @@ -35,7 +35,7 @@ from rich.table import Table from unshackle.core import __version__, binaries, login, providers 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.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.constants import ( DEFAULT_SAMPLE, @@ -62,7 +62,7 @@ from unshackle.core.drm import ( from unshackle.core.drm.key_resolution import ContentKeyResolver from unshackle.core.events import events 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.mux_step import mux_title from unshackle.core.placement import SAMPLE_DIR, Placement, sample_name @@ -1343,27 +1343,17 @@ class dl: self.is_remote = bool(ctx.params.get("remote")) 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: - 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") - # log key names only: the full config carries service certificates, - # device fingerprints and endpoints that bloat the log and may be sensitive - log_event( - "load_service_config", - level="DEBUG", - service=self.service, - context={ - "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) + self.log.info("Service Config loaded") + # log key names only: the full config carries service certificates, + # device fingerprints and endpoints that bloat the log and may be sensitive + log_event( + "load_service_config", + level="DEBUG", + service=self.service, + context={"config_keys": sorted(map(str, self.service_config))}, + ) service_config = ci_get(config.services, self.service, {}) if service_config: diff --git a/unshackle/commands/search.py b/unshackle/commands/search.py index 8c3b70d1..558fa867 100644 --- a/unshackle/commands/search.py +++ b/unshackle/commands/search.py @@ -11,10 +11,9 @@ from rich.rule import Rule from rich.tree import Tree from unshackle.core import login -from unshackle.core.config import config, load_yaml from unshackle.core.console import console 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.resolve import ( REGION, @@ -28,7 +27,6 @@ from unshackle.core.proxies.resolve import ( from unshackle.core.service import Service from unshackle.core.services import Services from unshackle.core.utils.click_types import ContextData -from unshackle.core.utils.collections import ci_get, merge_dict @click.command( @@ -86,14 +84,10 @@ def search( if profile: log.info(f"Using profile: '{profile}'") - service_config: dict = {} + with console.status("Loading Service Config...", spinner="dots"): + service_config = load_service_config(service, local=not remote) if not remote: - with console.status("Loading Service Config...", spinner="dots"): - service_config_path = Services.get_path(service) / config.filenames.config - if service_config_path.exists(): - service_config = load_yaml(service_config_path) - log.info("Service Config loaded") - merge_dict(ci_get(config.services, service), service_config) + log.info("Service Config loaded") if ctx.params.get("local_proxy"): require_alone_local_proxy(ctx) diff --git a/unshackle/core/api/handlers.py b/unshackle/core/api/handlers.py index 9374b393..fbdaf8ed 100644 --- a/unshackle/core/api/handlers.py +++ b/unshackle/core/api/handlers.py @@ -37,7 +37,7 @@ from unshackle.core.cacher import Cacher 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.loader import device_system -from unshackle.core.config import config, load_yaml +from unshackle.core.config import config from unshackle.core.dl_options import ( DEFAULT_DOWNLOAD_PARAMS, DL_OPTION_API_NAMES, @@ -45,7 +45,7 @@ from unshackle.core.dl_options import ( forwarded_dl_params, ) 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.providers.anilist import parse_anilist_ref 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) -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]: """``cast_service_options``, with a refused value as ``400 INVALID_PARAMETERS``.""" 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: - """: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 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) if block: merge_dict(copy.deepcopy(block), service_config) diff --git a/unshackle/core/import_service.py b/unshackle/core/import_service.py index a4a09d88..8509aca2 100644 --- a/unshackle/core/import_service.py +++ b/unshackle/core/import_service.py @@ -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.track import Track 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 log = logging.getLogger("import") @@ -386,7 +387,7 @@ class ImportService: 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.""" - 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) def get_tracks(self, title: Title_T) -> Tracks: diff --git a/unshackle/core/launch.py b/unshackle/core/launch.py index a9c4d063..97dea804 100644 --- a/unshackle/core/launch.py +++ b/unshackle/core/launch.py @@ -1,10 +1,14 @@ """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 import click +from unshackle.core.config import config, load_yaml from unshackle.core.utils.click_types import ContextData +from unshackle.core.utils.collections import ci_get, merge_dict class LaunchKeys(TypedDict, total=False): @@ -46,6 +50,34 @@ def served_context(obj: ContextData, params: Dict[str, Any], keys: LaunchKeys) - 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.`` 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: """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 {} diff --git a/unshackle/core/remote_service.py b/unshackle/core/remote_service.py index c70f2ead..d7ed62a1 100644 --- a/unshackle/core/remote_service.py +++ b/unshackle/core/remote_service.py @@ -973,7 +973,7 @@ class RemoteService: self._server_accounts: Optional[dict] = services_config.get("_server_accounts") self._anonymous_search = bool(services_config.get("_anonymous_search")) # 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.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} if extra: - existing = config.services.get(self.service_tag, {}) + existing = ci_get(config.services, self.service_tag) or {} for key, value in extra.items(): if key in existing and isinstance(existing[key], dict) and isinstance(value, dict): existing[key].update(value) @@ -1457,7 +1457,7 @@ class RemoteService: Lets users rename titles for remote services they do not have installed locally. The server sends raw titles. The client's own ``services..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) def get_tracks(self, title: Title_T) -> Tracks: diff --git a/unshackle/core/service.py b/unshackle/core/service.py index 51bd34a9..e6eb8f2e 100644 --- a/unshackle/core/service.py +++ b/unshackle/core/service.py @@ -45,6 +45,7 @@ from unshackle.core.tracks import Chapters, Tracks from unshackle.core.tracks.video import Video from unshackle.core.utilities import declared_kwargs 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.redact import mask_proxy @@ -216,7 +217,7 @@ class Service(metaclass=ABCMeta): proxy_provider_name = keys.get("proxy_provider") 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", {}) if proxy_map and proxy_query: