From 9f3d75143233a4ca4b7de06df440a40201b2d021 Mon Sep 17 00:00:00 2001 From: Ziad Arafat Date: Mon, 23 Nov 2026 09:07:49 -0700 Subject: [PATCH] Import public Spotify playlists and notify requesters on completion --- README.md | 85 ++++- tests/music_helpers.py | 251 ++++++++++++++ tests/test_acquisition.py | 15 + tests/test_background_jobs.py | 576 +++++++++++++++++++++++++++++++ tests/test_command_completion.py | 73 ++++ tests/test_completion.py | 67 ++++ tests/test_music_import.py | 223 ++++++++++++ tests/test_music_matching.py | 80 +++++ tests/test_music_services.py | 194 +++++++++++ tests/test_playlist_command.py | 372 ++++++++++++++++++++ tests/test_season_requests.py | 16 + tests/test_spotify.py | 204 +++++++++++ tests/test_watch_cog.py | 5 +- tests/watch_helpers.py | 10 + watch/__init__.py | 10 +- watch/info.json | 6 +- watch/jellyfin.py | 145 ++++++++ watch/jobs.py | 349 +++++++++++++++++++ watch/music.py | 347 +++++++++++++++++++ watch/notify.py | 42 +++ watch/spotify.py | 165 +++++++++ watch/watch.py | 319 ++++++++++++++++- 22 files changed, 3537 insertions(+), 17 deletions(-) create mode 100644 tests/music_helpers.py create mode 100644 tests/test_background_jobs.py create mode 100644 tests/test_command_completion.py create mode 100644 tests/test_completion.py create mode 100644 tests/test_music_import.py create mode 100644 tests/test_music_matching.py create mode 100644 tests/test_music_services.py create mode 100644 tests/test_playlist_command.py create mode 100644 tests/test_spotify.py create mode 100644 watch/jellyfin.py create mode 100644 watch/jobs.py create mode 100644 watch/music.py create mode 100644 watch/notify.py create mode 100644 watch/spotify.py diff --git a/README.md b/README.md index 44ebf5e..47f8447 100644 --- a/README.md +++ b/README.md @@ -274,9 +274,8 @@ 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. +These status replies remain on-demand snapshots. Durable requester completion +notifications are described below; existing ARR Discord webhooks are unchanged. ### The client library @@ -309,3 +308,83 @@ the exact requirements from each `info.json`, installed the way Red's Downloader operator name broke pictures once), so run it before pushing anything that draws. Set `DOGEBOT_HOST` or `DOGEBOT_RED_IMAGE` to test elsewhere; extra arguments go to pytest. Keep `wand` in `pyproject.toml` equal to `doge_alignment/info.json`. ImageMagick itself is pinned in dogebot's `containers/red/Containerfile`. + + +### Public Spotify playlists + +Run `[p]watch link ` once, then: + +```text +d!importplaylist https://open.spotify.com/playlist/PLAYLIST_ID +d!importplaylist status +``` + +`spotifyimport` is an alias. This deliberately uses a different command name +from Red Audio's existing `playlist` command. Confirm the import in the +requester-only menu. The same bot-owner/default and `request allow/revoke` +permissions apply to music downloads and are checked again before mutations. + +Existing, uniquely matching Jellyfin songs are reused. Missing songs are mapped +from their public Spotify track pages to their albums; only a unique matching +artist/release group is selected in Lidarr. New artists use the music root's +current quality/metadata defaults, with other albums and future albums +unmonitored. Only targeted `AlbumSearch` commands are submitted. No entire +artist/discography search, tag rewrite or deletion is performed. + +The Jellyfin playlist is **public to all users**, named +**Discord username - Spotify playlist name**, and owned by the linked account. +The integration's service account has edit access so the bot can update it. +Source order and duplicate song positions are preserved. Reimporting the same +source updates the bot-created playlist rather than creating another one. +Unrelated/manual Jellyfin playlists are never overwritten. + +This workflow reads public metadata without a Spotify account token or audio +previews. Spotify embeds expose at most100songs;100visible songs are explicitly +labelled potentially incomplete, and the user must confirm **Import visible100 +only**. This imports a snapshot, not an ongoing Spotify account synchronization. +Private playlists and tracks absent from public metadata require another export +or a working Spotify API connection. No silent claim of a complete long playlist +is made. + +A saved job continues after cog reloads/restarts. It creates/fills the Jellyfin +playlist as files arrive, and pings the requester only after every requested +song is actually available there. Title, credited artist and duration must +match uniquely. Unresolved tracks produce a **finished with gaps** result, +not an all-added message; `importplaylist status` lists review titles. A write +whose acknowledgement is uncertain stops for owner verification, avoiding +blindly repeated creates/searches. Seven-day unresolved jobs report attention. + +Operators configure Red shared API tokens `lidarr` (`url`, `api_key`) and +`jellyfin` (`url`, `api_key`, `user_id`). Despite the generic field name, Jellyfin's +`api_key` must be a **user-bound service-device session token** on current +servers: playlist ACL/update APIs need a real UserId. Use a distinct device ID, +keep the password outside the bot, and set `user_id` to the service account ID. +A separate edit share is created when it differs from the linked playlist owner. +Credentials go into protected Red configuration through secure stdin/admin +provisioning; never paste secrets into Discord channels or command arguments. +All private service credentials stay in HTTP headers, separate from public +Spotify fetching. The bot adds no new service or API listener. + +### Completion notifications + +Watch preloads and confirmed movie/TV requests now save requester/channel +subscriptions and ping when processing finishes. Movies require an imported +file; TV checks the selected aired season's files. An empty queue is never proof +of completion. Preload partial/failed/cancelled results are described explicitly. +Notification checks resume on startup and run once per minute; slow music imports +do not block unrelated completions. Deleted/inaccessible channels fall back to +a requester DM. Only the requester is mentionable, never roles or everyone. +Failed Discord delivery is retried. A crash precisely between Discord accepting +a message and its acknowledgement being saved can still repeat that message. +Existing ARR Discord webhooks remain independent and unchanged. + +Other awaited commands taking at least10seconds, such as alignment guessing or +baseline rebuilds, ping their requester on command completion/error. Instant +commands and the already-tracked media commands avoid duplicate generic pings. +These generic in-flight timers do not resume arbitrary third-party cog operations +after a restart. + +Completed notification/job details expire after seven days. The per-user +source-to-Jellyfin playlist ID mapping persists for safe reimports. Red user-data +deletion removes that user's pending jobs, mappings, linked name and download/TV +choices; it does not delete shared library files or public playlists. diff --git a/tests/music_helpers.py b/tests/music_helpers.py new file mode 100644 index 0000000..9102bf8 --- /dev/null +++ b/tests/music_helpers.py @@ -0,0 +1,251 @@ +"""HTTP edges for the playlist importer, with persistent server-side state.""" + +import copy +import json +from collections.abc import AsyncGenerator +from contextlib import asynccontextmanager +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, cast + +import httpx +import pytest +from aiohttp import web +from aiohttp.test_utils import TestServer +from redbot.core import Config + + +@dataclass +class MusicEdge: + """Serve Lidarr/Jellyfin HTTP with persistent state.""" + + albums: list[dict[str, Any]] = field(default_factory=list) + artists: list[dict[str, Any]] = field(default_factory=list) + playlist: dict[str, Any] = field(default_factory=dict) + searches: list[list[int]] = field(default_factory=list) + ready: set[str] = field(default_factory=set) + creations: int = 0 + after_lookup: Any = None + + async def http(self, request: web.Request) -> web.Response: + """Use the actual API routes and JSON casing.""" + if request.path.startswith("/api/v1/"): + if request.headers.get("X-Api-Key") != "test-key": + return web.Response(status=401) + return await self.arr(request) + if ( + request.headers.get("Authorization") + != 'MediaBrowser Token="test-key"' + ): + return web.Response(status=401) + if request.path == "/Items": + title = request.query.get("searchTerm", "") + items = ( + [ + { + "Id": title, + "Name": title, + "Artists": ["Depeche Mode"], + "RunTimeTicks": 2700000000, + } + ] + if title in self.ready + else [] + ) + return web.json_response( + {"Items": items, "TotalRecordCount": len(items)} + ) + if request.path == "/Playlists": + self.creations += 1 + self.playlist.update(await request.json()) + return web.json_response({"Id": "playlist-1"}) + if request.path == "/Playlists/playlist-1": + self.playlist.update(await request.json()) + return web.Response(status=204) + return web.Response(status=404) + + async def arr(self, request: web.Request) -> web.Response: # noqa: C901 + """Persist albums and targeted searches.""" + path = request.path.removeprefix("/api/v1/") + body = await request.json() if request.can_read_body else {} + if path == "album/lookup": + if self.after_lookup: + await self.after_lookup() + return web.json_response( + [ + { + "title": "Violator", + "foreignAlbumId": "mb-album", + "artist": { + "artistName": "Depeche Mode", # noqa: E501 + "foreignArtistId": "mb-artist", # noqa: E501 + }, + "releases": [], + "images": [], + } + ] + ) + if path == "rootfolder": + return web.json_response( + [ + { + "path": "/arr/library/Music", + "defaultQualityProfileId": 5, + "defaultMetadataProfileId": 1, + } + ] + ) + if path == "artist": + return web.json_response(self.artists) + if path == "artist/8": + if request.method == "PUT": + self.artists[0] = body + return web.json_response(self.artists[0]) + if path == "album" and request.method == "GET": + return web.json_response(self.albums) + if path == "album" and request.method == "POST": + self.artists.append( + {**body["artist"], "id": 8, "monitored": False} + ) + album = {**body, "id": 7, "artistId": 8} + self.albums.append(album) + return web.json_response(album, status=201) + if path == "album/7": + if request.method == "PUT": + self.albums[0] = body + return web.json_response(self.albums[0]) + if path == "command" and request.method == "POST": + if body.get("name") != "AlbumSearch": + return web.Response(status=400) + self.searches.append(body["albumIds"]) + return web.json_response( + {"id": 123, "status": "queued"}, status=201 + ) + return web.Response(status=404) + + +def public_page(request: httpx.Request) -> httpx.Response: + """Both distinct test songs belong to the same album.""" + if request.url.path.startswith("/track/"): + return httpx.Response( + 200, + text=( + '' + ), + ) + if request.url.path == "/embed/album/45YmvYK4hB4CgQgTMuNRm8": + data = { + "props": { + "pageProps": { + "state": { + "data": { + "entity": { + "name": "Violator", # noqa: E501 + "subtitle": "Depeche Mode", # noqa: E501 + } + } + } + } + } + } + return httpx.Response( + 200, + text='", + ) + return httpx.Response(404) + + +def music_job() -> dict[str, Any]: + """Return ordered songs with duplicate positions.""" + return { + "stage": "preparing", + "username": "doge", + "name": "My mix", + "user_id": "user-1", + "partial": False, + "tracks": [ + { + "id": "6kwEU2hLQpMToj1PHsBrOE", + "title": "Halo", + "artist": "Depeche Mode", + "duration": 270186, + }, + { + "id": "3CA4RlbsFJEtHKdsLAMgb4", + "title": "Enjoy the Silence", + "artist": "Depeche Mode", + "duration": 270186, + }, + { + "id": "6kwEU2hLQpMToj1PHsBrOE", + "title": "Halo", + "artist": "Depeche Mode", + "duration": 270186, + }, + ], + } + + +if TYPE_CHECKING: + from watch.music import MusicImporter + + +@asynccontextmanager +async def import_environment( + config: Config, monkeypatch: pytest.MonkeyPatch, edge: MusicEdge +) -> AsyncGenerator[tuple["MusicImporter", dict[str, Any], list[bool]]]: + """Exercise production code above real HTTP.""" + from watch.jellyfin import Jellyfin + from watch.music import MusicImporter + from watch.spotify import SpotifyPublic + from watch.watch import Watch + + app = web.Application() + app.router.add_route("*", "/{path:.*}", edge.http) + async with TestServer(app) as server: + + class Bot: + async def get_shared_api_tokens( + self, _service: str + ) -> dict[str, str]: + return { + "url": str(server.make_url("/")), + "api_key": "test-key", + } + + monkeypatch.setattr( + Config, "get_conf", lambda *_a, **_k: config + ) + bot = Bot() + cog = Watch(cast("Any", bot)) + saved: dict[str, Any] = {} + permitted = [True] + + async def save(job: dict[str, Any]) -> None: + saved.clear() + saved.update(copy.deepcopy(job)) + + async def authorize() -> None: + if not permitted[0]: + message = "Download permission was revoked." + raise PermissionError(message) + + async def arr(path: str, **kwargs: Any) -> Any: # noqa: ANN401 + return await cog._arr_call("music", path, **kwargs) + + async def tokens() -> dict[str, str]: + return await bot.get_shared_api_tokens("jellyfin") + + async with httpx.AsyncClient( + transport=httpx.MockTransport(public_page) + ) as public: + engine = MusicImporter( + arr, + Jellyfin(tokens), + SpotifyPublic(public), + save, + authorize, + ) + yield engine, saved, permitted diff --git a/tests/test_acquisition.py b/tests/test_acquisition.py index 6dfd07f..60d7e67 100644 --- a/tests/test_acquisition.py +++ b/tests/test_acquisition.py @@ -779,3 +779,18 @@ async def test_mutation_timeout_is_never_retried( await cog._arr_call("movie", "movie", body={"title": "Zohan"}) assert len(requests) == 1 assert "private-detail" not in str(error.value) + + +async def test_confirmed_movie_request_subscribes_its_requester_to_completion( + acquisition: tuple[Watch, list[Any], dict[str, Any]], +) -> None: + """Catch missing movie completion subscriptions.""" + cog, _calls, _state = acquisition + ctx = WizardContext(["movie", "0", "1080p"], author=FakeAuthor(id=99)) + await Watch.request.callback(cog, ctx, query="Dune") + jobs = await cog.config.pending_jobs() + assert len(jobs) == 1 + job = next(iter(jobs.values())) + assert job["owner"] == 99 + assert job["kind"] == "movie" + assert job["foreign_id"] == 438631 diff --git a/tests/test_background_jobs.py b/tests/test_background_jobs.py new file mode 100644 index 0000000..ac36f93 --- /dev/null +++ b/tests/test_background_jobs.py @@ -0,0 +1,576 @@ +"""Durable completion subscriptions around the real Watch service clients.""" + +from dataclasses import dataclass, field +from types import SimpleNamespace +from typing import Any, cast + +import pytest +from aiohttp import web +from aiohttp.test_utils import TestServer +from redbot.core import Config +from watch_helpers import FakeContext, preload_request + +from watch.watch import Watch + + +@dataclass +class Notifications: + """Record Discord deliveries and their mention policy.""" + + sent: list[Any] = field(default_factory=list) + + async def send(self, content: str, **kwargs: Any) -> None: # noqa: ANN401 + """Record a Discord delivery.""" + self.sent.append((content, kwargs)) + + +async def test_movie_completion_survives_restart_and_is_not_repeated( + config: Config, monkeypatch: pytest.MonkeyPatch +) -> None: + """Catch lost, premature or repeated movie notifications.""" + from watch.jobs import Jobs + + ready = [False] + + async def handler(request: web.Request) -> web.Response: + if request.path == "/api/v3/movie": + return web.json_response( + [ + { + "id": 7, + "tmdbId": 101, + "title": "Dune", + "hasFile": ready[0], + } + ] + ) + return web.Response(status=404) + + app = web.Application() + app.router.add_route("*", "/{path:.*}", handler) + async with TestServer(app) as server: + channel = Notifications() + + class Bot: + async def get_shared_api_tokens( + self, _service: str + ) -> dict[str, str]: + return { + "url": str(server.make_url("/")), + "api_key": "test-key", + } + + def get_channel(self, _id: int) -> Notifications: + return channel + + monkeypatch.setattr( + Config, "get_conf", lambda *_a, **_k: config + ) + cog = Watch(cast("Any", Bot())) + ctx = FakeContext() + ctx.channel = SimpleNamespace(id=10) + jobs = Jobs(cog) + await jobs.register( + cast("Any", ctx), + "movie:101", + {"kind": "movie", "foreign_id": 101, "title": "Dune"}, + ) + await jobs.tick() + assert channel.sent == [] + ready[0] = True + resumed = Jobs(cog) + await resumed.tick() + assert len(channel.sent) == 1 + assert channel.sent[0][0].startswith("<@1>") + assert "Dune" in channel.sent[0][0] + await resumed.tick() + assert len(channel.sent) == 1 + + +async def test_season_completion_uses_only_the_requested_season( + config: Config, monkeypatch: pytest.MonkeyPatch +) -> None: + """Catch using whole-show counts for a season request.""" + from watch.jobs import Jobs + + ready = [False] + + async def handler(request: web.Request) -> web.Response: + if request.path == "/api/v3/series": + return web.json_response( + [{"id": 7, "tvdbId": 101, "title": "Show"}] + ) + if ( + request.path == "/api/v3/episode" + and request.query.get("seriesId") == "7" + ): + return web.json_response( + [ + { + "seasonNumber": 1, + "hasFile": False, + "airDateUtc": "2020-01-01T00:00:00Z", # noqa: E501 + }, + { + "seasonNumber": 2, + "hasFile": ready[0], + "airDateUtc": "2020-01-01T00:00:00Z", # noqa: E501 + }, + ] + ) + return web.Response(status=404) + + app = web.Application() + app.router.add_route("*", "/{path:.*}", handler) + async with TestServer(app) as server: + channel = Notifications() + + class Bot: + async def get_shared_api_tokens( + self, _service: str + ) -> dict[str, str]: + return { + "url": str(server.make_url("/")), + "api_key": "test-key", + } + + def get_channel(self, _id: int) -> Notifications: + return channel + + monkeypatch.setattr( + Config, "get_conf", lambda *_a, **_k: config + ) + cog = Watch(cast("Any", Bot())) + ctx = FakeContext() + ctx.channel = SimpleNamespace(id=10) + jobs = Jobs(cog) + await jobs.register( + cast("Any", ctx), + "tv:101:2", + { + "kind": "tv", + "foreign_id": 101, + "title": "Show", + "season": 2, + }, + ) + await jobs.tick() + assert channel.sent == [] + ready[0] = True + await jobs.tick() + assert len(channel.sent) == 1 + assert "season 2" in channel.sent[0][0] + + +async def test_preload_completion_pings_after_its_terminal_result( + config: Config, monkeypatch: pytest.MonkeyPatch +) -> None: + """Catch dropping notifications for watch's cache/preload process.""" + from watch.jobs import Jobs + + status = ["queued"] + + async def handler(_request: web.Request) -> web.Response: + return web.json_response( + preload_request(5, "Dune", status=status[0]) + ) + + app = web.Application() + app.router.add_get("/v1/requests/5", handler) + async with TestServer(app) as server: + channel = Notifications() + + class Bot: + async def get_shared_api_tokens( + self, _service: str + ) -> dict[str, str]: + return { + "url": str(server.make_url("/")), + "token": "test-bot-token", + } + + def get_channel(self, _id: int) -> Notifications: + return channel + + monkeypatch.setattr( + Config, "get_conf", lambda *_a, **_k: config + ) + monkeypatch.delenv("PRELOAD_API_URL", raising=False) + monkeypatch.delenv("PRELOAD_BOT_TOKEN", raising=False) + cog = Watch(cast("Any", Bot())) + ctx = FakeContext() + ctx.channel = SimpleNamespace(id=10) + jobs = Jobs(cog) + await jobs.register( + cast("Any", ctx), + "preload:5", + {"kind": "preload", "request_id": 5, "title": "Dune"}, + ) + await jobs.tick() + assert channel.sent == [] + status[0] = "done" + await jobs.tick() + assert len(channel.sent) == 1 + assert "Preloading" in channel.sent[0][0] + + +async def test_userdata_deletion_removes_only_that_users_jobs( + config: Config, monkeypatch: pytest.MonkeyPatch +) -> None: + """Catch retaining identities after data deletion.""" + from watch.jobs import Jobs + + monkeypatch.setattr(Config, "get_conf", lambda *_a, **_k: config) + cog = Watch(cast("Any", SimpleNamespace())) + Jobs(cog) + await config.pending_jobs.set( + {"one": {"owner": 1}, "two": {"owner": 2}} + ) + await cog.red_delete_data_for_user(requester="user", user_id=1) + assert await config.pending_jobs() == {"two": {"owner": 2}} + + +async def test_playlist_resumes_and_pings_after_all_songs_arrive( + config: Config, monkeypatch: pytest.MonkeyPatch +) -> None: + """Catch pinging before all songs become playable.""" + import httpx + from music_helpers import MusicEdge, music_job, public_page + + import watch.jobs as job_module + from watch.jobs import Jobs + from watch.spotify import SpotifyPublic + + edge = MusicEdge() + app = web.Application() + app.router.add_route("*", "/{path:.*}", edge.http) + async with TestServer(app) as server: + channel = Notifications() + + class Bot: + async def get_shared_api_tokens( + self, _service: str + ) -> dict[str, str]: + return { + "url": str(server.make_url("/")), + "api_key": "test-key", + } + + async def is_owner(self, _user: object) -> bool: + return True + + def get_channel(self, _id: int) -> Notifications: + return channel + + monkeypatch.setattr( + Config, "get_conf", lambda *_a, **_k: config + ) + cog = Watch(cast("Any", Bot())) + ctx = FakeContext() + ctx.channel = SimpleNamespace(id=10) + jobs = Jobs(cog) + await jobs.register( + cast("Any", ctx), + "playlist:test", + {"kind": "playlist", **music_job()}, + ) + async with httpx.AsyncClient( + transport=httpx.MockTransport(public_page) + ) as public: + monkeypatch.setattr( + job_module, + "SpotifyPublic", + lambda _client: SpotifyPublic(public), + raising=False, + ) + await jobs.tick() + assert channel.sent == [] + assert edge.searches == [[7]] + edge.ready.add("Halo") + await jobs.tick() + assert channel.sent == [] + edge.ready.add("Enjoy the Silence") + resumed = Jobs(cog) + await resumed.tick() + assert len(channel.sent) == 1 + assert "Jellyfin" in channel.sent[0][0] + assert "3/3" in channel.sent[0][0] + assert edge.playlist["Name"] == "doge - My mix" + assert edge.playlist["IsPublic"] is True + await resumed.tick() + assert len(channel.sent) == 1 + + +def test_incomplete_playlist_result_does_not_claim_all_music_was_added() -> ( + None +): + """Catch the completion message treating a review outcome as success.""" + from watch.jobs import Jobs + + text = Jobs.message( + { + "kind": "playlist", + "stage": "attention", + "name": "My mix", + "ready": 2, + "tracks": [{}, {}, {}], + } + ) + assert "2/3" in text + assert "gaps" in text.lower() or "review" in text.lower() + assert "downloaded and imported" not in text + + +async def test_uncertain_music_write_stops_for_attention( + config: Config, monkeypatch: pytest.MonkeyPatch +) -> None: + """Catch uncertain playlist creates being repeated.""" + from watch.jobs import Jobs + + channel = Notifications() + + class Bot: + async def is_owner(self, _user: object) -> bool: + return True + + def get_channel(self, _id: int) -> Notifications: + return channel + + monkeypatch.setattr(Config, "get_conf", lambda *_a, **_k: config) + cog = Watch(cast("Any", Bot())) + ctx = FakeContext() + ctx.channel = SimpleNamespace(id=10) + jobs = Jobs(cog) + await jobs.register( + cast("Any", ctx), + "playlist:test", + { + "kind": "playlist", + "stage": "preparing", + "name": "Mix", + "tracks": [{}], + "mutation": "Jellyfin playlist create", + }, + ) + await jobs.tick() + assert len(channel.sent) == 1 + state = next(iter((await config.pending_jobs()).values())) + assert state["stage"] == "attention" + assert state["mutation"] == "Jellyfin playlist create" + await jobs.tick() + assert len(channel.sent) == 1 + + +async def test_stalled_jobs_report_attention_and_old_notifications_are_pruned( + config: Config, monkeypatch: pytest.MonkeyPatch +) -> None: + """Catch stuck jobs and stale identity retention.""" + from watch.jobs import Jobs + + channel = Notifications() + + class Bot: + def get_channel(self, _id: int) -> Notifications: + return channel + + monkeypatch.setattr(Config, "get_conf", lambda *_a, **_k: config) + cog = Watch(cast("Any", Bot())) + jobs = Jobs(cog) + await config.pending_jobs.set( + { + "one": { + "owner": 1, + "channel": 10, + "kind": "movie", + "title": "Dune", + "stage": "waiting", + "created": 1, + "notified": False, + } + } + ) + await jobs.tick() + assert len(channel.sent) == 1 + assert "attention" in channel.sent[0][0].lower() + state = await config.pending_jobs() + state["one"]["finished"] = 1 + await config.pending_jobs.set(state) + await jobs.tick() + assert await config.pending_jobs() == {} + assert len(channel.sent) == 1 + + +async def test_cog_load_resumes_notifications_and_unload_stops_the_worker( + config: Config, monkeypatch: pytest.MonkeyPatch +) -> None: + """Catch durable records that are never checked after a bot restart.""" + import asyncio + from datetime import UTC, datetime + + from watch.jobs import Jobs + + delivered = asyncio.Event() + + class Channel(Notifications): + async def send(self, content: str, **kwargs: Any) -> None: # noqa: ANN401 + await super().send(content, **kwargs) + delivered.set() + + async def handler(_request: web.Request) -> web.Response: + return web.json_response( + [ + { + "id": 7, + "tmdbId": 101, + "title": "Dune", + "hasFile": True, + } + ] + ) + + app = web.Application() + app.router.add_get("/api/v3/movie", handler) + async with TestServer(app) as server: + channel = Channel() + + class Bot: + async def get_shared_api_tokens( + self, _service: str + ) -> dict[str, str]: + return { + "url": str(server.make_url("/")), + "api_key": "test-key", + } + + async def wait_until_red_ready(self) -> None: + return None + + def get_channel(self, _id: int) -> Notifications: + return channel + + monkeypatch.setattr( + Config, "get_conf", lambda *_a, **_k: config + ) + cog = Watch(cast("Any", Bot())) + Jobs(cog) + await config.pending_jobs.set( + { + "one": { + "owner": 1, + "channel": 10, + "kind": "movie", + "foreign_id": 101, + "title": "Dune", + "stage": "waiting", + "created": datetime.now( + UTC + ).timestamp(), + "notified": False, + } + } + ) + await cog.cog_load() + try: + await asyncio.wait_for(delivered.wait(), timeout=2) + finally: + await cog.cog_unload() + assert len(channel.sent) == 1 + assert not cog._pollers + + +async def test_slow_music_import_does_not_delay_another_commands_completion( + config: Config, monkeypatch: pytest.MonkeyPatch +) -> None: + """Catch slow imports delaying movie notifications.""" + import asyncio + + import httpx + from music_helpers import MusicEdge, music_job, public_page + + import watch.jobs as job_module + from watch.jobs import Jobs + from watch.spotify import SpotifyPublic + + release = asyncio.Event() + notified = asyncio.Event() + + class Channel(Notifications): + async def send(self, content: str, **kwargs: Any) -> None: # noqa: ANN401 + await super().send(content, **kwargs) + if "Dune" in content: + notified.set() + + class Edge(MusicEdge): + async def http(self, request: web.Request) -> web.Response: + if request.path == "/api/v3/movie": + return web.json_response( + [ + { + "id": 7, + "tmdbId": 101, + "title": "Dune", + "hasFile": True, + } + ] + ) + return await super().http(request) + + async def slow_public(request: httpx.Request) -> httpx.Response: + await release.wait() + return public_page(request) + + edge = Edge() + app = web.Application() + app.router.add_route("*", "/{path:.*}", edge.http) + async with TestServer(app) as server: + channel = Channel() + + class Bot: + async def get_shared_api_tokens( + self, _service: str + ) -> dict[str, str]: + return { + "url": str(server.make_url("/")), + "api_key": "test-key", + } + + async def is_owner(self, _user: object) -> bool: + return True + + def get_channel(self, _id: int) -> Notifications: + return channel + + monkeypatch.setattr( + Config, "get_conf", lambda *_a, **_k: config + ) + cog = Watch(cast("Any", Bot())) + ctx = FakeContext() + ctx.channel = SimpleNamespace(id=10) + jobs = Jobs(cog) + await jobs.register( + cast("Any", ctx), + "playlist:test", + {"kind": "playlist", **music_job()}, + ) + await jobs.register( + cast("Any", ctx), + "movie:101", + {"kind": "movie", "foreign_id": 101, "title": "Dune"}, + ) + async with httpx.AsyncClient( + transport=httpx.MockTransport(slow_public) + ) as public: + monkeypatch.setattr( + job_module, + "SpotifyPublic", + lambda _client: SpotifyPublic(public), + raising=False, + ) + task = asyncio.create_task(jobs.tick()) + try: + await asyncio.wait_for( + notified.wait(), timeout=1 + ) + finally: + release.set() + await task diff --git a/tests/test_command_completion.py b/tests/test_command_completion.py new file mode 100644 index 0000000..c22da6e --- /dev/null +++ b/tests/test_command_completion.py @@ -0,0 +1,73 @@ +"""Test completion pings for other long commands.""" + +from types import SimpleNamespace +from typing import Any, cast + +import pytest +from redbot.core import Config, commands +from watch_helpers import FakeContext + +from watch.watch import Watch + + +@pytest.mark.parametrize( + ("name", "elapsed", "expected"), + [ + ("alignment guess", 15, True), + ("alignment baseline", 20, True), + ("help", 1, False), + ("watch", 30, False), + ("request", 30, False), + ("importplaylist", 30, False), + ], +) +async def test_only_long_untracked_commands_get_a_generic_completion_ping( + config: Config, + monkeypatch: pytest.MonkeyPatch, + name: str, + elapsed: int, + *, + expected: bool, +) -> None: + """Catch instant or duplicate completion pings.""" + monkeypatch.setattr(Config, "get_conf", lambda *_a, **_k: config) + cog = Watch(cast("Any", SimpleNamespace())) + ctx = FakeContext() + ctx.channel = SimpleNamespace(id=10) + ctx.message = SimpleNamespace(id=123) + ctx.command = SimpleNamespace(qualified_name=name) + now = [0.0] + monkeypatch.setattr( + "watch.watch.monotonic", lambda: now[0], raising=False + ) + await cog.command_started(cast("Any", ctx)) + now[0] = elapsed + await cog.command_finished(cast("Any", ctx)) + assert bool(ctx.sent) is expected + if expected: + assert ctx.texts[0].startswith("<@1>") + assert name in ctx.texts[0] + + +async def test_failed_long_command_pings_without_repeating_its_private_error( + config: Config, monkeypatch: pytest.MonkeyPatch +) -> None: + """Catch silence or credential disclosure on failure.""" + monkeypatch.setattr(Config, "get_conf", lambda *_a, **_k: config) + cog = Watch(cast("Any", SimpleNamespace())) + ctx = FakeContext() + ctx.channel = SimpleNamespace(id=10) + ctx.message = SimpleNamespace(id=123) + ctx.command = SimpleNamespace(qualified_name="alignment guess") + now = [0.0] + monkeypatch.setattr( + "watch.watch.monotonic", lambda: now[0], raising=False + ) + await cog.command_started(cast("Any", ctx)) + now[0] = 20 + await cog.command_failed( + cast("Any", ctx), commands.CommandError("private-credential") + ) + assert ctx.texts[0].startswith("<@1>") + assert "error" in ctx.texts[0] + assert "private-credential" not in ctx.texts[0] diff --git a/tests/test_completion.py b/tests/test_completion.py new file mode 100644 index 0000000..fa65157 --- /dev/null +++ b/tests/test_completion.py @@ -0,0 +1,67 @@ +"""Requester-only notifications after background work finishes.""" + +from typing import Any, cast + + +async def test_completion_pings_only_the_requester_not_names_or_roles() -> None: + """Catch mentioning everyone/roles via a hostile playlist title.""" + from watch.notify import completion_ping + + sent: list[dict[str, Any]] = [] + + class Channel: + async def send(self, content: str, **kwargs: Any) -> None: # noqa: ANN401 + sent.append({"content": content, **kwargs}) + + class Bot: + def get_channel(self, _channel: int) -> Channel: + return Channel() + + assert ( + await completion_ping( + cast("Any", Bot()), + 123, + 42, + "Finished @everyone <@&999>", + ) + is True + ) + assert sent[0]["content"].startswith("<@42> ") + mentions = sent[0]["allowed_mentions"].to_dict() + assert mentions["users"] == [42] + assert "everyone" not in mentions["parse"] + assert "roles" not in mentions["parse"] + + +async def test_missing_channel_falls_back_to_requester_dm() -> None: + """Catch losing the completion when the original channel disappears.""" + from types import SimpleNamespace + + import discord + + from watch.notify import completion_ping + + sent: list[str] = [] + + class User: + async def send(self, content: str, **_kwargs: Any) -> None: # noqa: ANN401 + sent.append(content) + + class Bot: + def get_channel(self, _channel: int) -> None: + return None + + async def fetch_channel(self, _channel: int) -> None: + raise discord.NotFound( + SimpleNamespace(status=404, reason="gone"), + "gone", + ) + + def get_user(self, user_id: int) -> User | None: + return User() if user_id == 42 else None + + assert ( + await completion_ping(cast("Any", Bot()), 123, 42, "Finished") + is True + ) + assert sent == ["<@42> Finished"] diff --git a/tests/test_music_import.py b/tests/test_music_import.py new file mode 100644 index 0000000..39ae007 --- /dev/null +++ b/tests/test_music_import.py @@ -0,0 +1,223 @@ +"""Test playlist acquisition and restart behavior through HTTP.""" + +import copy +from typing import Any, cast + +import httpx +import pytest +from aiohttp import web +from aiohttp.test_utils import TestServer +from music_helpers import MusicEdge, music_job, public_page +from redbot.core import Config + +from watch.jellyfin import Jellyfin +from watch.spotify import SpotifyPublic +from watch.watch import Watch + + +async def test_import_waits_and_resumes_without_duplicates( + config: Config, monkeypatch: pytest.MonkeyPatch +) -> None: + """Catch broad searches and duplicate imports.""" + from watch.music import MusicImporter + + edge = MusicEdge() + app = web.Application() + app.router.add_route("*", "/{path:.*}", edge.http) + async with TestServer(app) as server: + + class Bot: + async def get_shared_api_tokens( + self, _service: str + ) -> dict[str, str]: + return { + "url": str(server.make_url("/")), + "api_key": "test-key", + } + + monkeypatch.setattr( + Config, "get_conf", lambda *_a, **_k: config + ) + bot = Bot() + cog = Watch(cast("Any", bot)) + saved: dict[str, Any] = {} + + async def save(job: dict[str, Any]) -> None: + saved.clear() + saved.update(copy.deepcopy(job)) + + async def allowed() -> None: + return None + + async def arr(path: str, **kwargs: Any) -> Any: # noqa: ANN401 + return await cog._arr_call("music", path, **kwargs) + + async def tokens() -> dict[str, str]: + return await bot.get_shared_api_tokens("jellyfin") + + async with httpx.AsyncClient( + transport=httpx.MockTransport(public_page) + ) as public: + engine = MusicImporter( + arr, + Jellyfin(tokens), + SpotifyPublic(public), + save, + allowed, + ) + job = music_job() + await engine.prepare(job) + assert job["stage"] == "waiting" + assert len(edge.albums) == 1 + assert edge.albums[0]["monitored"] is True + assert edge.artists[0]["addOptions"] == { + "monitor": "none", + "searchForMissingAlbums": False, + } + assert edge.artists[0]["monitorNewItems"] == "none" + assert edge.searches == [[7]] + edge.ready.add("Halo") + await engine.refresh(job) + assert job["stage"] == "waiting" + assert edge.playlist["Name"] == "doge - My mix" + assert edge.playlist["IsPublic"] is True + assert edge.playlist["Ids"] == ["Halo", "Halo"] + job = copy.deepcopy(saved) + resumed = MusicImporter( + arr, + Jellyfin(tokens), + SpotifyPublic(public), + save, + allowed, + ) + await resumed.prepare(job) + edge.ready.add("Enjoy the Silence") + await resumed.refresh(job) + assert job["stage"] == "complete" + assert edge.playlist["Ids"] == [ + "Halo", + "Enjoy the Silence", + "Halo", + ] + assert edge.creations == 1 + assert edge.searches == [[7]] + + +async def test_revoked_permission_blocks_the_first_write_after_lookup( + config: Config, monkeypatch: pytest.MonkeyPatch +) -> None: + """Catch checking permission only at command entry.""" + import pytest + from music_helpers import import_environment + + edge = MusicEdge() + async with import_environment(config, monkeypatch, edge) as ( + engine, + _saved, + allowed, + ): + + async def revoke() -> None: + allowed[0] = False + + edge.after_lookup = revoke + with pytest.raises(PermissionError): + await engine.prepare(music_job()) + assert edge.albums == [] + assert edge.searches == [] + + +async def test_uncertain_playlist_creation_is_not_repeated_after_restart( + config: Config, monkeypatch: pytest.MonkeyPatch +) -> None: + """Catch duplicates after lost create replies.""" + import pytest + from music_helpers import import_environment + + from watch.errors import PreloadError + + class LostReply(MusicEdge): + async def http(self, request: web.Request) -> web.Response: + response = await super().http(request) + if request.path == "/Playlists": + return web.Response(status=503) + return response + + edge = LostReply(ready={"Halo", "Enjoy the Silence"}) + async with import_environment(config, monkeypatch, edge) as ( + engine, + saved, + _allowed, + ): + job = music_job() + await engine.prepare(job) + with pytest.raises(PreloadError): + await engine.refresh(job) + with pytest.raises(PreloadError, match="uncertain"): + await engine.refresh(copy.deepcopy(saved)) + assert edge.creations == 1 + + +async def test_unresolved_music_does_not_turn_into_an_all_added_result( + config: Config, monkeypatch: pytest.MonkeyPatch +) -> None: + """Catch claiming completion when the MusicBrainz match is missing.""" + from music_helpers import import_environment + + class MissingAlbum(MusicEdge): + async def arr(self, request: web.Request) -> web.Response: + if request.path.endswith("/album/lookup"): + return web.json_response([]) + return await super().arr(request) + + edge = MissingAlbum() + async with import_environment(config, monkeypatch, edge) as ( + engine, + _saved, + _allowed, + ): + job = music_job() + await engine.prepare(job) + await engine.refresh(job) + assert job["stage"] == "attention" + assert job["ready"] == 0 + assert edge.searches == [] + + +async def test_create_id_is_saved_atomically_with_acknowledgement( + config: Config, monkeypatch: pytest.MonkeyPatch +) -> None: + """Catch losing a created playlist ID after acknowledgement.""" + import asyncio + + import pytest + from music_helpers import import_environment + + edge = MusicEdge(ready={"Halo", "Enjoy the Silence"}) + async with import_environment(config, monkeypatch, edge) as ( + engine, + saved, + _allowed, + ): + job = music_job() + await engine.prepare(job) + original_save = engine.save + interrupted = False + + async def interrupted_save(state: dict[str, Any]) -> None: + nonlocal interrupted + await original_save(state) + if ( + edge.creations + and not state.get("mutation") + and not interrupted + ): + interrupted = True + raise asyncio.CancelledError + + engine.save = interrupted_save + with pytest.raises(asyncio.CancelledError): + await engine.refresh(job) + engine.save = original_save + await engine.refresh(copy.deepcopy(saved)) + assert edge.creations == 1 diff --git a/tests/test_music_matching.py b/tests/test_music_matching.py new file mode 100644 index 0000000..d3f6249 --- /dev/null +++ b/tests/test_music_matching.py @@ -0,0 +1,80 @@ +"""Conservative album and audio matching for playlist acquisition.""" + + +def test_only_one_canonical_album_for_the_credited_artist_is_selected() -> None: + """Reject first-hit and wrong-artist album matches.""" + from watch.music import choose_album + + candidates = [ + { + "id": 4, + "foreignAlbumId": "wrong", + "title": "Violator", + "artist": {"artistName": "Other"}, + }, + { + "id": 7, + "foreignAlbumId": "right", + "title": "Violator", + "artist": {"artistName": "Depeche Mode"}, + }, + ] + selected = choose_album( + {"title": "Violator (Remastered)", "artist": "Depeche Mode"}, + candidates, + ) + assert selected is not None + assert selected["id"] == 7 + candidates.append( + { + "id": 8, + "foreignAlbumId": "different", + "title": "Violator", + "artist": {"artistName": "Depeche Mode"}, + } + ) + assert ( + choose_album( + {"title": "Violator", "artist": "Depeche Mode"}, + candidates, + ) + is None + ) + + +def test_audio_match_requires_unique_artist_title_and_length() -> None: + """Reject wrong artists, versions and ambiguity.""" + from watch.music import find_audio + + track = {"title": "Halo", "artist": "Depeche Mode", "duration": 270186} + items = [ + { + "Id": "wrong-artist", + "Name": "Halo", + "Artists": ["Beyoncé"], + "RunTimeTicks": 2700000000, + }, + { + "Id": "wrong-version", + "Name": "Halo", + "Artists": ["Depeche Mode"], + "RunTimeTicks": 3300000000, + }, + { + "Id": "correct", + "Name": "Halo", + "Artists": ["Depeche Mode"], + "RunTimeTicks": 2700000000, + }, + ] + assert find_audio(track, items) == "correct" + items.append( + { + "Id": "ambiguous", + "Name": "Halo", + "Artists": ["Depeche Mode"], + "RunTimeTicks": 2701000000, + } + ) + assert find_audio(track, items) is None + assert find_audio({**track, "duration": 0}, items) is None diff --git a/tests/test_music_services.py b/tests/test_music_services.py new file mode 100644 index 0000000..734dd1e --- /dev/null +++ b/tests/test_music_services.py @@ -0,0 +1,194 @@ +"""Jellyfin playlist contracts against a real HTTP edge.""" + +from typing import Any, cast + +import pytest +from aiohttp import web +from aiohttp.test_utils import TestServer +from redbot.core import Config + + +async def test_playlist_is_public_owned_and_updated_in_source_order() -> None: + """Catch private, unowned or unordered playlists.""" + from watch.jellyfin import Jellyfin + + created: dict[str, Any] = {} + + async def handler(request: web.Request) -> web.Response: + if ( + request.headers.get("Authorization") + != 'MediaBrowser Token="test-key"' + ): + return web.Response(status=401) + if request.path == "/Users": + return web.json_response( + [ + { + "Id": "user-1", + "Name": "doge", + "Policy": {"IsDisabled": False}, + } + ] + ) + if request.path == "/Playlists": + created.update(await request.json()) + return web.json_response({"Id": "playlist-1"}) + if request.path == "/Playlists/playlist-1": + created.update(await request.json()) + return web.Response(status=204) + return web.Response(status=404) + + app = web.Application() + app.router.add_route("*", "/{path:.*}", handler) + async with TestServer(app) as server: + + async def tokens() -> dict[str, str]: + return { + "url": str(server.make_url("/")), + "api_key": "test-key", + "user_id": "service-1", + } + + api = Jellyfin(tokens) + uid = await api.user("doge") + assert uid == "user-1" + pid = await api.create_playlist( + "doge - My mix", uid, ["song-b", "song-a", "song-b"] + ) + assert pid == "playlist-1" + assert created == { + "Name": "doge - My mix", + "UserId": "user-1", + "Ids": ["song-b", "song-a", "song-b"], + "MediaType": "Audio", + "IsPublic": True, + "Users": [{"UserId": "service-1", "CanEdit": True}], + } + await api.update_playlist(pid, ["song-a", "song-b"]) + assert created["Ids"] == ["song-a", "song-b"] + + +async def test_private_service_errors_do_not_expose_credentials() -> None: + """Catch forwarding upstream bodies or token-bearing URLs to Discord.""" + from watch.errors import PreloadError + from watch.jellyfin import Jellyfin + + async def handler(_request: web.Request) -> web.Response: + return web.json_response( + {"secret": "private-credential"}, status=503 + ) + + app = web.Application() + app.router.add_get("/Users", handler) + async with TestServer(app) as server: + + async def tokens() -> dict[str, str]: + return { + "url": str(server.make_url("/")), + "api_key": "private-credential", + } + + with pytest.raises(PreloadError) as error: + await Jellyfin(tokens).user("doge") + assert "503" in str(error.value) + assert "private-credential" not in str(error.value) + + +async def test_lidarr_uses_v1_and_never_discloses_an_api_error_body( + config: Config, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Catch accidentally using the movie API version for music.""" + from watch.errors import PreloadError + from watch.watch import Watch + + async def handler(request: web.Request) -> web.Response: + if request.path != "/api/v1/album": + return web.Response(status=404) + if request.headers.get("X-Api-Key") != "secret-key": + return web.Response(status=401) + return web.json_response([{"id": 7, "title": "Violator"}]) + + app = web.Application() + app.router.add_route("*", "/{path:.*}", handler) + async with TestServer(app) as server: + + class Bot: + async def get_shared_api_tokens( + self, service: str + ) -> dict[str, str]: + return ( + { + "url": str( + server.make_url("/") + ), + "api_key": "secret-key", + } + if service == "lidarr" + else {} + ) + + monkeypatch.setattr( + Config, "get_conf", lambda *_a, **_k: config + ) + cog = Watch(cast("Any", Bot())) + assert await cog._arr_call("music", "album") == [ + {"id": 7, "title": "Violator"} + ] + with pytest.raises(PreloadError) as error: + await cog._arr_call("music", "private") + assert "404" in str(error.value) + assert "secret-key" not in str(error.value) + + +async def test_audio_search_pages_within_the_linked_user_scope() -> None: + """Catch incomplete or unscoped library searches.""" + from watch.jellyfin import Jellyfin + + async def handler(request: web.Request) -> web.Response: + if ( + request.query.get("userId") != "user-1" + or request.query.get("includeItemTypes") != "Audio" + ): + return web.Response(status=403) + if request.query.get("startIndex") == "0": + items = [ + { + "Id": "wrong", + "Name": "Halo", + "Artists": ["Other"], + "RunTimeTicks": 2700000000, + } + ] * 100 + else: + items = [ + { + "Id": "right", + "Name": "Halo", + "Artists": ["Depeche Mode"], + "RunTimeTicks": 2700000000, + } + ] + return web.json_response( + {"Items": items, "TotalRecordCount": 101} + ) + + app = web.Application() + app.router.add_get("/Items", handler) + async with TestServer(app) as server: + + async def tokens() -> dict[str, str]: + return { + "url": str(server.make_url("/")), + "api_key": "test-key", + } + + result = await Jellyfin(tokens).audio( + { + "title": "Halo", + "artist": "Depeche Mode", + "duration": 270186, + }, + "user-1", + ) + assert result == "right" diff --git a/tests/test_playlist_command.py b/tests/test_playlist_command.py new file mode 100644 index 0000000..913ce8c --- /dev/null +++ b/tests/test_playlist_command.py @@ -0,0 +1,372 @@ +"""Test playlist permissions, confirmation and job scope.""" + +import asyncio +from collections.abc import AsyncIterator +from dataclasses import dataclass +from types import SimpleNamespace +from typing import Any, cast + +import pytest +from aiohttp import web +from aiohttp.test_utils import TestServer +from music_helpers import MusicEdge, music_job +from redbot.core import Config +from test_background_jobs import Notifications +from watch_helpers import FakeContext + +from watch.watch import Watch + + +@dataclass +class PlaylistBot: + """Discord/service boundaries for command tests.""" + + url: str + channel: Notifications + owner: bool = True + + async def is_owner(self, _user: object) -> bool: + """Return the configured owner permission.""" + return self.owner + + async def get_shared_api_tokens(self, _service: str) -> dict[str, str]: + """Route service calls to the HTTP edge.""" + return {"url": self.url, "api_key": "test-key"} + + def get_channel(self, _channel_id: int) -> Notifications: + """Return the notification channel.""" + return self.channel + + +CommandCase = tuple[Watch, FakeContext, MusicEdge, Notifications, PlaylistBot] + + +@pytest.fixture +async def playlist_command( + config: Config, monkeypatch: pytest.MonkeyPatch +) -> AsyncIterator[CommandCase]: + """Keep configuration and all service traffic real up to HTTP.""" + + class Edge(MusicEdge): + async def http(self, request: web.Request) -> web.Response: + if request.path == "/Users": + return web.json_response( + [ + { + "Id": "user-1", + "Name": "doge", + "Policy": { + "IsDisabled": False # noqa: E501 + }, + } + ] + ) + return await super().http(request) + + edge = Edge(ready={"Halo", "Enjoy the Silence"}) + app = web.Application() + app.router.add_route("*", "/{path:.*}", edge.http) + async with TestServer(app) as server: + channel = Notifications() + bot = PlaylistBot(str(server.make_url("/")), channel) + monkeypatch.setattr( + Config, "get_conf", lambda *_a, **_k: config + ) + cog = Watch(cast("Any", bot)) + ctx = FakeContext() + ctx.channel = SimpleNamespace(id=10) + await config.user_from_id(1).jellyfin_user.set("doge") + yield cog, ctx, edge, channel, bot + await cog.cog_unload() + + +async def test_playlist_permission_precedes_service_calls( + playlist_command: CommandCase, +) -> None: + """Catch music download permission bypasses.""" + cog, ctx, edge, _channel, bot = playlist_command + bot.owner = False + await Watch.playlist.callback( + cog, + ctx, + url="https://open.spotify.com/playlist/7kRUsOsraSiY4fyDcu7Bnb", + ) + assert "permission" in ctx.texts[0].lower() + assert edge.playlist == {} + + +async def test_playlist_requires_a_linked_jellyfin_account( + playlist_command: CommandCase, +) -> None: + """Catch silently choosing an admin playlist owner.""" + cog, ctx, edge, _channel, _bot = playlist_command + await cog.config.user_from_id(1).jellyfin_user.clear() + await Watch.playlist.callback( + cog, + ctx, + url="https://open.spotify.com/playlist/7kRUsOsraSiY4fyDcu7Bnb", + ) + assert "watch link" in ctx.texts[0] + assert edge.playlist == {} + + +async def test_playlist_has_username_prefix_and_pings_when_ready( + playlist_command: CommandCase, monkeypatch: pytest.MonkeyPatch +) -> None: + """Catch acknowledging without importing.""" + from watch.spotify import SpotifyPublic + + cog, ctx, edge, channel, _bot = playlist_command + + async def snapshot(_self: object, _url: str) -> dict[str, Any]: + return { + "id": "7kRUsOsraSiY4fyDcu7Bnb", + "name": "My mix", + "tracks": music_job()["tracks"], + "partial": False, + } + + async def confirm(*_args: object) -> str: + return "import" + + monkeypatch.setattr(SpotifyPublic, "snapshot", snapshot) + monkeypatch.setattr(cog, "_download_choice", confirm) + await Watch.playlist.callback( + cog, + ctx, + url="https://open.spotify.com/playlist/7kRUsOsraSiY4fyDcu7Bnb?si=share", + ) + await asyncio.gather(*cog._pollers) + assert edge.playlist["Name"] == "doge - My mix" + assert edge.playlist["IsPublic"] is True + assert edge.playlist["Ids"] == ["Halo", "Enjoy the Silence", "Halo"] + assert len(channel.sent) == 1 + assert channel.sent[0][0].startswith("<@1>") + assert "3/3" in channel.sent[0][0] + jobs = await cog.config.pending_jobs() + assert len(jobs) == 1 + assert ( + next(iter(jobs.values()))["source_id"] + == "7kRUsOsraSiY4fyDcu7Bnb" + ) + + +async def test_public_limit_requires_an_explicit_visible_subset_confirmation( + playlist_command: CommandCase, monkeypatch: pytest.MonkeyPatch +) -> None: + """Catch silently treating a capped public playlist as complete.""" + from watch.spotify import SpotifyPublic + + cog, ctx, edge, _channel, _bot = playlist_command + prompts = [] + + async def snapshot(_self: object, _url: str) -> dict[str, Any]: + return { + "id": "7kRUsOsraSiY4fyDcu7Bnb", + "name": "Long mix", + "tracks": [music_job()["tracks"][0]] * 100, + "partial": True, + } + + async def cancel( + _ctx: object, text: str, choices: list[tuple[str, str]] + ) -> None: + prompts.append((text, choices)) + return + + monkeypatch.setattr(SpotifyPublic, "snapshot", snapshot) + monkeypatch.setattr(cog, "_download_choice", cancel) + await Watch.playlist.callback( + cog, + ctx, + url="https://open.spotify.com/playlist/7kRUsOsraSiY4fyDcu7Bnb", + ) + assert "100" in prompts[0][0] + assert "incomplete" in prompts[0][0].lower() + assert ("visible", "Import visible 100 only") in prompts[0][1] + assert edge.playlist == {} + assert await cog.config.pending_jobs() == {} + + +async def test_revocation_during_confirmation_does_not_queue_an_import( + playlist_command: CommandCase, monkeypatch: pytest.MonkeyPatch +) -> None: + """Catch revoked permission after confirmation.""" + from watch.spotify import SpotifyPublic + + cog, ctx, edge, _channel, bot = playlist_command + bot.owner = False + await cog.config.user_from_id(1).download_allowed.set(True) + + async def snapshot(_self: object, _url: str) -> dict[str, Any]: + return { + "id": "7kRUsOsraSiY4fyDcu7Bnb", + "name": "My mix", + "tracks": music_job()["tracks"], + "partial": False, + } + + async def revoke(*_args: object) -> str: + await cog.config.user_from_id(1).download_allowed.clear() + return "import" + + monkeypatch.setattr(SpotifyPublic, "snapshot", snapshot) + monkeypatch.setattr(cog, "_download_choice", revoke) + await Watch.playlist.callback( + cog, + ctx, + url="https://open.spotify.com/playlist/7kRUsOsraSiY4fyDcu7Bnb", + ) + assert edge.playlist == {} + assert await cog.config.pending_jobs() == {} + assert any("permission" in text.lower() for text in ctx.texts) + + +async def test_reimport_updates_the_existing_playlist( + playlist_command: CommandCase, monkeypatch: pytest.MonkeyPatch +) -> None: + """Catch creating another public playlist for the same owner/source.""" + from watch.spotify import SpotifyPublic + + cog, ctx, edge, _channel, _bot = playlist_command + + async def snapshot(_self: object, _url: str) -> dict[str, Any]: + return { + "id": "7kRUsOsraSiY4fyDcu7Bnb", + "name": "My mix", + "tracks": music_job()["tracks"], + "partial": False, + } + + async def confirm(*_args: object) -> str: + return "import" + + monkeypatch.setattr(SpotifyPublic, "snapshot", snapshot) + monkeypatch.setattr(cog, "_download_choice", confirm) + for _ in range(2): + await Watch.playlist.callback( + cog, + ctx, + url="https://open.spotify.com/playlist/7kRUsOsraSiY4fyDcu7Bnb", + ) + await asyncio.gather(*cog._pollers) + assert edge.creations == 1 + + +async def test_playlist_status_scopes_jobs_and_lists_review_tracks( + playlist_command: CommandCase, +) -> None: + """Catch leaking other users' jobs or hiding unresolved song names.""" + cog, ctx, _edge, _channel, _bot = playlist_command + cog.background() + await cog.config.pending_jobs.set( + { + "one": { + "owner": 1, + "kind": "playlist", + "name": "Own mix", + "stage": "attention", + "ready": 1, + "tracks": [ + { + "title": "Missing song", + "review": "No match", + }, + {}, + ], + }, + "two": { + "owner": 2, + "kind": "playlist", + "name": "Other user job", + "stage": "waiting", + "ready": 0, + "tracks": [], + }, + } + ) + await Watch.playlist_status.callback(cog, ctx) + assert "Own mix" in ctx.texts[0] + assert "1/2" in ctx.texts[0] + assert "Missing song" in ctx.texts[0] + assert "Other user" not in ctx.texts[0] + + +async def test_playlist_identity_survives_completed_job_cleanup( + playlist_command: CommandCase, monkeypatch: pytest.MonkeyPatch +) -> None: + """Catch duplicates after completion records expire.""" + from watch.spotify import SpotifyPublic + + cog, ctx, edge, _channel, _bot = playlist_command + + async def snapshot(_self: object, _url: str) -> dict[str, Any]: + return { + "id": "7kRUsOsraSiY4fyDcu7Bnb", + "name": "My mix", + "tracks": music_job()["tracks"], + "partial": False, + } + + async def confirm(*_args: object) -> str: + return "import" + + monkeypatch.setattr(SpotifyPublic, "snapshot", snapshot) + monkeypatch.setattr(cog, "_download_choice", confirm) + await Watch.playlist.callback( + cog, + ctx, + url="https://open.spotify.com/playlist/7kRUsOsraSiY4fyDcu7Bnb", + ) + await asyncio.gather(*cog._pollers) + await cog.config.pending_jobs.set({}) + await Watch.playlist.callback( + cog, + ctx, + url="https://open.spotify.com/playlist/7kRUsOsraSiY4fyDcu7Bnb", + ) + await asyncio.gather(*cog._pollers) + assert edge.creations == 1 + + +async def test_uncertain_prior_create_requires_verification_before_reimport( + playlist_command: CommandCase, monkeypatch: pytest.MonkeyPatch +) -> None: + """Catch silently duplicating a prior unacknowledged playlist create.""" + from watch.spotify import SpotifyPublic + + cog, ctx, edge, _channel, _bot = playlist_command + cog.background() + await cog.config.pending_jobs.set( + { + "1:playlist:7kRUsOsraSiY4fyDcu7Bnb": { + "owner": 1, + "notified": True, + "stage": "attention", + "kind": "playlist", + "mutation": "Jellyfin playlist create", + } + } + ) + + async def snapshot(_self: object, _url: str) -> dict[str, Any]: + return { + "id": "7kRUsOsraSiY4fyDcu7Bnb", + "name": "Mix", + "tracks": music_job()["tracks"], + "partial": False, + } + + async def confirm(*_args: object) -> str: + return "import" + + monkeypatch.setattr(SpotifyPublic, "snapshot", snapshot) + monkeypatch.setattr(cog, "_download_choice", confirm) + await Watch.playlist.callback( + cog, + ctx, + url="https://open.spotify.com/playlist/7kRUsOsraSiY4fyDcu7Bnb", + ) + await asyncio.gather(*cog._pollers) + assert edge.creations == 0 + assert any("verification" in text for text in ctx.texts) diff --git a/tests/test_season_requests.py b/tests/test_season_requests.py index 4fbbd53..a7fc7e8 100644 --- a/tests/test_season_requests.py +++ b/tests/test_season_requests.py @@ -467,3 +467,19 @@ async def test_user_data_deletion_forgets_claims_without_deleting_media( assert await cog.config.user_from_id(1).tv_seasons() == {} assert [f["id"] for f in fake.files] == [101] assert fake.calls == [] + + +async def test_tv_request_completion_subscription_keeps_the_selected_season( + seasons: tuple[Watch, FakeSonarr], +) -> None: + """Catch sending a completion for a different retained user's season.""" + cog, fake = seasons + existing_seasons(fake, [1]) + ctx = WizardContext(["tv", "0", "2", "1080p"], author=FakeAuthor(id=99)) + await Watch.request.callback(cog, ctx, query="Dune") + jobs = await cog.config.pending_jobs() + assert len(jobs) == 1 + job = next(iter(jobs.values())) + assert job["owner"] == 99 + assert job["kind"] == "tv" + assert job["season"] == 2 diff --git a/tests/test_spotify.py b/tests/test_spotify.py new file mode 100644 index 0000000..b758f1d --- /dev/null +++ b/tests/test_spotify.py @@ -0,0 +1,204 @@ +"""Public playlist input contracts, independent of Spotify account sessions.""" + +import pytest + + +def test_playlist_url_does_not_allow_an_arbitrary_fetch_target() -> None: + """Reject arbitrary hosts and non-playlist URLs.""" + from watch.spotify import playlist_id + + assert ( + playlist_id( + "https://open.spotify.com/playlist/7kRUsOsraSiY4fyDcu7Bnb?si=share" + ) + == "7kRUsOsraSiY4fyDcu7Bnb" + ) + for bad in ( + "http://127.0.0.1/playlist/7kRUsOsraSiY4fyDcu7Bnb", + "https://open.spotify.com.evil/playlist/7kRUsOsraSiY4fyDcu7Bnb", + "https://user@open.spotify.com/playlist/7kRUsOsraSiY4fyDcu7Bnb", + "https://open.spotify.com:444/playlist/7kRUsOsraSiY4fyDcu7Bnb", + "https://open.spotify.com/track/7kRUsOsraSiY4fyDcu7Bnb", + ): + with pytest.raises(ValueError, match="public Spotify playlist"): + playlist_id(bad) + + +def test_snapshot_keeps_playlist_order_and_marks_public_limits() -> None: + """Catch lost order and undisclosed public limits.""" + import json + + from watch.spotify import parse_playlist + + track = { + "uri": "spotify:track:6kwEU2hLQpMToj1PHsBrOE", + "title": "Halo", + "subtitle": "Depeche Mode", + "duration": 270186, + } + entity = { + "id": "0rA4Uu2pJd3IoHLcLS8rOx", + "name": "My mix", + "trackList": [track, track], + } + + def page() -> str: + return ( + '" + ) + + result = parse_playlist(page()) + assert result["name"] == "My mix" + assert [t["id"] for t in result["tracks"]] == [ + "6kwEU2hLQpMToj1PHsBrOE", + "6kwEU2hLQpMToj1PHsBrOE", + ] + assert result["partial"] is False + entity["trackList"] = [track] * 100 + assert parse_playlist(page())["partial"] is True + with pytest.raises(ValueError, match="public"): + parse_playlist("Sign in to view this playlist") + + +def test_album_pages_supply_metadata_without_guessing_a_recommendation() -> ( + None +): + """Catch using any album link on the page instead of music:album.""" + import json + + from watch.spotify import parse_album, track_album + + assert ( + track_album( + "Other' # noqa: E501 + ) + == "45YmvYK4hB4CgQgTMuNRm8" + ) + data = { + "props": { + "pageProps": { + "state": { + "data": { + "entity": { + "name": "Violator", + "subtitle": "Depeche Mode", # noqa: E501 + } + } + } + } + } + } + assert parse_album( + '" + ) == {"title": "Violator", "artist": "Depeche Mode"} + + +async def test_public_fetch_refuses_redirects_and_oversized_pages() -> None: + """Catch redirects and unbounded public input.""" + import httpx + + from watch.spotify import SpotifyPublic + + async def handler(request: httpx.Request) -> httpx.Response: + if request.url.path.endswith("7kRUsOsraSiY4fyDcu7Bnb"): + return httpx.Response( + 302, + headers={ + "Location": "http://127.0.0.1/private" + }, + ) + return httpx.Response(200, content=b"x" * (4 * 1024 * 1024 + 1)) + + async with httpx.AsyncClient( + transport=httpx.MockTransport(handler) + ) as client: + reader = SpotifyPublic(client) + with pytest.raises(ValueError, match="Spotify"): + await reader.snapshot( + "https://open.spotify.com/playlist/7kRUsOsraSiY4fyDcu7Bnb" + ) + with pytest.raises(ValueError, match="large"): + await reader.snapshot( + "https://open.spotify.com/playlist/0rA4Uu2pJd3IoHLcLS8rOx" + ) + + +async def test_track_album_resolution_uses_only_explicit_public_metadata() -> ( + None +): + """Catch guessing albums or fetching audio previews.""" + import json + + import httpx + + from watch.spotify import SpotifyPublic + + async def handler(request: httpx.Request) -> httpx.Response: + if ( + request.url.host != "open.spotify.com" + or "Authorization" in request.headers + ): + return httpx.Response(403) + if request.url.path == "/track/6kwEU2hLQpMToj1PHsBrOE": + return httpx.Response( + 200, + text=( + '' + ), + ) + if request.url.path == "/embed/album/45YmvYK4hB4CgQgTMuNRm8": + entity = { + "name": "Violator", + "subtitle": "Depeche Mode", + } + return httpx.Response( + 200, + text='", + ) + return httpx.Response(404) + + async with httpx.AsyncClient( + transport=httpx.MockTransport(handler) + ) as client: + reader = SpotifyPublic(client) + assert await reader.album_for_track( + "6kwEU2hLQpMToj1PHsBrOE" + ) == { + "id": "45YmvYK4hB4CgQgTMuNRm8", + "title": "Violator", + "artist": "Depeche Mode", + } + with pytest.raises(ValueError): + await reader.album_for_track("../../private") diff --git a/tests/test_watch_cog.py b/tests/test_watch_cog.py index a522329..2a4223c 100644 --- a/tests/test_watch_cog.py +++ b/tests/test_watch_cog.py @@ -212,7 +212,10 @@ async def test_watch_starts_an_exact_match( assert fake.calls_to("POST", "/v1/requests") == [ {"itemId": "m1", "requestedBy": "discord:doge"} ] - assert ctx.texts == ["Preloading The Matrix"] + assert ctx.texts == [ + "Preloading The Matrix", + "<@1> Preloading **The Matrix** finished: done.", + ] @pytest.mark.parametrize( diff --git a/tests/watch_helpers.py b/tests/watch_helpers.py index 9e32eaa..dfd2c1f 100644 --- a/tests/watch_helpers.py +++ b/tests/watch_helpers.py @@ -10,6 +10,7 @@ in the bot's image with requirements installed the way Red installs them. from collections.abc import AsyncGenerator from contextlib import asynccontextmanager from dataclasses import dataclass, field +from types import SimpleNamespace from typing import Any import discord @@ -223,6 +224,15 @@ class FakeContext: author: FakeAuthor = field(default_factory=FakeAuthor) clean_prefix: str = "d!" sent: list[FakeMessage] = field(default_factory=list) + channel: SimpleNamespace = field( + default_factory=lambda: SimpleNamespace(id=10) + ) + message: SimpleNamespace = field( + default_factory=lambda: SimpleNamespace(id=1) + ) + command: SimpleNamespace = field( + default_factory=lambda: SimpleNamespace(qualified_name="") + ) async def send( self, diff --git a/watch/__init__.py b/watch/__init__.py index a1d0adb..9c33d04 100644 --- a/watch/__init__.py +++ b/watch/__init__.py @@ -5,11 +5,11 @@ from redbot.core.bot import Red from .watch import Watch __red_end_user_data_statement__ = ( - "This cog stores the Jellyfin user name you link with `watch link`, " - "to find your next unwatched episodes, plus an owner-managed download " - "permission and selected TV season per show per user. `watch unlink` " - "deletes the linked name; Red user-data deletion removes all choices " - "and permissions without immediately deleting shared media." + "Stores Jellyfin names, download grants, TV season choices, " + "playlist ID mappings, and requester/channel/job metadata. Completed " + "job details expire after seven days; playlist mappings persist for " + "safe reimports. Red user-data deletion removes these records without " + "deleting shared media or public Jellyfin playlists." ) diff --git a/watch/info.json b/watch/info.json index bd96bf5..09a3f9b 100644 --- a/watch/info.json +++ b/watch/info.json @@ -3,10 +3,10 @@ "GodEmperorDoge" ], "name": "Watch", - "short": "Preload library media or request a movie/TV download.", - "description": "Preload library media or request English movie/TV downloads with owner-managed permissions, shared per-user season retention, and download progress.", + "short": "Preload media, request downloads and import public Spotify playlists.", + "description": "Owner-permitted movie/TV and music acquisition, public Jellyfin playlists, per-user TV season retention and durable completion notifications.", "install_msg": "Set the API token with the PRELOAD_BOT_TOKEN environment variable or `[p]set api media_preload token,` (and url, if it isn't http://host.containers.internal:8125).", - "end_user_data_statement": "Stores a linked Jellyfin name, download permission, and one selected TV season per show per Discord user. watch unlink removes the name; Red user-data deletion clears all choices and permissions without immediately deleting shared media.", + "end_user_data_statement": "Stores a linked Jellyfin name, download permission, TV season choices, playlist source-to-Jellyfin ID mappings, and requester/channel/job metadata. Completed job details expire after seven days; mappings persist for safe reimports. Red user-data deletion removes these records without deleting shared media or public Jellyfin playlists.", "requirements": [ "media-preload-client @ git+https://github.com/RustyRaptor/doge_cogs.git#subdirectory=clients/media-preload-client" ], diff --git a/watch/jellyfin.py b/watch/jellyfin.py new file mode 100644 index 0000000..71d3eda --- /dev/null +++ b/watch/jellyfin.py @@ -0,0 +1,145 @@ +"""Owner-scoped Jellyfin playlist operations.""" + +from collections.abc import Awaitable, Callable +from typing import Any +from urllib.parse import quote + +import httpx + +from .errors import PreloadError + + +class Jellyfin: + """Use a named bot integration, with credentials confined to headers.""" + + def __init__( + self, tokens: Callable[[], Awaitable[dict[str, str]]] + ) -> None: + """Read current integration credentials at each operation.""" + self.tokens = tokens + + async def call( + self, + path: str, + *, + body: dict[str, Any] | None = None, + params: dict[str, str] | None = None, + method: str = "GET", + ) -> Any: # noqa: ANN401 (upstream JSON) + """Confine credentials and redact upstream errors.""" + config = await self.tokens() + if not config.get("url") or not config.get("api_key"): + msg = "Jellyfin playlist integration is not configured." + raise PreloadError(msg) + try: + async with httpx.AsyncClient( + base_url=config["url"].rstrip("/") + "/", + headers={ + "Authorization": 'MediaBrowser Token="' + + config["api_key"] + + '"' + }, + timeout=30, + ) as client: + response = await client.request( + method, path, json=body, params=params + ) + except httpx.HTTPError: + msg = ( + "Jellyfin could not be reached; check status " + "before retrying." + ) + raise PreloadError(msg) from None + if response.status_code >= 400: + msg = f"Jellyfin answered HTTP {response.status_code}." + raise PreloadError(msg) + if response.status_code == 204 or not response.content: + return None + try: + return response.json() + except ValueError: + msg = "Jellyfin returned an invalid response." + raise PreloadError(msg) from None + + async def user(self, name: str) -> str: + """Resolve exactly one enabled linked account.""" + users = await self.call("Users") + matches = [ + u + for u in users + if u.get("Name", "").casefold() == name.casefold() + and not u.get("Policy", {}).get("IsDisabled", False) + ] + if len(matches) != 1: + msg = ( + "Link an enabled Jellyfin account with `watch " + "link `." + ) + raise PreloadError(msg) + return str(matches[0]["Id"]) + + async def create_playlist( + self, name: str, user_id: str, ids: list[str] + ) -> str: + """Create a public playlist owned by the linked user.""" + config = await self.tokens() + service_user = config.get("user_id") + editors = ( + [{"UserId": service_user, "CanEdit": True}] + if service_user and service_user != user_id + else [] + ) + result = await self.call( + "Playlists", + method="POST", + body={ + "Name": name, + "UserId": user_id, + "Ids": ids, + "MediaType": "Audio", + "IsPublic": True, + "Users": editors, + }, + ) + return str(result["Id"]) + + async def update_playlist( + self, playlist_id: str, ids: list[str] + ) -> None: + """Replace playlist contents in source order.""" + await self.call( + "Playlists/" + quote(playlist_id, safe=""), + method="POST", + body={"Ids": ids}, + ) + + async def audio( + self, track: dict[str, Any], user_id: str + ) -> str | None: + """Find one available track within user scope.""" + from .music import find_audio + + items = [] + start = 0 + while True: + result = await self.call( + "Items", + params={ + "userId": user_id, + "includeItemTypes": "Audio", + "recursive": "true", + "searchTerm": track["title"], + "fields": "ProviderIds", + "limit": "100", + "startIndex": str(start), + }, + ) + page = result.get("Items", []) + items.extend(page) + start += len(page) + total = result.get("TotalRecordCount", start) + if total > 500: + return None + if start >= total or not page: + break + return find_audio(track, items) diff --git a/watch/jobs.py b/watch/jobs.py new file mode 100644 index 0000000..3633b37 --- /dev/null +++ b/watch/jobs.py @@ -0,0 +1,349 @@ +"""Persist media subscriptions until background work reaches a result.""" + +from __future__ import annotations + +import asyncio +import logging +from datetime import UTC, datetime +from functools import partial +from typing import TYPE_CHECKING, Any, cast + +import discord +import httpx + +from .errors import PreloadError +from .jellyfin import Jellyfin +from .music import MusicImporter +from .notify import completion_ping +from .spec import is_finished +from .spotify import SpotifyPublic + +if TYPE_CHECKING: + from collections.abc import Awaitable, Callable + + from media_preload_client.models import PreloadRequest + from redbot.core import commands + + from .watch import Person, Watch + + +log = logging.getLogger("red.doge_cogs.watch.jobs") + + +class Jobs: + """Keep pending notifications through cog reloads and bot restarts.""" + + def __init__(self, cog: Watch) -> None: + """Use the existing Watch configuration namespace.""" + self.cog = cog + self.config = cog.config + self.config.register_global(pending_jobs={}) + self.config.register_user(playlist_links={}) + self.active: set[str] = set() + self.notify_lock = asyncio.Lock() + self.limiter = asyncio.Semaphore(3) + + async def register( + self, ctx: commands.Context, key: str, data: dict[str, Any] + ) -> str: + """Subscribe the requester without duplicate jobs.""" + owner = ctx.author.id + key = f"{owner}:{key}" + async with self.config.pending_jobs() as jobs: + previous = jobs.get(key) + if previous and not previous.get("notified"): + return key + links = await self.config.user_from_id( + owner + ).playlist_links() + link = ( + links.get(data.get("source_id")) + if data.get("kind") == "playlist" + else None + ) + carry = ( + {"playlist_id": link["playlist_id"]} + if link + and link["user_id"] == data.get("user_id") + else {} + ) + jobs[key] = { + **carry, + "owner": owner, + "username": ctx.author.name, + "channel": getattr( + getattr(ctx, "channel", None), "id", 0 + ), + "created": datetime.now(UTC).timestamp(), + "stage": "waiting", + "notified": False, + **data, + } + return key + + async def save(self, key: str, job: dict[str, Any]) -> None: + """Update an extant job; never resurrect deleted user data.""" + async with self.config.pending_jobs() as jobs: + if key not in jobs: + raise asyncio.CancelledError + jobs[key] = job + if ( + job.get("kind") == "playlist" + and job.get("playlist_id") + and job.get("source_id") + ): + group = self.config.user_from_id(job["owner"]) + links = await group.playlist_links() + links[job["source_id"]] = { + "playlist_id": job["playlist_id"], + "user_id": job["user_id"], + } + await group.playlist_links.set(links) + + async def tick(self) -> None: + """Check each pending subscription once.""" + cutoff = datetime.now(UTC).timestamp() - 7 * 86400 + async with self.config.pending_jobs() as jobs: + for key in list(jobs): + if ( + jobs[key].get("notified") + and jobs[key].get("finished", 0) + < cutoff + ): + del jobs[key] + results = await asyncio.gather( + *( + self.run_once(key) + for key in await self.config.pending_jobs() + ), + return_exceptions=True, + ) + for result in results: + if isinstance(result, Exception): + log.warning( + "Background job check failed (%s)", + type(result).__name__, + ) + + async def run_once(self, key: str) -> None: + """Advance one job without overlapping another check of it.""" + if key in self.active: + return + self.active.add(key) + try: + async with self.limiter: + await self._advance(key) + finally: + self.active.discard(key) + + async def watch_loop(self) -> None: + """Resume stored work and check once per minute.""" + await self.cog.bot.wait_until_red_ready() + while True: + await self.tick() + await asyncio.sleep(60) + + async def _advance(self, key: str) -> None: + """Check one extant job and deliver a terminal result.""" + job = (await self.config.pending_jobs()).get(key) + if not job or job.get("notified"): + return + if ( + job["stage"] + not in {"complete", "attention", "cancelled"} + and datetime.now(UTC).timestamp() - job["created"] + > 7 * 86400 + ): + job["stage"] = "attention" + await self.save(key, job) + if job["stage"] not in {"complete", "attention", "cancelled"}: + try: + if job["kind"] == "playlist": + await self._music(key, job) + else: + await self._media(job) + except PermissionError: + job["stage"] = "cancelled" + except PreloadError: + if job.get("mutation"): + job["stage"] = "attention" + else: + return + await self.save(key, job) + if job["stage"] in {"complete", "attention", "cancelled"}: + await self.finish(key, job) + + async def _music(self, key: str, job: dict[str, Any]) -> None: + """Run the album importer using the same durable job record.""" + + async def authorize() -> None: + if not await self.cog.can_download( + cast("Person", discord.Object(id=job["owner"])) + ): + msg = "Download permission was revoked." + raise PermissionError(msg) + + async def save(state: dict[str, Any]) -> None: + await self.save(key, state) + + async def tokens() -> dict[str, str]: + return await self.cog.bot.get_shared_api_tokens( + "jellyfin" + ) + + await authorize() + async with httpx.AsyncClient() as client: + engine = MusicImporter( + partial(self.cog._arr_call, "music"), + Jellyfin(tokens), + SpotifyPublic(client), + save, + authorize, + lock=self.cog._acquisition_lock, + ) + await engine.prepare(job) + await engine.refresh(job) + + async def _media(self, job: dict[str, Any]) -> None: + """Check imported files rather than an empty queue.""" + kind = job["kind"] + if kind == "preload": + request = await self.cog.fetch(job["request_id"]) + if is_finished(request): + job["stage"] = "complete" + job["result"] = request.status.value + return + field = "tmdbId" if kind == "movie" else "tvdbId" + title = await self.cog._existing_title( + kind, {field: job["foreign_id"]} + ) + if title is None: + return + if kind == "movie": + if title.get("hasFile"): + job["stage"] = "complete" + return + episodes = await self.cog._arr_call( + "tv", "episode", params={"seriesId": str(title["id"])} + ) + selected = [ + e + for e in episodes + if e.get("seasonNumber") == job["season"] + and self._aired(e) + ] + if selected and all(e.get("hasFile") for e in selected): + job["stage"] = "complete" + + @staticmethod + def _aired(episode: dict[str, Any]) -> bool: + """Exclude unknown or future episodes without files.""" + if episode.get("hasFile"): + return True + try: + when = datetime.fromisoformat( + episode["airDateUtc"].replace("Z", "+00:00") + ) + return when <= datetime.now(UTC) + except (ValueError, KeyError, TypeError): + return False + + @staticmethod + def message(job: dict[str, Any]) -> str: + """Describe completion without private service details.""" + if job["kind"] == "playlist": + name = discord.utils.escape_markdown( + job.get("name", "Playlist") + ) + ready = job.get("ready", 0) + count = len(job["tracks"]) + if job["stage"] == "cancelled": + return ( + f"Playlist **{name}** import " + f"cancelled: download permission was " + f"removed." + ) + if job["stage"] == "attention": + detail = ( + " An earlier write needs verification." + if job.get("mutation") + else ( + " Check `importplaylist " + "status` for tracks needing " + "review." + ) + ) + return ( + f"Playlist **{name}** import " + f"finished with gaps: " + f"{ready}/{count} songs in " + f"Jellyfin." + ) + detail + detail = ( + ( + " These are the visible public " + "snapshot songs; Spotify may contain " + "more." + ) + if job.get("partial") + else "" + ) + return ( + f"Your Jellyfin playlist **{name}** is " + f"ready ({ready}/{count} songs)." + ) + detail + title = discord.utils.escape_markdown(job.get("title", "Media")) + if job["stage"] == "attention": + return ( + f"**{title}** still needs attention; it did " + f"not finish within seven days." + ) + if job["kind"] == "preload": + return ( + f"Preloading **{title}** finished: " + f"{job.get('result', 'done')}." + ) + season = ( + f", season {job['season']}" + if job["kind"] == "tv" + else "" + ) + return f"**{title}**{season} is downloaded and imported." + + async def finish_preload( + self, + key: str, + request: PreloadRequest, + send: Callable[..., Awaitable[Any]], + ) -> None: + """Notify when an active follower reaches a result.""" + job = (await self.config.pending_jobs()).get(key) + if job and is_finished(request): + job.update( + stage="complete", result=request.status.value + ) + await self.save(key, job) + await self.finish(key, job, send=send) + + async def finish( + self, + key: str, + job: dict[str, Any], + *, + send: Callable[..., Awaitable[Any]] | None = None, + ) -> None: + """Persist delivery to prevent repeated pings.""" + async with self.notify_lock: + current = (await self.config.pending_jobs()).get(key) + if not current or current.get("notified"): + return + if await completion_ping( + self.cog.bot, + job["channel"], + job["owner"], + self.message(job), + send=send, + ): + job["notified"] = True + job["finished"] = datetime.now(UTC).timestamp() + await self.save(key, job) diff --git a/watch/music.py b/watch/music.py new file mode 100644 index 0000000..120fcce --- /dev/null +++ b/watch/music.py @@ -0,0 +1,347 @@ +"""Conservative music identity matching for public playlist imports.""" + +import asyncio +import re +import unicodedata +from collections.abc import Awaitable, Callable +from functools import partial +from typing import Any + +from .errors import PreloadError +from .jellyfin import Jellyfin +from .spotify import SpotifyPublic + + +def normalized(value: str) -> str: + """Normalize punctuation and Unicode presentation.""" + return "".join( + c + for c in unicodedata.normalize("NFKC", value).casefold() + if c.isalnum() + ) + + +def album_title(value: str) -> str: + """Ignore editions without stripping live/remix identity.""" + value = re.sub( + r"\s*[([][^)\]]*(?:remaster|deluxe|anniversary|expanded|" + r"special edition)[^)\]]*[)\]]\s*", + " ", + value, + flags=re.IGNORECASE, + ) + value = re.sub( + r"\s+-\s+(?:\d{4}\s+)?remaster(?:ed)?.*$", + "", + value, + flags=re.IGNORECASE, + ) + return normalized(value) + + +def choose_album( + source: dict[str, str], candidates: list[dict[str, Any]] +) -> dict[str, Any] | None: + """Require one canonical release group with matching artist/title.""" + matches = [ + a + for a in candidates + if normalized(a.get("artist", {}).get("artistName", "")) + == normalized(source["artist"].split(",")[0]) + and album_title(a["title"]) == album_title(source["title"]) + ] + ids = {a["foreignAlbumId"] for a in matches} + return matches[0] if len(ids) == 1 else None + + +def find_audio( + source: dict[str, Any], items: list[dict[str, Any]] +) -> str | None: + """Require a unique title/artist/length match in the user's library.""" + duration = source.get("duration", 0) + if not isinstance(duration, (int, float)) or duration <= 0: + return None + matches = [ + item + for item in items + if normalized(item.get("Name", "")) + == normalized(source["title"]) + and normalized(source["artist"].split(",")[0]) + in {normalized(a) for a in item.get("Artists", [])} + and abs(item.get("RunTimeTicks", 0) / 10000 - duration) <= 3000 + ] + return str(matches[0]["Id"]) if len(matches) == 1 else None + + +class MusicImporter: + """Resolve albums and fill a durable Jellyfin playlist.""" + + def __init__( + self, + arr: Callable[..., Awaitable[Any]], + jellyfin: Jellyfin, + spotify: SpotifyPublic, + save: Callable[[dict[str, Any]], Awaitable[None]], + authorize: Callable[[], Awaitable[None]], + *, + lock: asyncio.Lock | None = None, + ) -> None: + """Inject service clients, persistence and permissions.""" + self.arr = arr + self.jellyfin = jellyfin + self.spotify = spotify + self.save = save + self.authorize = authorize + self.lock = lock if lock is not None else asyncio.Lock() + + @staticmethod + def _certain(job: dict[str, Any]) -> None: + """Stop writes whose acknowledgement was lost.""" + if job.get("mutation"): + msg = ( + "A previous write has an uncertain outcome; " + "inspect the job before retrying." + ) + raise PreloadError(msg) + + async def _write( + self, + job: dict[str, Any], + action: str, + operation: Callable[[], Awaitable[Any]], + *, + result_key: str | None = None, + ) -> Any: # noqa: ANN401 (upstream JSON) + """Persist write intent until acknowledgement.""" + await self.authorize() + job["mutation"] = action + await self.save(job) + await self.authorize() + result = await operation() + if result_key: + job[result_key] = ( + result["id"] + if isinstance(result, dict) + else result + ) + job.pop("mutation", None) + await self.save(job) + return result + + async def _album( + self, job: dict[str, Any], source: dict[str, str] + ) -> int | None: + """Monitor one album without changing other choices.""" + candidates = await self.arr( + "album/lookup", params={"term": source["title"]} + ) + match = choose_album(source, candidates) + if match is None: + return None + async with self.lock: + existing = await self.arr( + "album", + params={ + "foreignAlbumId": match[ + "foreignAlbumId" + ] + }, + ) + if existing: + album = existing[0] + if not album.get("artistId"): + return None + if not album["monitored"]: + album["monitored"] = True + await self._write( + job, + "Lidarr album monitoring", + partial( + self.arr, + f"album/{album['id']}", + body=album, + method="PUT", + ), + ) + return int(album["id"]) + roots = await self.arr("rootfolder") + root = next( + ( + r + for r in roots + if r["path"] == "/arr/library/Music" + ), + None, + ) + if root is None: + msg = "The Lidarr music root is not configured." + raise PreloadError(msg) + artists = await self.arr("artist") + known = {a["foreignArtistId"] for a in artists} + artist = dict(match["artist"]) + artist.update( + rootFolderPath=root["path"], + qualityProfileId=root[ + "defaultQualityProfileId" + ], + metadataProfileId=root[ + "defaultMetadataProfileId" + ], + monitored=True, + monitorNewItems="none", + addOptions={ + "monitor": "none", + "searchForMissingAlbums": False, + }, + ) + payload = { + **match, + "artist": artist, + "monitored": True, + "addOptions": {"searchForNewAlbum": False}, + } + album = await self._write( + job, + "Lidarr album add", + partial( + self.arr, + "album", + body=payload, + method="POST", + ), + ) + if artist["foreignArtistId"] not in known: + created = await self.arr( + f"artist/{album['artistId']}" + ) + created.update( + monitored=True, monitorNewItems="none" + ) + await self._write( + job, + "Lidarr selected-artist activation", + partial( + self.arr, + f"artist/{created['id']}", + body=created, + method="PUT", + ), + ) + return int(album["id"]) + + async def _resolve_row( + self, job: dict[str, Any], row: dict[str, Any] + ) -> None: + """Resolve one source row without losing saved progress.""" + albums = job.setdefault("albums", {}) + metadata = job.setdefault("track_albums", {}) + found = await self.jellyfin.audio(row, job["user_id"]) + if found: + row.update(resolved=True, item_id=found) + await self.save(job) + return + if not row.get("id"): + row.update( + resolved=True, + review="Unavailable source track", + ) + await self.save(job) + return + try: + details = metadata.get(row["id"]) + if details is None: + details = await self.spotify.album_for_track( + row["id"] + ) + metadata[row["id"]] = details + sid = details["id"] + if sid not in albums: + albums[sid] = await self._album(job, details) + if albums[sid] is None: + row["review"] = "No unique artist/album match" + else: + row["album_id"] = albums[sid] + except ValueError: + row["review"] = "Public album metadata unavailable" + row["resolved"] = True + await self.save(job) + + async def prepare(self, job: dict[str, Any]) -> None: + """Resolve songs and search only their selected albums.""" + self._certain(job) + if job["stage"] != "preparing": + return + albums = job.setdefault("albums", {}) + for row in job["tracks"]: + if row.get("resolved"): + continue + await self._resolve_row(job, row) + ids = sorted({i for i in albums.values() if i is not None}) + if ids and not job.get("search_id"): + command = await self._write( + job, + "Lidarr selected-album search", + partial( + self.arr, + "command", + body={ + "name": "AlbumSearch", + "albumIds": ids, + }, + method="POST", + ), + result_key="search_id", + ) + job["search_id"] = command["id"] + job["stage"] = "waiting" + await self.save(job) + + async def refresh(self, job: dict[str, Any]) -> None: + """Publish songs and verify complete availability.""" + self._certain(job) + ids = [] + review = 0 + cache = {} + for row in job["tracks"]: + key = (row.get("id"), row["title"], row["artist"]) + if key not in cache: + cache[key] = await self.jellyfin.audio( + row, job["user_id"] + ) + found = cache[key] + if found: + ids.append(found) + elif row.get("review"): + review += 1 + job["ready"] = len(ids) + if not job.get("playlist_id") and ( + ids or review < len(job["tracks"]) + ): + name = f"{job['username']} - {job['name']}"[:250] + job["playlist_id"] = await self._write( + job, + "Jellyfin playlist create", + partial( + self.jellyfin.create_playlist, + name, + job["user_id"], + ids, + ), + result_key="playlist_id", + ) + job["playlist_items"] = ids + elif job.get("playlist_id") and ids != job.get( + "playlist_items" + ): + await self.authorize() + await self.jellyfin.update_playlist( + job["playlist_id"], ids + ) + job["playlist_items"] = ids + if len(ids) == len(job["tracks"]): + job["stage"] = "complete" + elif len(ids) + review == len(job["tracks"]): + job["stage"] = "attention" + else: + job["stage"] = "waiting" + await self.save(job) diff --git a/watch/notify.py b/watch/notify.py new file mode 100644 index 0000000..3d3e4b1 --- /dev/null +++ b/watch/notify.py @@ -0,0 +1,42 @@ +"""Completion delivery with only the requesting Discord user mentionable.""" + +from collections.abc import Awaitable, Callable +from typing import Any + +import discord +from redbot.core.bot import Red + + +async def completion_ping( + bot: Red, + channel_id: int, + user_id: int, + text: str, + *, + send: Callable[..., Awaitable[Any]] | None = None, +) -> bool: + """Try the channel, then a DM; retain failed deliveries.""" + content = f"<@{user_id}> {text}" + mentions = discord.AllowedMentions( + users=[discord.Object(id=user_id)], + roles=False, + everyone=False, + replied_user=False, + ) + try: + if send is None: + channel = bot.get_channel(channel_id) + if channel is None: + channel = await bot.fetch_channel(channel_id) + send = channel.send + await send(content, allowed_mentions=mentions) + except discord.HTTPException: + pass + else: + return True + try: + user = bot.get_user(user_id) or await bot.fetch_user(user_id) + await user.send(content, allowed_mentions=mentions) + except discord.HTTPException: + return False + return True diff --git a/watch/spotify.py b/watch/spotify.py new file mode 100644 index 0000000..fed33e9 --- /dev/null +++ b/watch/spotify.py @@ -0,0 +1,165 @@ +"""Read public Spotify metadata without audio or account-session access.""" + +import json +import re +from html.parser import HTMLParser +from typing import Any +from urllib.parse import urlsplit + +import httpx + + +def playlist_id(value: str) -> str: + """Validate a public playlist URL; discard sharing parameters.""" + url = urlsplit(value.strip()) + match = re.fullmatch(r"/playlist/([A-Za-z0-9]{22})/?", url.path) + if ( + url.scheme != "https" + or url.netloc != "open.spotify.com" + or match is None + ): + msg = "Use a public Spotify playlist URL." + raise ValueError(msg) + return match[1] + + +# Spotify's public embed carries structured metadata. Never inspect web-player +# session tokens or audio preview URLs from the surrounding page. + + +class _Page(HTMLParser): + def __init__(self) -> None: + super().__init__() + self.reading = False + self.data: list[str] = [] + self.album = "" + + def handle_starttag( + self, tag: str, attrs: list[tuple[str, str | None]] + ) -> None: + values = dict(attrs) + if tag == "script" and values.get("id") == "__NEXT_DATA__": + self.reading = True + if tag == "meta" and values.get("name") == "music:album": + self.album = values.get("content") or "" + + def handle_endtag(self, tag: str) -> None: + if tag == "script": + self.reading = False + + def handle_data(self, data: str) -> None: + if self.reading: + self.data.append(data) + + +def _entity(page: str) -> dict[str, Any]: + parser = _Page() + parser.feed(page) + try: + return json.loads("".join(parser.data))["props"]["pageProps"][ + "state" + ]["data"]["entity"] + except (ValueError, KeyError, TypeError): + msg = "No readable public Spotify metadata was returned." + raise ValueError(msg) from None + + +def parse_playlist(page: str) -> dict[str, Any]: + """Keep source order/duplicates and disclose the public embed limit.""" + entity = _entity(page) + if not entity.get("trackList"): + msg = "This public playlist is empty, private or unavailable." + raise ValueError(msg) + tracks = [] + for track in entity["trackList"]: + match = re.fullmatch( + r"spotify:track:([A-Za-z0-9]{22})", + str(track.get("uri", "")), + ) + tracks.append( + { + "id": match[1] if match else None, + "title": str(track.get("title", "Unavailable")), + "artist": str(track.get("subtitle", "")), + "duration": track.get("duration", 0), + } + ) + return { + "id": str(entity.get("id", "")), + "name": str(entity.get("name", "Spotify playlist"))[:200], + "tracks": tracks, + "partial": len(tracks) >= 100, + } + + +def track_album(page: str) -> str: + """Read the track's explicit album, ignoring other links.""" + parser = _Page() + parser.feed(page) + match = re.fullmatch( + r"https://open.spotify.com/album/([A-Za-z0-9]{22})", + parser.album, + ) + if not match: + msg = "The public track page does not identify its album." + raise ValueError(msg) + return match[1] + + +def parse_album(page: str) -> dict[str, str]: + """Read an album's title and credited artist.""" + entity = _entity(page) + return {"title": entity["name"], "artist": entity["subtitle"]} + + +class SpotifyPublic: + """Fetch bounded public metadata from fixed HTTPS routes only.""" + + def __init__(self, client: httpx.AsyncClient) -> None: + """Use a client with no private service credentials attached.""" + self.client = client + + async def _page(self, path: str) -> str: + try: + async with self.client.stream( + "GET", + "https://open.spotify.com/" + path, + follow_redirects=False, + timeout=30, + ) as response: + if response.status_code != 200: + msg = ( + "Spotify public metadata is " + "unavailable." + ) + raise ValueError(msg) + chunks = bytearray() + async for chunk in response.aiter_bytes(): + chunks.extend(chunk) + if len(chunks) > 4 * 1024 * 1024: + msg = ( + "Spotify metadata page " + "is too large." + ) + raise ValueError(msg) + except httpx.HTTPError: + msg = "Spotify public metadata could not be reached." + raise ValueError(msg) from None + return chunks.decode("utf-8", errors="replace") + + async def snapshot(self, url: str) -> dict[str, Any]: + """Read a playlist in visible source order.""" + return parse_playlist( + await self._page("embed/playlist/" + playlist_id(url)) + ) + + async def album_for_track(self, track_id: str) -> dict[str, str]: + """Resolve the explicitly linked album of a track.""" + if not re.fullmatch(r"[A-Za-z0-9]{22}", track_id): + msg = "Invalid public Spotify track identity." + raise ValueError(msg) + album_id = track_album(await self._page("track/" + track_id)) + details = parse_album( + await self._page("embed/album/" + album_id) + ) + return {"id": album_id, **details} diff --git a/watch/watch.py b/watch/watch.py index 9353061..d8050c0 100644 --- a/watch/watch.py +++ b/watch/watch.py @@ -9,6 +9,8 @@ import asyncio import contextlib import logging import os +from collections.abc import Awaitable, Callable, Coroutine +from time import monotonic from typing import Any, Literal import discord @@ -34,6 +36,9 @@ from redbot.core.bot import Red from .downloads import describe_downloads, normalized_title from .errors import PreloadError, SeasonError +from .jellyfin import Jellyfin +from .jobs import Jobs +from .notify import completion_ping from .retention import SeasonPlan from .seasonal import SeasonManager from .spec import ( @@ -46,6 +51,7 @@ from .spec import ( parse_season, split_query, ) +from .spotify import SpotifyPublic, playlist_id log = logging.getLogger("red.doge_cogs.watch") @@ -356,19 +362,99 @@ class Watch(commands.Cog): ) self.config.register_global(season_retention_baseline=None) self._acquisition_lock = asyncio.Lock() + self._background: Jobs | None = None + self._command_runs: dict[int, tuple[float, int]] = {} self._pollers: set[asyncio.Task[None]] = set() + @commands.Cog.listener("on_command") + async def command_started(self, ctx: commands.Context) -> None: + """Remember when a human starts a command in any cog.""" + if ctx.command is not None and not getattr( + ctx.author, "bot", False + ): + self._command_runs[ctx.message.id] = ( + monotonic(), + ctx.author.id, + ) + + @commands.Cog.listener("on_command_completion") + async def command_finished(self, ctx: commands.Context) -> None: + """Ping after long commands outside media workflows.""" + await self._command_result(ctx, failed=False) + + @commands.Cog.listener("on_command_error") + async def command_failed( + self, ctx: commands.Context, error: commands.CommandError + ) -> None: + """Report failure without private exception bodies.""" + del error + await self._command_result(ctx, failed=True) + + async def _command_result( + self, ctx: commands.Context, *, failed: bool + ) -> None: + """Avoid instant and duplicate completion pings.""" + start = self._command_runs.pop(ctx.message.id, None) + if ( + start is None + or ctx.command is None + or monotonic() - start[0] < 10 + ): + return + name = ctx.command.qualified_name + if name.split()[0] in {"watch", "request", "importplaylist"}: + return + result = "ended with an error" if failed else "finished" + await completion_ping( + self.bot, + ctx.channel.id, + ctx.author.id, + f"Command `{name}` {result}.", + send=ctx.send, + ) + + def background(self) -> Jobs: + """Initialize durable jobs during cog upgrades.""" + jobs = getattr(self, "_background", None) + if jobs is None: + jobs = Jobs(self) + self._background = jobs + return jobs + + def _spawn(self, coroutine: Coroutine[Any, Any, None]) -> None: + """Track a background task so unloading cancels it.""" + task = asyncio.create_task(coroutine) + self._pollers.add(task) + task.add_done_callback(self._pollers.discard) + + async def cog_load(self) -> None: + """Resume persisted imports and notifications after startup.""" + self._spawn(self.background().watch_loop()) + async def cog_unload(self) -> None: """Stop polling.""" - for task in self._pollers: + tasks = list(self._pollers) + for task in tasks: task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) async def red_delete_data_for_user( self, *, requester: RequestType, user_id: int ) -> None: """Forget a user's linked Jellyfin name.""" del requester - await self.config.user_from_id(user_id).clear() + if hasattr(self, "_command_runs"): + self._command_runs = { + key: run + for key, run in self._command_runs.items() + if run[1] != user_id + } + self.config.register_global(pending_jobs={}) + async with self.config.pending_jobs() as jobs: + for key in list(jobs): + if jobs[key].get("owner") == user_id: + del jobs[key] + await self.config.user_from_id(user_id).clear() async def _client(self) -> AuthenticatedClient: tokens = await self.bot.get_shared_api_tokens("media_preload") @@ -481,6 +567,9 @@ class Watch(commands.Cog): self, message: discord.Message, request: PreloadRequest, + *, + job_key: str | None = None, + send: Callable[..., Awaitable[Any]] | None = None, ) -> None: """Edit ``message`` with progress until the request finishes.""" waited = 0 @@ -502,6 +591,10 @@ class Watch(commands.Cog): await message.edit( embed=self._embed(request), view=None ) + if job_key and send and is_finished(request): + await self.background().finish_preload( + job_key, request, send + ) async def _start( self, @@ -525,13 +618,26 @@ class Watch(commands.Cog): return await ctx.send(f"Couldn't start that: {exc}") return + job_key = await self.background().register( + ctx, + f"preload:{request.id}", + { + "kind": "preload", + "request_id": request.id, + "title": request.title, + }, + ) message = await ctx.send( embed=self._embed(request), view=None if is_finished(request) else CancelView(self, request.id, ctx.author.id), ) - task = asyncio.create_task(self._follow(message, request)) + task = asyncio.create_task( + self._follow( + message, request, job_key=job_key, send=ctx.send + ) + ) self._pollers.add(task) task.add_done_callback(self._pollers.discard) @@ -643,7 +749,11 @@ class Watch(commands.Cog): method: str | None = None, ) -> Any: # noqa: ANN401 (ARR JSON resources) """Call ARR without exposing private error bodies.""" - service = {"movie": "radarr", "tv": "sonarr"}.get(kind) + service = { + "movie": "radarr", + "tv": "sonarr", + "music": "lidarr", + }.get(kind) if service is None: msg = "Choose movie or TV show." raise PreloadError(msg) @@ -658,11 +768,13 @@ class Watch(commands.Cog): in { "movie/lookup", "series/lookup", + "album/lookup", } ) timeout = httpx.Timeout(30.0, read=60.0 if lookup else 30.0) async with httpx.AsyncClient( - base_url=tokens["url"].rstrip("/") + "/api/v3/", + base_url=tokens["url"].rstrip("/") + + ("/api/v1/" if kind == "music" else "/api/v3/"), headers={"X-Api-Key": tokens["api_key"]}, timeout=timeout, ) as client: @@ -1074,6 +1186,9 @@ class Watch(commands.Cog): title = titles[int(chosen)] existing = await self._existing_title(kind, title) if existing is not None and kind == "movie": + await self._subscribe_request( + ctx, kind, existing, None + ) await ctx.send( await self.acquisition_status( kind, existing @@ -1118,6 +1233,7 @@ class Watch(commands.Cog): if preview else None, ) + await self._subscribe_request(ctx, kind, title, season) await ctx.send( result, allowed_mentions=discord.AllowedMentions.none(), @@ -1125,6 +1241,32 @@ class Watch(commands.Cog): except (PreloadError, PermissionError, SeasonError) as exc: await ctx.send(f"Request not submitted: {exc}") + async def _require_download(self, user: Person) -> None: + """Recheck download permission immediately before submission.""" + if not await self.can_download(user): + message = "Download permission was removed." + raise PermissionError(message) + + async def _subscribe_request( + self, + ctx: commands.Context, + kind: str, + title: dict[str, Any], + season: int | None, + ) -> None: + """Track requested titles and seasons until import.""" + foreign_id = title["tmdbId" if kind == "movie" else "tvdbId"] + data = { + "kind": kind, + "foreign_id": foreign_id, + "title": title["title"], + } + if kind == "tv": + data["season"] = season + await self.background().register( + ctx, f"{kind}:{foreign_id}:{season}", data + ) + @request.command(name="allow") @commands.is_owner() async def request_allow( @@ -1160,6 +1302,173 @@ class Watch(commands.Cog): "Bot owners retain access." ) + @commands.group( + name="importplaylist", + aliases=["spotifyimport"], + invoke_without_command=True, + ) + @commands.cooldown(1, 15, commands.BucketType.user) + async def playlist( + self, ctx: commands.Context, *, url: str = "" + ) -> None: + """Import a public Spotify playlist via Lidarr. + + Link your Jellyfin account first. Download permission matches + owner-managed permission as `request`. Public snapshots may stop + at100songs, in which case the visible subset needs confirmation. + """ + jobs = self.background() + if not await self.can_download(ctx.author): + await ctx.send( + "Download permission is required; ask " + "the owner to use `request allow`." + ) + return + linked = await self.config.user(ctx.author).jellyfin_user() + if not linked: + await ctx.send( + "First link your Jellyfin account with " + "`watch link `." + ) + return + try: + source_id = playlist_id(url) + key = f"{ctx.author.id}:playlist:{source_id}" + previous = (await self.config.pending_jobs()).get(key) + if previous and previous.get("mutation"): + await ctx.send( + "An earlier write needs owner " + "verification before reimporting. " + "Use `importplaylist status`." + ) + return + if previous and not previous.get("notified"): + await ctx.send( + "That playlist import is " + "already running. Use " + "`importplaylist status`." + ) + return + + async def tokens() -> dict[str, str]: + return await self.bot.get_shared_api_tokens( + "jellyfin" + ) + + user_id = await Jellyfin(tokens).user(linked) + async with httpx.AsyncClient() as client: + snapshot = await SpotifyPublic(client).snapshot( + url + ) + name = discord.utils.escape_markdown(snapshot["name"]) + username = discord.utils.escape_markdown( + ctx.author.name + ) + count = len(snapshot["tracks"]) + partial = snapshot["partial"] + warning = ( + ( + f"Spotify exposes only the visible " + f"{count} songs; this playlist may be " + f"incomplete. " + ) + if partial + else "" + ) + option = "visible" if partial else "import" + choice = await self._download_choice( + ctx, + warning + + ( + f"Import **{name}** ({count} songs)? " + f"Missing songs request their albums " + f"in Lidarr. The Jellyfin playlist " + f"will be public and named " + f"**{username} - {name}**." + ), + [ + ( + option, + f"Import visible {count} only" + if partial + else "Import playlist", + ) + ], + ) + if choice != option: + return + await self._require_download(ctx.author) + key = await jobs.register( + ctx, + f"playlist:{source_id}", + { + "kind": "playlist", + "stage": "preparing", + "source_id": source_id, + "name": snapshot["name"], + "tracks": snapshot["tracks"], + "partial": partial, + "user_id": user_id, + }, + ) + await ctx.send( + "Playlist import started. I'll ping " + "you when the songs are in Jellyfin; " + "`importplaylist status` shows " + "progress." + ) + self._spawn(jobs.run_once(key)) + except (PreloadError, ValueError, PermissionError) as exc: + await ctx.send( + f"Playlist import not started: {exc}", + allowed_mentions=discord.AllowedMentions.none(), + ) + + @playlist.command(name="status") + async def playlist_status(self, ctx: commands.Context) -> None: + """Show your imports and songs needing review.""" + self.background() + own = [ + j + for j in (await self.config.pending_jobs()).values() + if j.get("owner") == ctx.author.id + and j.get("kind") == "playlist" + ] + if not own: + await ctx.send("You have no playlist import jobs.") + return + lines = [] + for job in own[-5:]: + name = discord.utils.escape_markdown(job["name"]) + ready = job.get("ready", 0) + count = len(job["tracks"]) + lines.append( + f"**{name}** · {job['stage']} · " + f"{ready}/{count} songs ready" + ) + review = [ + r.get("title", "Unavailable track") + for r in job["tracks"] + if r.get("review") + ] + if review: + lines.append( + "Needs review: " + + ", ".join( + discord.utils.escape_markdown(t) + for t in review[:5] + ) + ) + if job.get("mutation"): + lines.append( + "An earlier write needs owner " + "verification before retrying." + ) + await ctx.send( + "\n".join(lines)[:1900], + allowed_mentions=discord.AllowedMentions.none(), + ) + @watch.command(name="link") async def watch_link(self, ctx: commands.Context, *, name: str) -> None: """Link your Jellyfin user name, for "next" requests."""