mirror of
https://github.com/RustyRaptor/doge_cogs.git
synced 2026-12-03 15:55:21 -07:00
Retain one TV season per user with shared claims and archive protection
This commit is contained in:
1 parent
5e8acbf7d0
commit
64c37b39ec
10 files changed
+1419
-71
No files matched your search
@@ -153,7 +153,7 @@ points to `[p]request <title>` instead of downloading automatically.
|
||||
|
||||
| Command | Purpose |
|
||||
|---|---|
|
||||
| `[p]request Dune` | Choose Movie/TV, a matching catalogue title/year, then 1080p or 4K |
|
||||
| `[p]request Dune` | Choose Movie/TV, title/year, a TV season, then 1080p or 4K |
|
||||
| `[p]request allow @person` | Bot owner: grant an individual download permission |
|
||||
| `[p]request revoke @person` | Bot owner: remove that permission |
|
||||
|
||||
@@ -166,15 +166,15 @@ Each menu belongs to its requester, includes Cancel, and expires after two
|
||||
minutes. Even a single matching title requires explicit selection. Results show
|
||||
title/year (up to24 matches); search again with a year to narrow them. The final
|
||||
quality choice confirms the request. No ARR add/search happens before that step.
|
||||
TV requests include **all regular seasons and future monitored episodes**;
|
||||
specials are excluded. Movie requests use released-only availability. Spanish
|
||||
libraries and music acquisition are outside this command.
|
||||
TV requests select **one regular season per Discord user per show**; specials
|
||||
are excluded. Movie requests use released-only availability. Spanish libraries
|
||||
and music acquisition are outside this command.
|
||||
|
||||
Title lookup uses Radarr/Sonarr's metadata catalogues, rather than exposing raw
|
||||
release/torrent names. ARR subsequently searches its configured indexers under
|
||||
the chosen quality/custom-format profile. Existing ARR titles are not changed,
|
||||
added twice or searched again. Selecting an existing title shows its current ARR
|
||||
status immediately, without asking for another quality choice. A successful
|
||||
the chosen quality/custom-format profile. Existing movies show status without
|
||||
being added or searched again. TV choices update shared season retention as
|
||||
described below. A successful
|
||||
request means ARR accepted it, not that a matching release was found or imported.
|
||||
The existing RDTC download/import/NFO/Jellyfin integration handles subsequent work.
|
||||
|
||||
@@ -188,6 +188,60 @@ profile/root stops the request instead of silently selecting another one.
|
||||
Raw ARR errors/headers are not sent to Discord. No new service or API endpoint
|
||||
is required.
|
||||
|
||||
### Shared TV season retention
|
||||
|
||||
TV requests now follow **TV → title → season → quality/confirmation**. The
|
||||
season menu supports long-running shows through pagination. Each person has one
|
||||
selected season per show, shared across Discord servers. The stored selection
|
||||
uses the Discord user ID and TVDB ID, not a changeable user/title name.
|
||||
|
||||
- If Alice chooses season1 and Bob chooses season2, both seasons are retained.
|
||||
- If Alice switches to season3, season1 is removed only if nobody else still
|
||||
selects it; Bob's season2 remains.
|
||||
- If both choose season1 and Alice switches to season2, season1 stays for Bob.
|
||||
- Requesting an already-downloaded/downloading season records the person's
|
||||
selection without starting a duplicate download. `watch` does not claim it.
|
||||
|
||||
**The user decides when to switch.** Jellyfin watched/completion status is not
|
||||
consulted. The final confirmation lists the seasons that would be deleted.
|
||||
To keep a season while somebody else switches, request that season once so the
|
||||
bot records your selection. Existing partial shows have no historical per-user
|
||||
claims; their unclaimed seasons can be removed when an authorized user confirms
|
||||
a new season request. Deployment does not perform a bulk cleanup.
|
||||
|
||||
**Complete existing shows are exempt.** The first adoption snapshot records
|
||||
Sonarr shows with every aired regular episode present. That protected TVDB list
|
||||
is frozen; completing a new on-demand show later does not automatically turn it
|
||||
into a permanent archive. Protected shows keep all their existing files and
|
||||
monitoring. Untracked legacy files outside Sonarr are never deleted by this code.
|
||||
|
||||
For other shows, Sonarr monitors only the union of users' requested seasons and
|
||||
sets `monitorNewItems=none`; it cannot automatically fetch later seasons. Future
|
||||
episodes of an explicitly selected ongoing season remain monitored. TV quality
|
||||
profiles apply to the entire show, which the confirmation states.
|
||||
|
||||
A switch first unmonitors released seasons, preserving other users' selections.
|
||||
The actor's new season is activated only after cleanup succeeds. Old unclaimed
|
||||
downloads are cancelled without blocklisting, and episode files are deleted
|
||||
through Sonarr's scoped API using freshly resolved file IDs. Multi-season packs
|
||||
needed by another person are not cancelled; ambiguous cases stop for review.
|
||||
Imports racing a switch are re-read before cleanup/search. Newly added shows use
|
||||
post-add `monitor=skip` so Sonarr's initial scan cannot overwrite the selection.
|
||||
Only `SeasonSearch` for the chosen season is submitted, never a whole-show search.
|
||||
|
||||
Permission is rechecked before every Sonarr mutation. Expanded/stale deletion
|
||||
previews stop rather than silently deleting additional seasons. If cleanup fails,
|
||||
the saved choice remains for retry, the new season stays paused, and no new
|
||||
season search starts. If the bot restarts mid-switch, repeat the same request to
|
||||
reconcile it. File removal follows Sonarr's normal deletion settings; the current
|
||||
instance has no recycle bin configured. A missing/revoked download grant prevents
|
||||
further mutations. Revoking access does not automatically erase retained choices.
|
||||
|
||||
Choices live in Red Config `Watch` user field `tv_seasons`; the archive baseline
|
||||
is global `season_retention_baseline`. Red user-data deletion clears that user's
|
||||
choices without deleting shared media immediately. No periodic watched-status
|
||||
job or extra service/API endpoint is involved.
|
||||
|
||||
### In-progress download status
|
||||
|
||||
When `watch` cannot find playable library media, it checks existing English
|
||||
@@ -196,10 +250,11 @@ preload fails (for example, a series is in Jellyfin but its requested episode
|
||||
has not finished downloading). This is read-only and works for users without
|
||||
download permission. Existing playable media keeps the normal preload behavior.
|
||||
|
||||
`request` shows an existing title's status after title selection, skipping the
|
||||
quality step. New-title download permissions are unchanged. Neither path starts
|
||||
a second download, triggers a release search, or changes a quality profile
|
||||
simply to check status.
|
||||
`request` shows an existing movie's status after title selection, skipping the
|
||||
quality step. For TV it records a season choice, then includes download progress
|
||||
in the response. `watch` remains a read-only progress/preload command; use it
|
||||
when you want status without changing your season choice. Download permissions
|
||||
remain owner-controlled.
|
||||
|
||||
Status is a snapshot of ARR's queue, with percentage and ETA when available.
|
||||
Paused, queued, needs-attention and downloaded/importing states are shown
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
"""Stateful Sonarr HTTP edge for season ownership and file deletion tests."""
|
||||
|
||||
import inspect
|
||||
from collections.abc import Awaitable, Callable
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from aiohttp import web
|
||||
|
||||
|
||||
def series_resource(series_id: int = 7, tvdb: int = 123) -> dict[str, Any]:
|
||||
"""Build one series with three regular seasons and specials."""
|
||||
return {
|
||||
"id": series_id,
|
||||
"tvdbId": tvdb,
|
||||
"title": "Dune",
|
||||
"year": 2021,
|
||||
"titleSlug": "dune",
|
||||
"qualityProfileId": 1,
|
||||
"path": "/arr/library/TV/Dune",
|
||||
"monitored": True,
|
||||
"monitorNewItems": "all",
|
||||
"seasonFolder": True,
|
||||
"seasons": [
|
||||
{"seasonNumber": n, "monitored": True} for n in range(4)
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def episode_resource(season: int, *, has_file: bool = True) -> dict[str, Any]:
|
||||
"""Build an aired episode, with an associated file if downloaded."""
|
||||
return {
|
||||
"id": 700 + season,
|
||||
"seriesId": 7,
|
||||
"seasonNumber": season,
|
||||
"episodeNumber": 1,
|
||||
"airDateUtc": "2020-01-01T00:00:00Z",
|
||||
"hasFile": has_file,
|
||||
"episodeFileId": 100 + season if has_file else 0,
|
||||
}
|
||||
|
||||
|
||||
@dataclass
|
||||
class FakeSonarr:
|
||||
"""Keep API resources mutable between requests."""
|
||||
|
||||
series: list[dict[str, Any]] = field(default_factory=list)
|
||||
episodes: list[dict[str, Any]] = field(default_factory=list)
|
||||
files: list[dict[str, Any]] = field(default_factory=list)
|
||||
queue: list[dict[str, Any]] = field(default_factory=list)
|
||||
calls: list[Any] = field(default_factory=list)
|
||||
fail: str = ""
|
||||
add_monitor: str = ""
|
||||
after_write: Callable[[str, str], Awaitable[None] | None] | None = None
|
||||
|
||||
async def handle(self, request: web.Request) -> web.Response:
|
||||
"""Route authenticated requests to this fake server."""
|
||||
body = await request.json() if request.can_read_body else None
|
||||
path = request.path.removeprefix("/api/v3/")
|
||||
self.calls.append(
|
||||
(request.method, path, dict(request.query), body)
|
||||
)
|
||||
if request.headers.get("X-Api-Key") != "test-key":
|
||||
return web.json_response({}, status=401)
|
||||
if self.fail == request.method + " " + path:
|
||||
return web.json_response(
|
||||
{"error": "private-details"}, status=503
|
||||
)
|
||||
if request.method == "GET":
|
||||
return self.read(path, request.query)
|
||||
response = self.write(request.method, path, body)
|
||||
if self.after_write:
|
||||
result = self.after_write(request.method, path)
|
||||
if inspect.isawaitable(result):
|
||||
await result
|
||||
return response
|
||||
|
||||
def read(self, path: str, params: Any) -> web.Response: # noqa: ANN401
|
||||
"""Return real-shaped Sonarr resources."""
|
||||
if path == "series/lookup":
|
||||
return web.json_response([series_resource()])
|
||||
if path == "series":
|
||||
return web.json_response(self.series)
|
||||
if path.startswith("series/"):
|
||||
return web.json_response(
|
||||
next(
|
||||
s
|
||||
for s in self.series
|
||||
if s["id"] == int(path.split("/")[1])
|
||||
)
|
||||
)
|
||||
if path in {"episode", "episodefile", "queue/details"}:
|
||||
values = {
|
||||
"episode": self.episodes,
|
||||
"episodefile": self.files,
|
||||
"queue/details": self.queue,
|
||||
}[path]
|
||||
return web.json_response(
|
||||
[
|
||||
r
|
||||
for r in values
|
||||
if r.get("seriesId")
|
||||
== int(params.get("seriesId", 7))
|
||||
]
|
||||
)
|
||||
values = {
|
||||
"qualityprofile": [
|
||||
{"id": 1, "name": "Doge - 1080p default"},
|
||||
{"id": 3, "name": "Doge - 4K optional"},
|
||||
],
|
||||
"rootfolder": [
|
||||
{"path": "/arr/library/TV", "accessible": True}
|
||||
],
|
||||
}
|
||||
return web.json_response(values.get(path, []))
|
||||
|
||||
def write(self, method: str, path: str, body: Any) -> web.Response: # noqa: ANN401
|
||||
"""Apply series changes and scoped file/queue removals."""
|
||||
if method == "POST" and path == "series":
|
||||
created = {**body, "id": 7}
|
||||
self.series.append(created)
|
||||
self.add_monitor = body["addOptions"]["monitor"]
|
||||
self.episodes = [
|
||||
episode_resource(n, has_file=False)
|
||||
for n in [1, 2, 3]
|
||||
]
|
||||
return web.json_response(created, status=201)
|
||||
if method == "PUT" and path.startswith("series/"):
|
||||
self.series[:] = [
|
||||
body if s["id"] == body["id"] else s
|
||||
for s in self.series
|
||||
]
|
||||
return web.json_response(body)
|
||||
if method == "DELETE" and path == "episodefile/bulk":
|
||||
ids = set(body["episodeFileIds"])
|
||||
self.files[:] = [
|
||||
f for f in self.files if f["id"] not in ids
|
||||
]
|
||||
for episode in self.episodes:
|
||||
if episode["episodeFileId"] in ids:
|
||||
episode.update(
|
||||
hasFile=False, episodeFileId=0
|
||||
)
|
||||
return web.Response(status=204)
|
||||
if method == "DELETE" and path.startswith("queue/"):
|
||||
row = next(
|
||||
q
|
||||
for q in self.queue
|
||||
if q["id"] == int(path.split("/")[1])
|
||||
)
|
||||
self.queue[:] = [
|
||||
q
|
||||
for q in self.queue
|
||||
if q["downloadId"] != row["downloadId"]
|
||||
]
|
||||
return web.Response(status=204)
|
||||
if method == "POST" and path == "command":
|
||||
return web.json_response({"id": 88, **body}, status=201)
|
||||
return web.json_response(
|
||||
{"error": "unexpected write"}, status=400
|
||||
)
|
||||
|
||||
def finish_initial_scan(self) -> None:
|
||||
"""Model Sonarr's documented post-add monitor processing."""
|
||||
if self.add_monitor == "none":
|
||||
for series in self.series:
|
||||
for season in series["seasons"]:
|
||||
season["monitored"] = False
|
||||
@@ -103,7 +103,7 @@ async def acquisition( # noqa: C901 (HTTP fixture edge)
|
||||
},
|
||||
]
|
||||
)
|
||||
if path == "movie":
|
||||
if path == "movie" and request.method == "GET":
|
||||
return web.json_response(
|
||||
[
|
||||
t
|
||||
@@ -111,7 +111,7 @@ async def acquisition( # noqa: C901 (HTTP fixture edge)
|
||||
if t.get("tmdbId")
|
||||
]
|
||||
)
|
||||
if path == "series":
|
||||
if path == "series" and request.method == "GET":
|
||||
return web.json_response(
|
||||
[
|
||||
t
|
||||
@@ -119,6 +119,12 @@ async def acquisition( # noqa: C901 (HTTP fixture edge)
|
||||
if t.get("tvdbId")
|
||||
]
|
||||
)
|
||||
if path in {"episode", "episodefile"}:
|
||||
return web.json_response([])
|
||||
if path == "series" and request.method == "POST":
|
||||
created = {**(body or {}), "id": 7}
|
||||
state["existing"].append(created)
|
||||
return web.json_response(created, status=201)
|
||||
if request.method == "GET":
|
||||
return web.json_response(state["existing"])
|
||||
return web.json_response({**(body or {}), "id": 7}, status=201)
|
||||
@@ -198,7 +204,11 @@ async def test_selected_profile_and_type_reach_arr(
|
||||
assert results[0]["title"] == "Dune"
|
||||
assert all(method == "GET" for method, *_ in calls)
|
||||
await cog.acquire(
|
||||
cast("Any", FakeAuthor(id=99)), kind, results[0], quality
|
||||
cast("Any", FakeAuthor(id=99)),
|
||||
kind,
|
||||
results[0],
|
||||
quality,
|
||||
season=1 if kind == "tv" else None,
|
||||
)
|
||||
added = [
|
||||
body
|
||||
@@ -208,20 +218,20 @@ async def test_selected_profile_and_type_reach_arr(
|
||||
assert len(added) == 1
|
||||
assert added[0]["qualityProfileId"] == profile
|
||||
assert added[0]["rootFolderPath"] == root
|
||||
assert added[0]["monitored"] is True
|
||||
assert added[0]["monitored"] is (kind == "movie")
|
||||
if kind == "movie":
|
||||
assert added[0]["tmdbId"] == 438631
|
||||
assert added[0]["addOptions"]["searchForMovie"] is True
|
||||
else:
|
||||
assert added[0]["tvdbId"] == 123
|
||||
assert added[0]["monitorNewItems"] == "all"
|
||||
assert added[0]["monitorNewItems"] == "none"
|
||||
assert added[0]["seasons"] == [
|
||||
{"seasonNumber": 0, "monitored": False},
|
||||
{"seasonNumber": 1, "monitored": True},
|
||||
{"seasonNumber": 1, "monitored": False},
|
||||
]
|
||||
assert (
|
||||
added[0]["addOptions"]["searchForMissingEpisodes"]
|
||||
is True
|
||||
is False
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,469 @@
|
||||
"""Test per-user TV seasons, sharing and archive protection."""
|
||||
|
||||
from collections.abc import AsyncIterator
|
||||
from typing import Any, cast
|
||||
|
||||
import pytest
|
||||
from aiohttp import web
|
||||
from aiohttp.test_utils import TestServer
|
||||
from redbot.core import Config
|
||||
from season_helpers import FakeSonarr, episode_resource, series_resource
|
||||
from test_acquisition import RequestBot, WizardContext
|
||||
from watch_helpers import FakeAuthor
|
||||
|
||||
from watch.watch import Watch
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def seasons(
|
||||
config: Config, monkeypatch: pytest.MonkeyPatch
|
||||
) -> AsyncIterator[tuple[Watch, FakeSonarr]]:
|
||||
"""Use real Config and client HTTP with a stateful Sonarr edge."""
|
||||
fake = FakeSonarr()
|
||||
app = web.Application()
|
||||
app.router.add_route("*", "/api/v3/{path:.*}", fake.handle)
|
||||
server = TestServer(app)
|
||||
await server.start_server()
|
||||
bot = RequestBot()
|
||||
bot.url = str(server.make_url("/")).rstrip("/")
|
||||
monkeypatch.setattr(Config, "get_conf", lambda *_a, **_k: config)
|
||||
cog = Watch(cast("Any", bot))
|
||||
# Most tests isolate transitions after the immutable baseline exists.
|
||||
await config.season_retention_baseline.set({"protected": []})
|
||||
try:
|
||||
yield cog, fake
|
||||
finally:
|
||||
await server.close()
|
||||
|
||||
|
||||
async def claim(cog: Watch, user_id: int, season: int) -> None:
|
||||
"""Create a prior explicit season choice in Red's user data."""
|
||||
await cog.config.user_from_id(user_id).tv_seasons.set({"123": season})
|
||||
|
||||
|
||||
def existing_seasons(fake: FakeSonarr, numbers: list[int]) -> None:
|
||||
"""Populate files and all three seasons' episode metadata."""
|
||||
fake.series = [series_resource()]
|
||||
fake.episodes = [
|
||||
episode_resource(n, has_file=n in numbers) for n in [1, 2, 3]
|
||||
]
|
||||
fake.files = [
|
||||
{"id": 100 + n, "seriesId": 7, "seasonNumber": n}
|
||||
for n in numbers
|
||||
]
|
||||
|
||||
|
||||
async def acquire_season(
|
||||
cog: Watch,
|
||||
season: int,
|
||||
*,
|
||||
user: int = 99,
|
||||
expected: set[int] | None = None,
|
||||
) -> str:
|
||||
"""Invoke the real acquisition entry point with an explicit season."""
|
||||
return await cog.acquire(
|
||||
cast("Any", FakeAuthor(id=user)),
|
||||
"tv",
|
||||
series_resource(),
|
||||
"1080p",
|
||||
season=season,
|
||||
expected_delete=expected,
|
||||
)
|
||||
|
||||
|
||||
async def test_new_show_monitors_and_searches_only_selected_season(
|
||||
seasons: tuple[Watch, FakeSonarr],
|
||||
) -> None:
|
||||
"""Request only season two, not all or future seasons."""
|
||||
cog, fake = seasons
|
||||
await acquire_season(cog, 2)
|
||||
assert fake.series[0]["monitorNewItems"] == "none"
|
||||
assert [
|
||||
(s["seasonNumber"], s["monitored"])
|
||||
for s in fake.series[0]["seasons"]
|
||||
] == [(0, False), (1, False), (2, True), (3, False)]
|
||||
commands = [
|
||||
b for m, p, _, b in fake.calls if m == "POST" and p == "command"
|
||||
]
|
||||
assert commands == [
|
||||
{"name": "SeasonSearch", "seriesId": 7, "seasonNumber": 2}
|
||||
]
|
||||
added = next(
|
||||
b for m, p, _, b in fake.calls if m == "POST" and p == "series"
|
||||
)
|
||||
assert added["addOptions"]["searchForMissingEpisodes"] is False
|
||||
assert await cog.config.user_from_id(99).tv_seasons() == {"123": 2}
|
||||
|
||||
|
||||
async def test_switch_deletes_unclaimed_old_season_without_watched_checks(
|
||||
seasons: tuple[Watch, FakeSonarr],
|
||||
) -> None:
|
||||
"""Release the old season when the user chooses another."""
|
||||
cog, fake = seasons
|
||||
existing_seasons(fake, [1])
|
||||
await claim(cog, 99, 1)
|
||||
await acquire_season(cog, 2, expected={1})
|
||||
assert fake.files == []
|
||||
assert await cog.config.user_from_id(99).tv_seasons() == {"123": 2}
|
||||
deleted = [
|
||||
b
|
||||
for m, p, _, b in fake.calls
|
||||
if m == "DELETE" and p == "episodefile/bulk"
|
||||
]
|
||||
assert deleted == [{"episodeFileIds": [101]}]
|
||||
assert [m for m, p, _, _ in fake.calls if p == "episodefile/bulk"] == [
|
||||
"DELETE"
|
||||
]
|
||||
|
||||
|
||||
async def test_another_person_keeps_their_season(
|
||||
seasons: tuple[Watch, FakeSonarr],
|
||||
) -> None:
|
||||
"""Keep season one while another user still requests it."""
|
||||
cog, fake = seasons
|
||||
existing_seasons(fake, [1])
|
||||
await claim(cog, 99, 1)
|
||||
await claim(cog, 88, 1)
|
||||
await acquire_season(cog, 2, expected=set())
|
||||
assert [f["id"] for f in fake.files] == [101]
|
||||
assert [
|
||||
s["seasonNumber"]
|
||||
for s in fake.series[0]["seasons"]
|
||||
if s["monitored"]
|
||||
] == [1, 2]
|
||||
assert await cog.config.user_from_id(88).tv_seasons() == {"123": 1}
|
||||
|
||||
|
||||
async def test_different_users_keep_two_different_seasons(
|
||||
seasons: tuple[Watch, FakeSonarr],
|
||||
) -> None:
|
||||
"""Per-user limits do not become a single global season per show."""
|
||||
cog, fake = seasons
|
||||
existing_seasons(fake, [1, 2])
|
||||
await claim(cog, 99, 1)
|
||||
await claim(cog, 88, 2)
|
||||
await acquire_season(cog, 3, expected={1})
|
||||
assert [f["id"] for f in fake.files] == [102]
|
||||
assert [
|
||||
s["seasonNumber"]
|
||||
for s in fake.series[0]["seasons"]
|
||||
if s["monitored"]
|
||||
] == [2, 3]
|
||||
|
||||
|
||||
async def test_fully_downloaded_archive_is_never_pruned(
|
||||
seasons: tuple[Watch, FakeSonarr],
|
||||
) -> None:
|
||||
"""Retain the protected show's seasons and monitoring."""
|
||||
cog, fake = seasons
|
||||
existing_seasons(fake, [1, 2, 3])
|
||||
await cog.config.season_retention_baseline.set({"protected": [123]})
|
||||
await acquire_season(cog, 2, expected=set())
|
||||
assert [f["id"] for f in fake.files] == [101, 102, 103]
|
||||
assert not any(m == "DELETE" for m, *_ in fake.calls)
|
||||
|
||||
|
||||
async def test_season_wizard_previews_the_season_removed(
|
||||
seasons: tuple[Watch, FakeSonarr],
|
||||
) -> None:
|
||||
"""Preview deletion after season choice, before quality."""
|
||||
cog, fake = seasons
|
||||
existing_seasons(fake, [1])
|
||||
await claim(cog, 99, 1)
|
||||
ctx = WizardContext(["tv", "0", "2", "1080p"], author=FakeAuthor(id=99))
|
||||
await Watch.request.callback(cog, ctx, query="Dune")
|
||||
assert len(ctx.views) == 4
|
||||
assert "season" in ctx.texts[2].lower()
|
||||
assert "season 1" in ctx.texts[3].lower()
|
||||
assert "delete" in ctx.texts[3].lower()
|
||||
assert fake.files == []
|
||||
|
||||
|
||||
async def test_cancel_season_picker_is_read_only(
|
||||
seasons: tuple[Watch, FakeSonarr],
|
||||
) -> None:
|
||||
"""Cancel without changing claims or deleting files."""
|
||||
cog, fake = seasons
|
||||
existing_seasons(fake, [1])
|
||||
await claim(cog, 99, 1)
|
||||
ctx = WizardContext(["tv", "0", "cancel"], author=FakeAuthor(id=99))
|
||||
await Watch.request.callback(cog, ctx, query="Dune")
|
||||
assert all(m == "GET" for m, *_ in fake.calls)
|
||||
assert len(ctx.views) == 3
|
||||
assert await cog.config.user_from_id(99).tv_seasons() == {"123": 1}
|
||||
|
||||
|
||||
async def test_stale_preview_cannot_delete_unannounced_seasons(
|
||||
seasons: tuple[Watch, FakeSonarr],
|
||||
) -> None:
|
||||
"""Reject an expanded deletion without a new preview."""
|
||||
cog, fake = seasons
|
||||
existing_seasons(fake, [1, 2])
|
||||
await claim(cog, 99, 1)
|
||||
with pytest.raises(Exception, match="changed"):
|
||||
await acquire_season(cog, 3, expected={1})
|
||||
assert all(m == "GET" for m, *_ in fake.calls)
|
||||
assert [f["id"] for f in fake.files] == [101, 102]
|
||||
|
||||
|
||||
async def test_delete_failure_never_starts_next_season_search(
|
||||
seasons: tuple[Watch, FakeSonarr],
|
||||
) -> None:
|
||||
"""Do not search the next season after deletion fails."""
|
||||
cog, fake = seasons
|
||||
existing_seasons(fake, [1])
|
||||
await claim(cog, 99, 1)
|
||||
fake.fail = "DELETE episodefile/bulk"
|
||||
from watch.seasonal import SeasonError
|
||||
|
||||
with pytest.raises(SeasonError, match="saved.*incomplete"):
|
||||
await acquire_season(cog, 2, expected={1})
|
||||
assert [f["id"] for f in fake.files] == [101]
|
||||
assert not next(
|
||||
s for s in fake.series[0]["seasons"] if s["seasonNumber"] == 2
|
||||
)["monitored"]
|
||||
assert not any(
|
||||
m == "POST" and p == "command" for m, p, *_ in fake.calls
|
||||
)
|
||||
|
||||
|
||||
async def test_current_requested_season_is_shared_without_second_search(
|
||||
seasons: tuple[Watch, FakeSonarr],
|
||||
) -> None:
|
||||
"""Share an existing season without regrabbing it."""
|
||||
cog, fake = seasons
|
||||
existing_seasons(fake, [2])
|
||||
await claim(cog, 88, 2)
|
||||
reply = await acquire_season(cog, 2, expected=set())
|
||||
assert "already downloaded" in reply.lower()
|
||||
assert [f["id"] for f in fake.files] == [102]
|
||||
assert not any(
|
||||
m == "POST" and p == "command" for m, p, *_ in fake.calls
|
||||
)
|
||||
assert await cog.config.user_from_id(99).tv_seasons() == {"123": 2}
|
||||
|
||||
|
||||
async def test_complete_archive_snapshot_is_immutable(
|
||||
seasons: tuple[Watch, FakeSonarr],
|
||||
) -> None:
|
||||
"""Protect only shows complete at adoption."""
|
||||
from watch.seasonal import SeasonManager
|
||||
|
||||
cog, fake = seasons
|
||||
existing_seasons(fake, [1, 2, 3])
|
||||
other = series_resource(8, 456)
|
||||
fake.series.append(other)
|
||||
fake.episodes.extend(
|
||||
[
|
||||
{**episode_resource(n, has_file=n == 1), "seriesId": 8}
|
||||
for n in [1, 2, 3]
|
||||
]
|
||||
)
|
||||
await cog.config.season_retention_baseline.set(None)
|
||||
manager = SeasonManager(cog)
|
||||
baseline = await manager.initialize()
|
||||
assert baseline["protected"] == [123]
|
||||
fake.episodes[:] = []
|
||||
count = len(fake.calls)
|
||||
assert await manager.initialize() == baseline
|
||||
assert len(fake.calls) == count
|
||||
assert all(m == "GET" for m, *_ in fake.calls)
|
||||
|
||||
|
||||
async def test_unused_download_is_cancelled_before_new_season_search(
|
||||
seasons: tuple[Watch, FakeSonarr],
|
||||
) -> None:
|
||||
"""Cancel old downloads before searching the new season."""
|
||||
cog, fake = seasons
|
||||
existing_seasons(fake, [1])
|
||||
await claim(cog, 99, 1)
|
||||
fake.queue = [
|
||||
{
|
||||
"id": 50,
|
||||
"seriesId": 7,
|
||||
"seasonNumber": 1,
|
||||
"downloadId": "old",
|
||||
}
|
||||
]
|
||||
await acquire_season(cog, 2, expected={1})
|
||||
assert fake.queue == []
|
||||
writes = [(m, p) for m, p, *_ in fake.calls if m != "GET"]
|
||||
assert (
|
||||
writes.index(("DELETE", "queue/50"))
|
||||
< writes.index(("DELETE", "episodefile/bulk"))
|
||||
< writes.index(("POST", "command"))
|
||||
)
|
||||
params = next(
|
||||
q
|
||||
for m, p, q, _ in fake.calls
|
||||
if m == "DELETE" and p == "queue/50"
|
||||
)
|
||||
assert params == {
|
||||
"removeFromClient": "true",
|
||||
"blocklist": "false",
|
||||
"skipRedownload": "true",
|
||||
}
|
||||
|
||||
|
||||
async def test_cannot_cancel_pack_needed_by_another_user(
|
||||
seasons: tuple[Watch, FakeSonarr],
|
||||
) -> None:
|
||||
"""Refuse to cancel a pack serving another user."""
|
||||
from watch.seasonal import SeasonError
|
||||
|
||||
cog, fake = seasons
|
||||
existing_seasons(fake, [1, 2])
|
||||
await claim(cog, 99, 1)
|
||||
await claim(cog, 88, 2)
|
||||
fake.queue = [
|
||||
{
|
||||
"id": 50,
|
||||
"seriesId": 7,
|
||||
"seasonNumber": 1,
|
||||
"downloadId": "shared",
|
||||
},
|
||||
{
|
||||
"id": 51,
|
||||
"seriesId": 7,
|
||||
"seasonNumber": 2,
|
||||
"downloadId": "shared",
|
||||
},
|
||||
]
|
||||
with pytest.raises(SeasonError, match="shared season pack"):
|
||||
await acquire_season(cog, 3, expected={1})
|
||||
assert all(m == "GET" for m, *_ in fake.calls)
|
||||
assert [f["id"] for f in fake.files] == [101, 102]
|
||||
|
||||
|
||||
async def test_season_picker_supports_long_running_shows(
|
||||
seasons: tuple[Watch, FakeSonarr],
|
||||
) -> None:
|
||||
"""Offer season thirty through pagination."""
|
||||
cog, fake = seasons
|
||||
title = series_resource()
|
||||
title["seasons"] = [{"seasonNumber": n} for n in range(31)]
|
||||
ctx = WizardContext(["next", "30"])
|
||||
chosen = await cog._choose_requested_season(cast("Any", ctx), title)
|
||||
assert chosen == 30
|
||||
assert all(len(view.children[0].options) <= 25 for view in ctx.views)
|
||||
assert fake.calls == []
|
||||
|
||||
|
||||
async def test_user_without_permission_cannot_switch_seasons(
|
||||
seasons: tuple[Watch, FakeSonarr],
|
||||
) -> None:
|
||||
"""Refuse unauthorized deletion and claim changes."""
|
||||
cog, fake = seasons
|
||||
existing_seasons(fake, [1])
|
||||
with pytest.raises(PermissionError):
|
||||
await acquire_season(cog, 2, user=1)
|
||||
assert fake.calls == []
|
||||
assert [f["id"] for f in fake.files] == [101]
|
||||
|
||||
|
||||
async def test_late_old_season_import_is_removed_before_next_search(
|
||||
seasons: tuple[Watch, FakeSonarr],
|
||||
) -> None:
|
||||
"""Clean up an old-season import racing this request."""
|
||||
cog, fake = seasons
|
||||
existing_seasons(fake, [1])
|
||||
await claim(cog, 99, 1)
|
||||
|
||||
imported_once = False
|
||||
|
||||
def imported(method: str, path: str) -> None:
|
||||
nonlocal imported_once
|
||||
if method == "PUT" and path == "series/7" and not imported_once:
|
||||
imported_once = True
|
||||
fake.files.append(
|
||||
{"id": 111, "seriesId": 7, "seasonNumber": 1}
|
||||
)
|
||||
fake.episodes.append(
|
||||
{
|
||||
**episode_resource(1),
|
||||
"id": 711,
|
||||
"episodeNumber": 2,
|
||||
"episodeFileId": 111,
|
||||
}
|
||||
)
|
||||
|
||||
fake.after_write = imported
|
||||
await acquire_season(cog, 2, expected={1})
|
||||
assert fake.files == []
|
||||
|
||||
|
||||
async def test_post_add_scan_preserves_selected_season_monitoring(
|
||||
seasons: tuple[Watch, FakeSonarr],
|
||||
) -> None:
|
||||
"""Delayed Sonarr add processing must not undo the chosen season."""
|
||||
cog, fake = seasons
|
||||
await acquire_season(cog, 2)
|
||||
fake.finish_initial_scan()
|
||||
assert [
|
||||
s["seasonNumber"]
|
||||
for s in fake.series[0]["seasons"]
|
||||
if s["monitored"]
|
||||
] == [2]
|
||||
|
||||
|
||||
async def test_season_claim_still_reports_existing_download_progress(
|
||||
seasons: tuple[Watch, FakeSonarr],
|
||||
) -> None:
|
||||
"""Preserve download progress after recording a season choice."""
|
||||
cog, fake = seasons
|
||||
existing_seasons(fake, [])
|
||||
fake.queue = [
|
||||
{
|
||||
"id": 50,
|
||||
"seriesId": 7,
|
||||
"seasonNumber": 2,
|
||||
"downloadId": "shared",
|
||||
"size": 1000,
|
||||
"sizeleft": 250,
|
||||
"status": "downloading",
|
||||
}
|
||||
]
|
||||
await claim(cog, 88, 2)
|
||||
reply = await acquire_season(cog, 2, expected=set())
|
||||
assert "75%" in reply
|
||||
assert await cog.config.user_from_id(99).tv_seasons() == {"123": 2}
|
||||
assert not any(
|
||||
m == "POST" and p == "command" for m, p, *_ in fake.calls
|
||||
)
|
||||
|
||||
|
||||
async def test_revoked_permission_blocks_deletion_mid_switch(
|
||||
seasons: tuple[Watch, FakeSonarr],
|
||||
) -> None:
|
||||
"""Recheck permission after the preceding Sonarr mutation."""
|
||||
cog, fake = seasons
|
||||
existing_seasons(fake, [1])
|
||||
await claim(cog, 1, 1)
|
||||
await cog.config.user_from_id(1).download_allowed.set(True)
|
||||
|
||||
async def revoked(method: str, _path: str) -> None:
|
||||
if method == "PUT":
|
||||
await cog.config.user_from_id(
|
||||
1
|
||||
).download_allowed.clear()
|
||||
|
||||
fake.after_write = revoked
|
||||
with pytest.raises(PermissionError):
|
||||
await acquire_season(cog, 2, user=1, expected={1})
|
||||
assert [f["id"] for f in fake.files] == [101]
|
||||
assert not any(
|
||||
m == "DELETE" or p == "command" for m, p, *_ in fake.calls
|
||||
)
|
||||
|
||||
|
||||
async def test_user_data_deletion_forgets_claims_without_deleting_media(
|
||||
seasons: tuple[Watch, FakeSonarr],
|
||||
) -> None:
|
||||
"""A privacy request clears choices, not the shared library itself."""
|
||||
cog, fake = seasons
|
||||
existing_seasons(fake, [1])
|
||||
await claim(cog, 1, 1)
|
||||
await cog.red_delete_data_for_user(requester="user", user_id=1)
|
||||
assert await cog.config.user_from_id(1).tv_seasons() == {}
|
||||
assert [f["id"] for f in fake.files] == [101]
|
||||
assert fake.calls == []
|
||||
+3
-2
@@ -7,8 +7,9 @@ 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 per user. `watch unlink` deletes the name; Red user-data "
|
||||
"deletion removes both."
|
||||
"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."
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
"""Shared sanitized errors for media service and season requests."""
|
||||
|
||||
|
||||
class PreloadError(Exception):
|
||||
"""A media service refused or failed a call."""
|
||||
|
||||
|
||||
class SeasonError(ValueError):
|
||||
"""A season change cannot proceed under the selected retention plan."""
|
||||
+2
-2
@@ -4,9 +4,9 @@
|
||||
],
|
||||
"name": "Watch",
|
||||
"short": "Preload library media or request a movie/TV download.",
|
||||
"description": "Preload existing library media, or request English movie/TV downloads through ARR with title/quality selection and owner-managed individual permissions.",
|
||||
"description": "Preload library media or request English movie/TV downloads with owner-managed permissions, shared per-user season retention, and download progress.",
|
||||
"install_msg": "Set the API token with the PRELOAD_BOT_TOKEN environment variable or `[p]set api media_preload token,<token>` (and url,<url> if it isn't http://host.containers.internal:8125).",
|
||||
"end_user_data_statement": "Stores a linked Jellyfin name and an owner-managed per-user download permission. watch unlink removes the name; Red user-data deletion removes both.",
|
||||
"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.",
|
||||
"requirements": [
|
||||
"media-preload-client @ git+https://github.com/RustyRaptor/doge_cogs.git#subdirectory=clients/media-preload-client"
|
||||
],
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Plan retained seasons independently of watched status."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SeasonPlan:
|
||||
"""Keep shared choices and release unclaimed seasons."""
|
||||
|
||||
keep: frozenset[int]
|
||||
remove: frozenset[int]
|
||||
protected: bool
|
||||
shared: frozenset[int]
|
||||
|
||||
|
||||
def plan_seasons(
|
||||
users: dict[int, dict[str, Any]],
|
||||
tvdb: int,
|
||||
actor: int,
|
||||
selected: int,
|
||||
present: set[int],
|
||||
*,
|
||||
protected: bool,
|
||||
) -> SeasonPlan:
|
||||
"""Replace the actor's choice without dropping anyone else's season."""
|
||||
keep = {selected}
|
||||
shared: set[int] = set()
|
||||
for user_id, data in users.items():
|
||||
if int(user_id) == actor:
|
||||
continue
|
||||
number = (data.get("tv_seasons") or {}).get(str(tvdb))
|
||||
if isinstance(number, int) and number > 0:
|
||||
keep.add(number)
|
||||
shared.add(number)
|
||||
remove = set() if protected else present - keep - {0}
|
||||
return SeasonPlan(
|
||||
frozenset(keep), frozenset(remove), protected, frozenset(shared)
|
||||
)
|
||||
|
||||
|
||||
def complete_archive(episodes: list[dict[str, Any]], now: datetime) -> bool:
|
||||
"""Protect shows complete at snapshot time."""
|
||||
aired = []
|
||||
for episode in episodes:
|
||||
if episode.get("seasonNumber", 0) <= 0:
|
||||
continue
|
||||
value = episode.get("airDateUtc") or episode.get("airDate")
|
||||
if not value:
|
||||
continue
|
||||
try:
|
||||
date = datetime.fromisoformat(
|
||||
value.replace("Z", "+00:00")
|
||||
)
|
||||
except ValueError:
|
||||
continue
|
||||
if date.tzinfo is None:
|
||||
date = date.replace(tzinfo=UTC)
|
||||
if date <= now:
|
||||
aired.append(episode)
|
||||
return bool(aired) and all(e.get("hasFile") for e in aired)
|
||||
@@ -0,0 +1,491 @@
|
||||
"""Shared per-person TV-season requests against the existing Sonarr API."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from .errors import PreloadError, SeasonError
|
||||
from .retention import SeasonPlan, complete_archive, plan_seasons
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .watch import Person, Watch
|
||||
|
||||
|
||||
@dataclass
|
||||
class SeasonSnapshot:
|
||||
"""Resolve episode files by ID, never arbitrary paths."""
|
||||
|
||||
series: dict[str, Any] | None
|
||||
episodes: list[dict[str, Any]]
|
||||
files: list[dict[str, Any]]
|
||||
queue: list[dict[str, Any]]
|
||||
|
||||
def queued_season(self, row: dict[str, Any]) -> int | None:
|
||||
"""Resolve episode-less season-pack rows conservatively."""
|
||||
number = row.get("seasonNumber")
|
||||
if number is None:
|
||||
number = (row.get("episode") or {}).get("seasonNumber")
|
||||
if number is None:
|
||||
number = next(
|
||||
(
|
||||
e["seasonNumber"]
|
||||
for e in self.episodes
|
||||
if e["id"] == row.get("episodeId")
|
||||
),
|
||||
None,
|
||||
)
|
||||
return number if isinstance(number, int) else None
|
||||
|
||||
def present_seasons(self) -> set[int]:
|
||||
"""Collect downloaded and queued seasons for previews."""
|
||||
result = {f["seasonNumber"] for f in self.files}
|
||||
result.update(
|
||||
n
|
||||
for row in self.queue
|
||||
if (n := self.queued_season(row)) is not None
|
||||
)
|
||||
return result
|
||||
|
||||
def deletion_ids(self, plan: SeasonPlan) -> list[int]:
|
||||
"""Delete files belonging only to unclaimed seasons."""
|
||||
result = []
|
||||
if plan.protected:
|
||||
return result
|
||||
for file in self.files:
|
||||
if file.get("seriesId") != (self.series or {}).get(
|
||||
"id"
|
||||
):
|
||||
msg = (
|
||||
"Sonarr returned a file from "
|
||||
"another show; nothing was "
|
||||
"deleted."
|
||||
)
|
||||
raise SeasonError(msg)
|
||||
seasons = {
|
||||
e["seasonNumber"]
|
||||
for e in self.episodes
|
||||
if e.get("episodeFileId") == file["id"]
|
||||
}
|
||||
seasons.add(file["seasonNumber"])
|
||||
if seasons and seasons <= plan.remove:
|
||||
result.append(file["id"])
|
||||
return sorted(result)
|
||||
|
||||
def cancellation_ids(self, plan: SeasonPlan) -> list[int]:
|
||||
"""Cancel no shared pack that still serves a retained season."""
|
||||
if plan.protected:
|
||||
return []
|
||||
grouped: dict[str, list[dict[str, Any]]] = {}
|
||||
for row in self.queue:
|
||||
grouped.setdefault(
|
||||
str(row.get("downloadId") or row["id"]), []
|
||||
).append(row)
|
||||
result = []
|
||||
for rows in grouped.values():
|
||||
numbers = {self.queued_season(row) for row in rows}
|
||||
if None in numbers:
|
||||
msg = (
|
||||
"An active download has an "
|
||||
"unknown season. Check Sonarr "
|
||||
"before switching."
|
||||
)
|
||||
raise SeasonError(msg)
|
||||
if numbers & plan.remove:
|
||||
if numbers & plan.keep:
|
||||
msg = (
|
||||
"A shared season pack "
|
||||
"spans retained "
|
||||
"seasons. Check Sonarr "
|
||||
"before switching."
|
||||
)
|
||||
raise SeasonError(msg)
|
||||
result.append(rows[0]["id"])
|
||||
return result
|
||||
|
||||
|
||||
class SeasonManager:
|
||||
"""Apply durable per-user choices serially."""
|
||||
|
||||
def __init__(self, cog: Watch) -> None:
|
||||
"""Reuse the cog connection and permission checks."""
|
||||
self.cog = cog
|
||||
|
||||
async def initialize(self) -> dict[str, Any]:
|
||||
"""Freeze complete-show exceptions before new requests."""
|
||||
cfg = self.cog.config
|
||||
async with self.cog._acquisition_lock:
|
||||
baseline = await cfg.season_retention_baseline()
|
||||
if baseline is not None:
|
||||
return baseline
|
||||
protected = []
|
||||
for series in await self.cog._arr_call("tv", "series"):
|
||||
episodes = await self.cog._arr_call(
|
||||
"tv",
|
||||
"episode",
|
||||
params={"seriesId": str(series["id"])},
|
||||
)
|
||||
if complete_archive(
|
||||
episodes, datetime.now(UTC)
|
||||
):
|
||||
protected.append(series["tvdbId"])
|
||||
baseline = {
|
||||
"protected": protected,
|
||||
"at": datetime.now(UTC).isoformat(),
|
||||
}
|
||||
await self.cog.config.season_retention_baseline.set(
|
||||
baseline
|
||||
)
|
||||
return baseline
|
||||
|
||||
async def snapshot(self, title: dict[str, Any]) -> SeasonSnapshot:
|
||||
"""Resolve episode files and queues for the selected show."""
|
||||
series = await self.cog._existing_title("tv", title)
|
||||
if series is None:
|
||||
return SeasonSnapshot(None, [], [], [])
|
||||
params = {"seriesId": str(series["id"])}
|
||||
episodes, files, queue = await asyncio.gather(
|
||||
self.cog._arr_call("tv", "episode", params=params),
|
||||
self.cog._arr_call("tv", "episodefile", params=params),
|
||||
self.cog._arr_call(
|
||||
"tv",
|
||||
"queue/details",
|
||||
params={**params, "includeEpisode": "true"},
|
||||
),
|
||||
)
|
||||
queue = [q for q in queue if q.get("seriesId") == series["id"]]
|
||||
return SeasonSnapshot(series, episodes, files, queue)
|
||||
|
||||
async def preview(
|
||||
self, user: Person, title: dict[str, Any], season: int
|
||||
) -> SeasonPlan:
|
||||
"""Preview deletion after freezing archive protection."""
|
||||
baseline = await self.initialize()
|
||||
snapshot = await self.snapshot(title)
|
||||
return await self.plan(user, title, season, baseline, snapshot)
|
||||
|
||||
async def plan(
|
||||
self,
|
||||
user: Person,
|
||||
title: dict[str, Any],
|
||||
season: int | None,
|
||||
baseline: dict[str, Any],
|
||||
snapshot: SeasonSnapshot,
|
||||
) -> SeasonPlan:
|
||||
"""Validate a season and combine users' claims."""
|
||||
if not isinstance(season, int) or season not in {
|
||||
s["seasonNumber"]
|
||||
for s in title.get("seasons", [])
|
||||
if s["seasonNumber"] > 0
|
||||
}:
|
||||
msg = "Choose a regular season listed for this show."
|
||||
raise SeasonError(msg)
|
||||
if (
|
||||
not isinstance(title.get("tvdbId"), int)
|
||||
or title["tvdbId"] <= 0
|
||||
):
|
||||
msg = "The show has no valid TVDB identifier."
|
||||
raise SeasonError(msg)
|
||||
return plan_seasons(
|
||||
await self.cog.config.all_users(),
|
||||
title["tvdbId"],
|
||||
user.id,
|
||||
season,
|
||||
snapshot.present_seasons(),
|
||||
protected=title["tvdbId"] in baseline["protected"],
|
||||
)
|
||||
|
||||
async def write(
|
||||
self,
|
||||
user: Person,
|
||||
method: str,
|
||||
path: str,
|
||||
*,
|
||||
body: dict[str, Any] | None = None,
|
||||
params: dict[str, str] | None = None,
|
||||
) -> Any: # noqa: ANN401 (ARR resource)
|
||||
"""Check permission before each Sonarr mutation."""
|
||||
if not await self.cog.can_download(user):
|
||||
msg = "Download permission was revoked."
|
||||
raise PermissionError(msg)
|
||||
return await self.cog._arr_call(
|
||||
"tv", path, body=body, params=params, method=method
|
||||
)
|
||||
|
||||
async def cleanup(
|
||||
self,
|
||||
user: Person,
|
||||
title: dict[str, Any],
|
||||
season: int | None,
|
||||
baseline: dict[str, Any],
|
||||
reviewed: SeasonPlan,
|
||||
) -> SeasonSnapshot:
|
||||
"""Re-read to catch imports racing this request."""
|
||||
current = await self.snapshot(title)
|
||||
plan = await self.plan(user, title, season, baseline, current)
|
||||
if plan.remove - reviewed.remove:
|
||||
msg = (
|
||||
"Season requests changed; review the "
|
||||
"request again before deleting more "
|
||||
"seasons."
|
||||
)
|
||||
raise SeasonError(msg)
|
||||
for queue_id in current.cancellation_ids(plan):
|
||||
await self.write(
|
||||
user,
|
||||
"DELETE",
|
||||
f"queue/{queue_id}",
|
||||
params={
|
||||
"removeFromClient": "true",
|
||||
"blocklist": "false",
|
||||
"skipRedownload": "true",
|
||||
},
|
||||
)
|
||||
# A completed transfer may have imported while it was cancelled.
|
||||
current = await self.snapshot(title)
|
||||
plan = await self.plan(user, title, season, baseline, current)
|
||||
if plan.remove - reviewed.remove or current.cancellation_ids(
|
||||
plan
|
||||
):
|
||||
msg = (
|
||||
"Downloads changed during the season "
|
||||
"switch. Run the request again to retry"
|
||||
" safely."
|
||||
)
|
||||
raise SeasonError(msg)
|
||||
ids = current.deletion_ids(plan)
|
||||
if ids:
|
||||
await self.write(
|
||||
user,
|
||||
"DELETE",
|
||||
"episodefile/bulk",
|
||||
body={"episodeFileIds": ids},
|
||||
)
|
||||
current = await self.snapshot(title)
|
||||
if current.deletion_ids(
|
||||
plan
|
||||
) or current.cancellation_ids(plan):
|
||||
msg = (
|
||||
"The previous season is not "
|
||||
"fully removed. No new season "
|
||||
"search was started; retry the "
|
||||
"request."
|
||||
)
|
||||
raise SeasonError(msg)
|
||||
return current
|
||||
|
||||
async def finish(
|
||||
self,
|
||||
user: Person,
|
||||
title: dict[str, Any],
|
||||
season: int | None,
|
||||
baseline: dict[str, Any],
|
||||
plan: SeasonPlan,
|
||||
snapshot: SeasonSnapshot,
|
||||
activation: dict[str, Any],
|
||||
) -> str:
|
||||
"""Finish a saved choice; make partial failures explicit."""
|
||||
try:
|
||||
if not plan.protected:
|
||||
snapshot = await self.cleanup(
|
||||
user, title, season, baseline, plan
|
||||
)
|
||||
# Only activate the new target after old files are gone.
|
||||
await self.write(
|
||||
user,
|
||||
"PUT",
|
||||
f"series/{activation['id']}",
|
||||
body=activation,
|
||||
)
|
||||
active = any(
|
||||
snapshot.queued_season(q) == season
|
||||
for q in snapshot.queue
|
||||
)
|
||||
target_episodes = [
|
||||
e
|
||||
for e in snapshot.episodes
|
||||
if e["seasonNumber"] == season
|
||||
]
|
||||
downloaded = bool(target_episodes) and all(
|
||||
e.get("hasFile") for e in target_episodes
|
||||
)
|
||||
if not active and not downloaded:
|
||||
await self.write(
|
||||
user,
|
||||
"POST",
|
||||
"command",
|
||||
body={
|
||||
"name": "SeasonSearch",
|
||||
"seriesId": activation["id"],
|
||||
"seasonNumber": season,
|
||||
},
|
||||
)
|
||||
except PreloadError:
|
||||
msg = (
|
||||
"Your season choice was saved, but the "
|
||||
"change is incomplete. Retry the same "
|
||||
"request to finish it safely."
|
||||
)
|
||||
raise SeasonError(msg) from None
|
||||
if not active and not downloaded:
|
||||
return f"Season {season} search requested."
|
||||
if downloaded:
|
||||
return f"Season {season} is already downloaded."
|
||||
return f"Season {season} is already in the download queue."
|
||||
|
||||
async def acquire(
|
||||
self,
|
||||
user: Person,
|
||||
title: dict[str, Any],
|
||||
quality: str,
|
||||
season: int | None,
|
||||
expected_delete: set[int] | None,
|
||||
) -> str:
|
||||
"""Retain others' choices and remove unclaimed seasons."""
|
||||
if not await self.cog.can_download(user):
|
||||
msg = "Download permission is required."
|
||||
raise PermissionError(msg)
|
||||
baseline = await self.initialize()
|
||||
async with self.cog._acquisition_lock:
|
||||
snapshot = await self.snapshot(title)
|
||||
plan = await self.plan(
|
||||
user, title, season, baseline, snapshot
|
||||
)
|
||||
if (
|
||||
expected_delete is not None
|
||||
and plan.remove - expected_delete
|
||||
):
|
||||
msg = (
|
||||
"Season requests changed. Run "
|
||||
"the command again to review "
|
||||
"what will be deleted."
|
||||
)
|
||||
raise SeasonError(msg)
|
||||
snapshot.deletion_ids(plan)
|
||||
snapshot.cancellation_ids(plan)
|
||||
profiles = await self.cog._arr_call(
|
||||
"tv", "qualityprofile"
|
||||
)
|
||||
name = {
|
||||
"1080p": "Doge - 1080p default",
|
||||
"4k": "Doge - 4K optional",
|
||||
}.get(quality)
|
||||
profile = next(
|
||||
(p for p in profiles if p["name"] == name), None
|
||||
)
|
||||
roots = await self.cog._arr_call("tv", "rootfolder")
|
||||
root = "/arr/library/TV"
|
||||
if profile is None or not any(
|
||||
r["path"] == root and r.get("accessible", True)
|
||||
for r in roots
|
||||
):
|
||||
msg = (
|
||||
"The selected profile or TV "
|
||||
"library root is unavailable."
|
||||
)
|
||||
raise SeasonError(msg)
|
||||
series = snapshot.series
|
||||
if series is None:
|
||||
body = dict(title)
|
||||
body.pop("id", None)
|
||||
body.pop("path", None)
|
||||
body.update(
|
||||
rootFolderPath=root,
|
||||
qualityProfileId=profile["id"],
|
||||
monitored=False,
|
||||
monitorNewItems="none",
|
||||
seasonFolder=True,
|
||||
)
|
||||
body["seasons"] = [
|
||||
dict(s, monitored=False)
|
||||
for s in title["seasons"]
|
||||
]
|
||||
body["addOptions"] = {
|
||||
"monitor": "skip",
|
||||
"searchForMissingEpisodes": False,
|
||||
"searchForCutoffUnmetEpisodes": False,
|
||||
}
|
||||
series = await self.write(
|
||||
user, "POST", "series", body=body
|
||||
)
|
||||
update = dict(series)
|
||||
update.pop("addOptions", None)
|
||||
update.update(
|
||||
monitored=True, qualityProfileId=profile["id"]
|
||||
)
|
||||
if not plan.protected:
|
||||
update["monitorNewItems"] = "none"
|
||||
existing_flags = {
|
||||
s["seasonNumber"]: s for s in series["seasons"]
|
||||
}
|
||||
for s in title["seasons"]:
|
||||
existing_flags.setdefault(
|
||||
s["seasonNumber"],
|
||||
dict(s, monitored=False),
|
||||
)
|
||||
update["seasons"] = [
|
||||
dict(
|
||||
s,
|
||||
monitored=(
|
||||
s.get("monitored", False)
|
||||
or n in plan.keep
|
||||
)
|
||||
if plan.protected
|
||||
else n in plan.keep,
|
||||
)
|
||||
for n, s in sorted(existing_flags.items())
|
||||
]
|
||||
staging = dict(update)
|
||||
if not plan.protected:
|
||||
staging["qualityProfileId"] = series[
|
||||
"qualityProfileId"
|
||||
]
|
||||
staging["seasons"] = [
|
||||
dict(
|
||||
s,
|
||||
monitored=s["seasonNumber"]
|
||||
in plan.shared,
|
||||
)
|
||||
for s in update["seasons"]
|
||||
]
|
||||
await self.write(
|
||||
user,
|
||||
"PUT",
|
||||
f"series/{series['id']}",
|
||||
body=staging,
|
||||
)
|
||||
await self.cog.config.user(user).tv_seasons.set_raw(
|
||||
str(title["tvdbId"]), value=season
|
||||
)
|
||||
outcome = await self.finish(
|
||||
user,
|
||||
title,
|
||||
season,
|
||||
baseline,
|
||||
plan,
|
||||
snapshot,
|
||||
update,
|
||||
)
|
||||
kept = ", ".join(str(n) for n in sorted(plan.keep))
|
||||
status = await self.cog.acquisition_status("tv", update)
|
||||
return (
|
||||
f"Season {season} is now your selected season. "
|
||||
f"Retaining requested seasons: {kept}. {outcome} "
|
||||
+ (
|
||||
(
|
||||
"This complete-show archive is "
|
||||
"protected; no seasons were "
|
||||
"deleted."
|
||||
)
|
||||
if plan.protected
|
||||
else (
|
||||
"Other seasons are kept only "
|
||||
"while another user requests "
|
||||
"them."
|
||||
)
|
||||
)
|
||||
+ "\n"
|
||||
+ status
|
||||
)
|
||||
+132
-49
@@ -33,6 +33,9 @@ from redbot.core import Config, commands
|
||||
from redbot.core.bot import Red
|
||||
|
||||
from .downloads import describe_downloads, normalized_title
|
||||
from .errors import PreloadError, SeasonError
|
||||
from .retention import SeasonPlan
|
||||
from .seasonal import SeasonManager
|
||||
from .spec import (
|
||||
DEFAULT_NEXT,
|
||||
EpisodeSpec,
|
||||
@@ -59,10 +62,6 @@ Person = discord.User | discord.Member
|
||||
RequestType = Literal["discord_deleted_user", "owner", "user", "user_strict"]
|
||||
|
||||
|
||||
class PreloadError(Exception):
|
||||
"""media-preload refused or failed a call."""
|
||||
|
||||
|
||||
def _unwrap(response: Response[Any]) -> Any: # noqa: ANN401 (generated types)
|
||||
"""Return a response's model, or raise with the API's error message."""
|
||||
if isinstance(response.parsed, Problem):
|
||||
@@ -351,8 +350,11 @@ class Watch(commands.Cog):
|
||||
self, identifier=0x0D06EBA7C4, force_registration=True
|
||||
)
|
||||
self.config.register_user(
|
||||
jellyfin_user=None, download_allowed=False
|
||||
jellyfin_user=None,
|
||||
download_allowed=False,
|
||||
tv_seasons={},
|
||||
)
|
||||
self.config.register_global(season_retention_baseline=None)
|
||||
self._acquisition_lock = asyncio.Lock()
|
||||
self._pollers: set[asyncio.Task[None]] = set()
|
||||
|
||||
@@ -638,6 +640,7 @@ class Watch(commands.Cog):
|
||||
*,
|
||||
body: dict[str, Any] | None = None,
|
||||
params: dict[str, str] | None = None,
|
||||
method: str | None = None,
|
||||
) -> Any: # noqa: ANN401 (ARR JSON resources)
|
||||
"""Call ARR without exposing private error bodies."""
|
||||
service = {"movie": "radarr", "tv": "sonarr"}.get(kind)
|
||||
@@ -655,7 +658,8 @@ class Watch(commands.Cog):
|
||||
) as client:
|
||||
try:
|
||||
response = await client.request(
|
||||
"GET" if body is None else "POST",
|
||||
method
|
||||
or ("GET" if body is None else "POST"),
|
||||
path,
|
||||
params=params,
|
||||
json=body,
|
||||
@@ -666,6 +670,8 @@ class Watch(commands.Cog):
|
||||
if response.status_code >= 400: # noqa: PLR2004
|
||||
msg = f"{service} 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:
|
||||
@@ -780,8 +786,15 @@ class Watch(commands.Cog):
|
||||
kind: str,
|
||||
title: dict[str, Any],
|
||||
quality: str,
|
||||
*,
|
||||
season: int | None = None,
|
||||
expected_delete: set[int] | None = None,
|
||||
) -> str:
|
||||
"""Check permission and add the chosen title once."""
|
||||
"""Check permission and add the chosen title or season."""
|
||||
if kind == "tv":
|
||||
return await SeasonManager(self).acquire(
|
||||
user, title, quality, season, expected_delete
|
||||
)
|
||||
if not await self.can_download(user):
|
||||
msg = "Download permission is required."
|
||||
raise PermissionError(msg)
|
||||
@@ -838,28 +851,10 @@ class Watch(commands.Cog):
|
||||
rootFolderPath=root,
|
||||
monitored=True,
|
||||
)
|
||||
if kind == "movie":
|
||||
body.update(
|
||||
minimumAvailability="released",
|
||||
addOptions={"searchForMovie": True},
|
||||
)
|
||||
else:
|
||||
body.update(
|
||||
seasonFolder=True,
|
||||
monitorNewItems="all",
|
||||
seriesType=title.get(
|
||||
"seriesType", "standard"
|
||||
),
|
||||
)
|
||||
body["seasons"] = [
|
||||
dict(s, monitored=s["seasonNumber"] > 0)
|
||||
for s in title.get("seasons", [])
|
||||
]
|
||||
body["addOptions"] = {
|
||||
"monitor": "all",
|
||||
"searchForMissingEpisodes": True,
|
||||
"searchForCutoffUnmetEpisodes": False,
|
||||
}
|
||||
body.update(
|
||||
minimumAvailability="released",
|
||||
addOptions={"searchForMovie": True},
|
||||
)
|
||||
# Recheck after HTTP calls in case access was revoked.
|
||||
if not await self.can_download(user):
|
||||
msg = "Download permission was revoked."
|
||||
@@ -889,26 +884,105 @@ class Watch(commands.Cog):
|
||||
return None
|
||||
return view.chosen
|
||||
|
||||
@commands.group(name="request", invoke_without_command=True)
|
||||
async def request(
|
||||
self, ctx: commands.Context, *, query: str = ""
|
||||
) -> None:
|
||||
"""Request a movie/show: type, title, then quality.
|
||||
async def _choose_requested_season(
|
||||
self,
|
||||
ctx: commands.Context,
|
||||
title: dict[str, Any],
|
||||
) -> int | None:
|
||||
"""Ask for one regular season, paginating long-running shows."""
|
||||
numbers = sorted(
|
||||
{
|
||||
s["seasonNumber"]
|
||||
for s in title.get("seasons", [])
|
||||
if s["seasonNumber"] > 0
|
||||
}
|
||||
)
|
||||
if not numbers:
|
||||
await ctx.send(
|
||||
"No regular seasons are listed for this show."
|
||||
)
|
||||
return None
|
||||
page = 0
|
||||
while True:
|
||||
options = [
|
||||
(str(n), f"Season {n}")
|
||||
for n in numbers[page : page + 22]
|
||||
]
|
||||
if page:
|
||||
options.append(("previous", "Previous seasons"))
|
||||
if page + 22 < len(numbers):
|
||||
options.append(("next", "More seasons"))
|
||||
chosen = await self._download_choice(
|
||||
ctx,
|
||||
"Which season would you like to keep?",
|
||||
options,
|
||||
)
|
||||
if chosen is None:
|
||||
return None
|
||||
if chosen == "next":
|
||||
page += 22
|
||||
elif chosen == "previous":
|
||||
page -= 22
|
||||
else:
|
||||
return int(chosen)
|
||||
|
||||
Owner permission is required. TV includes all regular
|
||||
seasons and monitor future episodes; specials are excluded.
|
||||
"""
|
||||
async def _season_request_plan(
|
||||
self,
|
||||
ctx: commands.Context,
|
||||
title: dict[str, Any],
|
||||
) -> tuple[int | None, SeasonPlan | None, str]:
|
||||
"""Preview a season switch before quality confirmation."""
|
||||
season = await self._choose_requested_season(ctx, title)
|
||||
if season is None:
|
||||
return None, None, ""
|
||||
preview = await SeasonManager(self).preview(
|
||||
ctx.author, title, season
|
||||
)
|
||||
scope = f"Request season {season}. "
|
||||
if preview.protected:
|
||||
scope += (
|
||||
"Complete archive: existing seasons are"
|
||||
" protected. "
|
||||
)
|
||||
elif preview.remove:
|
||||
removed = ", ".join(
|
||||
f"season {n}" for n in sorted(preview.remove)
|
||||
)
|
||||
scope += (
|
||||
f"This will delete {removed} "
|
||||
"if nobody else requests them. "
|
||||
)
|
||||
scope += "TV quality applies to this show. "
|
||||
return season, preview, scope
|
||||
|
||||
async def _request_allowed(
|
||||
self, ctx: commands.Context, query: str
|
||||
) -> bool:
|
||||
"""Check permission and title before looking anything up."""
|
||||
if not await self.can_download(ctx.author):
|
||||
await ctx.send(
|
||||
"Download permission is "
|
||||
"required. Ask the bot owner to"
|
||||
" grant it."
|
||||
)
|
||||
return
|
||||
return False
|
||||
if len(query.strip()) < 2: # noqa: PLR2004
|
||||
await ctx.send(
|
||||
f"Use `{ctx.clean_prefix}request <title>`."
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
@commands.group(name="request", invoke_without_command=True)
|
||||
async def request(
|
||||
self, ctx: commands.Context, *, query: str = ""
|
||||
) -> None:
|
||||
"""Request a movie/show: type, title, then quality.
|
||||
|
||||
Owner permission is required. TV asks for one season per user;
|
||||
seasons selected by other users remain available.
|
||||
"""
|
||||
if not await self._request_allowed(ctx, query):
|
||||
return
|
||||
kind = await self._download_choice(
|
||||
ctx,
|
||||
@@ -957,7 +1031,7 @@ class Watch(commands.Cog):
|
||||
return
|
||||
title = titles[int(chosen)]
|
||||
existing = await self._existing_title(kind, title)
|
||||
if existing is not None:
|
||||
if existing is not None and kind == "movie":
|
||||
await ctx.send(
|
||||
await self.acquisition_status(
|
||||
kind, existing
|
||||
@@ -965,15 +1039,17 @@ class Watch(commands.Cog):
|
||||
allowed_mentions=discord.AllowedMentions.none(),
|
||||
)
|
||||
return
|
||||
scope = (
|
||||
season = None
|
||||
preview = None
|
||||
scope = ""
|
||||
if kind == "tv":
|
||||
(
|
||||
"All regular seasons; future "
|
||||
"episodes monitored; specials "
|
||||
"excluded. "
|
||||
)
|
||||
if kind == "tv"
|
||||
else ""
|
||||
)
|
||||
season,
|
||||
preview,
|
||||
scope,
|
||||
) = await self._season_request_plan(ctx, title)
|
||||
if season is None:
|
||||
return
|
||||
label = discord.utils.escape_markdown(
|
||||
catalogue_label(title)
|
||||
)
|
||||
@@ -991,13 +1067,20 @@ class Watch(commands.Cog):
|
||||
return
|
||||
async with ctx.typing():
|
||||
result = await self.acquire(
|
||||
ctx.author, kind, title, quality
|
||||
ctx.author,
|
||||
kind,
|
||||
title,
|
||||
quality,
|
||||
season=season,
|
||||
expected_delete=set(preview.remove)
|
||||
if preview
|
||||
else None,
|
||||
)
|
||||
await ctx.send(
|
||||
result,
|
||||
allowed_mentions=discord.AllowedMentions.none(),
|
||||
)
|
||||
except (PreloadError, PermissionError) as exc:
|
||||
except (PreloadError, PermissionError, SeasonError) as exc:
|
||||
await ctx.send(f"Request not submitted: {exc}")
|
||||
|
||||
@request.command(name="allow")
|
||||
|
||||
Reference in new issue
Block a user