diff --git a/tests/test_watch_cog.py b/tests/test_watch_cog.py index 2a4223c..7d18492 100644 --- a/tests/test_watch_cog.py +++ b/tests/test_watch_cog.py @@ -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: diff --git a/tests/watch_helpers.py b/tests/watch_helpers.py index dfd2c1f..5b957da 100644 --- a/tests/watch_helpers.py +++ b/tests/watch_helpers.py @@ -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 diff --git a/watch/errors.py b/watch/errors.py index 381eb57..fa4d373 100644 --- a/watch/errors.py +++ b/watch/errors.py @@ -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.""" diff --git a/watch/watch.py b/watch/watch.py index 3a2f471..f65d13a 100644 --- a/watch/watch.py +++ b/watch/watch.py @@ -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,