The movie card's poster is now a button that opens the full-resolution TMDB poster (/original/, the w342 thumbnail painted while it loads) in the app's shared image viewer. The title links to the title's IMDb page in a new tab, with a small ↗ after it and an underline on hover; when Seerr has no IMDb id it links to the TMDB page instead. The hub's /api/movies/status now returns `imdb` (Seerr's imdbId for a film, externalIds.imdbId for a series). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
907 lines
39 KiB
Python
907 lines
39 KiB
Python
"""
|
|
The ``media`` tool group: movie requests (and, for the owner, series) on the
|
|
lab's Jellyfin through Seerr (``services/media``), its API key kept in the hub.
|
|
|
|
Gabriel's picks (form ``seerr-for-the-movie-skill_z5gm4h``, 2026-11-16):
|
|
|
|
* **Seerr is the request layer** — the hub never talks to Radarr / Sonarr. A
|
|
request goes to Seerr *as the caller's Seerr user* (the API key's
|
|
``userId``), so Seerr applies that user's quota and auto-approval itself.
|
|
* **Guests: movies only, 3 a week, auto-approved** — that is Seerr's default
|
|
for a new user (``defaultPermissions`` = request + auto-approve movies,
|
|
``defaultQuotas.movie`` = 3 / 7 days); the hub makes one local Seerr user
|
|
per guest on their first request (``guest-<uid>``, no login: Seerr's local
|
|
sign-in is off) and keeps the mapping in ``TOOLS_MEDIA_PATH``. Gabriel
|
|
changes one guest's quota in Seerr (Users → the guest → General).
|
|
* **Gabriel: movies and series**, as his own Seerr user
|
|
(``SEERR_OWNER_USER_ID``, his Jellyfin account, an admin there); a series
|
|
without ``seasons`` asks for its latest aired season, the library's rule
|
|
(``services/media/README.md`` → "Sonarr: only the latest season").
|
|
* **Pushes** — Gabriel on each guest request (the hub sends it); the
|
|
requester once it is on Jellyfin, in the conversation they asked from
|
|
(Seerr's webhook → ``handle_webhook``: ``MEDIA_AVAILABLE``, ``MEDIA_FAILED``,
|
|
``MEDIA_DECLINED``). A guest without a Jellyfin account asks Gabriel for one
|
|
(the skill says so).
|
|
* **Disk guard** — a guest's request is refused while the movie library's
|
|
disk has less than ``MEDIA_MIN_FREE_GB`` free.
|
|
|
|
* **Claude watches** (form ``movies-widget-guests-what-s-new_uqbyga``,
|
|
2026-11-18) — after a request the skill runs ``movies wait`` in the
|
|
background: it polls ``status`` with ``watch`` (a lease of
|
|
``WATCH_LEASE_S``, renewed on every poll) and Claude says it in the
|
|
conversation and pushes (notify-done) once it lands. While a lease is alive
|
|
the webhook's push for that title is **held**; the wait that sees the end
|
|
claims it (no second push), and a hold nobody claimed goes out when the
|
|
lease lapses (the wait timed out, was stopped or died). ``status`` also
|
|
feeds the conversation's movie card (``/api/movies/*``, ``webroutes.py``):
|
|
the stage and Radarr's download progress, as Seerr last synced it.
|
|
* **Importing** (2026-11-18) — once Radarr has the file its queue empties,
|
|
but Seerr only marks the title available after its Jellyfin scan (every
|
|
5 min): in between it read as ``searching`` again, and a watching Claude
|
|
went debugging Radarr. A title whose download the hub saw leave the queue
|
|
is ``importing`` for ``IMPORT_WINDOW_S``, and while it is the hub runs that
|
|
scan itself (``SCAN_JOB``, at most every ``SCAN_EVERY_S``) — Jellyfin's
|
|
realtime monitor has it within a minute, so it lands in about one.
|
|
|
|
Free, counted in the tool ledger (``units.calls``, ``units.movies`` for a
|
|
request that went through).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import dataclasses
|
|
import datetime
|
|
import json
|
|
import logging
|
|
import os
|
|
import pathlib
|
|
import secrets
|
|
import threading
|
|
import time
|
|
import urllib.parse
|
|
|
|
import httpx
|
|
|
|
log = logging.getLogger("toolproxy.media")
|
|
|
|
URL = (os.environ.get("SEERR_URL") or "http://seerr:5055").rstrip("/")
|
|
PUBLIC_URL = (os.environ.get("SEERR_PUBLIC_URL") or "https://seerr.lab.gabvdl.xyz").rstrip("/")
|
|
WATCH_URL = (os.environ.get("MEDIA_WATCH_URL") or "https://netflix.gabvdl.xyz").rstrip("/")
|
|
PATH = pathlib.Path(os.environ.get("TOOLS_MEDIA_PATH", "/data/tools-media.json"))
|
|
MIN_FREE_GB = float(os.environ.get("MEDIA_MIN_FREE_GB", "40"))
|
|
GUEST_EMAIL_DOMAIN = "guests.ai-agent.gabvdl.xyz"
|
|
TMDB_IMG = "https://image.tmdb.org/t/p/w342"
|
|
KEEP_REQUESTS = 500
|
|
# How long one `movies wait` poll keeps the webhook's push on hold.
|
|
WATCH_LEASE_S = int(os.environ.get("MEDIA_WATCH_LEASE_S", "180"))
|
|
# The stages a wait ends on.
|
|
FINAL = ("available", "failed", "declined")
|
|
# Seerr's job that notices what Jellyfin just added (every 5 min on its own).
|
|
SCAN_JOB = os.environ.get("SEERR_SCAN_JOB", "jellyfin-recently-added-scan")
|
|
SCAN_EVERY_S = 45
|
|
# How long after a download left Radarr's queue the title counts as being
|
|
# added to Jellyfin; past it, ``searching`` again (Radarr rejected the file).
|
|
IMPORT_WINDOW_S = 10 * 60
|
|
# (type, tmdb) → when the hub last saw it in Radarr's queue. In memory: a
|
|
# hub restart in the middle of an import only shows ``searching`` a while.
|
|
_downloads: dict[tuple[str, int], float] = {}
|
|
_last_scan = 0.0
|
|
|
|
MEDIA_STATUS = {1: "not requested", 2: "requested", 3: "downloading",
|
|
4: "partially available", 5: "available", 6: "blocklisted", 7: "deleted"}
|
|
REQUEST_STATUS = {1: "waiting for approval", 2: "approved", 3: "declined",
|
|
4: "failed", 5: "completed"}
|
|
|
|
|
|
def api_key() -> str:
|
|
return os.environ.get("SEERR_API_KEY") or ""
|
|
|
|
|
|
def webhook_token() -> str:
|
|
return os.environ.get("SEERR_WEBHOOK_TOKEN") or ""
|
|
|
|
|
|
def owner_user_id() -> int | None:
|
|
try:
|
|
return int(os.environ.get("SEERR_OWNER_USER_ID") or 0) or None
|
|
except ValueError:
|
|
return None
|
|
|
|
|
|
class MediaError(Exception):
|
|
def __init__(self, status: int, message: str, kind: str = "seerr"):
|
|
super().__init__(message)
|
|
self.status = status
|
|
self.message = message
|
|
self.kind = kind
|
|
|
|
|
|
class SeerrHTTP(Exception):
|
|
def __init__(self, status: int, message: str):
|
|
super().__init__(message)
|
|
self.status = status
|
|
self.message = message
|
|
|
|
|
|
# ── the hub's own state: guest → Seerr user, request → who / where ──────────
|
|
class Store:
|
|
def __init__(self, path: pathlib.Path = PATH):
|
|
self.path = path
|
|
self._lock = threading.Lock()
|
|
|
|
def _read(self) -> dict:
|
|
try:
|
|
d = json.loads(self.path.read_text())
|
|
return d if isinstance(d, dict) else {}
|
|
except (OSError, ValueError):
|
|
return {}
|
|
|
|
def _write(self, d: dict) -> None:
|
|
self.path.parent.mkdir(parents=True, exist_ok=True)
|
|
tmp = self.path.with_name(f".{self.path.name}.{os.getpid()}")
|
|
tmp.write_text(json.dumps(d, indent=1, ensure_ascii=False))
|
|
os.replace(tmp, self.path)
|
|
|
|
def user(self, uid: str) -> int | None:
|
|
with self._lock:
|
|
v = (self._read().get("users") or {}).get(uid)
|
|
return int(v) if v else None
|
|
|
|
def set_user(self, uid: str, seerr_id: int) -> None:
|
|
with self._lock:
|
|
d = self._read()
|
|
d.setdefault("users", {})[uid] = int(seerr_id)
|
|
self._write(d)
|
|
|
|
def add_request(self, rid: int, rec: dict) -> None:
|
|
with self._lock:
|
|
d = self._read()
|
|
reqs = d.setdefault("requests", {})
|
|
reqs[str(rid)] = rec
|
|
if len(reqs) > KEEP_REQUESTS:
|
|
for k in sorted(reqs, key=lambda k: reqs[k].get("at") or "")[:len(reqs) - KEEP_REQUESTS]:
|
|
reqs.pop(k, None)
|
|
self._write(d)
|
|
|
|
def request(self, rid) -> dict | None:
|
|
with self._lock:
|
|
return ((self._read().get("requests") or {}).get(str(rid)))
|
|
|
|
def find(self, media_type: str, tmdb: int) -> list[tuple[str, dict]]:
|
|
"""The not-yet-told requests of one title (a webhook without a request id)."""
|
|
with self._lock:
|
|
reqs = self._read().get("requests") or {}
|
|
return [(k, r) for k, r in reqs.items()
|
|
if r.get("type") == media_type and int(r.get("tmdb") or 0) == tmdb
|
|
and not r.get("told")]
|
|
|
|
def mark(self, rid, **fields) -> None:
|
|
with self._lock:
|
|
d = self._read()
|
|
r = (d.get("requests") or {}).get(str(rid))
|
|
if r is not None:
|
|
r.update(fields)
|
|
self._write(d)
|
|
|
|
# ── watches (``movies wait``) ────────────────────────────────────────────
|
|
@staticmethod
|
|
def _mine(r: dict, uid: str | None, kind: str, tmdb: int) -> bool:
|
|
return (r.get("uid") == uid and r.get("type") == kind
|
|
and int(r.get("tmdb") or 0) == tmdb)
|
|
|
|
def watch(self, uid: str | None, session: str | None, kind: str, tmdb: int,
|
|
label_: str, until: float) -> None:
|
|
"""Hold the webhook's push for the caller's records of this title
|
|
until ``until`` — a watch-only record when they never requested it
|
|
here (someone else did, or it went through Seerr's own page), so the
|
|
push still reaches them if the wait gives up first."""
|
|
with self._lock:
|
|
d = self._read()
|
|
reqs = d.setdefault("requests", {})
|
|
hits = [r for r in reqs.values() if self._mine(r, uid, kind, tmdb) and not r.get("told")]
|
|
if not hits:
|
|
key = f"w:{kind}:{tmdb}:{uid or 'owner'}"
|
|
reqs[key] = {"uid": uid, "session": session, "type": kind, "tmdb": tmdb,
|
|
"label": label_, "watchOnly": True,
|
|
"at": datetime.datetime.now(datetime.timezone.utc).isoformat()}
|
|
hits = [reqs[key]]
|
|
for r in hits:
|
|
r["watchUntil"] = until
|
|
if session and not r.get("session"):
|
|
r["session"] = session
|
|
self._write(d)
|
|
|
|
def unwatch(self, uid: str | None, kind: str, tmdb: int) -> list[str]:
|
|
"""End the caller's watch of this title; the keys whose push is held."""
|
|
held: list[str] = []
|
|
with self._lock:
|
|
d = self._read()
|
|
for k, r in (d.get("requests") or {}).items():
|
|
if self._mine(r, uid, kind, tmdb) and r.get("watchUntil"):
|
|
r["watchUntil"] = 0
|
|
if r.get("held") and not r.get("told"):
|
|
held.append(k)
|
|
self._write(d)
|
|
return held
|
|
|
|
def claim(self, uid: str | None, kind: str, tmdb: int, what: str) -> int:
|
|
"""The wait saw it end: the caller's records count as told (by
|
|
Claude, in the conversation) — the webhook won't push them again."""
|
|
n = 0
|
|
with self._lock:
|
|
d = self._read()
|
|
for r in (d.get("requests") or {}).values():
|
|
if self._mine(r, uid, kind, tmdb) and not r.get("told"):
|
|
r.update(told=what, toldAt=int(time.time()), toldBy="claude", watchUntil=0)
|
|
r.pop("held", None)
|
|
n += 1
|
|
if n:
|
|
self._write(d)
|
|
return n
|
|
|
|
def watching(self, kind: str, tmdb: int, now: float | None = None) -> bool:
|
|
now = now if now is not None else time.time()
|
|
with self._lock:
|
|
reqs = self._read().get("requests") or {}
|
|
return any(r.get("type") == kind and int(r.get("tmdb") or 0) == tmdb
|
|
and float(r.get("watchUntil") or 0) > now for r in reqs.values())
|
|
|
|
def latest(self, uid: str | None, kind: str, tmdb: int) -> dict | None:
|
|
"""The caller's newest record of this title (its seasons, when)."""
|
|
with self._lock:
|
|
reqs = self._read().get("requests") or {}
|
|
mine = [r for r in reqs.values() if self._mine(r, uid, kind, tmdb)
|
|
and not r.get("watchOnly")]
|
|
return max(mine, key=lambda r: r.get("at") or "") if mine else None
|
|
|
|
def titles(self) -> dict[tuple[str, int], str]:
|
|
with self._lock:
|
|
reqs = self._read().get("requests") or {}
|
|
return {(r.get("type"), int(r.get("tmdb") or 0)): r.get("label") or r.get("title")
|
|
for r in reqs.values()}
|
|
|
|
|
|
STORE = Store()
|
|
|
|
|
|
# ── Seerr's API ──────────────────────────────────────────────────────────────
|
|
class Seerr:
|
|
def __init__(self, http: httpx.AsyncClient):
|
|
self.http = http
|
|
|
|
async def call(self, method: str, path: str, *, params: dict | None = None,
|
|
body: dict | None = None):
|
|
url = f"{URL}/api/v1{path}"
|
|
if params:
|
|
# Seerr wants %20, not '+', in its query strings (search breaks on '+').
|
|
url += "?" + urllib.parse.urlencode(
|
|
{k: v for k, v in params.items() if v is not None}, quote_via=urllib.parse.quote)
|
|
try:
|
|
r = await self.http.request(method, url, json=body, timeout=30,
|
|
headers={"X-Api-Key": api_key(),
|
|
"Accept": "application/json"})
|
|
except httpx.HTTPError as e:
|
|
raise MediaError(502, f"Seerr didn't answer ({type(e).__name__}) — the media "
|
|
"stack may be down; ask the hub's owner", "upstream") from None
|
|
if r.status_code >= 400:
|
|
msg = ""
|
|
try:
|
|
d = r.json()
|
|
msg = str(d.get("message") or d.get("error") or "")
|
|
except ValueError:
|
|
msg = r.text[:200]
|
|
raise SeerrHTTP(r.status_code, msg or f"HTTP {r.status_code}")
|
|
if not r.content:
|
|
return None
|
|
try:
|
|
return r.json()
|
|
except ValueError:
|
|
raise MediaError(502, "Seerr answered without JSON", "upstream") from None
|
|
|
|
|
|
@dataclasses.dataclass
|
|
class Ctx:
|
|
deps: object
|
|
uid: str | None # the guest; None = the owner
|
|
name: str = ""
|
|
lang: str = "en"
|
|
session: str | None = None
|
|
|
|
@property
|
|
def guest(self) -> bool:
|
|
return self.uid is not None
|
|
|
|
|
|
def ctx_for(deps, uid: str | None, session: str | None) -> Ctx:
|
|
if uid is None:
|
|
return Ctx(deps, None, "Gabriel", "en", session)
|
|
u = deps.users.get(uid) or {}
|
|
try:
|
|
lang = deps.users.lang_of(uid) or "en"
|
|
except Exception:
|
|
lang = "en"
|
|
return Ctx(deps, uid, str(u.get("name") or uid), lang, session)
|
|
|
|
|
|
def _year(r: dict) -> int | None:
|
|
d = r.get("releaseDate") or r.get("firstAirDate") or ""
|
|
return int(d[:4]) if d[:4].isdigit() else None
|
|
|
|
|
|
def _status(r: dict) -> str:
|
|
return MEDIA_STATUS.get((r.get("mediaInfo") or {}).get("status"), "not requested")
|
|
|
|
|
|
def brief(r: dict) -> dict:
|
|
"""One search hit, as the skill shows it."""
|
|
out = {"type": r.get("mediaType"), "tmdb": r.get("id"),
|
|
"title": r.get("title") or r.get("name") or "",
|
|
"year": _year(r), "status": _status(r),
|
|
"rating": round(float(r.get("voteAverage") or 0), 1),
|
|
"overview": " ".join((r.get("overview") or "").split())[:300]}
|
|
orig = r.get("originalTitle") or r.get("originalName")
|
|
if orig and orig != out["title"]:
|
|
out["originalTitle"] = orig
|
|
if r.get("posterPath"):
|
|
out["poster"] = TMDB_IMG + r["posterPath"]
|
|
return out
|
|
|
|
|
|
def imdb_of(details: dict) -> str | None:
|
|
"""The title's IMDb id (``tt…``): a film's details carry it at the top, a
|
|
series' only under ``externalIds``."""
|
|
v = details.get("imdbId") or (details.get("externalIds") or {}).get("imdbId")
|
|
return v if isinstance(v, str) and v.startswith("tt") else None
|
|
|
|
|
|
def label(title: str, year: int | None) -> str:
|
|
return f"{title} ({year})" if year else title
|
|
|
|
|
|
def _kind(body: dict, ctx: Ctx, default: str | None = "movie") -> str | None:
|
|
kind = str(body.get("type") or "").strip().lower() or default
|
|
if kind in ("series", "show"):
|
|
kind = "tv"
|
|
if kind not in (None, "movie", "tv"):
|
|
raise MediaError(400, "type is movie or tv", "type")
|
|
if kind == "tv" and ctx.guest:
|
|
raise MediaError(403, "only movies can be requested — series stay with the hub's owner",
|
|
"tv")
|
|
return kind
|
|
|
|
|
|
def _tmdb(body: dict) -> int:
|
|
try:
|
|
n = int(body.get("tmdb"))
|
|
except (TypeError, ValueError):
|
|
raise MediaError(400, "tmdb: the TMDB id from a search", "tmdb") from None
|
|
if n <= 0:
|
|
raise MediaError(400, "tmdb: the TMDB id from a search", "tmdb")
|
|
return n
|
|
|
|
|
|
async def _details(s: Seerr, kind: str, tmdb: int, lang: str) -> dict:
|
|
try:
|
|
return await s.call("GET", f"/{kind}/{tmdb}", params={"language": lang})
|
|
except SeerrHTTP as e:
|
|
if e.status == 404:
|
|
raise MediaError(404, f"no {('movie' if kind == 'movie' else 'series')} "
|
|
f"with TMDB id {tmdb}", "notfound") from None
|
|
raise MediaError(502, f"Seerr: {e.message}", "upstream") from None
|
|
|
|
|
|
def watch_url(details: dict) -> str:
|
|
"""The title on the public Jellyfin (netflix.gabvdl.xyz) — never Seerr's
|
|
own ``mediaUrl``, which names the Jellyfin it talks to on the lab."""
|
|
jid = (details.get("mediaInfo") or {}).get("jellyfinMediaId")
|
|
return f"{WATCH_URL}/web/#/details?id={jid}" if jid else WATCH_URL
|
|
|
|
|
|
def progress_of(mi: dict) -> dict | None:
|
|
"""Radarr / Sonarr's queue for this title, as Seerr last synced it (its
|
|
download-sync job, about every minute): ``{pct, eta, size, sizeLeft,
|
|
state}`` over every item in the queue, None when nothing is downloading."""
|
|
items = [x for x in mi.get("downloadStatus") or [] if isinstance(x, dict)]
|
|
if not items:
|
|
return None
|
|
size = sum(int(x.get("size") or 0) for x in items)
|
|
left = sum(int(x.get("sizeLeft") or 0) for x in items)
|
|
pct = round(100 * (size - left) / size) if size else 0
|
|
etas = [str(x["estimatedCompletionTime"]) for x in items if x.get("estimatedCompletionTime")]
|
|
states = {str(x.get("status") or "").lower() for x in items}
|
|
state = next((s_ for s_ in ("downloading", "warning", "paused", "queued", "completed")
|
|
if s_ in states), next(iter(states), "") or "downloading")
|
|
return {"pct": max(0, min(100, pct)), "eta": max(etas) if etas else None,
|
|
"size": size, "sizeLeft": left, "state": state}
|
|
|
|
|
|
def stage_of(kind: str, details: dict, seasons=None) -> str:
|
|
"""Where a title is, in one word: ``available`` · ``downloading`` (in
|
|
Radarr's queue) · ``searching`` (approved, no release grabbed yet) ·
|
|
``requested`` (waiting for approval) · ``failed`` · ``declined`` ·
|
|
``not requested``. A series is ``available`` once the seasons asked for
|
|
are (``seasons``; else the whole show)."""
|
|
mi = details.get("mediaInfo") or {}
|
|
st = mi.get("status")
|
|
if st == 5 or (st == 4 and kind == "movie"):
|
|
return "available"
|
|
if kind == "tv" and st == 4 and isinstance(seasons, list) and seasons:
|
|
here = {x.get("seasonNumber"): x.get("status") for x in mi.get("seasons") or []}
|
|
if all(here.get(n) == 5 for n in seasons):
|
|
return "available"
|
|
if mi.get("downloadStatus"):
|
|
return "downloading"
|
|
reqs = [r.get("status") for r in mi.get("requests") or [] if isinstance(r, dict)]
|
|
if st in (2, 3, 4):
|
|
if reqs and all(x == 4 for x in reqs):
|
|
return "failed"
|
|
return "requested" if st == 2 else "searching"
|
|
if reqs and all(x == 3 for x in reqs):
|
|
return "declined"
|
|
return "not requested"
|
|
|
|
|
|
# ── the ops ──────────────────────────────────────────────────────────────────
|
|
def settle(kind: str, tmdb: int, stage: str, progress: dict | None,
|
|
now: float | None = None) -> str:
|
|
"""``stage_of`` with the hub's memory of the download: ``importing``
|
|
once the file is complete (still in the queue at 100 %, or gone from it
|
|
within ``IMPORT_WINDOW_S``) and Jellyfin hasn't got it yet."""
|
|
now = now if now is not None else time.time()
|
|
key = (kind, tmdb)
|
|
if stage == "downloading":
|
|
_downloads[key] = now
|
|
if progress and progress.get("pct") == 100 and progress.get("state") == "completed":
|
|
return "importing"
|
|
return stage
|
|
if stage == "searching" and now - _downloads.get(key, 0) < IMPORT_WINDOW_S:
|
|
return "importing"
|
|
if stage in FINAL:
|
|
_downloads.pop(key, None)
|
|
return stage
|
|
|
|
|
|
async def kick_scan(s: Seerr, now: float | None = None) -> bool:
|
|
"""Run Seerr's Jellyfin scan now rather than at its next 5-minute tick
|
|
(at most every ``SCAN_EVERY_S``). True if it was asked."""
|
|
global _last_scan
|
|
now = now if now is not None else time.time()
|
|
if now - _last_scan < SCAN_EVERY_S:
|
|
return False
|
|
_last_scan = now
|
|
try:
|
|
await s.call("POST", f"/settings/jobs/{SCAN_JOB}/run")
|
|
except (SeerrHTTP, MediaError) as e:
|
|
log.warning("media: Seerr's %s didn't start: %s", SCAN_JOB, getattr(e, "message", e))
|
|
return False
|
|
return True
|
|
|
|
|
|
async def op_search(s: Seerr, ctx: Ctx, body: dict) -> dict:
|
|
q = " ".join(str(body.get("query") or "").split())[:200]
|
|
if not q:
|
|
raise MediaError(400, "query: the title to look for", "query")
|
|
kind = _kind(body, ctx, "movie" if ctx.guest else None)
|
|
year = body.get("year")
|
|
lang = str(body.get("lang") or ctx.lang)[:5]
|
|
out: list[dict] = []
|
|
for page in (1, 2):
|
|
try:
|
|
d = await s.call("GET", "/search", params={"query": q, "page": page, "language": lang})
|
|
except SeerrHTTP as e:
|
|
raise MediaError(502, f"Seerr's search failed: {e.message}", "upstream") from None
|
|
for r in d.get("results") or []:
|
|
if r.get("mediaType") not in ("movie", "tv") or (kind and r["mediaType"] != kind):
|
|
continue
|
|
b = brief(r)
|
|
if year and b["year"] and abs(b["year"] - int(year)) > 1:
|
|
continue
|
|
out.append(b)
|
|
if len(out) >= 5 or page >= int(d.get("totalPages") or 1):
|
|
break
|
|
return {"query": q, "results": out[:int(body.get("limit") or 8)]}
|
|
|
|
|
|
async def op_info(s: Seerr, ctx: Ctx, body: dict) -> dict:
|
|
kind = _kind(body, ctx)
|
|
tmdb = _tmdb(body)
|
|
d = await _details(s, kind, tmdb, str(body.get("lang") or ctx.lang)[:5])
|
|
info = brief({**d, "mediaType": kind})
|
|
info["genres"] = [g.get("name") for g in d.get("genres") or []][:5]
|
|
if kind == "movie":
|
|
info["runtime"] = d.get("runtime")
|
|
else:
|
|
seasons = {x.get("seasonNumber"): x.get("status") for x in
|
|
(d.get("mediaInfo") or {}).get("seasons") or []}
|
|
info["seasons"] = [{"season": x["seasonNumber"], "episodes": x.get("episodeCount"),
|
|
"aired": x.get("airDate"),
|
|
"status": MEDIA_STATUS.get(seasons.get(x["seasonNumber"]), "not requested")}
|
|
for x in d.get("seasons") or [] if x.get("seasonNumber")]
|
|
if info["status"] == "available":
|
|
info["watch"] = watch_url(d)
|
|
return info
|
|
|
|
|
|
def latest_season(details: dict) -> int | None:
|
|
today = datetime.date.today().isoformat()
|
|
aired = [x["seasonNumber"] for x in details.get("seasons") or []
|
|
if x.get("seasonNumber") and (x.get("airDate") or "9999") <= today]
|
|
return max(aired) if aired else None
|
|
|
|
|
|
async def _free_gb(s: Seerr) -> float | None:
|
|
"""Free space under Radarr's movie root (None: couldn't tell)."""
|
|
try:
|
|
servers = await s.call("GET", "/service/radarr") or []
|
|
default = next((x for x in servers if x.get("isDefault")), servers[0] if servers else None)
|
|
if not default:
|
|
return None
|
|
d = await s.call("GET", f"/service/radarr/{default['id']}")
|
|
roots = d.get("rootFolders") or []
|
|
root = next((r for r in roots if r.get("path") == default.get("activeDirectory")),
|
|
roots[0] if roots else None)
|
|
return (root or {}).get("freeSpace", 0) / 2 ** 30 if root else None
|
|
except (SeerrHTTP, MediaError, StopIteration, KeyError, TypeError):
|
|
return None
|
|
|
|
|
|
async def ensure_user(s: Seerr, ctx: Ctx) -> int | None:
|
|
"""The caller's Seerr user: the owner's own, or the guest's (made on first use)."""
|
|
if not ctx.guest:
|
|
return owner_user_id()
|
|
have = STORE.user(ctx.uid)
|
|
if have:
|
|
try:
|
|
await s.call("GET", f"/user/{have}")
|
|
return have
|
|
except SeerrHTTP as e:
|
|
if e.status != 404:
|
|
raise MediaError(502, f"Seerr: {e.message}", "upstream") from None
|
|
email = f"guest-{ctx.uid}@{GUEST_EMAIL_DOMAIN}"
|
|
try:
|
|
u = await s.call("POST", "/user", body={"email": email, "username": ctx.name[:40],
|
|
"password": secrets.token_urlsafe(24)})
|
|
sid = int(u["id"])
|
|
except SeerrHTTP as e:
|
|
if e.status != 409:
|
|
raise MediaError(502, f"Seerr couldn't make your user: {e.message}", "upstream") from None
|
|
users = (await s.call("GET", "/user", params={"take": 500})).get("results") or []
|
|
hit = next((u for u in users if (u.get("email") or "").lower() == email), None)
|
|
if not hit:
|
|
raise MediaError(502, "Seerr has a user with your address but won't show it",
|
|
"upstream") from None
|
|
sid = int(hit["id"])
|
|
STORE.set_user(ctx.uid, sid)
|
|
return sid
|
|
|
|
|
|
async def quota_of(s: Seerr, seerr_id: int | None) -> dict | None:
|
|
if not seerr_id:
|
|
return None
|
|
try:
|
|
q = await s.call("GET", f"/user/{seerr_id}/quota")
|
|
except (SeerrHTTP, MediaError):
|
|
return None
|
|
m = (q or {}).get("movie") or {}
|
|
out = {"movies": {"limit": m.get("limit") or None, "days": m.get("days"),
|
|
"used": m.get("used") or 0, "remaining": m.get("remaining")}}
|
|
if m.get("restricted") and m.get("limit"):
|
|
out["movies"]["nextFree"] = await _next_free(s, seerr_id, int(m.get("days") or 7))
|
|
return out
|
|
|
|
|
|
async def _next_free(s: Seerr, seerr_id: int, days: int) -> str | None:
|
|
"""When the oldest movie request inside the quota window leaves it."""
|
|
try:
|
|
d = await s.call("GET", f"/user/{seerr_id}/requests", params={"take": 50})
|
|
except (SeerrHTTP, MediaError):
|
|
return None
|
|
now = datetime.datetime.now(datetime.timezone.utc)
|
|
stamps = []
|
|
for r in (d or {}).get("results") or []:
|
|
if r.get("type") != "movie" or r.get("status") == 3:
|
|
continue
|
|
try:
|
|
at = datetime.datetime.fromisoformat(str(r.get("createdAt")).replace("Z", "+00:00"))
|
|
except ValueError:
|
|
continue
|
|
if now - at < datetime.timedelta(days=days):
|
|
stamps.append(at)
|
|
if not stamps:
|
|
return None
|
|
return (min(stamps) + datetime.timedelta(days=days)).date().isoformat()
|
|
|
|
|
|
async def op_request(s: Seerr, ctx: Ctx, body: dict) -> dict:
|
|
kind = _kind(body, ctx)
|
|
tmdb = _tmdb(body)
|
|
d = await _details(s, kind, tmdb, ctx.lang)
|
|
title, year = d.get("title") or d.get("name") or str(tmdb), _year(d)
|
|
name = label(title, year)
|
|
status = (d.get("mediaInfo") or {}).get("status")
|
|
if status == 5 or (status == 4 and kind == "movie"):
|
|
return {"already": "available", "title": title, "year": year, "watch": watch_url(d),
|
|
"message": f"{name} is already on Jellyfin"}
|
|
if status in (2, 3) and kind == "movie":
|
|
return {"already": "requested", "title": title, "year": year,
|
|
"status": MEDIA_STATUS[status],
|
|
"message": f"{name} is already requested — it shows up on Jellyfin once downloaded"}
|
|
if ctx.guest:
|
|
free = await _free_gb(s)
|
|
if free is not None and free < MIN_FREE_GB:
|
|
raise MediaError(507, f"the lab's disk is nearly full ({free:.0f} GB left) — "
|
|
"ask the hub's owner to make room first", "disk")
|
|
seerr_id = await ensure_user(s, ctx)
|
|
payload: dict = {"mediaType": kind, "mediaId": tmdb, "is4k": False}
|
|
if seerr_id:
|
|
payload["userId"] = seerr_id
|
|
seasons = None
|
|
if kind == "tv":
|
|
raw = body.get("seasons")
|
|
if raw == "all":
|
|
seasons = "all"
|
|
elif raw:
|
|
seasons = sorted({int(x) for x in (raw if isinstance(raw, list) else [raw])})
|
|
else:
|
|
last = latest_season(d)
|
|
if last is None:
|
|
raise MediaError(400, f"{name} has no aired season yet", "seasons")
|
|
seasons = [last]
|
|
payload["seasons"] = seasons
|
|
try:
|
|
req = await s.call("POST", "/request", body=payload)
|
|
except SeerrHTTP as e:
|
|
low = e.message.lower()
|
|
if e.status == 403 and "quota" in low:
|
|
q = await quota_of(s, seerr_id) or {}
|
|
m = q.get("movies") or {}
|
|
when = m.get("nextFree")
|
|
raise MediaError(429, (f"you've used your {m.get('limit') or 'weekly'} movies for the "
|
|
f"last {m.get('days') or 7} days"
|
|
+ (f" — the next one frees up on {when}" if when else "")),
|
|
"quota") from None
|
|
if e.status == 409:
|
|
return {"already": "requested", "title": title, "year": year,
|
|
"message": f"{name} is already requested"}
|
|
if e.status == 403:
|
|
raise MediaError(403, f"Seerr refused the request: {e.message}", "refused") from None
|
|
raise MediaError(502, f"Seerr couldn't take the request: {e.message}", "upstream") from None
|
|
rid = int(req.get("id") or 0)
|
|
rstatus = REQUEST_STATUS.get(req.get("status"), "requested")
|
|
if rid:
|
|
STORE.add_request(rid, {"uid": ctx.uid, "session": ctx.session, "type": kind,
|
|
"tmdb": tmdb, "title": title, "year": year, "label": name,
|
|
"seasons": seasons,
|
|
"at": datetime.datetime.now(datetime.timezone.utc).isoformat()})
|
|
quota = await quota_of(s, seerr_id) if ctx.guest else None
|
|
if ctx.guest:
|
|
_owner_push_request(ctx, kind, tmdb, name, rstatus, quota)
|
|
out = {"request": {"id": rid, "status": rstatus}, "title": title, "year": year,
|
|
"type": kind, "message": f"{name}: {rstatus} — downloading starts now; "
|
|
"the requester gets a push once it is on Jellyfin"}
|
|
if seasons:
|
|
out["seasons"] = seasons
|
|
if quota:
|
|
out["quota"] = quota
|
|
return out
|
|
|
|
|
|
async def op_requests(s: Seerr, ctx: Ctx, body: dict) -> dict:
|
|
seerr_id = STORE.user(ctx.uid) if ctx.guest else (owner_user_id() or 1)
|
|
if not seerr_id:
|
|
return {"requests": [], "quota": {"movies": {"limit": None, "used": 0}},
|
|
"message": "no request yet"}
|
|
try:
|
|
d = await s.call("GET", f"/user/{seerr_id}/requests",
|
|
params={"take": min(int(body.get("limit") or 20), 50)})
|
|
except SeerrHTTP as e:
|
|
raise MediaError(502, f"Seerr: {e.message}", "upstream") from None
|
|
known = STORE.titles()
|
|
rows = []
|
|
for r in (d or {}).get("results") or []:
|
|
media = r.get("media") or {}
|
|
rows.append({"id": r.get("id"), "type": r.get("type"), "tmdb": media.get("tmdbId"),
|
|
"title": known.get((r.get("type"), int(media.get("tmdbId") or 0))),
|
|
"request": REQUEST_STATUS.get(r.get("status"), "?"),
|
|
"status": MEDIA_STATUS.get(media.get("status"), "?"),
|
|
"at": (r.get("createdAt") or "")[:10]})
|
|
missing = [x for x in rows if not x["title"] and x["tmdb"]]
|
|
|
|
async def fill(x):
|
|
try:
|
|
dd = await s.call("GET", f"/{x['type']}/{x['tmdb']}", params={"language": ctx.lang})
|
|
x["title"] = label(dd.get("title") or dd.get("name") or "", _year(dd))
|
|
except (SeerrHTTP, MediaError):
|
|
x["title"] = f"TMDB {x['tmdb']}"
|
|
await asyncio.gather(*(fill(x) for x in missing[:20]))
|
|
return {"requests": rows, "quota": await quota_of(s, seerr_id)}
|
|
|
|
|
|
async def op_status(s: Seerr, ctx: Ctx, body: dict) -> dict:
|
|
"""One title's live state — the conversation's movie card, and each poll
|
|
of ``movies wait`` (``watch: true``: renews the caller's lease on the
|
|
webhook's push; the poll that sees it end claims that push)."""
|
|
kind = _kind(body, ctx)
|
|
tmdb = _tmdb(body)
|
|
d = await _details(s, kind, tmdb, str(body.get("lang") or ctx.lang)[:5])
|
|
title, year = d.get("title") or d.get("name") or str(tmdb), _year(d)
|
|
mine = STORE.latest(ctx.uid, kind, tmdb)
|
|
seasons = (mine or {}).get("seasons")
|
|
stage = stage_of(kind, d, seasons if isinstance(seasons, list) else None)
|
|
progress = progress_of(d.get("mediaInfo") or {}) if stage == "downloading" else None
|
|
stage = settle(kind, tmdb, stage, progress)
|
|
if stage == "importing":
|
|
await kick_scan(s)
|
|
out = {"type": kind, "tmdb": tmdb, "title": title, "year": year,
|
|
"stage": stage, "status": _status(d),
|
|
"rating": round(float(d.get("voteAverage") or 0), 1),
|
|
"runtime": d.get("runtime") if kind == "movie" else None,
|
|
"progress": progress if stage == "downloading" else None}
|
|
if d.get("posterPath"):
|
|
out["poster"] = TMDB_IMG + d["posterPath"]
|
|
if imdb := imdb_of(d):
|
|
out["imdb"] = imdb
|
|
if stage == "available":
|
|
out["watch"] = watch_url(d)
|
|
if mine:
|
|
out["requestedAt"] = mine.get("at")
|
|
if seasons:
|
|
out["seasons"] = seasons
|
|
if body.get("watch"):
|
|
if stage in FINAL:
|
|
STORE.claim(ctx.uid, kind, tmdb, stage)
|
|
elif stage != "not requested":
|
|
STORE.watch(ctx.uid, ctx.session, kind, tmdb, label(title, year),
|
|
time.time() + WATCH_LEASE_S)
|
|
out["watching"] = STORE.watching(kind, tmdb)
|
|
return out
|
|
|
|
|
|
async def op_unwatch(s: Seerr, ctx: Ctx, body: dict) -> dict:
|
|
"""The wait is over without seeing the end (timed out, stopped): a push
|
|
the webhook held for the caller goes out now."""
|
|
kind = _kind(body, ctx)
|
|
tmdb = _tmdb(body)
|
|
held = STORE.unwatch(ctx.uid, kind, tmdb)
|
|
for key in held:
|
|
release(ctx.deps, key)
|
|
return {"ok": True, "released": len(held)}
|
|
|
|
|
|
OPS = {"search": op_search, "info": op_info, "request": op_request, "requests": op_requests,
|
|
"status": op_status, "unwatch": op_unwatch}
|
|
|
|
|
|
# ── pushes ───────────────────────────────────────────────────────────────────
|
|
def _notify(deps, d: dict) -> None:
|
|
from notifications.service import _create_notify
|
|
try:
|
|
_create_notify(deps, d)
|
|
except Exception:
|
|
log.exception("media push failed")
|
|
|
|
|
|
def _owner_push_request(ctx: Ctx, kind: str, tmdb: int, name: str, status: str,
|
|
quota: dict | None) -> None:
|
|
m = (quota or {}).get("movies") or {}
|
|
week = (f" · {m.get('used')}/{m.get('limit')} in {m.get('days')} days"
|
|
if m.get("limit") else "")
|
|
_notify(ctx.deps, {"title": f"🎬 {ctx.name} requested {name}",
|
|
"message": f"{status.capitalize()}{week} · Seerr",
|
|
"type": "media", "url": f"{PUBLIC_URL}/{kind}/{tmdb}", "sessionId": ""})
|
|
|
|
|
|
TEXT = {
|
|
"available": {"en": ("🎬 {name} is ready", "Watch it on {host} with your Jellyfin account."),
|
|
"fr": ("🎬 {name} est disponible", "Regarde-le sur {host} avec ton compte Jellyfin.")},
|
|
"failed": {"en": ("⚠️ {name} couldn't be downloaded", "Gabriel has been told."),
|
|
"fr": ("⚠️ {name} n'a pas pu être téléchargé", "Gabriel est prévenu.")},
|
|
"declined": {"en": ("🎬 {name} was declined", "Ask Gabriel if you think it's a mistake."),
|
|
"fr": ("🎬 {name} a été refusé", "Demande à Gabriel si c'est une erreur.")},
|
|
}
|
|
|
|
|
|
def _tell(deps, rec: dict, what: str, url: str) -> None:
|
|
"""Push the requester (a guest in their language, else the owner)."""
|
|
name = rec.get("label") or rec.get("title") or "your request"
|
|
host = urllib.parse.urlsplit(WATCH_URL).netloc or WATCH_URL
|
|
en_t, en_m = (x.format(name=name, host=host) for x in TEXT[what]["en"])
|
|
fr_t, fr_m = (x.format(name=name, host=host) for x in TEXT[what]["fr"])
|
|
note = {"title": en_t, "message": en_m, "type": "media" if what == "available" else "warn",
|
|
"url": url, "i18n": {"fr": {"title": fr_t, "message": fr_m}}}
|
|
uid, session = rec.get("uid"), rec.get("session")
|
|
if session:
|
|
_notify(deps, {**note, "sessionId": session})
|
|
return
|
|
if uid:
|
|
from notifications.service import VIEW_URL
|
|
from users import deliver
|
|
try:
|
|
deliver.to_guests(deps, [uid], en_t, en_m, url, VIEW_URL,
|
|
extra={"type": note["type"]}, i18n=note["i18n"])
|
|
except Exception:
|
|
log.exception("media push to %s failed", uid)
|
|
return
|
|
_notify(deps, {**note, "sessionId": ""})
|
|
|
|
|
|
def handle_webhook(deps, payload: dict) -> dict:
|
|
"""Seerr's notification (its webhook agent, template in
|
|
``services/media/README.md``): tell whoever asked through the hub."""
|
|
kind = str(payload.get("notification_type") or "")
|
|
if kind == "TEST_NOTIFICATION":
|
|
return {"ok": True, "test": True}
|
|
what = {"MEDIA_AVAILABLE": "available", "MEDIA_FAILED": "failed",
|
|
"MEDIA_DECLINED": "declined"}.get(kind)
|
|
if not what:
|
|
return {"ok": True, "ignored": kind}
|
|
media_type = str(payload.get("media_type") or "")
|
|
try:
|
|
tmdb = int(payload.get("tmdb") or 0)
|
|
except ValueError:
|
|
tmdb = 0
|
|
rid = str(payload.get("request_id") or "").strip()
|
|
rec = STORE.request(rid) if rid else None
|
|
hits = [(rid, rec)] if rec else []
|
|
# …and whoever else waits for this title (another requester, a watcher).
|
|
if tmdb:
|
|
hits += [(k, r) for k, r in STORE.find(media_type, tmdb) if k != rid]
|
|
url = WATCH_URL
|
|
if payload.get("jellyfin_id") and what == "available":
|
|
url = f"{WATCH_URL}/web/#/details?id={payload['jellyfin_id']}"
|
|
told = held = 0
|
|
now = time.time()
|
|
for key, r in hits:
|
|
if r.get("told") == what:
|
|
continue
|
|
# Claude is watching it (`movies wait`): it says it in the
|
|
# conversation itself — hold this push until its lease lapses.
|
|
if float(r.get("watchUntil") or 0) > now:
|
|
STORE.mark(key, held=what, heldUrl=url if what == "available" else "")
|
|
_schedule_release(deps, key, float(r["watchUntil"]) - now + 5)
|
|
held += 1
|
|
continue
|
|
# The owner's own failure is the push below; a guest's failure or
|
|
# decline links back to the conversation they asked from.
|
|
if not (what == "failed" and not r.get("uid")):
|
|
_tell(deps, r, what, url if what == "available" else "")
|
|
told += 1
|
|
STORE.mark(key, told=what, toldAt=int(time.time()))
|
|
if what == "failed":
|
|
subject = str(payload.get("subject") or "a request")
|
|
_notify(deps, {"title": f"⚠️ Seerr: {subject} failed",
|
|
"message": str(payload.get("message") or "")[:200] or "Radarr/Sonarr refused it",
|
|
"type": "warn", "url": PUBLIC_URL, "sessionId": ""})
|
|
return {"ok": True, "told": told, **({"held": held} if held else {})}
|
|
|
|
|
|
def release(deps, key: str) -> bool:
|
|
"""A held push whose watch is over: send it, unless the wait claimed it
|
|
(Claude told them) or a renewed lease still covers it. True if sent."""
|
|
r = STORE.request(key)
|
|
if not r or r.get("told") or not r.get("held"):
|
|
return False
|
|
left = float(r.get("watchUntil") or 0) - time.time()
|
|
if left > 0:
|
|
_schedule_release(deps, key, left + 5)
|
|
return False
|
|
what = r["held"]
|
|
if not (what == "failed" and not r.get("uid")):
|
|
_tell(deps, r, what, r.get("heldUrl") or "")
|
|
STORE.mark(key, told=what, toldAt=int(time.time()), held=None)
|
|
return True
|
|
|
|
|
|
def _schedule_release(deps, key: str, delay: float) -> None:
|
|
t = threading.Timer(max(1.0, delay), lambda: _safe_release(deps, key))
|
|
t.daemon = True
|
|
t.start()
|
|
|
|
|
|
def _safe_release(deps, key: str) -> None:
|
|
try:
|
|
release(deps, key)
|
|
except Exception:
|
|
log.exception("media: releasing the held push %s failed", key)
|