The core API keys page (backend/apikeys/, business/apiKeys/) and the host
sidecar's /homelab-env writer are retired: a managed plugin that declares
managed.keyHealth gets the same page on its Settings page, generic.
Manifest
- settings.links[]: {label, url} https:// links with {{config.<field>}}
placeholders (URL-quoted; a link whose field is empty is left out).
- managed.keyHealth: alertLimit + currency (alertLimitEur still reads),
secretKey (default: the first hub secret), legacyLedgerTool (a core ledger
tool whose rows count as the plugin's spend: nanobanana → plugin:nanobanana).
Store / metering
- set_secret keeps a non-secret last-4 hint (installed.json → secretHints);
secrets stored before hints get theirs on first read.
- Runtime key settings per plugin (alertLimit, currency, pushAtPct,
pushOnBreak) over the manifest defaults.
- Key health: ok / broken states set the state, other failures are listed
only; a break pushes once (type error), the recovery once ("✅ <Plugin> key
works again", type success); the month pushes at pushAtPct and at 100 %,
each once per month; spend merges the legacy ledger tool.
Routes
- GET /api/plugins/{pid}/spend (plugins.manage): health + hint, settings,
month, byCaller, byModel, 30 days with failures, recent successes +
failures with session links, the links filled in (plugins/keyspend.py).
- PUT /api/plugins/{pid}/key-settings (plugins.manage).
- POST /api/plugins/{pid}/test records the testAction's verdict (its _meter
billed as via "test", or a structured _error whose kind is a key state).
- PUT /api/plugins/{pid}/secrets/{key} on the watched hub key: checked with
testAction before saving — the run's handler token carries the candidate in
memory (plugins.proxy.register_candidate) so its proxy calls use it;
invalid / denied → 400, no-credit / capped → saved, anything else → 502.
- /proxy/tools/nanobanana/<model> (the cli hub edition) reads the plugin's hub
key and feeds its health; Gemini's classify moves to toolproxy/catalog.
Frontend
- PluginKeyHealthSection (status + hint + Test / Replace + links, month with
progress, threshold marker and the limit / currency / alerts form, by caller
/ model + 30-day bars with failure dots, recent calls) on PluginSettingsPage
for the owner; /settings/api-keys redirects to /settings/plugin/nanobanana;
the settings entry, mock, lazy page and unused French strings go.
openapi.json is not re-dumped here (the coordinator does it after Batch 2).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
478 lines
27 KiB
Python
478 lines
27 KiB
Python
"""The tool proxy's Movies group (toolproxy/media.py → the lab's Seerr): a
|
|
guest needs the switch, sees and requests movies only, as their own Seerr user
|
|
(made on first use) within Seerr's quota, never while the disk is nearly full;
|
|
the owner also gets series (latest aired season by default) as his own user;
|
|
the owner is pushed on each guest request, the requester once Seerr's webhook
|
|
says it's on Jellyfin. ``python -m pytest test_tool_proxy_media.py`` from
|
|
``backend/``."""
|
|
|
|
import datetime
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import tempfile
|
|
import unittest
|
|
|
|
TMP = pathlib.Path(tempfile.mkdtemp())
|
|
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t",
|
|
"WORKSPACE": TMP, "REPO_DIR": TMP, "ARCHIVE_DIR": TMP / "arch",
|
|
"META_PATH": TMP / "meta.json", "WORKERS_PATH": TMP / "w.json",
|
|
"PROFILES_PATH": TMP / "profiles.json",
|
|
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror",
|
|
"CRON_PATH": TMP / "cron.json", "NOTIFY_PATH": TMP / "n.json",
|
|
"FORMS_PATH": TMP / "f.json", "UI_STATE_PATH": TMP / "ui.json",
|
|
"NOTIF_READ_PATH": TMP / "nr.json",
|
|
"MAIL_TRIGGER_SENDERS_PATH": TMP / "mt.json",
|
|
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
|
|
"PROJECTS_DIR": TMP / "projects", "PROXY_LEDGER_DIR": TMP / "ledger",
|
|
"WORKER_ENROLL_PATH": TMP / "enroll.json",
|
|
"SECURITY_LOG_PATH": TMP / "sec.jsonl",
|
|
"TOOLS_TOKEN_KEY": TMP / "tools.key", "TOOLS_OWNED_PATH": TMP / "owned.json",
|
|
"TOOLS_MEDIA_PATH": TMP / "media.json", "SEERR_URL": "http://seerr.test",
|
|
"SEERR_API_KEY": "seerr-key", "SEERR_WEBHOOK_TOKEN": "hook-token",
|
|
"SEERR_OWNER_USER_ID": "2", "MEDIA_MIN_FREE_GB": "40",
|
|
"INTERNAL_API_TOKEN": "tok", "GUEST_HOSTS": "claude.example.test",
|
|
"GUEST_PUBLIC_URL": "https://claude.example.test",
|
|
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": "",
|
|
"PLUGINS_DIR": TMP / "plugins"}.items():
|
|
os.environ[k] = str(v)
|
|
(TMP / "projects" / "film").mkdir(parents=True)
|
|
|
|
import httpx # noqa: E402
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
from toolproxy import access, catalog, media, routes # noqa: E402
|
|
from toolproxy.ledger import LEDGER # noqa: E402
|
|
from users.caller import SESSION_COOKIE # noqa: E402
|
|
|
|
DEPS = main.app.state.ai
|
|
SID = "0190e0a1-0000-7000-8000-0000000000aa"
|
|
GIB = 2 ** 30
|
|
|
|
|
|
class FakeSeerr:
|
|
"""Just enough of Seerr's API: search, details, users, quota, requests."""
|
|
|
|
def __init__(self):
|
|
self.movies = {438631: {"title": "Dune", "releaseDate": "2021-09-15", "status": None},
|
|
693134: {"title": "Dune : Deuxième partie", "releaseDate": "2024-02-27",
|
|
"status": None},
|
|
1: {"title": "Here", "releaseDate": "2009-01-01", "status": 5}}
|
|
self.tv = {95396: {"name": "Severance", "firstAirDate": "2022-02-17", "seasons": [
|
|
{"seasonNumber": 0, "airDate": "2022-01-01", "episodeCount": 3},
|
|
{"seasonNumber": 1, "airDate": "2022-02-17", "episodeCount": 9},
|
|
{"seasonNumber": 2, "airDate": "2025-01-17", "episodeCount": 10},
|
|
{"seasonNumber": 3, "airDate": "2099-01-01", "episodeCount": 10}]}}
|
|
# tmdb → a full mediaInfo for /movie/<id> (download queue, Jellyfin id…)
|
|
self.info: dict[int, dict] = {}
|
|
self.users = {1: {"id": 1, "email": "seerr@gabvdl.xyz"},
|
|
2: {"id": 2, "email": "gabrielvidal"}}
|
|
self.requests: list[dict] = []
|
|
self.free = 118 * GIB
|
|
self.seen: list[httpx.Request] = []
|
|
self.scans: list[str] = [] # the jobs the hub ran (POST /settings/jobs/<id>/run)
|
|
|
|
def __call__(self, req: httpx.Request) -> httpx.Response:
|
|
self.seen.append(req)
|
|
assert req.headers.get("x-api-key") == "seerr-key"
|
|
p = req.url.path.removeprefix("/api/v1")
|
|
body = json.loads(req.content) if req.content else {}
|
|
if p == "/search":
|
|
hits = [{"mediaType": "movie", "id": i, "title": m["title"],
|
|
"releaseDate": m["releaseDate"], "voteAverage": 7.9, "overview": "Sand.",
|
|
**({"mediaInfo": {"status": m["status"]}} if m["status"] else {})}
|
|
for i, m in self.movies.items()]
|
|
hits.append({"mediaType": "tv", "id": 95396, "name": "Severance",
|
|
"firstAirDate": "2022-02-17"})
|
|
hits.append({"mediaType": "person", "id": 5, "name": "Someone"})
|
|
return httpx.Response(200, json={"page": 1, "totalPages": 1, "results": hits})
|
|
if p.startswith("/movie/"):
|
|
m = self.movies.get(int(p.rsplit("/", 1)[1]))
|
|
if not m:
|
|
return httpx.Response(404, json={"message": "Unable to retrieve movie."})
|
|
tmdb = int(p.rsplit("/", 1)[1])
|
|
mi = self.info.get(tmdb) or ({"status": m["status"]} if m["status"] else None)
|
|
return httpx.Response(200, json={"id": tmdb, **m, "runtime": 155,
|
|
"posterPath": "/p.jpg", "voteAverage": 8.14,
|
|
"imdbId": f"tt{tmdb:07d}",
|
|
**({"mediaInfo": mi} if mi else {})})
|
|
if p.startswith("/tv/"):
|
|
t = self.tv[int(p.rsplit("/", 1)[1])]
|
|
return httpx.Response(200, json={"id": 95396, **t})
|
|
if p.startswith("/settings/jobs/") and p.endswith("/run") and req.method == "POST":
|
|
self.scans.append(p.split("/")[3])
|
|
return httpx.Response(200, json={"id": p.split("/")[3], "running": True})
|
|
if p == "/service/radarr":
|
|
return httpx.Response(200, json=[{"id": 0, "isDefault": True,
|
|
"activeDirectory": "/media/movies"}])
|
|
if p == "/service/radarr/0":
|
|
return httpx.Response(200, json={"rootFolders": [{"path": "/media/movies",
|
|
"freeSpace": self.free}]})
|
|
if p == "/user" and req.method == "POST":
|
|
if any(u["email"] == body["email"] for u in self.users.values()):
|
|
return httpx.Response(409, json={"message": "User already exists"})
|
|
uid = max(self.users) + 1
|
|
self.users[uid] = {"id": uid, "email": body["email"], "username": body["username"]}
|
|
return httpx.Response(201, json=self.users[uid])
|
|
if p == "/user":
|
|
return httpx.Response(200, json={"results": list(self.users.values())})
|
|
if p.endswith("/quota"):
|
|
uid = int(p.split("/")[2])
|
|
used = len([r for r in self.requests if r["userId"] == uid and r["type"] == "movie"])
|
|
return httpx.Response(200, json={"movie": {"days": 7, "limit": 3, "used": used,
|
|
"remaining": max(0, 3 - used),
|
|
"restricted": used >= 3}})
|
|
if p.endswith("/requests"):
|
|
uid = int(p.split("/")[2])
|
|
return httpx.Response(200, json={"results": [
|
|
{"id": r["id"], "type": r["type"], "status": 2, "createdAt": r["at"],
|
|
"media": {"tmdbId": r["tmdb"], "status": 3}}
|
|
for r in self.requests if r["userId"] == uid]})
|
|
if p.startswith("/user/"):
|
|
uid = int(p.split("/")[2])
|
|
return (httpx.Response(200, json=self.users[uid]) if uid in self.users
|
|
else httpx.Response(404, json={"message": "User not found."}))
|
|
if p == "/request":
|
|
uid = body.get("userId", 1)
|
|
if any(r["tmdb"] == body["mediaId"] for r in self.requests):
|
|
return httpx.Response(409, json={"message": "Request for this media already exists."})
|
|
if body["mediaType"] == "movie" and uid != 2 and len(
|
|
[r for r in self.requests if r["userId"] == uid]) >= 3:
|
|
return httpx.Response(403, json={"message": "Movie Quota exceeded."})
|
|
rid = len(self.requests) + 1
|
|
self.requests.append({"id": rid, "userId": uid, "type": body["mediaType"],
|
|
"tmdb": body["mediaId"], "seasons": body.get("seasons"),
|
|
"at": datetime.datetime.now(datetime.timezone.utc).isoformat()})
|
|
return httpx.Response(201, json={"id": rid, "status": 2})
|
|
return httpx.Response(404, json={"message": f"no route {p}"})
|
|
|
|
|
|
class MoviesTest(unittest.TestCase):
|
|
def setUp(self):
|
|
try:
|
|
media.PATH.unlink()
|
|
except FileNotFoundError:
|
|
pass
|
|
media.STORE = media.Store(media.PATH)
|
|
media._downloads.clear()
|
|
media._last_scan = 0.0
|
|
self.uid = self._guest("ana@example.test", "Ana", {"groups": ["media"]})
|
|
self.off = self._guest("bo@example.test", "Bo", {"groups": ["3d"]})
|
|
self.seerr = FakeSeerr()
|
|
routes._client = httpx.AsyncClient(transport=httpx.MockTransport(self.seerr))
|
|
self.client = TestClient(main.app)
|
|
# The push log is shared by every test: count only this test's.
|
|
self.before = {e.get("id") for e in DEPS.notify_store.log(500)}
|
|
|
|
def _guest(self, email, name, tools):
|
|
try:
|
|
u = DEPS.users.create(email, name)
|
|
except ValueError:
|
|
u = DEPS.users.by_email(email)
|
|
DEPS.users.update(u["id"], {"tools": tools, "projects": {"film": "chat"}, "lang": "fr"})
|
|
return u["id"]
|
|
|
|
def call(self, op, body=None, uid=None, owner=False, sid=None):
|
|
h = {"Authorization": "Bearer tok" if owner else f"Bearer {access.mint(uid or self.uid)}"}
|
|
if sid:
|
|
h["X-Claude-Code-Session-Id"] = sid
|
|
return self.client.post(f"/proxy/tools/movies/{op}", json=body or {}, headers=h)
|
|
|
|
def pushes(self, needle):
|
|
return [e for e in DEPS.notify_store.log(500) if needle in (e.get("title") or "")
|
|
and e.get("id") not in self.before]
|
|
|
|
def test_the_group_is_registered(self):
|
|
self.assertIn("media", catalog.GROUPS)
|
|
self.assertEqual(catalog.GROUP_OF["movies"], "media")
|
|
self.assertIn("movies", catalog.HUB_SKILLS)
|
|
|
|
def test_a_guest_needs_the_switch(self):
|
|
r = self.call("search", {"query": "dune"}, uid=self.off)
|
|
self.assertEqual(r.status_code, 403, r.text)
|
|
self.assertEqual(r.json()["error"]["kind"], "group")
|
|
|
|
def test_a_guest_searches_movies_only_in_their_language(self):
|
|
r = self.call("search", {"query": "dune deuxième partie"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
d = r.json()
|
|
self.assertEqual({x["type"] for x in d["results"]}, {"movie"})
|
|
here = next(x for x in d["results"] if x["tmdb"] == 1)
|
|
self.assertEqual(here["status"], "available")
|
|
q = str(self.seerr.seen[-1].url)
|
|
self.assertIn("dune%20deuxi%C3%A8me%20partie", q)
|
|
self.assertIn("language=fr", q)
|
|
r = self.call("search", {"query": "severance", "type": "tv"})
|
|
self.assertEqual((r.status_code, r.json()["error"]["kind"]), (403, "tv"))
|
|
r = self.call("request", {"type": "tv", "tmdb": 95396})
|
|
self.assertEqual((r.status_code, r.json()["error"]["kind"]), (403, "tv"))
|
|
|
|
def test_a_guest_request_goes_as_their_own_seerr_user_and_pings_the_owner(self):
|
|
DEPS.meta_store.update(SID, {"owner": self.uid})
|
|
r = self.call("request", {"tmdb": 693134}, sid=SID)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
d = r.json()
|
|
self.assertEqual(d["request"]["status"], "approved")
|
|
self.assertEqual(d["quota"]["movies"]["used"], 1)
|
|
mine = media.STORE.user(self.uid)
|
|
self.assertEqual(self.seerr.requests[-1]["userId"], mine)
|
|
self.assertEqual(self.seerr.users[mine]["email"],
|
|
f"guest-{self.uid}@{media.GUEST_EMAIL_DOMAIN}")
|
|
self.assertEqual(media.STORE.request(d["request"]["id"])["session"], SID)
|
|
ping = self.pushes("Ana requested Dune : Deuxième partie (2024)")
|
|
self.assertEqual(len(ping), 1)
|
|
self.assertEqual(ping[0]["to"], ["owner"])
|
|
line = LEDGER.summary("who", self.uid)["byTool"]["movies"]
|
|
self.assertEqual(line["units"].get("movies"), 1)
|
|
# Same user next time; a second ask for it is "already requested".
|
|
self.call("request", {"tmdb": 438631})
|
|
self.assertEqual(len([u for u in self.seerr.users.values()
|
|
if u["email"].startswith("guest-")]), 1)
|
|
r = self.call("request", {"tmdb": 438631})
|
|
self.assertEqual(r.json()["already"], "requested")
|
|
|
|
def test_already_on_jellyfin_requests_nothing(self):
|
|
r = self.call("request", {"tmdb": 1})
|
|
self.assertEqual(r.json()["already"], "available")
|
|
self.assertFalse(self.seerr.requests)
|
|
|
|
def test_the_quota_is_seerrs_and_says_when_one_frees_up(self):
|
|
for i in range(10, 13):
|
|
self.seerr.movies[i] = {"title": f"M{i}", "releaseDate": "2020-01-01", "status": None}
|
|
self.assertEqual(self.call("request", {"tmdb": i}).status_code, 200)
|
|
self.seerr.movies[13] = {"title": "M13", "releaseDate": "2020-01-01", "status": None}
|
|
r = self.call("request", {"tmdb": 13})
|
|
self.assertEqual(r.status_code, 429, r.text)
|
|
e = r.json()["error"]
|
|
self.assertEqual(e["kind"], "quota")
|
|
week = (datetime.date.today() + datetime.timedelta(days=7)).isoformat()
|
|
self.assertIn(week, e["message"])
|
|
|
|
def test_a_nearly_full_disk_refuses_guests(self):
|
|
self.seerr.free = 12 * GIB
|
|
r = self.call("request", {"tmdb": 438631})
|
|
self.assertEqual((r.status_code, r.json()["error"]["kind"]), (507, "disk"))
|
|
r = self.call("request", {"tmdb": 438631}, owner=True)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
|
|
def test_the_owner_gets_series_latest_aired_season_by_default(self):
|
|
r = self.call("request", {"type": "tv", "tmdb": 95396}, owner=True)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(self.seerr.requests[-1]["seasons"], [2])
|
|
self.assertEqual(self.seerr.requests[-1]["userId"], 2)
|
|
self.assertFalse(self.pushes("requested Severance"))
|
|
info = self.call("info", {"type": "tv", "tmdb": 95396}, owner=True).json()
|
|
self.assertEqual([s["season"] for s in info["seasons"]], [1, 2, 3])
|
|
|
|
def test_my_requests_with_titles_and_quota(self):
|
|
self.call("request", {"tmdb": 438631})
|
|
d = self.call("requests").json()
|
|
self.assertEqual(d["requests"][0]["title"], "Dune (2021)")
|
|
self.assertEqual(d["quota"]["movies"]["used"], 1)
|
|
fresh = self.call("requests", uid=self._guest("cy@example.test", "Cy",
|
|
{"groups": ["media"]})).json()
|
|
self.assertEqual(fresh["requests"], [])
|
|
|
|
# ── Seerr's webhook ──────────────────────────────────────────────────────
|
|
def hook(self, payload, token="hook-token", host=None):
|
|
h = {"Authorization": f"Bearer {token}"}
|
|
if host:
|
|
h["Host"] = host
|
|
return self.client.post("/proxy/tools/movies/webhook", json=payload, headers=h)
|
|
|
|
def test_the_webhook_wants_its_token_and_stays_off_the_guest_host(self):
|
|
self.assertEqual(self.hook({}, token="nope").status_code, 401)
|
|
self.assertEqual(self.hook({}, host="claude.example.test").status_code, 404)
|
|
self.assertEqual(self.hook({"notification_type": "TEST_NOTIFICATION"}).json()["test"], True)
|
|
|
|
def test_available_pushes_the_guest_in_the_conversation_they_asked_from(self):
|
|
DEPS.meta_store.update(SID, {"owner": self.uid})
|
|
rid = self.call("request", {"tmdb": 438631}, sid=SID).json()["request"]["id"]
|
|
payload = {"notification_type": "MEDIA_AVAILABLE", "media_type": "movie",
|
|
"tmdb": "438631", "request_id": str(rid), "jellyfin_id": "abc"}
|
|
self.assertEqual(self.hook(payload).json()["told"], 1)
|
|
hit = self.pushes("Dune (2021) is ready")
|
|
self.assertEqual(len(hit), 1)
|
|
self.assertEqual(hit[0]["sessionId"], SID)
|
|
self.assertIn(self.uid, hit[0]["to"])
|
|
self.assertNotIn("owner", hit[0]["to"])
|
|
self.assertEqual(hit[0]["i18n"]["fr"]["title"], "🎬 Dune (2021) est disponible")
|
|
self.assertIn("id=abc", hit[0]["url"])
|
|
# Told once, even if Seerr says it again.
|
|
self.assertEqual(self.hook(payload).json()["told"], 0)
|
|
|
|
def test_a_failure_pings_the_owner(self):
|
|
self.hook({"notification_type": "MEDIA_FAILED", "subject": "Dune (2021)",
|
|
"media_type": "movie", "tmdb": "438631"})
|
|
self.assertEqual(len(self.pushes("Seerr: Dune (2021) failed")), 1)
|
|
|
|
|
|
# ── the live card and `movies wait` ──────────────────────────────────────
|
|
def downloading(self, tmdb, pct=64):
|
|
size = 10 * GIB
|
|
self.seerr.info[tmdb] = {"status": 3, "requests": [{"status": 2}], "downloadStatus": [
|
|
{"size": size, "sizeLeft": round(size * (100 - pct) / 100), "status": "downloading",
|
|
"estimatedCompletionTime": "2099-01-01T00:12:00.000Z"}]}
|
|
|
|
def test_status_stages_and_download_progress(self):
|
|
d = self.call("status", {"tmdb": 438631}).json()
|
|
self.assertEqual(d["stage"], "not requested")
|
|
self.assertEqual(d["poster"], media.TMDB_IMG + "/p.jpg")
|
|
self.assertEqual(d["imdb"], "tt0438631")
|
|
self.seerr.info[438631] = {"status": 3, "requests": [{"status": 2}]}
|
|
self.assertEqual(self.call("status", {"tmdb": 438631}).json()["stage"], "searching")
|
|
self.downloading(438631)
|
|
d = self.call("status", {"tmdb": 438631}).json()
|
|
self.assertEqual(d["stage"], "downloading")
|
|
self.assertEqual((d["progress"]["pct"], d["progress"]["eta"]),
|
|
(64, "2099-01-01T00:12:00.000Z"))
|
|
self.seerr.info[438631] = {"status": 3, "requests": [{"status": 4}]}
|
|
self.assertEqual(self.call("status", {"tmdb": 438631}).json()["stage"], "failed")
|
|
self.seerr.info[438631] = {"status": 5, "jellyfinMediaId": "abc123"}
|
|
d = self.call("status", {"tmdb": 438631}).json()
|
|
self.assertEqual(d["stage"], "available")
|
|
self.assertEqual(d["watch"], f"{media.WATCH_URL}/web/#/details?id=abc123")
|
|
self.assertIsNone(d["progress"])
|
|
|
|
def test_a_downloaded_title_is_importing_and_the_hub_runs_seerrs_scan(self):
|
|
# Radarr has the file, Seerr hasn't seen it on Jellyfin yet: not
|
|
# "searching" again (2026-11-18: a watching Claude went debugging).
|
|
self.downloading(438631, pct=90)
|
|
self.assertEqual(self.call("status", {"tmdb": 438631}).json()["stage"], "downloading")
|
|
self.assertEqual(self.seerr.scans, [])
|
|
self.seerr.info[438631] = {"status": 3, "requests": [{"status": 2}]}
|
|
d = self.call("status", {"tmdb": 438631}).json()
|
|
self.assertEqual((d["stage"], d["progress"]), ("importing", None))
|
|
self.assertEqual(self.seerr.scans, ["jellyfin-recently-added-scan"])
|
|
# The next poll inside SCAN_EVERY_S doesn't run it again.
|
|
self.assertEqual(self.call("status", {"tmdb": 438631}).json()["stage"], "importing")
|
|
self.assertEqual(len(self.seerr.scans), 1)
|
|
# Long after the download left the queue: Radarr is searching again.
|
|
media._downloads[("movie", 438631)] -= media.IMPORT_WINDOW_S + 1
|
|
self.assertEqual(self.call("status", {"tmdb": 438631}).json()["stage"], "searching")
|
|
# Complete but still in the queue (Radarr importing it) counts too.
|
|
size = 10 * GIB
|
|
self.seerr.info[438631] = {"status": 3, "requests": [{"status": 2}], "downloadStatus": [
|
|
{"size": size, "sizeLeft": 0, "status": "completed"}]}
|
|
self.assertEqual(self.call("status", {"tmdb": 438631}).json()["stage"], "importing")
|
|
self.seerr.info[438631] = {"status": 5, "jellyfinMediaId": "abc123"}
|
|
self.assertEqual(self.call("status", {"tmdb": 438631}).json()["stage"], "available")
|
|
self.assertNotIn(("movie", 438631), media._downloads)
|
|
# A title nobody saw downloading stays "searching", and runs nothing.
|
|
media._last_scan = 0.0
|
|
self.seerr.info[693134] = {"status": 3, "requests": [{"status": 2}]}
|
|
self.assertEqual(self.call("status", {"tmdb": 693134}).json()["stage"], "searching")
|
|
self.assertEqual(len(self.seerr.scans), 1)
|
|
|
|
def test_a_watch_holds_the_webhook_push_and_claims_it(self):
|
|
DEPS.meta_store.update(SID, {"owner": self.uid})
|
|
rid = self.call("request", {"tmdb": 438631}, sid=SID).json()["request"]["id"]
|
|
self.downloading(438631)
|
|
d = self.call("status", {"tmdb": 438631, "watch": True}, sid=SID).json()
|
|
self.assertTrue(d["watching"])
|
|
self.assertGreater(media.STORE.request(rid)["watchUntil"], 0)
|
|
payload = {"notification_type": "MEDIA_AVAILABLE", "media_type": "movie",
|
|
"tmdb": "438631", "request_id": str(rid)}
|
|
out = self.hook(payload).json()
|
|
self.assertEqual((out["told"], out.get("held")), (0, 1))
|
|
self.assertFalse(self.pushes("Dune (2021) is ready"))
|
|
# The wait's next poll sees it: Claude tells them; the hold is claimed.
|
|
self.seerr.info[438631] = {"status": 5}
|
|
d = self.call("status", {"tmdb": 438631, "watch": True}, sid=SID).json()
|
|
self.assertEqual(d["stage"], "available")
|
|
rec = media.STORE.request(rid)
|
|
self.assertEqual((rec["told"], rec["toldBy"]), ("available", "claude"))
|
|
self.assertFalse(media.release(DEPS, str(rid)))
|
|
self.assertFalse(self.pushes("Dune (2021) is ready"))
|
|
|
|
def test_a_wait_that_gives_up_releases_the_held_push(self):
|
|
DEPS.meta_store.update(SID, {"owner": self.uid})
|
|
rid = self.call("request", {"tmdb": 438631}, sid=SID).json()["request"]["id"]
|
|
self.downloading(438631)
|
|
self.call("status", {"tmdb": 438631, "watch": True}, sid=SID)
|
|
self.hook({"notification_type": "MEDIA_AVAILABLE", "media_type": "movie",
|
|
"tmdb": "438631", "request_id": str(rid), "jellyfin_id": "j1"})
|
|
self.assertFalse(self.pushes("Dune (2021) is ready"))
|
|
# Still leased: a timer's early release does nothing.
|
|
self.assertFalse(media.release(DEPS, str(rid)))
|
|
self.assertEqual(self.call("unwatch", {"tmdb": 438631}).json()["released"], 1)
|
|
hit = self.pushes("Dune (2021) is ready")
|
|
self.assertEqual(len(hit), 1)
|
|
self.assertEqual(hit[0]["sessionId"], SID)
|
|
self.assertIn("id=j1", hit[0]["url"])
|
|
self.assertFalse(media.STORE.watching("movie", 438631))
|
|
|
|
def test_watching_a_title_someone_else_asked_for_still_pushes_on_time_out(self):
|
|
self.call("request", {"tmdb": 438631}, owner=True)
|
|
other = self._guest("di@example.test", "Di", {"groups": ["media"]})
|
|
DEPS.meta_store.update(SID, {"owner": other})
|
|
self.assertEqual(self.call("request", {"tmdb": 438631}, uid=other).json()["already"],
|
|
"requested")
|
|
self.downloading(438631)
|
|
self.call("status", {"tmdb": 438631, "watch": True}, uid=other, sid=SID)
|
|
self.call("unwatch", {"tmdb": 438631}, uid=other)
|
|
self.hook({"notification_type": "MEDIA_AVAILABLE", "media_type": "movie",
|
|
"tmdb": "438631"})
|
|
hit = [h for h in self.pushes("Dune (2021) is ready") if other in h["to"]]
|
|
self.assertEqual(len(hit), 1)
|
|
self.assertEqual(hit[0]["sessionId"], SID)
|
|
|
|
# ── /api/movies/* (the cards) ────────────────────────────────────────────
|
|
def web(self, path, uid=None):
|
|
if uid is None:
|
|
return self.client.get(path, headers={"X-Internal-Auth": "tok"})
|
|
c = TestClient(main.app, base_url="https://claude.example.test")
|
|
c.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(uid))
|
|
return c.get(path)
|
|
|
|
def test_the_cards_read_status_and_search_for_the_owner_and_movies_guests(self):
|
|
from toolproxy import webroutes
|
|
webroutes._cache.clear()
|
|
self.downloading(693134, pct=40)
|
|
r = self.web("/api/movies/status?tmdb=693134")
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json()["progress"]["pct"], 40)
|
|
r = self.web("/api/movies/status?tmdb=693134", uid=self.uid)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(self.web("/api/movies/status?tmdb=693134", uid=self.off).status_code, 403)
|
|
r = self.web("/api/movies/search?q=dune", uid=self.uid)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertIn(438631, [x["tmdb"] for x in r.json()["results"]])
|
|
# Cached: the second search doesn't reach Seerr.
|
|
n = len(self.seerr.seen)
|
|
self.web("/api/movies/search?q=Dune", uid=self.uid)
|
|
self.assertEqual(len(self.seerr.seen), n)
|
|
# Reads make no Seerr user and record nothing.
|
|
self.assertIsNone(media.STORE.user(self.uid))
|
|
|
|
# ── Movies on by default, and it brings Jellyfin ─────────────────────────
|
|
def test_movies_is_on_by_default_and_switching_it_on_brings_jellyfin(self):
|
|
from users import idp
|
|
apps = idp.APPS
|
|
idp.APPS = [{"group": "jellyfin", "label": "Jellyfin", "url": ""}]
|
|
try:
|
|
r = self.client.post("/api/users", headers={"X-Internal-Auth": "tok"},
|
|
json={"email": "eve@example.test", "name": "Eve"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
eve = DEPS.users.get(r.json()["id"])
|
|
self.assertIn("media", access.config(DEPS, access.Who(eve["id"]))["groups"])
|
|
self.assertTrue((eve.get("apps") or {}).get("jellyfin"))
|
|
# Movies off, Jellyfin off by hand, Movies back on → Jellyfin on.
|
|
uid = eve["id"]
|
|
for body in ({"tools": {"groups": ["3d"]}}, {"apps": {"jellyfin": False}}):
|
|
self.client.put(f"/api/users/{uid}", headers={"X-Internal-Auth": "tok"}, json=body)
|
|
self.assertFalse(DEPS.users.get(uid)["apps"].get("jellyfin"))
|
|
self.client.put(f"/api/users/{uid}", headers={"X-Internal-Auth": "tok"},
|
|
json={"tools": {"groups": ["3d"], "budgetUsd": 12}})
|
|
self.assertFalse(DEPS.users.get(uid)["apps"].get("jellyfin"))
|
|
self.client.put(f"/api/users/{uid}", headers={"X-Internal-Auth": "tok"},
|
|
json={"tools": {"groups": ["3d", "media"]}})
|
|
self.assertTrue(DEPS.users.get(uid)["apps"]["jellyfin"])
|
|
finally:
|
|
idp.APPS = apps
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|