"""The review screen: candidates on the left, evidence on the right, decisions persisted as you go.""" from __future__ import annotations import contextlib import json from datetime import datetime from pathlib import Path from rich.markup import escape from textual import work from textual.app import App, ComposeResult from textual.binding import Binding from textual.containers import Horizontal, VerticalScroll from textual.screen import ModalScreen from textual.widgets import DataTable, Footer, Header, Input, Static from plexreaper.config import Config from plexreaper.execute import PlanItem, build_plan, close_clients, load_indexes, open_clients, run_plan from plexreaper.ledger import Ledger from plexreaper.models import Candidate, ScanResult from plexreaper.sources.arr import summarize from plexreaper.sources.tmdb import TmdbClient TMDB_TTL_HOURS = 24 * 14 SORTS = ("score", "size", "age", "title") MAX_ROWS = 3000 # DataTable stays snappy; the tail is low-score anyway, and the filter narrows MARK = {"reap": "[red]✘[/]", "keep": "[green]✔[/]", "downgrade": "[yellow]▼[/]", "protect": "[blue]⛨[/]"} def candidate_json(c: Candidate) -> dict: return { "guid": c.title.guid, "rating_key": c.title.rating_key, "kind": c.title.kind, "title": c.title.title, "year": c.title.year, "library": c.title.library_name, "size_gb": round(c.title.size_gb, 2), "score": c.score, "decision": c.decision, "flags": c.breakdown.flags, "external_ids": c.title.external_ids, } class ConfirmScreen(ModalScreen[bool]): BINDINGS = [Binding("y", "yes", "Yes, execute"), Binding("n,escape", "no", "No")] def __init__(self, text: str) -> None: super().__init__() self.text = text def compose(self) -> ComposeResult: yield Static(self.text, id="confirm") yield Footer() def action_yes(self) -> None: self.dismiss(True) def action_no(self) -> None: self.dismiss(False) class ReviewScreen(ModalScreen[None]): """Marked items → plan (dry run, automatic) → execute (X, confirmed).""" BINDINGS = [ Binding("escape", "dismiss", "Back"), Binding("e", "export", "Export JSON"), Binding("r", "plan", "Re-plan"), Binding("X", "execute", "Execute"), ] def __init__(self, marked: list[Candidate], export_path: Path, cfg: Config | None, ledger: Ledger) -> None: super().__init__() self.marked = marked self.export_path = export_path self.cfg = cfg self.ledger = ledger self.plan: list[PlanItem] | None = None self.note = "" self.busy = False def compose(self) -> ComposeResult: with VerticalScroll(id="review"): yield Static(self._text(), id="review-text") yield Footer() def on_mount(self) -> None: self.action_plan() def _text(self) -> str: gb = sum(c.title.size_gb for c in self.marked) lines = [f"[b]{len(self.marked)} marked · {gb:.0f} GB[/b]", ""] if self.plan is None: for c in self.marked: lines.append( f"{MARK.get(c.decision or '', ' ')} {c.score:3d} {c.title.size_gb:6.1f}G {escape(c.title.title)} ({c.title.year or '?'})" ) lines += ["", "[dim]planning against Radarr/Sonarr…[/dim]" if self.busy else "[dim]no plan yet (r)[/dim]"] else: for p in self.plan: colour = "green" if p.ok else "yellow" lines.append(f"[{colour}]{p.action:<9}[/{colour}] {escape(p.title)} ({p.year or '?'}) [dim]{escape(p.describe())}[/dim]") doable = [p for p in self.plan if p.ok] lines += ["", f"[b]{len(doable)} executable · {sum(p.size_gb for p in doable):.1f} GB[/b]"] lines.append("[dim]X executes for real after confirmation · e exports JSON · r re-plans[/dim]") if self.note: lines += ["", self.note] return "\n".join(lines) def _refresh(self) -> None: self.query_one("#review-text", Static).update(self._text()) def action_export(self) -> None: payload = {"exported_at": datetime.now().isoformat(timespec="seconds"), "items": [candidate_json(c) for c in self.marked]} self.export_path.write_text(json.dumps(payload, indent=1), encoding="utf-8") self.note = f"[green]wrote {self.export_path}[/green]" self._refresh() def action_plan(self) -> None: if self.cfg is None or not self.cfg.arr: self.note = "[yellow]no [[arr]] instances configured; export only[/yellow]" self._refresh() return if not self.busy: self.busy = True self._refresh() self._plan_worker(dry_run=True) def action_execute(self) -> None: if not self.plan or not any(p.ok for p in self.plan) or self.busy: return doable = [p for p in self.plan if p.ok] text = ( f"[b]Execute {len(doable)} action(s) through Radarr/Sonarr?[/b]\n\n" f"{sum(p.size_gb for p in doable):.1f} GB of files will be deleted. The *arr entries stay.\n\n" "[b]y[/b] yes [b]n[/b] no" ) def done(confirmed: bool | None) -> None: if confirmed: self.busy = True self.note = "[yellow]executing…[/yellow]" self._refresh() self._plan_worker(dry_run=False) self.app.push_screen(ConfirmScreen(text), done) @work(exclusive=True, group="execute") async def _plan_worker(self, *, dry_run: bool) -> None: assert self.cfg is not None clients = open_clients(self.cfg) try: indexes = await load_indexes(clients) self.plan = await build_plan(self.cfg, self.marked, clients, indexes) if not dry_run: outcomes = await run_plan(self.plan, clients, indexes, self.ledger, dry_run=False) done = [o for o in outcomes if o.ok] failed = [o for o in outcomes if o.item.ok and not o.ok] self.note = f"[green]executed {len(done)}[/green]" + (f" · [red]failed {len(failed)}[/red]" if failed else "") for o in failed: self.note += f"\n[red]{escape(o.item.title)}: {escape(o.detail)}[/red]" app = self.app if isinstance(app, ReaperApp): app.after_execution({o.item.guid for o in done}) else: self.note = "" except Exception as exc: # noqa: BLE001 self.note = f"[red]{type(exc).__name__}: {escape(str(exc))}[/red]" finally: await close_clients(clients) self.busy = False self._refresh() class ReaperApp(App[None]): CSS_PATH = "app.tcss" TITLE = "PlexReaper" BINDINGS = [ Binding("space", "mark('reap')", "Reap"), Binding("k", "mark('keep')", "Keep"), Binding("d", "mark('downgrade')", "Downgrade"), Binding("p", "mark('protect')", "Protect"), Binding("u", "clear", "Clear"), Binding("slash", "filter", "Filter"), Binding("escape", "hide_filter", "Hide filter", show=False), Binding("s", "cycle_sort", "Sort"), Binding("h", "toggle_hidden", "Show kept"), Binding("x", "review", "Review"), Binding("q", "quit", "Quit"), ] def __init__( self, result: ScanResult, ledger: Ledger, *, cfg: Config | None = None, export_path: Path = Path("reap-list.json"), ) -> None: super().__init__() self.result = result self.ledger = ledger self.cfg = cfg self.export_path = export_path self.arr_info: dict[str, dict] = {} # guid -> summary, loaded in the background self.tmdb_info: dict[str, dict] = {} # guid -> tmdb summary self.by_key = {str(c.title.rating_key): c for c in result.candidates} self.filter_text = "" self.sort_index = 0 self.show_hidden = False self.truncated = 0 # ---- layout ------------------------------------------------------------- def compose(self) -> ComposeResult: yield Header() with Horizontal(id="body"): yield DataTable(id="table", cursor_type="row", zebra_stripes=True) with VerticalScroll(id="side"): yield Static("", id="evidence") yield Input(placeholder="filter by title, library or genre…", id="filter", classes="hidden") yield Static("", id="stats") yield Footer() def on_mount(self) -> None: table = self.query_one("#table", DataTable) self.cols = table.add_columns(" ", "score", "size", "age", "kind", "title", "why") self._fill() table.focus() if self.cfg and any(a.api_key for a in self.cfg.arr): self._load_arr() # ---- data ----------------------------------------------------------------- def visible(self) -> list[Candidate]: rows = [c for c in self.result.candidates if self.show_hidden or c.decision != "keep"] if self.filter_text: f = self.filter_text.lower() rows = [ c for c in rows if f in c.title.title.lower() or f in c.title.library_name.lower() or any(f in g.lower() for g in c.title.genres) ] key = { "score": lambda c: (-c.score, -c.title.size_bytes), "size": lambda c: -c.title.size_bytes, "age": lambda c: c.title.added_at, "title": lambda c: c.title.title.lower(), }[SORTS[self.sort_index]] return sorted(rows, key=key) def _row(self, c: Candidate) -> tuple[str, ...]: age = (self.result.scanned_at - c.title.added_at).days / 365 return ( MARK.get(c.decision or "", " "), str(c.score), f"{c.title.size_gb:.1f}G", f"{age:.1f}y", "M" if c.title.kind == "movie" else "S", f"{escape(c.title.title)} ({c.title.year or '?'})", c.why, ) def _fill(self) -> None: table = self.query_one("#table", DataTable) table.clear() rows = self.visible() self.truncated = max(0, len(rows) - MAX_ROWS) for c in rows[:MAX_ROWS]: table.add_row(*self._row(c), key=str(c.title.rating_key)) self._stats() if table.row_count: table.move_cursor(row=0) self._show(self.current()) def current(self) -> Candidate | None: table = self.query_one("#table", DataTable) if table.row_count == 0: return None key = table.coordinate_to_cell_key(table.cursor_coordinate).row_key.value return self.by_key.get(str(key)) def on_data_table_row_highlighted(self, event: DataTable.RowHighlighted) -> None: if event.row_key is not None and event.row_key.value is not None: c = self.by_key.get(str(event.row_key.value)) self._show(c) if c is not None and self.cfg and self.cfg.tmdb.api_key and c.title.guid not in self.tmdb_info: self._load_tmdb(c) # ---- on-the-fly enrichment --------------------------------------------------- @work(exclusive=True, group="arr", thread=False) async def _load_arr(self) -> None: assert self.cfg is not None clients = open_clients(self.cfg) try: indexes = await load_indexes(clients) for c in self.result.candidates: a = self.cfg.arr_for_library(c.title.library_id) if a is None or a.name not in indexes: continue found = indexes[a.name].resolve(c.title) if found is not None: self.arr_info[c.title.guid] = summarize(a, found, indexes[a.name].profiles) self.notify(f"arr: matched {len(self.arr_info)} titles", timeout=3) except Exception as exc: # noqa: BLE001 self.notify(f"arr enrichment failed: {exc}", severity="error") finally: await close_clients(clients) self._show(self.current()) @work(exclusive=True, group="tmdb", thread=False) async def _load_tmdb(self, c: Candidate) -> None: assert self.cfg is not None tmdb_id = c.title.external_ids.get("tmdb", "") if not tmdb_id.isdigit(): return key = f"tmdb:{c.title.kind}:{tmdb_id}" info = self.ledger.cache_get(key, TMDB_TTL_HOURS) if info is None: try: async with TmdbClient(self.cfg.tmdb) as tmdb: info = await tmdb.lookup(c.title.kind, int(tmdb_id)) except Exception as exc: # noqa: BLE001 info = {"error": str(exc)} else: self.ledger.cache_set(key, info) self.tmdb_info[c.title.guid] = info if self.current() is c: self._show(c) def after_execution(self, guids: set[str]) -> None: """Executed titles lose their decision; they vanish from Plex after its next scan.""" table = self.query_one("#table", DataTable) for c in self.result.candidates: if c.title.guid in guids: c.decision = None with contextlib.suppress(Exception): # row may be filtered out of the table table.update_cell(str(c.title.rating_key), self.cols[0], "[dim]⌫[/]") self._stats() # ---- panels --------------------------------------------------------------- def _show(self, c: Candidate | None) -> None: panel = self.query_one("#evidence", Static) if c is None: panel.update("[dim]no candidates[/dim]") return t, e = c.title, c.evidence lines = [ f"[b]{escape(t.title)}[/b] ({t.year or '?'})", f"[dim]{escape(t.library_name)} · {escape(', '.join(t.genres[:4]) or 'no genre')} · {t.size_gb:.1f} GB · {t.hours:.1f} h[/dim]", ] if t.kind == "show": lines.append(f"[dim]{t.season_count} seasons · {t.episode_count} episodes[/dim]") if t.collections: lines.append(f"[dim]collections: {escape(', '.join(t.collections[:3]))}[/dim]") lines.append("") if c.protected: lines.append(f"[blue]PROTECTED[/blue] {escape(c.protected)}") for s in c.breakdown.signals: colour = "red" if s.points > 0 else "green" lines.append(f"[{colour}]{s.points:+6.1f}[/{colour}] [b]{s.code:<9}[/b] {escape(s.note)}") lines.append(f"[b]{'score':>6} {c.score}[/b]") if c.breakdown.flags: lines.append(f"[yellow]flags: {', '.join(c.breakdown.flags)}[/yellow]") lines += [ "", f"sessions: {e.full_sessions} full · {e.abandoned_sessions} abandoned · {e.touch_sessions} touch · {e.qc_sessions} qc ignored", ] if e.last_full: lines.append(f"last full watch: {e.last_full:%Y-%m-%d}") if e.furthest_season is not None: lines.append(f"furthest reached: S{e.furthest_season:02d}E{e.furthest_episode or 0:02d}") if t.plex_view_count: lines.append(f"plex history views: {t.plex_view_count}") arr = self.arr_info.get(t.guid) if arr: extra = f" · {arr['status']} · {arr['episodes']}" if "status" in arr else "" lines += [ "", f"[b]{arr['arr']}[/b] #{arr['id']} · profile {escape(str(arr['profile']))} · " f"{'monitored' if arr['monitored'] else 'unmonitored'} · {arr['size_bytes'] / 1024**3:.1f} GB on disk{extra}", ] tm = self.tmdb_info.get(t.guid) if tm: if "error" in tm: lines.append(f"[dim]tmdb: {escape(tm['error'])}[/dim]") else: prov = ", ".join(tm["providers"][:4]) or "no streaming" sub = f" · [yellow]subscribed: {', '.join(tm['subscribed'])}[/yellow]" if tm["subscribed"] else "" lines.append(f"[b]tmdb[/b] {tm['vote_count']} votes · {tm['vote_average']:.1f} · popularity {tm['popularity']:.0f} · {escape(prov)}{sub}") if c.decision: lines += ["", f"decision: {MARK[c.decision]} {c.decision}"] panel.update("\n".join(lines)) def _stats(self) -> None: shown = self.visible() marked = [c for c in self.result.candidates if c.decision == "reap"] text = ( f"{len(shown)} shown · sort {SORTS[self.sort_index]} · " f"{len(marked)} marked · {sum(c.title.size_gb for c in marked) / 1024:.2f} TB to free" ) if self.result.disk: d = self.result.disk text += f" · disk {d.free_bytes / 1024**4:.2f} TB free of {d.total_bytes / 1024**4:.1f} TB" if self.filter_text: text += f" · filter {self.filter_text!r}" if self.truncated: text += f" · {self.truncated} more not shown (filter to narrow)" self.query_one("#stats", Static).update(text) # ---- actions -------------------------------------------------------------- def action_mark(self, action: str) -> None: c = self.current() if c is None: return if c.protected and action in ("reap", "downgrade"): self.notify(f"protected: {c.protected}", severity="warning") return if c.decision == action: self.ledger.clear(c.title.guid) c.decision = None else: self.ledger.set( c.title.guid, action, kind=c.title.kind, title=c.title.title, score=c.score, size_bytes=c.title.size_bytes, breakdown=c.breakdown.model_dump(), ) c.decision = action table = self.query_one("#table", DataTable) table.update_cell(str(c.title.rating_key), self.cols[0], MARK.get(c.decision or "", " ")) self._show(c) self._stats() if action != "keep" or self.show_hidden: table.action_cursor_down() def action_clear(self) -> None: c = self.current() if c and c.decision: self.action_mark(c.decision) def action_filter(self) -> None: box = self.query_one("#filter", Input) box.remove_class("hidden") box.focus() def action_hide_filter(self) -> None: box = self.query_one("#filter", Input) box.add_class("hidden") self.query_one("#table", DataTable).focus() def on_input_submitted(self, event: Input.Submitted) -> None: self.filter_text = event.value.strip() self.action_hide_filter() self._fill() def action_cycle_sort(self) -> None: self.sort_index = (self.sort_index + 1) % len(SORTS) self._fill() def action_toggle_hidden(self) -> None: self.show_hidden = not self.show_hidden self._fill() def action_review(self) -> None: marked = [c for c in self.result.candidates if c.decision in ("reap", "downgrade")] self.push_screen(ReviewScreen(marked, self.export_path, self.cfg, self.ledger))