feat(plex): forbid duplicate collection names + a "New collection" button

Two follow-ups after testing the collection editing against real Plex, which revealed that
Plex CONFLATES same-named collections (two rating_keys resolve to one merged member list) —
a genuine footgun.

- Duplicate-name guard: create and rename now reject (409) a title that already exists in the
  target section (case-insensitive), before any Plex write. create() can also derive the
  library from the seed item, so the caller needn't know the section key. The create dialogs
  surface the 409, and the New-collection panel warns inline before submit.
- A "New collection" button on the Collections browse surface (admin only) opens a panel:
  a name field (with the live duplicate check) + a search to pick the FIRST title — Plex can't
  create an empty collection, it needs a seed. Creating opens the new collection's detail page
  straight away, so you can keep adding titles there. This is the B-route the user wanted,
  vs. the only prior path (a movie's "add to collection").

Verified live: the 409 guard (creating an existing name is blocked, no Plex write), and the
full New-collection flow (name + first title → create → lands on the detail page); test
collections created and deleted, real account left clean.

Gate: tsc/lint/knip/prettier clean, 424 vitest; backend ruff clean, 7 collections tests
(+ a duplicate-name-rejection assertion).
This commit is contained in:
2026-08-23 05:51:48 +02:00
parent 5d99a5f253
commit b71b33654a
6 changed files with 220 additions and 21 deletions
+26 -3
View File
@@ -192,6 +192,22 @@ def _editable_collection_or_403(db: Session, rating_key: str) -> PlexCollection:
return col
def _reject_duplicate_name(
db: Session, library_id: int, title: str, exclude_rk: str | None = None
) -> None:
"""No two collections in a section may share a name: Plex CONFLATES same-named collections'
membership (both rating_keys resolve to one merged member list — a real footgun), so forbid it up
front on create + rename rather than mirror the mess."""
dup = db.execute(
select(PlexCollection).where(
PlexCollection.library_id == library_id,
func.lower(PlexCollection.title) == title.lower(),
)
).scalars().first()
if dup is not None and dup.rating_key != exclude_rk:
raise HTTPException(status_code=409, detail="A collection with this name already exists")
class CreateCollectionIn(BaseModel):
library: str = ""
title: str = ""
@@ -212,11 +228,17 @@ def create_collection(
raise HTTPException(
status_code=400, detail="title and item_rating_key are required"
)
lib = db.execute(
select(PlexLibrary).where(PlexLibrary.plex_key == library)
).scalars().first()
if library:
lib = db.execute(
select(PlexLibrary).where(PlexLibrary.plex_key == library)
).scalars().first()
else:
# The "New collection" flow only knows the seed title → derive its library.
seed_item = by_rating_key(db, PlexItem, seed) or by_rating_key(db, PlexShow, seed)
lib = db.get(PlexLibrary, seed_item.library_id) if seed_item else None
if lib is None:
raise HTTPException(status_code=404, detail="Unknown library")
_reject_duplicate_name(db, lib.id, title)
try:
with PlexClient(db) as plex:
new = plex.create_collection(lib.plex_key, title, seed)
@@ -284,6 +306,7 @@ def collection_rename(
title = body.title.strip()
if not title:
raise HTTPException(status_code=400, detail="title is required")
_reject_duplicate_name(db, col.library_id, title, exclude_rk=rating_key)
lib = db.get(PlexLibrary, col.library_id)
try:
with PlexClient(db) as plex:
+26 -1
View File
@@ -7,7 +7,7 @@ from datetime import datetime, timezone
from fastapi.testclient import TestClient
import app.state as state
from app.auth import current_user
from app.auth import admin_user, current_user
from app.db import get_db
from app.main import app
from app.models import PlexCollection, PlexItem, PlexLibrary, PlexShow, User
@@ -94,6 +94,31 @@ def test_collection_cards_carry_montage_art_and_total_runtime(db, monkeypatch):
assert card["total_runtime_s"] == 5400 # 3600 + 1800
def test_create_collection_rejects_duplicate_name(db, monkeypatch):
# Same-named collections conflate in Plex, so a create with an existing name (case-insensitive) is
# rejected 409 — BEFORE any Plex call (the guard runs first, so the DB lane can assert it).
monkeypatch.setattr(state, "_configured_cache", True)
lib = PlexLibrary(plex_key="1", title="Movies", kind="movie", enabled=True)
db.add(lib)
db.flush()
db.add(PlexCollection(rating_key="A", library_id=lib.id, title="Marvel"))
db.add(PlexItem(rating_key="m1", library_id=lib.id, kind="movie", title="M1"))
user = User(email="dup@example.com")
db.add(user)
db.commit()
app.dependency_overrides[get_db] = lambda: db
app.dependency_overrides[current_user] = lambda: user
app.dependency_overrides[admin_user] = lambda: user
try:
r = TestClient(app).post(
"/api/plex/collections",
json={"library": "1", "title": "marvel", "item_rating_key": "m1"},
)
assert r.status_code == 409, r.text
finally:
app.dependency_overrides.clear()
def test_collection_detail_hero_and_ordered_members(db, monkeypatch):
# The Collection info page: hero aggregates (year range, most-restrictive cert, total runtime) +
# members ordered by release year then title.