From 5e8acbf7d02cd4e65c976941b9184246e5816d9b Mon Sep 17 00:00:00 2001 From: Ziad Arafat Date: Sun, 22 Nov 2026 12:02:57 -0700 Subject: [PATCH] Report ARR download progress for watch and duplicate requests --- README.md | 34 ++++- tests/test_acquisition.py | 298 +++++++++++++++++++++++++++++++++++++- watch/downloads.py | 147 +++++++++++++++++++ watch/watch.py | 126 ++++++++++++++-- 4 files changed, 593 insertions(+), 12 deletions(-) create mode 100644 watch/downloads.py diff --git a/README.md b/README.md index fc99334..b23c6be 100644 --- a/README.md +++ b/README.md @@ -173,7 +173,8 @@ libraries and music acquisition are outside this command. Title lookup uses Radarr/Sonarr's metadata catalogues, rather than exposing raw release/torrent names. ARR subsequently searches its configured indexers under the chosen quality/custom-format profile. Existing ARR titles are not changed, -added twice or searched again; inspect the ARR app for their status. A successful +added twice or searched again. Selecting an existing title shows its current ARR +status immediately, without asking for another quality choice. A successful request means ARR accepted it, not that a matching release was found or imported. The existing RDTC download/import/NFO/Jellyfin integration handles subsequent work. @@ -187,6 +188,37 @@ profile/root stops the request instead of silently selecting another one. Raw ARR errors/headers are not sent to Discord. No new service or API endpoint is required. +### In-progress download status + +When `watch` cannot find playable library media, it checks existing English +Sonarr/Radarr entries before suggesting a new request. It also checks when a +preload fails (for example, a series is in Jellyfin but its requested episode +has not finished downloading). This is read-only and works for users without +download permission. Existing playable media keeps the normal preload behavior. + +`request` shows an existing title's status after title selection, skipping the +quality step. New-title download permissions are unchanged. Neither path starts +a second download, triggers a release search, or changes a quality profile +simply to check status. + +Status is a snapshot of ARR's queue, with percentage and ETA when available. +Paused, queued, needs-attention and downloaded/importing states are shown +separately. Unknown sizes produce **progress unavailable** rather than an +invented percentage. A managed title with no active queue entry is described +as waiting, not downloading. Movies already imported are reported as downloaded; +a missing Jellyfin result may need its library scan to finish. + +Series progress is shown per transfer; multiple episode rows for one season +pack count as one download. If multiple requested titles match, a menu lets the +user choose title/type/year. Replies show at most five transfers plus the +remaining count. Raw release names, private download IDs, filesystem paths and +upstream error messages are excluded. A failed queue API is reported as +**temporarily unavailable**. + +This adds no background message polling and does not modify ARR Discord webhook +notifications. Run the command again for an updated snapshot; existing channel +notifications continue to handle completion events. + ### The client library `clients/media-preload-client` is generated from media-preload's OpenAPI spec with diff --git a/tests/test_acquisition.py b/tests/test_acquisition.py index ae64530..7c60889 100644 --- a/tests/test_acquisition.py +++ b/tests/test_acquisition.py @@ -27,14 +27,14 @@ class RequestBot: @pytest.fixture -async def acquisition( +async def acquisition( # noqa: C901 (HTTP fixture edge) config: Config, monkeypatch: pytest.MonkeyPatch ) -> AsyncIterator[tuple[Watch, list[Any], dict[str, Any]]]: """Serve realistic lookup, profile, root and add endpoints.""" calls: list[Any] = [] state: dict[str, Any] = {"existing": [], "status": 200} - async def handler(request: web.Request) -> web.Response: + async def handler(request: web.Request) -> web.Response: # noqa: C901 (HTTP fixture edge) body = await request.json() if request.can_read_body else None calls.append( ( @@ -70,6 +70,12 @@ async def acquisition( } ] ) + if path == "queue/details": + if state.get("queue_error"): + return web.json_response( + {"error": "private-path"}, status=503 + ) + return web.json_response(state.get("queue", [])) if path == "qualityprofile": if "profiles" in state: return web.json_response(state["profiles"]) @@ -97,6 +103,22 @@ async def acquisition( }, ] ) + if path == "movie": + return web.json_response( + [ + t + for t in state["existing"] + if t.get("tmdbId") + ] + ) + if path == "series": + return web.json_response( + [ + t + for t in state["existing"] + if t.get("tvdbId") + ] + ) if request.method == "GET": return web.json_response(state["existing"]) return web.json_response({**(body or {}), "id": 7}, status=201) @@ -386,3 +408,275 @@ async def test_missing_quality_profile_never_posts( cast("Any", FakeAuthor(id=99)), "movie", title, "4k" ) assert all(method == "GET" for method, *_ in calls) + + +def queued_download(**changes: Any) -> dict[str, Any]: # noqa: ANN401 + """Build a queue resource with private release details to protect.""" + return { + "id": 10, + "movieId": 8, + "seriesId": 8, + "episodeId": 81, + "seasonNumber": 1, + "episode": {"id": 81, "seasonNumber": 1, "episodeNumber": 2}, + "size": 1000, + "sizeleft": 250, + "timeleft": "00:10:00", + "status": "downloading", + "trackedDownloadState": "downloading", + "trackedDownloadStatus": "ok", + "downloadId": "private-id", + "title": "private-release", + "outputPath": "/private/path", + "errorMessage": "private-credential", + "statusMessages": [], + **changes, + } + + +async def test_existing_movie_reports_progress_without_duplicate( + acquisition: tuple[Watch, list[Any], dict[str, Any]], +) -> None: + """A duplicate request reads queue bytes/ETA and performs no writes.""" + cog, calls, state = acquisition + state["existing"] = [ + { + "id": 8, + "title": "Dune", + "year": 2021, + "tmdbId": 438631, + "hasFile": False, + } + ] + state["queue"] = [ + queued_download(), + queued_download(movieId=99, sizeleft=0), + ] + title = (await cog.acquisition_search("movie", "Dune"))[0] + result = await cog.acquire( + cast("Any", FakeAuthor(id=99)), "movie", title, "4k" + ) + assert "downloading" in result.lower() + assert "75%" in result + assert "10m" in result + assert "1 download in ARR:" in result + assert "private-" not in result + assert all(method == "GET" for method, *_ in calls) + assert any( + path == "/api/v3/queue/details" and params.get("movieId") == "8" + for _, path, params, _ in calls + ) + + +async def test_request_existing_title_skips_quality_and_shows_progress( + acquisition: tuple[Watch, list[Any], dict[str, Any]], +) -> None: + """Existing-title requests do not ask for an irrelevant new profile.""" + cog, calls, state = acquisition + state["existing"] = [ + {"id": 8, "title": "Dune", "year": 2021, "tmdbId": 438631} + ] + state["queue"] = [queued_download()] + ctx = WizardContext(["movie", "0", "4k"], author=FakeAuthor(id=99)) + await Watch.request.callback(cog, ctx, query="Dune") + assert len(ctx.views) == 2 + assert "75%" in ctx.texts[-1] + assert all(method == "GET" for method, *_ in calls) + + +@pytest.mark.parametrize( + ("updates", "expected", "absent"), + [ + ({"status": "paused"}, "paused", "downloading"), + ( + { + "status": "downloading", + "trackedDownloadState": "importPending", + }, + "awaiting import", + "downloading", + ), + ( + {"status": "downloadClientUnavailable"}, + "client unavailable", + "downloading", + ), + ({"status": "stalled"}, "stalled", "downloading"), + ({"status": "queued"}, "queued", "downloading"), + ( + { + "status": "completed", + "trackedDownloadState": "importPending", + "sizeleft": 0, + }, + "awaiting import", + "downloading", + ), + ( + { + "status": "completed", + "trackedDownloadState": "importing", + "sizeleft": 0, + }, + "importing", + "downloading", + ), + ( + {"size": 0, "sizeleft": 0, "timeleft": None}, + "progress unavailable", + "100%", + ), + ({"sizeleft": 1500}, "0%", "-50%"), + ({"sizeleft": -100}, "100%", "110%"), + ( + {"trackedDownloadStatus": "warning"}, + "needs attention", + "private-credential", + ), + ], +) +async def test_download_status_does_not_misrepresent_queue_state( + acquisition: tuple[Watch, list[Any], dict[str, Any]], + updates: dict[str, Any], + expected: str, + absent: str, +) -> None: + """Report queue states and safely handle unknown byte counts.""" + cog, _, state = acquisition + state["queue"] = [queued_download(**updates)] + text = await cog.acquisition_status("movie", {"id": 8, "title": "Dune"}) + assert expected in text.lower() + assert absent not in text.lower() + + +async def test_no_active_download_is_not_called_downloading( + acquisition: tuple[Watch, list[Any], dict[str, Any]], +) -> None: + """Managed-but-unavailable media does not imply a download exists.""" + cog, _, _ = acquisition + text = await cog.acquisition_status( + "movie", {"id": 8, "title": "Dune", "hasFile": False} + ) + assert "no active download" in text.lower() + assert "downloading" not in text.lower() + + +async def test_tv_season_pack_is_not_counted_once_per_episode( + acquisition: tuple[Watch, list[Any], dict[str, Any]], +) -> None: + """Show one transfer row for a multi-episode season pack.""" + cog, _, state = acquisition + state["queue"] = [ + queued_download(), + queued_download(id=11, episodeId=82), + queued_download(id=12, downloadId="other", sizeleft=500), + ] + text = await cog.acquisition_status("tv", {"id": 8, "title": "Dune"}) + assert text.count("75%") == 1 + assert text.count("50%") == 1 + assert "2 downloads" in text.lower() + assert "private-" not in text + + +@pytest.mark.parametrize("query", ["Dune", "Dune 2021"]) +async def test_watch_reports_arr_progress_without_download_permission( + acquisition: tuple[Watch, list[Any], dict[str, Any]], + monkeypatch: pytest.MonkeyPatch, + query: str, +) -> None: + """Allow read-only status without permission to download.""" + from watch_helpers import TOKEN, FakePreload, serve + + cog, calls, state = acquisition + state["existing"] = [ + {"id": 8, "title": "Dune", "year": 2021, "tmdbId": 438631} + ] + state["queue"] = [queued_download()] + fake = FakePreload() + async with serve(fake) as url: + monkeypatch.setenv("PRELOAD_API_URL", url) + monkeypatch.setenv("PRELOAD_BOT_TOKEN", TOKEN) + ctx = FakeContext() + await Watch.watch.callback(cog, ctx, query=query) + assert "75%" in ctx.texts[-1] + assert "request Dune" not in ctx.texts[-1] + assert not await cog.can_download(cast("Any", FakeAuthor())) + assert all(method == "GET" for method, *_ in calls) + assert fake.calls_to("POST", "/v1/requests") == [] + + +async def test_queue_failure_does_not_claim_download_is_missing( + acquisition: tuple[Watch, list[Any], dict[str, Any]], +) -> None: + """Report unavailable status when the queue API fails.""" + cog, _, state = acquisition + state["queue_error"] = True + text = await cog.acquisition_status("movie", {"id": 8, "title": "Dune"}) + assert "temporarily unavailable" in text.lower() + assert "private-path" not in text + assert "no active download" not in text.lower() + + +async def test_partial_tv_library_reports_progress_when_episode_is_missing( + acquisition: tuple[Watch, list[Any], dict[str, Any]], + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A library series may exist while its requested episode downloads.""" + from watch_helpers import TOKEN, FakePreload, media_item, serve + + cog, calls, state = acquisition + state["existing"] = [ + {"id": 8, "title": "Dune", "year": 2021, "tvdbId": 123} + ] + state["queue"] = [queued_download()] + fake = FakePreload( + search_results=[media_item("jf1", "Dune", kind="series")] + ) + + async def missing_episode(_request: web.Request) -> web.Response: + return web.json_response( + { + "error": ( + "nothing to cache for Dune " + "with those options" + ) + }, + status=400, + ) + + monkeypatch.setattr(fake, "_create", missing_episode) + async with serve(fake) as url: + monkeypatch.setenv("PRELOAD_API_URL", url) + monkeypatch.setenv("PRELOAD_BOT_TOKEN", TOKEN) + ctx = FakeContext() + await Watch.watch.callback(cog, ctx, query="Dune s1e2") + assert "75%" in ctx.texts[-1] + assert "S01E02" in ctx.texts[-1] + assert all(method == "GET" for method, *_ in calls) + + +async def test_ambiguous_watch_selects_correct_media_type( + acquisition: tuple[Watch, list[Any], dict[str, Any]], + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A movie and series sharing a name must not show each other's job.""" + from watch_helpers import TOKEN, FakePreload, serve + + cog, calls, state = acquisition + state["existing"] = [ + {"id": 8, "title": "Dune", "year": 2021, "tmdbId": 438631}, + {"id": 9, "title": "Dune", "year": 2000, "tvdbId": 123}, + ] + state["queue"] = [ + queued_download(), + queued_download(id=11, seriesId=9, movieId=None, sizeleft=500), + ] + async with serve(FakePreload()) as url: + monkeypatch.setenv("PRELOAD_API_URL", url) + monkeypatch.setenv("PRELOAD_BOT_TOKEN", TOKEN) + ctx = WizardContext(["1"]) + await Watch.watch.callback(cog, ctx, query="Dune") + assert len(ctx.views) == 1 + assert "50%" in ctx.texts[-1] + assert "75%" not in ctx.texts[-1] + assert all(method == "GET" for method, *_ in calls) diff --git a/watch/downloads.py b/watch/downloads.py new file mode 100644 index 0000000..e3114ab --- /dev/null +++ b/watch/downloads.py @@ -0,0 +1,147 @@ +"""Safe user-facing ARR queue status, without release paths or identifiers.""" + +import math +import re +from typing import Any + +import discord + + +def normalized_title(text: str) -> str: + """Compare title/year queries despite punctuation differences.""" + return re.sub(r"[\W_]+", "", text.casefold()) + + +def _progress(row: dict[str, Any]) -> str: + """Handle unknown sizes and clamp inconsistent client byte counters.""" + size = row.get("size") + left = row.get("sizeleft", row.get("sizeLeft")) + if not isinstance(size, (int, float)) or not isinstance( + left, (int, float) + ): + return "progress unavailable" + if not math.isfinite(size) or not math.isfinite(left) or size <= 0: + return "progress unavailable" + percent = max(0, min(100, 100 * (1 - left / size))) + return f"{percent:.0f}%" + + +def _eta(row: dict[str, Any]) -> str: + """Accept only ARR durations, never arbitrary download-client text.""" + value = row.get("timeleft", row.get("timeLeft")) + if not isinstance(value, str): + return "" + match = re.fullmatch( + r"(?:(\d+)\.)?(\d{1,2}):(\d{2}):(\d{2})(?:\.\d+)?", value + ) + if match is None: + return "" + days, hours, minutes, seconds = (int(v or 0) for v in match.groups()) + total = days * 86400 + hours * 3600 + minutes * 60 + seconds + if total <= 0: + return "" + parts = [] + for unit, length in [("d", 86400), ("h", 3600), ("m", 60)]: + count, total = divmod(total, length) + if count: + parts.append(f"{count}{unit}") + return " · ETA " + (" ".join(parts[:2]) if parts else "<1m") + + +def _state(row: dict[str, Any]) -> str: + """Separate downloading from failed/stalled/import states.""" + status = str(row.get("status", "")).lower() + tracked = str(row.get("trackedDownloadState", "")).lower() + health = str(row.get("trackedDownloadStatus", "")).lower() + if health in {"warning", "error"} or "failed" in tracked: + return "Needs attention" + if tracked == "importpending": + return "Downloaded; awaiting import" + if tracked == "importing": + return "Importing into library" + if tracked == "imported": + return "Imported; waiting for Jellyfin" + return { + "paused": "Paused", + "stalled": "Stalled", + "downloadclientunavailable": "Download client unavailable", + "queued": "Queued", + "delay": "Queued", + "warning": "Needs attention", + "failed": "Needs attention", + "completed": "Downloaded; awaiting import", + "downloading": "Downloading", + }.get( + status, + "Downloaded; awaiting import" + if tracked == "importpending" + else "Download in progress", + ) + + +def describe_downloads( + kind: str, + title: dict[str, Any], + records: list[dict[str, Any]], +) -> str: + """Describe matching transfers once each, even Sonarr season packs.""" + name = discord.utils.escape_markdown(str(title.get("title", "Title"))) + year = f" ({title['year']})" if title.get("year") else "" + heading = f"Already requested: **{name}{year}**. " + id_key = "movieId" if kind == "movie" else "seriesId" + records = [r for r in records if r.get(id_key) == title["id"]] + if not records: + if kind == "movie" and title.get("hasFile"): + return heading + ( + "Already downloaded; Jellyfin " + "may still be scanning the " + "import." + ) + count = title.get("statistics", {}).get("episodeFileCount", 0) + available = ( + f"{count} episodes available. " + if kind == "tv" and count + else "" + ) + return ( + heading + + available + + ( + "No active download reported. Waiting " + "for a matching release or a future " + "search. No new download was started." + ) + ) + grouped: dict[str, list[dict[str, Any]]] = {} + for index, row in enumerate(records): + key = str(row.get("downloadId") or f"row:{index}") + grouped.setdefault(key, []).append(row) + noun = "download" if len(grouped) == 1 else "downloads" + lines = [heading + f"{len(grouped)} {noun} in ARR:"] + for group in list(grouped.values())[:5]: + row = group[0] + label = "" + if kind == "tv": + episode = row.get("episode") or {} + season = row.get( + "seasonNumber", episode.get("seasonNumber") + ) + number = episode.get("episodeNumber") + if isinstance(season, int): + label = ( + f"Season {season} pack" + if len(group) > 1 + else f"S{season:02}" + ) + if len(group) == 1 and isinstance(number, int): + label += f"E{number:02}" + label += " — " + state = _state(row) + eta = _eta(row) if state == "Downloading" else "" + lines.append(f"{label}{state} · {_progress(row)}{eta}") + if len(grouped) > 5: # noqa: PLR2004 + lines.append(f"…and {len(grouped) - 5} more downloads.") + lines.append( + "Progress is a snapshot. No duplicate download was started." + ) + return "\n".join(lines) diff --git a/watch/watch.py b/watch/watch.py index e5a9e82..b49e4d9 100644 --- a/watch/watch.py +++ b/watch/watch.py @@ -32,6 +32,7 @@ from media_preload_client.types import UNSET, Response from redbot.core import Config, commands from redbot.core.bot import Red +from .downloads import describe_downloads, normalized_title from .spec import ( DEFAULT_NEXT, EpisodeSpec, @@ -514,6 +515,12 @@ class Watch(commands.Cog): item, spec, ctx.author, jellyfin_user ) except (PreloadError, httpx.HTTPError) as exc: + if await self._show_download_status( + ctx, + item.name, + series_only=item.type_ == MediaType.SERIES, + ): + return await ctx.send(f"Couldn't start that: {exc}") return message = await ctx.send( @@ -576,6 +583,10 @@ class Watch(commands.Cog): return cacheable = [i for i in items if i.cacheable] if not cacheable: + if await self._show_download_status( + ctx, title, series_only=spec is not None + ): + return hint = f"{ctx.clean_prefix}request {title}" missing = ( f"Nothing cacheable matches **{title}**." @@ -670,6 +681,99 @@ class Watch(commands.Cog): kind, f"{endpoint}/lookup", params={"term": query} ) + async def _existing_title( + self, + kind: str, + selected: dict[str, Any], + ) -> dict[str, Any] | None: + """Match the selected catalogue ID against managed media.""" + endpoint = "movie" if kind == "movie" else "series" + key = "tmdbId" if kind == "movie" else "tvdbId" + titles = await self._arr_call(kind, endpoint) + return next( + (t for t in titles if t.get(key) == selected.get(key)), + None, + ) + + async def acquisition_status( + self, kind: str, title: dict[str, Any] + ) -> str: + """Read progress without requiring download permission.""" + key = "movieId" if kind == "movie" else "seriesId" + params = {key: str(title["id"])} + if kind == "tv": + params["includeEpisode"] = "true" + try: + records = await self._arr_call( + kind, "queue/details", params=params + ) + except PreloadError: + return ( + "Already requested; download status is " + "temporarily unavailable. No new " + "download was started." + ) + return describe_downloads(kind, title, records) + + async def _show_download_status( + self, + ctx: commands.Context, + query: str, + *, + series_only: bool, + ) -> bool: + """Find managed titles missing playable library media.""" + kinds = ["tv"] if series_only else ["movie", "tv"] + found: list[tuple[str, dict[str, Any]]] = [] + term = normalized_title(query) + for kind in kinds: + endpoint = "movie" if kind == "movie" else "series" + try: + titles = await self._arr_call(kind, endpoint) + except PreloadError: + continue + for title in titles: + label = normalized_title(catalogue_label(title)) + if term and term in label: + found.append((kind, title)) + if not found: + return False + exact = [ + p + for p in found + if term + in { + normalized_title(str(p[1]["title"])), + normalized_title(catalogue_label(p[1])), + } + ] + if len(exact) == 1: + found = exact + if len(found) > 1: + found = found[:24] + choice = await self._download_choice( + ctx, + "Which requested title do you mean?", + [ + ( + str(i), + catalogue_label(t) + + f" · {kind}", + ) + for i, (kind, t) in enumerate(found) + ], + ) + if choice is None: + return True + kind, title = found[int(choice)] + else: + kind, title = found[0] + await ctx.send( + await self.acquisition_status(kind, title), + allowed_mentions=discord.AllowedMentions.none(), + ) + return True + async def acquire( self, user: Person, @@ -697,15 +801,10 @@ class Watch(commands.Cog): ): msg = "The selected title has no catalogue ID." raise PreloadError(msg) - existing = await self._arr_call(kind, endpoint) - if any( - t.get(id_key) == title[id_key] for t in existing - ): - return ( - "Already managed by ARR; no " - "duplicate or new search was " - "submitted. Check the ARR app " - "for its status." + existing = await self._existing_title(kind, title) + if existing is not None: + return await self.acquisition_status( + kind, existing ) profiles = await self._arr_call(kind, "qualityprofile") profile = next( @@ -857,6 +956,15 @@ class Watch(commands.Cog): if chosen is None: return title = titles[int(chosen)] + existing = await self._existing_title(kind, title) + if existing is not None: + await ctx.send( + await self.acquisition_status( + kind, existing + ), + allowed_mentions=discord.AllowedMentions.none(), + ) + return scope = ( ( "All regular seasons; future "