Say why media-preload refused a watch request

A 400 from the preload API used to fall into the download-status path, so a
season that is not in the library yet looked like "the command doesn't
work" (She-Ra season 3 on 2026-12-01). Problem responses now raise
PreloadRefusedError and the cog replies with the service's own reason
before adding download context.
This commit is contained in:
Ziad Arafat committed 2026-12-01 00:22:19 -07:00
1 parent e5386d9b28
commit 827ae9db2c
4 files changed
+71 -3

No files matched your search

+40 -1
View File
@@ -10,6 +10,7 @@ from collections.abc import AsyncIterator
from typing import Any, cast
import pytest
from media_preload_client.models import MediaItem, MediaType
from redbot.core import Config
from watch_helpers import (
TOKEN,
@@ -22,7 +23,7 @@ from watch_helpers import (
)
from watch.spec import EpisodeSpec
from watch.watch import PreloadError, Watch
from watch.watch import PreloadError, PreloadRefusedError, Watch
class FakeBot:
@@ -115,6 +116,44 @@ async def test_api_errors_carry_the_api_message(cog: Watch) -> None:
await cog.fetch(404)
async def test_a_refusal_is_its_own_error(
cog: Watch, fake: FakePreload
) -> None:
"""A rejected request raises the refusal subclass, not a plain error."""
fake.search_results = [media_item("show", "She-Ra", kind="series")]
fake.create_refusal = "nothing to cache for She-Ra with those options"
item = MediaItem(
id="show",
name="She-Ra",
type_=MediaType.SERIES,
cacheable=True,
)
with pytest.raises(PreloadRefusedError, match="nothing to cache"):
await cog.create(item, None, cast("Any", FakeAuthor()), None)
async def test_a_refusal_reason_reaches_the_person(
cog: Watch, fake: FakePreload
) -> None:
"""The service's reason is sent, not hidden behind download status."""
fake.create_refusal = "nothing to cache for She-Ra with those options"
item = MediaItem(
id="show",
name="She-Ra",
type_=MediaType.SERIES,
cacheable=True,
)
ctx = FakeContext()
await cog._start( # noqa: SLF001 (the command path)
cast("Any", ctx), item, None
)
assert any(
"nothing to cache for She-Ra" in text for text in ctx.texts
), ctx.texts
async def test_wrong_token_is_reported(
cog: Watch, monkeypatch: pytest.MonkeyPatch
) -> None:
+6
View File
@@ -81,6 +81,8 @@ class FakePreload:
search_results: list[dict[str, Any]] = field(default_factory=list)
requests: dict[int, dict[str, Any]] = field(default_factory=dict)
# When set, POST /v1/requests answers 400 with this problem text
create_refusal: str | None = None
# Calls as (method, path, query, json body)
calls: list[tuple[str, str, dict[str, str], Any]] = field(
default_factory=list
@@ -130,6 +132,10 @@ class FakePreload:
async def _create(self, request: web.Request) -> web.Response:
body = await request.json()
if self.create_refusal is not None:
return web.json_response(
{"error": self.create_refusal}, status=400
)
match = [
i
for i in self.search_results
+9
View File
@@ -5,5 +5,14 @@ class PreloadError(Exception):
"""A media service refused or failed a call."""
class PreloadRefusedError(PreloadError):
"""The media service answered with a problem and said why.
The message is the service's own text, e.g. "nothing to cache for a
series with those options", so it belongs in the reply to the person
who asked rather than in a generic failure.
"""
class SeasonError(ValueError):
"""A season change cannot proceed under the selected retention plan."""
+16 -2
View File
@@ -36,7 +36,7 @@ from redbot.core import Config, commands
from redbot.core.bot import Red
from .downloads import describe_downloads, normalized_title
from .errors import PreloadError, SeasonError
from .errors import PreloadError, PreloadRefusedError, SeasonError
from .jellyfin import Jellyfin
from .jobs import Jobs
from .notify import completion_ping
@@ -73,7 +73,7 @@ RequestType = Literal["discord_deleted_user", "owner", "user", "user_strict"]
def _unwrap(response: Response[Any]) -> Any: # noqa: ANN401 (generated types)
"""Return a response's model, or raise with the API's error message."""
if isinstance(response.parsed, Problem):
raise PreloadError(response.parsed.error)
raise PreloadRefusedError(response.parsed.error)
if response.status_code >= 400 or response.parsed is None: # noqa: PLR2004
msg = f"media-preload answered HTTP {response.status_code}"
raise PreloadError(msg)
@@ -743,6 +743,20 @@ class Watch(commands.Cog):
item, spec, ctx.author, jellyfin_user
)
except (PreloadError, httpx.HTTPError) as exc:
if isinstance(exc, PreloadRefusedError):
# The service said exactly why (a season not in
# the library yet, a size limit...). Say that
# first, then add download context if any.
await ctx.send(
f"Can't preload **{item.name}**: {exc}"
)
await self._show_download_status(
ctx,
item.name,
series_only=item.type_
== MediaType.SERIES,
)
return
if await self._show_download_status(
ctx,
item.name,