mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-24 18:05:07 +00:00
fix(remote): forward dl track selection and profile to remote sessions
Remote sessions now carry -l/-vl/-al/-a/-fs under a nested dl_params, so services fetch the requested audio versions. Server-account tokens for non-default accounts move from default to the account name, so each account logs in once after upgrade.
This commit is contained in:
@@ -182,3 +182,45 @@ def test_worker_write_result_retries_denied_replace(tmp_path: Path, monkeypatch:
|
||||
download_worker.write_result(target, {"progress": 42.0})
|
||||
assert json.loads(target.read_text(encoding="utf-8")) == {"progress": 42.0}
|
||||
assert len(attempts) == 2
|
||||
|
||||
|
||||
class _CapturedCtx(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("params", "expected"),
|
||||
[
|
||||
({}, (["orig"], [], [], [], False)),
|
||||
(
|
||||
{"lang": ["es-419"], "v_lang": ["en"], "a_lang": ["ja"], "acodec": "AAC,EC3", "forced_subs": True},
|
||||
(["es-419"], ["en"], ["ja"], ["AAC", "EC3"], True),
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_perform_download_puts_the_lang_selection_in_the_service_ctx(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, params: dict, expected: tuple
|
||||
) -> None:
|
||||
"""Services read the language selection from ctx.parent.params, not from dl.result()."""
|
||||
import click
|
||||
|
||||
import unshackle.commands.dl as dl_module
|
||||
from unshackle.core.api import download_manager, handlers
|
||||
from unshackle.core.services import Services
|
||||
|
||||
class FakeDl:
|
||||
cli = click.Command("dl")
|
||||
|
||||
def __init__(self, ctx: click.Context, **kwargs: object) -> None:
|
||||
raise _CapturedCtx(ctx)
|
||||
|
||||
monkeypatch.setattr(dl_module, "dl", FakeDl)
|
||||
monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path))
|
||||
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
|
||||
|
||||
with pytest.raises(_CapturedCtx) as exc:
|
||||
download_manager.perform_download("job-1", "EXAMPLE", "t1", dict(params))
|
||||
|
||||
ctx = exc.value.args[0]
|
||||
p = ctx.params
|
||||
assert (p["lang"], p["v_lang"], p["a_lang"], [c.name for c in p["acodec"]], p["forced_subs"]) == expected
|
||||
|
||||
@@ -410,6 +410,27 @@ def test_save_returned_cache_writes_nested_keys_and_rejects_escapes(tmp_path, mo
|
||||
]
|
||||
|
||||
|
||||
def test_save_returned_cache_drops_other_profiles_files(tmp_path, monkeypatch) -> None:
|
||||
"""A returned file for another profile must not overwrite that profile's local file."""
|
||||
import base64
|
||||
import logging
|
||||
import zlib
|
||||
from types import SimpleNamespace
|
||||
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.remote_service import RemoteService
|
||||
|
||||
tag = "TESTSVC"
|
||||
monkeypatch.setattr(config.directories, "cache", tmp_path)
|
||||
monkeypatch.setattr(config, "credentials", {tag: {"default": "a@example.com:pw", "work": "b@example.com:pw"}})
|
||||
stub = SimpleNamespace(service_tag=tag, log=logging.getLogger("test"))
|
||||
blob = base64.b64encode(zlib.compress(b"x")).decode("ascii")
|
||||
|
||||
RemoteService.save_returned_cache(stub, {"tokens_work": blob, "tokens_default": blob, "tokens": blob}, "work")
|
||||
|
||||
assert sorted(p.name for p in (tmp_path / tag).iterdir()) == ["tokens.json", "tokens_work.json"]
|
||||
|
||||
|
||||
def test_save_returned_cache_ignores_oversized_payload(tmp_path, monkeypatch) -> None:
|
||||
import logging
|
||||
from types import SimpleNamespace
|
||||
@@ -536,3 +557,54 @@ def test_session_create_writes_nested_cache_and_skips_colliding_keys(tmp_path, m
|
||||
|
||||
written = {p.name: p.read_text() for p in tmp_path.rglob("*.json") if p.is_file()}
|
||||
assert written == {"x.json": "flat", "keys.v2.json": "dotted"}
|
||||
|
||||
|
||||
class _SentCreate(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _sent_create_data(parent_params: dict, service_params: dict) -> dict:
|
||||
import logging
|
||||
from types import SimpleNamespace
|
||||
|
||||
from unshackle.core.remote_service import RemoteService
|
||||
|
||||
def post(path: str, data: dict) -> dict:
|
||||
raise _SentCreate(data)
|
||||
|
||||
svc = object.__new__(RemoteService)
|
||||
svc.ctx = SimpleNamespace(parent=SimpleNamespace(params={"no_proxy": True, **parent_params}), obj=None)
|
||||
svc.service_tag = "EXAMPLE"
|
||||
svc.title_id = "t1"
|
||||
svc._server_accounts = {"global": True}
|
||||
svc._server_cdm = True
|
||||
svc._service_params = service_params
|
||||
svc.log = logging.getLogger("test")
|
||||
svc.client = SimpleNamespace(post=post)
|
||||
with pytest.raises(_SentCreate) as exc:
|
||||
svc.authenticate()
|
||||
return exc.value.args[0]
|
||||
|
||||
|
||||
def test_dl_selection_travels_nested_and_a_service_option_cannot_override_it() -> None:
|
||||
parent_params = {
|
||||
"lang": ["orig", "es-419"],
|
||||
"v_lang": [],
|
||||
"a_lang": [],
|
||||
"acodec": [Audio.Codec.EC3],
|
||||
"forced_subs": True,
|
||||
}
|
||||
data = _sent_create_data(parent_params, {"lang": 3, "a_lang": "x"})
|
||||
assert data["dl_params"] == {
|
||||
"lang": ["orig", "es-419"],
|
||||
"v_lang": [],
|
||||
"a_lang": [],
|
||||
"acodec": ["EC3"],
|
||||
"forced_subs": True,
|
||||
}
|
||||
assert data["lang"] == 3
|
||||
assert data["service_params"] == {"lang": 3, "a_lang": "x"}
|
||||
|
||||
|
||||
def test_no_dl_params_when_the_ctx_has_no_selection() -> None:
|
||||
assert "dl_params" not in _sent_create_data({}, {})
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
"""List and search requests on a --remote-only server run on a per-request cache directory.
|
||||
|
||||
The directory holds only what the client sent, goes back to the client when it logged in
|
||||
itself, and is always removed when the request ends.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import json
|
||||
import zlib
|
||||
|
||||
import click
|
||||
import pytest
|
||||
|
||||
from unshackle.core.api import handlers
|
||||
from unshackle.core.api.stats import stats
|
||||
from unshackle.core.cacher import Cacher
|
||||
from unshackle.core.config import config
|
||||
|
||||
|
||||
class _CacheService:
|
||||
fail_titles = False
|
||||
|
||||
def __init__(self, ctx, title):
|
||||
self.seen = _CacheService.seen
|
||||
self.seen["parent_params"] = ctx.parent.params
|
||||
self.cache = Cacher("EXAMPLE")
|
||||
|
||||
def authenticate(self, cookies, credential):
|
||||
self.seen["seeded"] = self.cache.get("tokens").data
|
||||
self.seen["cache_dir"] = self.cache.get("tokens").path.parent
|
||||
self.cache.get("tokens").set("new")
|
||||
self.cache.get("titles_abc").set("titles")
|
||||
|
||||
def get_titles(self):
|
||||
if self.fail_titles:
|
||||
raise RuntimeError("boom")
|
||||
return []
|
||||
|
||||
def search(self):
|
||||
return iter(())
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def seen(tmp_path, monkeypatch):
|
||||
import types
|
||||
|
||||
_CacheService.seen = {}
|
||||
_CacheService.fail_titles = False
|
||||
|
||||
@click.command()
|
||||
@click.argument("title")
|
||||
@click.pass_context
|
||||
def cli(ctx, **kwargs):
|
||||
return _CacheService(ctx, **kwargs)
|
||||
|
||||
module = types.SimpleNamespace(cli=cli)
|
||||
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, "resolve_handler_proxy", lambda *args: (None, []))
|
||||
monkeypatch.setattr(handlers, "resolve_server_account", lambda *args: None)
|
||||
monkeypatch.setattr(handlers, "load_full_cdm", lambda *args: None)
|
||||
monkeypatch.setattr(handlers.Services, "load", staticmethod(lambda service: module))
|
||||
monkeypatch.setattr("unshackle.commands.dl.dl.get_cookie_jar", staticmethod(lambda service, profile: None))
|
||||
monkeypatch.setattr("unshackle.commands.dl.dl.get_credentials", staticmethod(lambda service, profile: None))
|
||||
return _CacheService.seen
|
||||
|
||||
|
||||
def client_cache(tmp_path, value):
|
||||
Cacher("SRC").get("tokens").set(value)
|
||||
text = (tmp_path / "SRC" / "tokens.json").read_bytes()
|
||||
return {"tokens": base64.b64encode(zlib.compress(text)).decode("ascii")}
|
||||
|
||||
|
||||
def request_dirs(tmp_path):
|
||||
return list((tmp_path / "_requests").rglob("*")) if (tmp_path / "_requests").exists() else []
|
||||
|
||||
|
||||
CREDENTIALS = {"credentials": {"username": "a@example.com", "password": "pw"}}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_seeded_cache_is_read_and_returned_then_removed(seen, tmp_path):
|
||||
data = {"service": "EXAMPLE", "title_id": "t", "cache": client_cache(tmp_path, "old")}
|
||||
response = await handlers.list_titles_handler(data)
|
||||
body = json.loads(response.body)
|
||||
|
||||
assert seen["seeded"] == "old"
|
||||
assert seen["cache_dir"].is_relative_to(tmp_path / "_requests")
|
||||
assert set(body["cache"]) == {"tokens"}
|
||||
returned = json.loads(zlib.decompress(base64.b64decode(body["cache"]["tokens"])))
|
||||
assert returned["data"] == "new"
|
||||
assert not seen["cache_dir"].exists()
|
||||
assert not request_dirs(tmp_path)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_returns_cache_to_a_client_with_credentials(seen, tmp_path):
|
||||
response = await handlers.search_handler({"service": "EXAMPLE", "query": "q", **CREDENTIALS})
|
||||
body = json.loads(response.body)
|
||||
assert body["count"] == 0
|
||||
assert set(body["cache"]) == {"tokens"}
|
||||
assert not request_dirs(tmp_path)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_cache_returned_without_client_login(seen, tmp_path):
|
||||
response = await handlers.search_handler({"service": "EXAMPLE", "query": "q"})
|
||||
assert "cache" not in json.loads(response.body)
|
||||
assert seen["cache_dir"].is_relative_to(tmp_path / "_requests")
|
||||
assert not request_dirs(tmp_path)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cache_dir_removed_on_error(seen, tmp_path):
|
||||
_CacheService.fail_titles = True
|
||||
data = {"service": "EXAMPLE", "title_id": "t", **CREDENTIALS}
|
||||
response = await handlers.list_tracks_handler(data)
|
||||
assert response.status >= 400
|
||||
assert "cache" not in json.loads(response.body)
|
||||
assert seen["cache_dir"].is_relative_to(tmp_path / "_requests")
|
||||
assert not request_dirs(tmp_path)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invalid_client_cache_still_removes_the_dir(seen, tmp_path):
|
||||
data = {"service": "EXAMPLE", "query": "q", "cache": {"tokens": 1}}
|
||||
with pytest.raises(handlers.APIError):
|
||||
await handlers.search_handler(data)
|
||||
assert not request_dirs(tmp_path)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_server_account_uses_its_own_cache_and_returns_none(seen, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(handlers, "resolve_server_account", lambda *args: "acct")
|
||||
monkeypatch.setattr(handlers, "server_account_cookies", lambda *args: None)
|
||||
data = {"service": "EXAMPLE", "query": "q", "cache": client_cache(tmp_path, "old"), **CREDENTIALS}
|
||||
response = await handlers.search_handler(data)
|
||||
|
||||
assert "cache" not in json.loads(response.body)
|
||||
assert not seen["seeded"]
|
||||
assert seen["cache_dir"] == tmp_path / "_accounts" / "EXAMPLE" / "acct"
|
||||
assert not (tmp_path / "_requests").exists()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_full_mode_keeps_the_server_cache(seen, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(stats, "mode", "full")
|
||||
data = {"service": "EXAMPLE", "query": "q", "cache": client_cache(tmp_path, "old"), **CREDENTIALS}
|
||||
response = await handlers.search_handler(data)
|
||||
|
||||
assert "cache" not in json.loads(response.body)
|
||||
assert not seen["seeded"]
|
||||
assert seen["cache_dir"] == tmp_path / "EXAMPLE"
|
||||
assert not (tmp_path / "_requests").exists()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_tracks_service_sees_dl_params(seen):
|
||||
from unshackle.core.tracks import Audio
|
||||
|
||||
data = {"service": "EXAMPLE", "title_id": "t", "dl_params": {"a_lang": ["es-419"], "acodec": ["ddp"]}}
|
||||
await handlers.list_tracks_handler(data)
|
||||
assert seen["parent_params"]["a_lang"] == ["es-419"]
|
||||
assert seen["parent_params"]["acodec"] == [Audio.Codec.EC3]
|
||||
assert "dl_params" in handlers.LIST_HANDLER_TRANSPORT_KEYS
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_service_gets_no_dl_params(seen):
|
||||
await handlers.search_handler({"service": "EXAMPLE", "query": "q", "dl_params": {"a_lang": ["es-419"]}})
|
||||
assert "a_lang" not in seen["parent_params"]
|
||||
@@ -133,3 +133,90 @@ def test_server_cdm_ignores_client_cdm_type(monkeypatch):
|
||||
handlers.create_service_instance("OTHER", "t", data, None, [], None, server_cdm=True)
|
||||
handlers.create_service_instance("OTHER", "t", data, None, [], None)
|
||||
assert seen == [None, "playready"]
|
||||
|
||||
|
||||
class _LangOptionService:
|
||||
def __init__(self, ctx, title, lang):
|
||||
self.parent_params = ctx.parent.params
|
||||
self.lang = lang
|
||||
|
||||
|
||||
def _lang_option_module():
|
||||
import click
|
||||
|
||||
@click.command()
|
||||
@click.argument("title")
|
||||
@click.option("--lang", type=int, default=None)
|
||||
@click.pass_context
|
||||
def cli(ctx, **kwargs):
|
||||
return _LangOptionService(ctx, **kwargs)
|
||||
|
||||
return type("Module", (), {"cli": cli})
|
||||
|
||||
|
||||
def _create_with_real_ctx(monkeypatch, data):
|
||||
monkeypatch.setattr(handlers, "load_service_yaml", 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)
|
||||
return svc
|
||||
|
||||
|
||||
def test_nested_dl_params_reach_the_parent_ctx(monkeypatch):
|
||||
from unshackle.core.tracks import Audio
|
||||
|
||||
data = {
|
||||
"dl_params": {
|
||||
"lang": ["es-419", "en"],
|
||||
"v_lang": ["ja"],
|
||||
"a_lang": ["es-419"],
|
||||
"acodec": ["EC3", "NOPE", "AAC"],
|
||||
"forced_subs": True,
|
||||
}
|
||||
}
|
||||
svc = _create_with_real_ctx(monkeypatch, data)
|
||||
assert svc.parent_params["lang"] == ["es-419", "en"]
|
||||
assert svc.parent_params["v_lang"] == ["ja"]
|
||||
assert svc.parent_params["a_lang"] == ["es-419"]
|
||||
assert svc.parent_params["acodec"] == [Audio.Codec.EC3, Audio.Codec.AAC]
|
||||
assert svc.parent_params["forced_subs"] is True
|
||||
|
||||
|
||||
def test_absent_dl_params_fall_back_to_the_dl_defaults(monkeypatch):
|
||||
svc = _create_with_real_ctx(monkeypatch, {})
|
||||
selection = {k: svc.parent_params[k] for k in ("lang", "v_lang", "a_lang", "acodec", "forced_subs")}
|
||||
assert selection == {"lang": ["orig"], "v_lang": [], "a_lang": [], "acodec": [], "forced_subs": False}
|
||||
|
||||
|
||||
def test_an_empty_lang_list_is_kept(monkeypatch):
|
||||
svc = _create_with_real_ctx(monkeypatch, {"dl_params": {"lang": [], "a_lang": []}})
|
||||
assert svc.parent_params["lang"] == []
|
||||
|
||||
|
||||
def test_a_service_lang_option_never_gets_the_dl_lang(monkeypatch):
|
||||
svc = _create_with_real_ctx(monkeypatch, {"dl_params": {"lang": ["en"]}})
|
||||
assert svc.lang is None
|
||||
assert svc.parent_params["lang"] == ["en"]
|
||||
assert "dl_params" in handlers.SESSION_TRANSPORT_KEYS
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"dl_params",
|
||||
[
|
||||
"en",
|
||||
{"lang": "en", "v_lang": "ja", "a_lang": {"x": 1}, "acodec": "EC3", "forced_subs": "yes"},
|
||||
{"lang": [1], "v_lang": [None], "a_lang": ["en", None], "acodec": [3], "forced_subs": 1},
|
||||
],
|
||||
)
|
||||
def test_malformed_dl_params_are_ignored(monkeypatch, dl_params):
|
||||
svc = _create_with_real_ctx(monkeypatch, {"dl_params": dl_params})
|
||||
selection = {k: svc.parent_params[k] for k in ("lang", "v_lang", "a_lang", "acodec", "forced_subs")}
|
||||
assert selection == {"lang": ["orig"], "v_lang": [], "a_lang": [], "acodec": [], "forced_subs": False}
|
||||
|
||||
|
||||
def test_profile_reaches_the_parent_ctx_params(monkeypatch):
|
||||
monkeypatch.setattr(handlers, "load_service_yaml", 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")
|
||||
assert svc.parent_params["profile"] == "work"
|
||||
|
||||
Reference in New Issue
Block a user