From 569d31235d072f4934982944e5960687bab11c6b Mon Sep 17 00:00:00 2001 From: npeter83 Date: Fri, 10 Jul 2026 21:43:09 +0200 Subject: [PATCH 01/12] feat(plex): TV-show metadata sync + series filters (Phase 1 of series view) Give TV shows the same filterable metadata as movies so the TV grid can be filtered/sorted, not just library+sort. Backend: migration 0052 adds rating/content_rating/studio/originally_available_at/genres/directors/cast_names/ people_text to plex_shows (+ GIN/indexes, people_text folded into search_vector); _sync_shows populates them cheaply from the show section listing (no per-item calls). /browse show-branch gains the movie filter set (minus duration) plus an aggregate per-user watch-state (a show rolls up its episodes: all watched=watched, any progress=in_progress, none=new) with year/rating/release sorts; /facets returns show facets. Frontend: PlexSidebar renders the metadata filters + watch-state for TV libraries (duration stays movie-only); show cards show a watched/in-progress badge. i18n plex.inProgress (en/hu/de). Needs a Plex re-sync to populate the new columns. --- .../alembic/versions/0052_plex_show_meta.py | 91 ++++++++++++++ backend/app/models.py | 20 ++- backend/app/plex/sync.py | 10 ++ backend/app/routes/plex.py | 114 +++++++++++++++--- frontend/src/components/PlexBrowse.tsx | 6 + frontend/src/components/PlexSidebar.tsx | 74 ++++++------ frontend/src/i18n/locales/de/plex.json | 1 + frontend/src/i18n/locales/en/plex.json | 1 + frontend/src/i18n/locales/hu/plex.json | 1 + 9 files changed, 266 insertions(+), 52 deletions(-) create mode 100644 backend/alembic/versions/0052_plex_show_meta.py diff --git a/backend/alembic/versions/0052_plex_show_meta.py b/backend/alembic/versions/0052_plex_show_meta.py new file mode 100644 index 0000000..523421c --- /dev/null +++ b/backend/alembic/versions/0052_plex_show_meta.py @@ -0,0 +1,91 @@ +"""Plex show-level filterable/orderable metadata + +Revision ID: 0052_plex_show_meta +Revises: 0051_plex_link +Create Date: 2026-07-10 + +Gives TV shows the same filterable metadata movies already have (0045/0046), mirrored cheaply from +the Plex show section listing (no per-item calls): rating (audienceRating ~ IMDb), content rating, +studio/network, first-air date, and GIN-indexed genre / director / cast arrays + a `people_text` +blob folded into the generated `search_vector` (weight B). This lets the TV grid be filtered and +sorted like the movie grid. A generated column's expression can't be altered in place, so the +search_vector is dropped + recreated. All new columns are populated on the next Plex sync. +""" +from typing import Sequence, Union + +import sqlalchemy as sa +from alembic import op +from sqlalchemy.dialects import postgresql + +revision: str = "0052_plex_show_meta" +down_revision: Union[str, None] = "0051_plex_link" +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + +_CFG = "public.unaccent_simple" +_NEW_VECTOR = ( + f"setweight(to_tsvector('{_CFG}', coalesce(title, '')), 'A') || " + f"setweight(to_tsvector('{_CFG}', coalesce(people_text, '')), 'B') || " + f"setweight(to_tsvector('{_CFG}', left(coalesce(summary, ''), 1000)), 'C')" +) +_OLD_VECTOR = ( + f"setweight(to_tsvector('{_CFG}', coalesce(title, '')), 'A') || " + f"setweight(to_tsvector('{_CFG}', left(coalesce(summary, ''), 1000)), 'C')" +) + + +def _rebuild_vector(expr: str) -> None: + op.execute("DROP INDEX IF EXISTS ix_plex_shows_search_vector") + op.execute("ALTER TABLE plex_shows DROP COLUMN search_vector") + op.execute( + f"ALTER TABLE plex_shows ADD COLUMN search_vector tsvector " + f"GENERATED ALWAYS AS ({expr}) STORED" + ) + op.execute("CREATE INDEX ix_plex_shows_search_vector ON plex_shows USING gin (search_vector)") + + +def upgrade() -> None: + op.add_column("plex_shows", sa.Column("rating", sa.Float(), nullable=True)) + op.add_column("plex_shows", sa.Column("content_rating", sa.String(length=16), nullable=True)) + op.add_column("plex_shows", sa.Column("studio", sa.String(length=255), nullable=True)) + op.add_column("plex_shows", sa.Column("originally_available_at", sa.Date(), nullable=True)) + op.add_column("plex_shows", sa.Column("genres", postgresql.JSONB(), nullable=True)) + op.add_column("plex_shows", sa.Column("directors", postgresql.JSONB(), nullable=True)) + op.add_column("plex_shows", sa.Column("cast_names", postgresql.JSONB(), nullable=True)) + op.add_column("plex_shows", sa.Column("people_text", sa.Text(), nullable=True)) + + op.create_index("ix_plex_shows_rating", "plex_shows", ["rating"]) + op.create_index("ix_plex_shows_content_rating", "plex_shows", ["content_rating"]) + op.create_index("ix_plex_shows_studio", "plex_shows", ["studio"]) + op.create_index("ix_plex_shows_originally_available_at", "plex_shows", ["originally_available_at"]) + op.create_index("ix_plex_shows_genres_gin", "plex_shows", ["genres"], postgresql_using="gin") + op.create_index("ix_plex_shows_directors_gin", "plex_shows", ["directors"], postgresql_using="gin") + op.create_index("ix_plex_shows_cast_gin", "plex_shows", ["cast_names"], postgresql_using="gin") + # NB: ix_plex_shows_collections_gin already exists (created with collections in 0047). + + _rebuild_vector(_NEW_VECTOR) + + +def downgrade() -> None: + _rebuild_vector(_OLD_VECTOR) + for ix in ( + "ix_plex_shows_cast_gin", + "ix_plex_shows_directors_gin", + "ix_plex_shows_genres_gin", + "ix_plex_shows_originally_available_at", + "ix_plex_shows_studio", + "ix_plex_shows_content_rating", + "ix_plex_shows_rating", + ): + op.drop_index(ix, table_name="plex_shows") + for col in ( + "people_text", + "cast_names", + "directors", + "genres", + "originally_available_at", + "studio", + "content_rating", + "rating", + ): + op.drop_column("plex_shows", col) diff --git a/backend/app/models.py b/backend/app/models.py index 4638109..5e0c915 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -956,9 +956,17 @@ class PlexLibrary(Base, TimestampMixin, UpdatedAtMixin): class PlexShow(Base, TimestampMixin, UpdatedAtMixin): - """A TV show (grandparent of episodes) — holds poster + summary for the drill-down page.""" + """A TV show (grandparent of episodes) — holds poster + summary for the drill-down page, plus + the same filterable metadata as movies (genres/rating/content_rating/studio/people) so the TV + grid can be filtered/sorted like the movie grid. All mirrored cheaply from the show listing.""" __tablename__ = "plex_shows" + __table_args__ = ( + Index("ix_plex_shows_genres_gin", "genres", postgresql_using="gin"), + Index("ix_plex_shows_directors_gin", "directors", postgresql_using="gin"), + Index("ix_plex_shows_cast_gin", "cast_names", postgresql_using="gin"), + # ix_plex_shows_collections_gin already created with collections (migration 0047). + ) id: Mapped[int] = mapped_column(primary_key=True) rating_key: Mapped[str] = mapped_column(String(32), unique=True, index=True) @@ -973,10 +981,20 @@ class PlexShow(Base, TimestampMixin, UpdatedAtMixin): child_count: Mapped[int | None] = mapped_column(Integer) # seasons collection_keys: Mapped[list | None] = mapped_column(JSONB) # Plex collections this show is in added_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), index=True) + # Filterable / orderable metadata mirrored from the show section listing (parallels PlexItem). + rating: Mapped[float | None] = mapped_column(Float, index=True) # Plex audienceRating (~IMDb) + content_rating: Mapped[str | None] = mapped_column(String(16), index=True) + studio: Mapped[str | None] = mapped_column(String(255), index=True) # network/studio + originally_available_at: Mapped[Date | None] = mapped_column(Date, index=True) # first air date + genres: Mapped[list | None] = mapped_column(JSONB) + directors: Mapped[list | None] = mapped_column(JSONB) + cast_names: Mapped[list | None] = mapped_column(JSONB) + people_text: Mapped[str | None] = mapped_column(Text) # cast+directors, folded into search_vector search_vector: Mapped[object | None] = mapped_column( TSVECTOR, Computed( "setweight(to_tsvector('public.unaccent_simple', coalesce(title, '')), 'A') || " + "setweight(to_tsvector('public.unaccent_simple', coalesce(people_text, '')), 'B') || " "setweight(to_tsvector('public.unaccent_simple', left(coalesce(summary, ''), 1000)), 'C')", persisted=True, ), diff --git a/backend/app/plex/sync.py b/backend/app/plex/sync.py index 7cc3059..975369c 100644 --- a/backend/app/plex/sync.py +++ b/backend/app/plex/sync.py @@ -230,6 +230,16 @@ def _sync_shows(db: Session, plex: PlexClient, lib: PlexLibrary, stats: dict) -> sh.art_key = meta.get("art") sh.child_count = meta.get("childCount") sh.added_at = _epoch(meta.get("addedAt")) + # Filterable / orderable metadata — same cheap section-listing tags as movies. + sh.rating = _rating(meta) + sh.content_rating = (meta.get("contentRating") or None) + sh.studio = (meta.get("studio") or None) and str(meta.get("studio"))[:255] + sh.originally_available_at = _date(meta.get("originallyAvailableAt")) + sh.genres = _tags(meta, "Genre") + sh.directors = _tags(meta, "Director") + sh.cast_names = _tags(meta, "Role", limit=20) + people = list(dict.fromkeys((sh.directors or []) + (sh.cast_names or []))) + sh.people_text = " ".join(people) or None stats["shows"] += 1 db.flush() show_id = {rk: sh.id for rk, sh in shows.items()} diff --git a/backend/app/routes/plex.py b/backend/app/routes/plex.py index f44b5ec..59f700e 100644 --- a/backend/app/routes/plex.py +++ b/backend/app/routes/plex.py @@ -18,7 +18,7 @@ from urllib.parse import quote import httpx from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Request, Response from fastapi.responses import FileResponse -from sqlalchemy import and_, func, or_, text +from sqlalchemy import and_, case, func, or_, text from sqlalchemy.orm import Session, aliased from app import sysconfig @@ -228,7 +228,7 @@ def _movie_card(it: PlexItem, st: PlexState | None) -> dict: } -def _show_card(sh: PlexShow) -> dict: +def _show_card(sh: PlexShow, status: str = "new") -> dict: return { "id": sh.rating_key, "type": "show", @@ -236,9 +236,51 @@ def _show_card(sh: PlexShow) -> dict: "year": sh.year, "thumb": f"/api/plex/image/{sh.rating_key}", "season_count": sh.child_count, + # Aggregate watch-state across the show's episodes (new | in_progress | watched) → grid badge. + "status": status, } +def _show_status(total: int, watched: int, inprog: int) -> str: + """Roll a show's episodes up into a single watch state: fully watched, partially started, or new.""" + if total and watched >= total: + return "watched" + if (watched or 0) > 0 or (inprog or 0) > 0: + return "in_progress" + return "new" + + +def _show_agg_subq(db: Session, user_id: int): + """Per-show episode counts for a user: total, watched, in-progress. Reused to (a) filter the show + grid by aggregate watch-state and (b) compute each card's badge.""" + ps = aliased(PlexState) + return ( + db.query( + PlexItem.show_id.label("show_id"), + func.count(PlexItem.id).label("total"), + func.count(case((ps.status == "watched", 1))).label("watched"), + func.count( + case( + ( + and_(ps.position_seconds > 0, or_(ps.status.is_(None), ps.status != "watched")), + 1, + ) + ) + ).label("inprog"), + ) + .outerjoin(ps, and_(ps.item_id == PlexItem.id, ps.user_id == user_id)) + .filter(PlexItem.kind == "episode", PlexItem.show_id.isnot(None)) + .group_by(PlexItem.show_id) + ) + + +def _show_state_map(db: Session, user_id: int, show_ids: list[int]) -> dict[int, str]: + if not show_ids: + return {} + rows = _show_agg_subq(db, user_id).filter(PlexItem.show_id.in_(show_ids)).all() + return {r.show_id: _show_status(r.total, r.watched, r.inprog) for r in rows} + + def _episode_card(e: PlexItem, st: PlexState | None) -> dict: return { "id": e.rating_key, @@ -358,6 +400,43 @@ def browse( query = query.filter(PlexItem.studio.in_(stds)) else: query = query.filter(PlexShow.library_id == lib.id) + # Aggregate per-user watch-state across the show's episodes (a show isn't one row of state). + if show in ("watched", "in_progress", "unwatched"): + agg = _show_agg_subq(db, user.id).subquery() + query = query.outerjoin(agg, agg.c.show_id == PlexShow.id) + tot = func.coalesce(agg.c.total, 0) + wat = func.coalesce(agg.c.watched, 0) + inp = func.coalesce(agg.c.inprog, 0) + if show == "watched": + query = query.filter(tot > 0, wat >= tot) + elif show == "in_progress": + query = query.filter(or_(wat > 0, inp > 0), wat < tot) + else: # unwatched — no episode started + query = query.filter(wat == 0, inp == 0) + # --- Metadata filters (same as movies, minus duration which shows don't have) --- + gsel = _csv(genres) + if gsel: + conds = [PlexShow.genres.contains([g]) for g in gsel] + query = query.filter(and_(*conds) if genre_mode == "all" else or_(*conds)) + crs = _csv(content_ratings) + if crs: + query = query.filter(PlexShow.content_rating.in_(crs)) + if year_min is not None: + query = query.filter(PlexShow.year >= year_min) + if year_max is not None: + query = query.filter(PlexShow.year <= year_max) + if rating_min is not None: + query = query.filter(PlexShow.rating >= rating_min) + cutoff = _added_cutoff(added_within) + if cutoff is not None: + query = query.filter(PlexShow.added_at >= cutoff) + for d in _csv(directors): # AND + query = query.filter(PlexShow.directors.contains([d])) + for a in _csv(actors): # AND + query = query.filter(PlexShow.cast_names.contains([a])) + stds = _csv(studios) + if stds: # OR + query = query.filter(PlexShow.studio.in_(stds)) # Collection filter applies to both movies and shows (both carry collection_keys). if collection: @@ -376,14 +455,14 @@ def browse( else: if sort == "title": col = func.lower(model.title) - elif sort == "year" and model is PlexItem: - col = PlexItem.year - elif sort == "rating" and model is PlexItem: - col = PlexItem.rating + elif sort == "year": # both movies and shows have year + col = model.year + elif sort == "rating": # both have rating (audienceRating) + col = model.rating elif sort == "duration" and model is PlexItem: col = PlexItem.duration_s - elif sort == "release" and model is PlexItem: - col = PlexItem.originally_available_at + elif sort == "release": # both have originally_available_at + col = model.originally_available_at else: # added col = model.added_at asc = sort_dir == "asc" @@ -402,7 +481,8 @@ def browse( } items = [_movie_card(r, states.get(r.id)) for r in rows] else: - items = [_show_card(r) for r in rows] + statuses = _show_state_map(db, user.id, [r.id for r in rows]) + items = [_show_card(r, statuses.get(r.id, "new")) for r in rows] return {"kind": lib.kind, "total": total, "offset": offset, "limit": limit, "items": items} @@ -413,8 +493,9 @@ def facets( user: User = Depends(current_user), db: Session = Depends(get_db), ) -> dict: - """Available filter values for a movie library — genres + content ratings (with counts) and the - year/rating/duration bounds — so the sidebar only offers what the library actually contains.""" + """Available filter values for a movie OR show library — genres + content ratings (with counts) + and the year/rating[/duration] bounds — so the sidebar only offers what the library contains. + Shows carry the same filterable metadata as movies now (0052), minus duration.""" empty = { "genres": [], "content_ratings": [], @@ -425,9 +506,14 @@ def facets( "duration_max": None, } lib = db.query(PlexLibrary).filter_by(plex_key=str(library)).first() - if lib is None or lib.kind != "movie": + if lib is None: return empty - base = "FROM plex_items WHERE library_id = :lib AND kind = 'movie'" + if lib.kind == "movie": + base = "FROM plex_items WHERE library_id = :lib AND kind = 'movie'" + dur_sel = "min(duration_s), max(duration_s)" + else: # show library — same columns on plex_shows, no per-row duration + base = "FROM plex_shows WHERE library_id = :lib" + dur_sel = "NULL, NULL" genres = db.execute( text( f"SELECT g, count(*) AS c FROM (SELECT jsonb_array_elements_text(genres) AS g {base}) x " @@ -440,7 +526,7 @@ def facets( {"lib": lib.id}, ).all() b = db.execute( - text(f"SELECT min(year), max(year), max(rating), min(duration_s), max(duration_s) {base}"), + text(f"SELECT min(year), max(year), max(rating), {dur_sel} {base}"), {"lib": lib.id}, ).first() return { diff --git a/frontend/src/components/PlexBrowse.tsx b/frontend/src/components/PlexBrowse.tsx index 02a32a7..397f57a 100644 --- a/frontend/src/components/PlexBrowse.tsx +++ b/frontend/src/components/PlexBrowse.tsx @@ -406,6 +406,12 @@ function PlexPosterCard({ {t("plex.seasons", { count: card.season_count })} )} + {/* Aggregate in-progress badge for a partially-watched show. */} + {card.type === "show" && card.status === "in_progress" && ( + + {t("plex.inProgress")} + + )} {card.playable && ( api.plexFacets(library), - enabled: !!library && isMovieLib, + enabled: !!library, // facets now come for movie AND show libraries (0052) }); const facets = facetsQ.data; @@ -80,7 +81,7 @@ export default function PlexSidebar({ const collectionsQ = useQuery({ queryKey: ["plex-collections", library, collSearchDeb], queryFn: () => api.plexCollections(library, collSearchDeb || undefined), - enabled: !!library && isMovieLib && !filters.collection, + enabled: !!library && !filters.collection, // collections apply to shows too }); const collections = collectionsQ.data?.collections ?? []; @@ -89,9 +90,8 @@ export default function PlexSidebar({ if (libs.length && !libs.some((l) => l.key === library)) setLibrary(libs[0].key); }, [libs, library, setLibrary]); - const fCount = isMovieLib ? plexFilterCount(filters) : 0; - const activeCount = - fCount + (show !== "all" && isMovieLib ? 1 : 0) + (sort !== "added" ? 1 : 0); + const fCount = plexFilterCount(filters); // shows carry the same filters now (0052) + const activeCount = fCount + (show !== "all" ? 1 : 0) + (sort !== "added" ? 1 : 0); const anyActive = activeCount > 0; const patch = (p: Partial) => setFilters({ ...filters, ...p }); @@ -205,18 +205,16 @@ export default function PlexSidebar({ )} - {/* Watch state (movie libraries only) */} - {isMovieLib && ( -
- - {SHOW_OPTS.map((s) => ( - setShow(s)}> - {t(`plex.filter.showOpt.${s}`)} - - ))} - -
- )} + {/* Watch state — movies per-title, shows aggregated across their episodes (0052) */} +
+ + {SHOW_OPTS.map((s) => ( + setShow(s)}> + {t(`plex.filter.showOpt.${s}`)} + + ))} + +
{/* Sort + direction */}
@@ -236,8 +234,8 @@ export default function PlexSidebar({
- {/* Metadata filters (movie libraries only) */} - {isMovieLib && ( + {/* Metadata filters — movie AND show libraries (0052); the duration bucket is movie-only. */} + {( <> {/* Active people / studios — set by clicking the info page (stackable). */} {filters.directors.length + filters.actors.length + filters.studios.length > 0 && ( @@ -370,26 +368,28 @@ export default function PlexSidebar({ - {/* Duration buckets */} -
- - patch({ durationMin: null, durationMax: null })} - > - {t("plex.filter.any")} - - {DURATION_BUCKETS.map((b) => ( + {/* Duration buckets — movie-only (a show has no single runtime) */} + {isMovieLib && ( +
+ patch({ durationMin: b.min, durationMax: b.max })} + active={!durBucketKey && filters.durationMin == null && filters.durationMax == null} + onClick={() => patch({ durationMin: null, durationMax: null })} > - {t(`plex.filter.durationOpt.${b.key}`)} + {t("plex.filter.any")} - ))} - -
+ {DURATION_BUCKETS.map((b) => ( + patch({ durationMin: b.min, durationMax: b.max })} + > + {t(`plex.filter.durationOpt.${b.key}`)} + + ))} +
+
+ )} {/* Added to Plex */}
diff --git a/frontend/src/i18n/locales/de/plex.json b/frontend/src/i18n/locales/de/plex.json index d2fb8d0..d3145c6 100644 --- a/frontend/src/i18n/locales/de/plex.json +++ b/frontend/src/i18n/locales/de/plex.json @@ -63,6 +63,7 @@ "empty": "Noch nichts hier. Starte eine Plex-Synchronisierung auf der Admin-Konfigurationsseite.", "loadMore": "Mehr laden", "watched": "Angesehen", + "inProgress": "Läuft", "play": "Abspielen", "resume": "Fortsetzen", "openShow": "Serie öffnen", diff --git a/frontend/src/i18n/locales/en/plex.json b/frontend/src/i18n/locales/en/plex.json index 9c9dfba..2aef3b5 100644 --- a/frontend/src/i18n/locales/en/plex.json +++ b/frontend/src/i18n/locales/en/plex.json @@ -63,6 +63,7 @@ "empty": "Nothing here yet. Run a Plex sync from the admin Config page.", "loadMore": "Load more", "watched": "Watched", + "inProgress": "In progress", "play": "Play", "resume": "Resume", "openShow": "Open show", diff --git a/frontend/src/i18n/locales/hu/plex.json b/frontend/src/i18n/locales/hu/plex.json index 6cfeb88..9df0b51 100644 --- a/frontend/src/i18n/locales/hu/plex.json +++ b/frontend/src/i18n/locales/hu/plex.json @@ -63,6 +63,7 @@ "empty": "Még nincs itt semmi. Futtass egy Plex-szinkront az admin Konfiguráció oldalról.", "loadMore": "Több betöltése", "watched": "Megnézve", + "inProgress": "Folyamatban", "play": "Lejátszás", "resume": "Folytatás", "openShow": "Sorozat megnyitása", From 11b7558c6cc23cd5b6201ecb311eeabca5b561bf Mon Sep 17 00:00:00 2001 From: npeter83 Date: Fri, 10 Jul 2026 22:08:04 +0200 Subject: [PATCH 02/12] feat(plex): Plex-web-style 3-level series view (Phase 2 of series view) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Restructure TV browsing into show detail → seasons → season episodes → player, like the Plex web app. Backend: /show/{rk} now returns a rich show page — hero meta (rating/content_rating/ genres/studio + live IMDb), live Cast & Crew, Related shows (Plex 'related', mapped to our mirrored shows so they're openable), and per-season cards with an aggregate watch-state + on-deck episode, plus show-level resume (on-deck)/first(play-from-start)/ status rollup. New PlexClient.related(). New bulk-state endpoints POST /show/{rk}/state and /season/{rk}/state mark every episode watched/unwatched for the user and mirror each change to a linked Plex account in the background (best-effort, checked once). Frontend: PlexShowView reworked into the show detail page (hero + Resume/Play-from-start/ Mark-show-watched/Add-to-playlist/[admin]Add-to-collection + season card grid + cast + related strips); new PlexSeasonView season subpage (hero + Resume/Play/Mark-season/ Add-season-to-playlist + landscape episode grid). Both read the one cached ['plex-show'] payload (season page picks its season out of it — instant, no extra fetch). Player queue = the whole show (from the show page) or the season (from the season page) so prev/next + auto-advance follow order. New 'season' history subview; Backspace steps back one drill level (grid←show←season, out of info/playlist) alongside browser/mouse Back. Season-level 'Add to collection' intentionally omitted (Plex collections hold whole shows, not seasons). i18n plex.series.* (en/hu/de). --- backend/app/plex/client.py | 12 + backend/app/routes/plex.py | 178 +++++++- frontend/src/components/PlexBrowse.tsx | 544 ++++++++++++++++++++----- frontend/src/i18n/locales/de/plex.json | 12 + frontend/src/i18n/locales/en/plex.json | 12 + frontend/src/i18n/locales/hu/plex.json | 12 + frontend/src/lib/api.ts | 26 +- 7 files changed, 694 insertions(+), 102 deletions(-) diff --git a/backend/app/plex/client.py b/backend/app/plex/client.py index 034d6d4..54fbb28 100644 --- a/backend/app/plex/client.py +++ b/backend/app/plex/client.py @@ -96,6 +96,18 @@ class PlexClient: mc = self._get(f"/library/metadata/{rating_key}/children") return mc.get("Metadata", []) or [] + def related(self, rating_key: str) -> list[dict]: + """Related / similar items for a movie or show, flattened out of Plex's Hub grouping. + Best-effort (needs the library's related data) — returns [] if Plex has none.""" + try: + mc = self._get(f"/library/metadata/{rating_key}/related") + except PlexError: + return [] + out: list[dict] = [] + for hub in mc.get("Hub", []) or []: + out.extend(hub.get("Metadata", []) or []) + return out + def collections(self, section_key: str) -> list[dict]: """All collections in a library section (title/summary/thumb/childCount/smart).""" mc = self._get(f"/library/sections/{section_key}/collections") diff --git a/backend/app/routes/plex.py b/backend/app/routes/plex.py index 59f700e..e90ef1c 100644 --- a/backend/app/routes/plex.py +++ b/backend/app/routes/plex.py @@ -250,6 +250,26 @@ def _show_status(total: int, watched: int, inprog: int) -> str: return "new" +def _rollup(cards: list[dict]) -> dict: + """From ORDERED episode cards → the aggregate watch status, the "on deck" episode to Resume (the + last in-progress one, else the first unwatched), the first episode (for Play from the start), and + the episode count. Drives the show/season Resume + Play + mark-all buttons.""" + total = len(cards) + watched = sum(1 for c in cards if c.get("status") == "watched") + inprog = [c for c in cards if (c.get("position_seconds") or 0) > 0 and c.get("status") != "watched"] + resume = None + if inprog: + resume = inprog[-1] # continue the latest-started episode + else: + resume = next((c for c in cards if c.get("status") != "watched"), None) + return { + "status": _show_status(total, watched, len(inprog)), + "resume": resume, + "first": cards[0] if cards else None, + "episode_count": total, + } + + def _show_agg_subq(db: Session, user_id: int): """Per-show episode counts for a user: total, watched, in-progress. Reused to (a) filter the show grid by aggregate watch-state and (b) compute each card's badge.""" @@ -1033,8 +1053,24 @@ def show_detail( ) } by_season: dict[int | None, list] = {} + all_cards: list[dict] = [] # every episode, in season/episode order → show-level rollup for e in eps: - by_season.setdefault(e.season_id, []).append(_episode_card(e, states.get(e.id))) + card = _episode_card(e, states.get(e.id)) + by_season.setdefault(e.season_id, []).append(card) + all_cards.append(card) + show_roll = _rollup(all_cards) + + # Cast + IMDb (best-effort live metadata; same shape as the movie/episode info page). + rich: dict = {} + related: list[dict] = [] + try: + with PlexClient(db) as plex: + meta = plex.metadata(sh.rating_key) or {} + rich = _rich_meta(meta) + related = _related_show_cards(db, user.id, plex.related(sh.rating_key), exclude=sh.id) + except (PlexError, PlexNotConfigured): + pass + return { "show": { "id": sh.rating_key, @@ -1043,20 +1079,71 @@ def show_detail( "year": sh.year, "thumb": f"/api/plex/image/{sh.rating_key}", "art": f"/api/plex/image/{sh.rating_key}?variant=art", + "content_rating": sh.content_rating, + "rating": sh.rating, + "genres": sh.genres or [], + "studio": sh.studio, + "season_count": sh.child_count, + "imdb_rating": rich.get("imdb_rating"), + "imdb_id": rich.get("imdb_id"), + "imdb_url": rich.get("imdb_url"), + "cast": rich.get("cast", []), + # Show-level rollup for the hero action buttons. + "status": show_roll["status"], + "resume": show_roll["resume"], + "first": show_roll["first"], + "episode_count": show_roll["episode_count"], + "collection_keys": sh.collection_keys or [], }, "seasons": [ - { - "id": se.rating_key, - "season_number": se.season_number, - "title": se.title or (f"Season {se.season_number}" if se.season_number else "Season"), - "thumb": f"/api/plex/image/{se.rating_key}", - "episodes": by_season.get(se.id, []), - } + _season_block(se, by_season.get(se.id, [])) for se in seasons ], + "related": related, } +def _season_block(se: PlexSeason, cards: list[dict]) -> dict: + """A season's card for the show page (with its aggregate rollup) plus its episodes (used by the + season subpage, read from the same cached show-detail payload).""" + roll = _rollup(cards) + return { + "id": se.rating_key, + "season_number": se.season_number, + "title": se.title or (f"Season {se.season_number}" if se.season_number else "Season"), + "thumb": f"/api/plex/image/{se.rating_key}", + "episode_count": roll["episode_count"], + "status": roll["status"], + "resume": roll["resume"], + "first": roll["first"], + "episodes": cards, + } + + +def _related_show_cards(db: Session, user_id: int, related: list[dict], exclude: int) -> list[dict]: + """Map Plex 'related' metadata to show cards for the shows we actually mirror (so they're openable), + excluding the current show. Order preserved; capped.""" + rks = [str(m.get("ratingKey")) for m in related if m.get("ratingKey")] + if not rks: + return [] + shows = { + s.rating_key: s + for s in db.query(PlexShow).filter(PlexShow.rating_key.in_(rks[:60]), PlexShow.id != exclude) + } + statuses = _show_state_map(db, user_id, [s.id for s in shows.values()]) + out: list[dict] = [] + seen: set[str] = set() + for rk in rks: + sh = shows.get(rk) + if sh is None or rk in seen: + continue + seen.add(rk) + out.append(_show_card(sh, statuses.get(sh.id, "new"))) + if len(out) >= 20: + break + return out + + def _image_key(db: Session, rating_key: str, variant: str) -> str | None: """The stored Plex image path for a known rating_key (item/show/season). Only mirrored keys are proxyable — this is not an open image proxy.""" @@ -1695,6 +1782,81 @@ def item_state( return {"status": status} +def _bulk_state( + background: BackgroundTasks, db: Session, user_id: int, eps: list[PlexItem], watched: bool +) -> int: + """Mark every episode in `eps` watched (or unwatched) for a user, mirroring each change to a + linked Plex account in the background (best-effort). Returns how many rows actually changed.""" + now = datetime.now(timezone.utc) + existing = { + s.item_id: s + for s in db.query(PlexState).filter( + PlexState.user_id == user_id, PlexState.item_id.in_([e.id for e in eps] or [0]) + ) + } + pushable = plex_watch.link_for_push(db, user_id) is not None + to_push: list[tuple[int, str, str]] = [] + for e in eps: + st = existing.get(e.id) + prev = st.status if st is not None else "new" + if watched: + if st is None: + st = PlexState(user_id=user_id, item_id=e.id) + db.add(st) + st.status = "watched" + st.watched_at = now + st.position_seconds = 0 + st.synced_to_plex = False + if prev != "watched": + to_push.append((e.id, e.rating_key, "watched")) + else: # → new: drop any state (but keep the user's private "hidden" marks) + if st is not None and prev != "hidden": + db.delete(st) + if prev != "new": + to_push.append((e.id, e.rating_key, "unwatched")) + db.commit() + if pushable: + for item_id, rk, action in to_push: + background.add_task(plex_watch.push_state_to_plex, user_id, item_id, rk, action, 0, 0) + return len(to_push) + + +@router.post("/show/{rating_key}/state") +def show_state( + rating_key: str, + payload: dict, + background: BackgroundTasks, + user: User = Depends(current_user), + db: Session = Depends(get_db), +) -> dict: + """Mark a whole show watched/unwatched (all its episodes) for the current user + push to Plex.""" + sh = db.query(PlexShow).filter_by(rating_key=str(rating_key)).first() + if sh is None: + raise HTTPException(status_code=404, detail="Unknown Plex show") + watched = bool(payload.get("watched")) + eps = db.query(PlexItem).filter_by(show_id=sh.id, kind="episode").all() + changed = _bulk_state(background, db, user.id, eps, watched) + return {"changed": changed, "watched": watched} + + +@router.post("/season/{rating_key}/state") +def season_state( + rating_key: str, + payload: dict, + background: BackgroundTasks, + user: User = Depends(current_user), + db: Session = Depends(get_db), +) -> dict: + """Mark a whole season watched/unwatched (all its episodes) for the current user + push to Plex.""" + se = db.query(PlexSeason).filter_by(rating_key=str(rating_key)).first() + if se is None: + raise HTTPException(status_code=404, detail="Unknown Plex season") + watched = bool(payload.get("watched")) + eps = db.query(PlexItem).filter_by(season_id=se.id, kind="episode").all() + changed = _bulk_state(background, db, user.id, eps, watched) + return {"changed": changed, "watched": watched} + + @router.post("/stream/{rating_key}/session") def stream_session( rating_key: str, diff --git a/frontend/src/components/PlexBrowse.tsx b/frontend/src/components/PlexBrowse.tsx index 397f57a..f859d0b 100644 --- a/frontend/src/components/PlexBrowse.tsx +++ b/frontend/src/components/PlexBrowse.tsx @@ -1,18 +1,33 @@ import { lazy, Suspense, useEffect, useLayoutEffect, useRef, useState, type CSSProperties } from "react"; import { useTranslation } from "react-i18next"; import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query"; -import { ArrowLeft, CheckCircle2, Info, ListPlus, Play } from "lucide-react"; +import { + ArrowLeft, + Check, + CheckCheck, + CheckCircle2, + Info, + Layers, + ListPlus, + Play, + RotateCcw, + Star, + type LucideIcon, +} from "lucide-react"; import { api, EMPTY_PLEX_FILTERS, plexFilterCount, type PlexCard, + type PlexCastMember, type PlexFilters, type PlexPerson, + type PlexSeasonDetail, } from "../lib/api"; import { useDebounced } from "../lib/useDebounced"; import { useHistorySubview } from "../lib/history"; import PlexPlaylistAdd, { type PlexAddTarget } from "./PlexPlaylistAdd"; +import PlexCollectionEditor from "./PlexCollectionEditor"; // Lazy: the rich player (pulls in hls.js) loads only when something is first played. const PlexPlayer = lazy(() => import("./PlexPlayer")); @@ -22,6 +37,7 @@ const PlexPlaylistView = lazy(() => import("./PlexPlaylistView")); type Sub = | { kind: "grid" } | { kind: "show"; id: string } + | { kind: "season"; showId: string; seasonId: string } | { kind: "player"; id: string; queue?: string[] } | { kind: "info"; id: string } | { kind: "playlist"; id: number }; @@ -98,6 +114,24 @@ export default function PlexBrowse({ else if (sub.view.kind === "info" && infoScrollRef.current) el.scrollTop = infoScrollRef.current; }, [sub.view.kind]); + // Backspace steps back one drill-down level (grid ← show ← season, and out of info/playlist), + // matching the browser/mouse Back. The player has its OWN Backspace handling, so we skip it here; + // and never hijack Backspace while typing in a field. + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key !== "Backspace") return; + const el = document.activeElement as HTMLElement | null; + const tag = (el?.tagName || "").toLowerCase(); + if (tag === "input" || tag === "textarea" || tag === "select" || el?.isContentEditable) return; + if (["show", "season", "info", "playlist"].includes(sub.view.kind)) { + e.preventDefault(); + sub.back(); + } + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [sub]); + const browseQ = useInfiniteQuery({ queryKey: ["plex-browse", library, dq, sort, show, filters], enabled: !!library && sub.view.kind === "grid", @@ -217,11 +251,26 @@ export default function PlexBrowse({ ); } if (sub.view.kind === "show") { + const showId = sub.view.id; return ( sub.open({ kind: "player", id: ep.id })} + onPlay={(epRk, queue) => sub.open({ kind: "player", id: epRk, queue })} + onOpenSeason={(seasonId) => sub.open({ kind: "season", showId, seasonId })} + onOpenShow={(id) => sub.open({ kind: "show", id })} + /> + ); + } + if (sub.view.kind === "season") { + const { showId, seasonId } = sub.view; + return ( + sub.open({ kind: "player", id: epRk, queue })} /> ); } @@ -477,121 +526,430 @@ function PlexInfoView({ ); } +// --- Series drill-down: show detail page → season subpage → player ------------------------------- +// Both the show page and the season page read the SAME cached ["plex-show", showId] payload (the +// season page just picks its season out of it), so opening a season is instant and PlexPlaylistAdd's +// whole-show/season gather keeps working. Actions: Resume (on-deck episode), Play (from the start), +// Mark whole show/season watched/unwatched, Add to playlist (show/season/episode), and — admin only — +// Add the whole show to a collection. + +function epLabel(ep?: PlexCard | null): string | undefined { + if (!ep) return undefined; + if (ep.season_number != null && ep.episode_number != null) return `S${ep.season_number} · E${ep.episode_number}`; + return ep.title; +} + +function BackBtn({ onBack, label }: { onBack: () => void; label: string }) { + return ( + + ); +} + +function ActionBtn({ + onClick, + icon: Icon, + label, + sub, + primary, + disabled, +}: { + onClick: () => void; + icon: LucideIcon; + label: string; + sub?: string; + primary?: boolean; + disabled?: boolean; +}) { + return ( + + ); +} + +function SeasonCard({ se, onOpen }: { se: PlexSeasonDetail; onOpen: () => void }) { + const { t } = useTranslation(); + return ( + + ); +} + +function CastStrip({ cast }: { cast: PlexCastMember[] }) { + const { t } = useTranslation(); + return ( +
+

{t("plex.info.cast")}

+
+ {cast.map((c, i) => ( +
+
+ {c.thumb ? ( + + ) : ( +
{c.name.charAt(0)}
+ )} +
+
{c.name}
+ {c.role &&
{c.role}
} +
+ ))} +
+
+ ); +} + +function RelatedStrip({ related, onOpen }: { related: PlexCard[]; onOpen: (id: string) => void }) { + const { t } = useTranslation(); + return ( +
+

{t("plex.series.related")}

+
+ {related.map((r) => ( + + ))} +
+
+ ); +} + +function EpisodeCard({ ep, onPlay, onAdd }: { ep: PlexCard; onPlay: () => void; onAdd: () => void }) { + const { t } = useTranslation(); + const inProgress = (ep.position_seconds ?? 0) > 0 && ep.status !== "watched"; + const pct = + inProgress && ep.duration_seconds + ? Math.min(100, Math.round(((ep.position_seconds ?? 0) / ep.duration_seconds) * 100)) + : 0; + return ( +
+ +
+
+
+ {ep.episode_number}. + {ep.title} +
+
{dur(ep.duration_seconds)}
+
+ +
+
+ ); +} + function PlexShowView({ showId, + library, + onBack, + onPlay, + onOpenSeason, + onOpenShow, +}: { + showId: string; + library: string; + onBack: () => void; + onPlay: (epRk: string, queue: string[]) => void; + onOpenSeason: (seasonId: string) => void; + onOpenShow: (id: string) => void; +}) { + const { t } = useTranslation(); + const qc = useQueryClient(); + const isAdmin = qc.getQueryData<{ role?: string }>(["me"])?.role === "admin"; + const q = useQuery({ queryKey: ["plex-show", showId], queryFn: () => api.plexShow(showId) }); + const d = q.data; + const [addTarget, setAddTarget] = useState(null); + const [collOpen, setCollOpen] = useState(false); + const [busy, setBusy] = useState(false); + + const show = d?.show; + const allKeys = (d?.seasons ?? []).flatMap((se) => se.episodes.map((e) => e.id)); + const watched = show?.status === "watched"; + async function markAll(w: boolean) { + setBusy(true); + try { + await api.plexShowState(showId, w); + } finally { + setBusy(false); + } + qc.invalidateQueries({ queryKey: ["plex-show", showId] }); + qc.invalidateQueries({ queryKey: ["plex-browse"] }); + } + + return ( +
+ + + {q.isLoading || !d || !show ? ( +

{t("plex.loading")}

+ ) : ( + <> + {/* Hero */} +
+ +
+

{show.title}

+
+ {show.year && {show.year}} + {show.content_rating && · {show.content_rating}} + {show.season_count != null && · {t("plex.seasons", { count: show.season_count })}} + {show.imdb_rating != null && ( + + · + {show.imdb_rating} + + )} +
+ {show.genres.length > 0 && ( +
+ {show.genres.map((g) => ( + + {g} + + ))} +
+ )} + {show.summary && ( +

{show.summary}

+ )} +
+ {show.resume && ( + onPlay(show.resume!.id, allKeys)} + icon={Play} + label={show.status === "new" ? t("plex.play") : t("plex.resume")} + sub={epLabel(show.resume)} + /> + )} + {show.first && show.status !== "new" && ( + onPlay(show.first!.id, allKeys)} icon={RotateCcw} label={t("plex.series.playFromStart")} /> + )} + markAll(!watched)} + disabled={busy} + icon={watched ? CheckCheck : Check} + label={watched ? t("plex.series.markShowUnwatched") : t("plex.series.markShowWatched")} + /> + {allKeys.length > 0 && ( + setAddTarget({ kind: "group", ratingKeys: allKeys, title: show.title })} + icon={ListPlus} + label={t("plex.playlist.addShow")} + /> + )} + {isAdmin && library && ( + setCollOpen(true)} icon={Layers} label={t("plex.series.addShowCollection")} /> + )} +
+
+
+ + {/* Seasons */} +

{t("plex.series.seasons")}

+
+ {d.seasons.map((se) => ( + onOpenSeason(se.id)} /> + ))} +
+ + {show.cast.length > 0 && } + {d.related.length > 0 && } + + )} + + {addTarget && setAddTarget(null)} />} + {collOpen && show && ( + setCollOpen(false)} + onChanged={() => qc.invalidateQueries({ queryKey: ["plex-show", showId] })} + /> + )} +
+ ); +} + +function PlexSeasonView({ + showId, + seasonId, onBack, onPlay, }: { showId: string; + seasonId: string; onBack: () => void; - onPlay: (c: PlexCard) => void; + onPlay: (epRk: string, queue: string[]) => void; }) { const { t } = useTranslation(); + const qc = useQueryClient(); const q = useQuery({ queryKey: ["plex-show", showId], queryFn: () => api.plexShow(showId) }); const d = q.data; - // "Add to playlist" dialog target (single episode / whole season / whole show); null = closed. + const se = d?.seasons.find((s) => s.id === seasonId); const [addTarget, setAddTarget] = useState(null); - const allEpisodeKeys = (d?.seasons ?? []).flatMap((se) => se.episodes.map((e) => e.id)); + const [busy, setBusy] = useState(false); + + const seasonKeys = se?.episodes.map((e) => e.id) ?? []; + const watched = se?.status === "watched"; + async function markAll(w: boolean) { + setBusy(true); + try { + await api.plexSeasonState(seasonId, w); + } finally { + setBusy(false); + } + qc.invalidateQueries({ queryKey: ["plex-show", showId] }); + qc.invalidateQueries({ queryKey: ["plex-browse"] }); + } return (
- + - {q.isLoading || !d ? ( + {q.isLoading || !d || !se ? (

{t("plex.loading")}

) : ( <> -
+
-
-

{d.show.title}

- {d.show.year &&

{d.show.year}

} - {d.show.summary && ( -

{d.show.summary}

- )} - {allEpisodeKeys.length > 0 && ( - - )} +
+

{d.show.title}

+

{se.title}

+

{t("plex.series.episodeCount", { count: se.episode_count })}

+
+ {se.resume && ( + onPlay(se.resume!.id, seasonKeys)} + icon={Play} + label={se.status === "new" ? t("plex.play") : t("plex.resume")} + sub={epLabel(se.resume)} + /> + )} + {se.first && se.status !== "new" && ( + onPlay(se.first!.id, seasonKeys)} icon={RotateCcw} label={t("plex.series.playFromStart")} /> + )} + markAll(!watched)} + disabled={busy} + icon={watched ? CheckCheck : Check} + label={watched ? t("plex.series.markSeasonUnwatched") : t("plex.series.markSeasonWatched")} + /> + {seasonKeys.length > 0 && ( + + setAddTarget({ kind: "group", ratingKeys: seasonKeys, title: `${d.show.title} — ${se.title}` }) + } + icon={ListPlus} + label={t("plex.playlist.addSeason")} + /> + )} +
- {d.seasons.map((se) => ( -
-
-

{se.title}

- {se.episodes.length > 0 && ( - - )} -
-
- {se.episodes.map((ep) => { - const inProgress = (ep.position_seconds ?? 0) > 0 && ep.status !== "watched"; - return ( -
- - -
- ); - })} -
-
- ))} +
+ {se.episodes.map((ep) => ( + onPlay(ep.id, seasonKeys)} + onAdd={() => setAddTarget({ kind: "single", ratingKey: ep.id, title: ep.title })} + /> + ))} +
)} diff --git a/frontend/src/i18n/locales/de/plex.json b/frontend/src/i18n/locales/de/plex.json index d3145c6..0debbf7 100644 --- a/frontend/src/i18n/locales/de/plex.json +++ b/frontend/src/i18n/locales/de/plex.json @@ -70,6 +70,18 @@ "markWatched": "Als gesehen markieren", "markUnwatched": "Als ungesehen markieren", "seasons": "{{count}} Staffeln", + "series": { + "seasons": "Staffeln", + "backToShow": "Zurück zur Serie", + "episodeCount": "{{count}} Folgen", + "playFromStart": "Von Anfang an", + "related": "Ähnliche Serien", + "markShowWatched": "Serie als gesehen", + "markShowUnwatched": "Serie als ungesehen", + "markSeasonWatched": "Staffel als gesehen", + "markSeasonUnwatched": "Staffel als ungesehen", + "addShowCollection": "Zur Sammlung" + }, "playerSoon": "Player kommt bald — „{{title}}“", "people": { "match": "Personen", diff --git a/frontend/src/i18n/locales/en/plex.json b/frontend/src/i18n/locales/en/plex.json index 2aef3b5..71d32d6 100644 --- a/frontend/src/i18n/locales/en/plex.json +++ b/frontend/src/i18n/locales/en/plex.json @@ -70,6 +70,18 @@ "markWatched": "Mark watched", "markUnwatched": "Mark unwatched", "seasons": "{{count}} seasons", + "series": { + "seasons": "Seasons", + "backToShow": "Back to show", + "episodeCount": "{{count}} episodes", + "playFromStart": "Play from start", + "related": "Related shows", + "markShowWatched": "Mark show watched", + "markShowUnwatched": "Mark show unwatched", + "markSeasonWatched": "Mark season watched", + "markSeasonUnwatched": "Mark season unwatched", + "addShowCollection": "Add to collection" + }, "playerSoon": "Player coming soon — “{{title}}”", "people": { "match": "People", diff --git a/frontend/src/i18n/locales/hu/plex.json b/frontend/src/i18n/locales/hu/plex.json index 9df0b51..4dc8f63 100644 --- a/frontend/src/i18n/locales/hu/plex.json +++ b/frontend/src/i18n/locales/hu/plex.json @@ -70,6 +70,18 @@ "markWatched": "Megnézettnek jelöl", "markUnwatched": "Nem-nézettnek jelöl", "seasons": "{{count}} évad", + "series": { + "seasons": "Évadok", + "backToShow": "Vissza a sorozathoz", + "episodeCount": "{{count}} rész", + "playFromStart": "Lejátszás az elejéről", + "related": "Kapcsolódó sorozatok", + "markShowWatched": "Egész sorozat megnézve", + "markShowUnwatched": "Sorozat jelölés visszavonása", + "markSeasonWatched": "Egész évad megnézve", + "markSeasonUnwatched": "Évad jelölés visszavonása", + "addShowCollection": "Kollekcióhoz adás" + }, "playerSoon": "A lejátszó hamarosan jön — „{{title}}”", "people": { "match": "Személyek", diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index ab645b3..93b2dac 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -664,10 +664,14 @@ export interface PlexBrowseResult { items: PlexCard[]; } export interface PlexSeasonDetail { - id: string; + id: string; // season rating_key season_number: number | null; title: string; thumb: string; + episode_count: number; + status: string; // aggregate: new | in_progress | watched + resume?: PlexCard | null; // on-deck episode (last in-progress, else first unwatched) + first?: PlexCard | null; // first episode (Play from the start) episodes: PlexCard[]; } export interface PlexShowDetail { @@ -678,8 +682,23 @@ export interface PlexShowDetail { year?: number | null; thumb: string; art: string; + content_rating?: string | null; + rating?: number | null; + genres: string[]; + studio?: string | null; + season_count?: number | null; + imdb_rating?: number | null; + imdb_id?: string | null; + imdb_url?: string | null; + cast: PlexCastMember[]; + status: string; // aggregate across all episodes + resume?: PlexCard | null; + first?: PlexCard | null; + episode_count: number; + collection_keys: string[]; }; seasons: PlexSeasonDetail[]; + related: PlexCard[]; } export interface PlexMarker { @@ -1230,6 +1249,11 @@ export const api = { req(`/api/plex/playlists/${id}/order`, { method: "PUT", body: JSON.stringify({ item_rating_keys: itemRks }) }), plexShow: (id: string): Promise => req(`/api/plex/show/${encodeURIComponent(id)}`), + // Mark a whole show / season watched or unwatched (all its episodes) for the current user. + plexShowState: (rk: string, watched: boolean): Promise<{ changed: number; watched: boolean }> => + req(`/api/plex/show/${encodeURIComponent(rk)}/state`, { method: "POST", body: JSON.stringify({ watched }) }), + plexSeasonState: (rk: string, watched: boolean): Promise<{ changed: number; watched: boolean }> => + req(`/api/plex/season/${encodeURIComponent(rk)}/state`, { method: "POST", body: JSON.stringify({ watched }) }), plexItem: (id: string): Promise => req(`/api/plex/item/${encodeURIComponent(id)}`), plexSession: (id: string, start = 0, audio?: number | null, aoff = 0, multi = false): Promise => { From 736db017e4387e1668eb43cfe04b1c4d239ec1ba Mon Sep 17 00:00:00 2001 From: npeter83 Date: Sat, 11 Jul 2026 00:15:49 +0200 Subject: [PATCH 03/12] feat(plex): unify movies + shows into one cross-library browser MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Collapse the separate Movie/Show library sections into ONE unified library with a shared search + shared filter sidebar and a Movies/Shows/Both scope selector. Backend: new GET /api/plex/library — a cross-library UNION of movies (plex_items) and shows (plex_shows) as one mixed, paginated, sorted feed, scoped movie|show|both, with the shared filters (extracted into _apply_meta_filters, DRY), FTS search, and per-user watch-state (a show's state = the aggregate of its episodes). On a search that also matches episodes, matching episodes come back in a separate 'episodes' list (the grouped 'Episodes' section — Proposal 3). /facets is now scope-aware (merged across the scope's libraries). /item and /show now return their library section key (for the admin collection editor, since there's no single library prop in the unified view). Frontend: PlexSidebar's library picker -> a scope selector (Both/Movies/Shows); facets + browse follow the scope (App's plexLib repurposed to a validated scope, default both). PlexBrowse uses the unified endpoint, renders a mixed Titles grid + an Episodes section on search. Poster cards are generalized: a hover Play/Resume overlay on every card, a clickable title (not just the poster), and a movie/show type tag. The quick watched toggle is now optimistic so it reliably flips BOTH ways (fixes the movie card that could mark but not un-mark). Cast/crew members and the show hero's meta (year/rating/genre/ content-rating) are clickable filters; clicking a person widens the scope to Both so the result is a mixed movie+show feed. i18n plex.filter.scope*/plex.unified.* (en/hu/de). Still pending from the polish list (next pass): season-card quick toggles (watched + add-to-playlist), per-episode watched toggle, and the full glassy art-bg + hide-cast customize menu on the series pages. --- backend/app/routes/plex.py | 321 ++++++++++++++++++--- frontend/src/App.tsx | 12 +- frontend/src/components/PlexBrowse.tsx | 353 ++++++++++++++---------- frontend/src/components/PlexInfo.tsx | 2 +- frontend/src/components/PlexSidebar.tsx | 104 +++---- frontend/src/i18n/locales/de/plex.json | 10 + frontend/src/i18n/locales/en/plex.json | 10 + frontend/src/i18n/locales/hu/plex.json | 10 + frontend/src/lib/api.ts | 26 +- 9 files changed, 579 insertions(+), 269 deletions(-) diff --git a/backend/app/routes/plex.py b/backend/app/routes/plex.py index e90ef1c..aeba013 100644 --- a/backend/app/routes/plex.py +++ b/backend/app/routes/plex.py @@ -18,7 +18,7 @@ from urllib.parse import quote import httpx from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Request, Response from fastapi.responses import FileResponse -from sqlalchemy import and_, case, func, or_, text +from sqlalchemy import Integer, String, and_, case, cast, func, literal, null, or_, text from sqlalchemy.orm import Session, aliased from app import sysconfig @@ -301,6 +301,15 @@ def _show_state_map(db: Session, user_id: int, show_ids: list[int]) -> dict[int, return {r.show_id: _show_status(r.total, r.watched, r.inprog) for r in rows} +def _lib_key(db: Session, library_id: int | None) -> str | None: + """The Plex section key for a library id — the info/show page passes it to the admin collection + editor (in the unified cross-library view there's no single library prop otherwise).""" + if library_id is None: + return None + lib = db.get(PlexLibrary, library_id) + return lib.plex_key if lib else None + + def _episode_card(e: PlexItem, st: PlexState | None) -> dict: return { "id": e.rating_key, @@ -342,6 +351,38 @@ def _added_cutoff(within: str | None) -> datetime | None: return datetime.now(timezone.utc) - timedelta(days=days) if days else None +def _apply_meta_filters(q, model, p: dict): + """Apply the shared metadata filters (identical column names on plex_items + plex_shows) to a + query over `model`. `p` is the request's filter params dict. Duration is movie-only, applied by + the caller. Kept DRY so movies, shows, and the unified cross-library browse filter identically.""" + gsel = _csv(p.get("genres")) + if gsel: + conds = [model.genres.contains([g]) for g in gsel] + q = q.filter(and_(*conds) if p.get("genre_mode") == "all" else or_(*conds)) + crs = _csv(p.get("content_ratings")) + if crs: + q = q.filter(model.content_rating.in_(crs)) + if p.get("year_min") is not None: + q = q.filter(model.year >= p["year_min"]) + if p.get("year_max") is not None: + q = q.filter(model.year <= p["year_max"]) + if p.get("rating_min") is not None: + q = q.filter(model.rating >= p["rating_min"]) + cutoff = _added_cutoff(p.get("added_within")) + if cutoff is not None: + q = q.filter(model.added_at >= cutoff) + for d in _csv(p.get("directors")): # AND + q = q.filter(model.directors.contains([d])) + for a in _csv(p.get("actors")): # AND + q = q.filter(model.cast_names.contains([a])) + stds = _csv(p.get("studios")) + if stds: # OR + q = q.filter(model.studio.in_(stds)) + if p.get("collection"): + q = q.filter(model.collection_keys.contains([p["collection"]])) + return q + + @router.get("/browse") def browse( library: str, @@ -507,15 +548,201 @@ def browse( return {"kind": lib.kind, "total": total, "offset": offset, "limit": limit, "items": items} -@router.get("/facets") -def facets( - library: str, +@router.get("/library") +def unified_library( + scope: str = "both", + q: str | None = None, + sort: str = "added", + sort_dir: str = "desc", + show: str = "all", + offset: int = 0, + limit: int = Query(default=40, ge=1, le=100), + genres: str | None = None, + genre_mode: str = "any", + content_ratings: str | None = None, + year_min: int | None = None, + year_max: int | None = None, + rating_min: float | None = None, + duration_min: int | None = None, + duration_max: int | None = None, + added_within: str | None = None, + directors: str | None = None, + actors: str | None = None, + studios: str | None = None, + collection: str | None = None, user: User = Depends(current_user), db: Session = Depends(get_db), ) -> dict: - """Available filter values for a movie OR show library — genres + content ratings (with counts) - and the year/rating[/duration] bounds — so the sidebar only offers what the library contains. - Shows carry the same filterable metadata as movies now (0052), minus duration.""" + """Unified cross-library browse: movies + shows in ONE mixed, paginated feed, scoped to + movie|show|both, with the shared filters/search/watch-state (a show's state is the aggregate of + its episodes). On a search that also matches episodes (and shows are in scope), the matching + episodes come back in a separate `episodes` list (grouped result — the 'Episodes' section).""" + offset = max(0, offset) + p = { + "genres": genres, "genre_mode": genre_mode, "content_ratings": content_ratings, + "year_min": year_min, "year_max": year_max, "rating_min": rating_min, + "added_within": added_within, "directors": directors, "actors": actors, + "studios": studios, "collection": collection, + } + libs = db.query(PlexLibrary).filter_by(enabled=True).all() + movie_lib_ids = [lb.id for lb in libs if lb.kind == "movie"] + show_lib_ids = [lb.id for lb in libs if lb.kind == "show"] + want_movies = scope in ("movie", "both") and bool(movie_lib_ids) + want_shows = scope in ("show", "both") and bool(show_lib_ids) + + ts = _to_tsquery_str(q) if q else None + tsq = func.to_tsquery(_TS_CONFIG, ts) if ts else None + + selects = [] + if want_movies: + st = aliased(PlexState) + m_status = case( + (st.status == "watched", "watched"), + (and_(st.position_seconds > 0, or_(st.status.is_(None), st.status != "watched")), "in_progress"), + else_="new", + ) + mq = ( + db.query( + PlexItem.rating_key.label("rk"), + literal("movie").label("kind"), + PlexItem.title.label("title"), + PlexItem.year.label("year"), + PlexItem.rating.label("rating"), + PlexItem.added_at.label("added_at"), + PlexItem.originally_available_at.label("rel"), + PlexItem.duration_s.label("duration_s"), + PlexItem.playable.label("playable"), + cast(null(), Integer).label("season_count"), + func.coalesce(st.position_seconds, 0).label("position_seconds"), + m_status.label("status"), + (func.ts_rank(PlexItem.search_vector, tsq) if tsq is not None else literal(0.0)).label("rank"), + ) + .outerjoin(st, and_(st.item_id == PlexItem.id, st.user_id == user.id)) + .filter(PlexItem.kind == "movie", PlexItem.library_id.in_(movie_lib_ids)) + ) + if show == "watched": + mq = mq.filter(st.status == "watched") + elif show == "in_progress": + mq = mq.filter(st.position_seconds > 0, or_(st.status.is_(None), st.status != "watched")) + elif show == "unwatched": + mq = mq.filter(or_(st.status.is_(None), st.status.notin_(["watched", "hidden"]))) + else: + mq = mq.filter(or_(st.status.is_(None), st.status != "hidden")) + mq = _apply_meta_filters(mq, PlexItem, p) + if duration_min is not None: + mq = mq.filter(PlexItem.duration_s >= duration_min) + if duration_max is not None: + mq = mq.filter(PlexItem.duration_s <= duration_max) + if tsq is not None: + mq = mq.filter(PlexItem.search_vector.op("@@")(tsq)) + selects.append(mq) + if want_shows: + agg = _show_agg_subq(db, user.id).subquery() + tot = func.coalesce(agg.c.total, 0) + wat = func.coalesce(agg.c.watched, 0) + inp = func.coalesce(agg.c.inprog, 0) + s_status = case( + (and_(tot > 0, wat >= tot), "watched"), + (or_(wat > 0, inp > 0), "in_progress"), + else_="new", + ) + sq = ( + db.query( + PlexShow.rating_key.label("rk"), + literal("show").label("kind"), + PlexShow.title.label("title"), + PlexShow.year.label("year"), + PlexShow.rating.label("rating"), + PlexShow.added_at.label("added_at"), + PlexShow.originally_available_at.label("rel"), + cast(null(), Integer).label("duration_s"), + cast(null(), String).label("playable"), + PlexShow.child_count.label("season_count"), + literal(0).label("position_seconds"), + s_status.label("status"), + (func.ts_rank(PlexShow.search_vector, tsq) if tsq is not None else literal(0.0)).label("rank"), + ) + .outerjoin(agg, agg.c.show_id == PlexShow.id) + .filter(PlexShow.library_id.in_(show_lib_ids)) + ) + if show == "watched": + sq = sq.filter(tot > 0, wat >= tot) + elif show == "in_progress": + sq = sq.filter(or_(wat > 0, inp > 0), wat < tot) + elif show == "unwatched": + sq = sq.filter(wat == 0, inp == 0) + sq = _apply_meta_filters(sq, PlexShow, p) + if tsq is not None: + sq = sq.filter(PlexShow.search_vector.op("@@")(tsq)) + selects.append(sq) + + if not selects: + return {"scope": scope, "total": 0, "offset": offset, "limit": limit, "items": [], "episodes": []} + union = selects[0] if len(selects) == 1 else selects[0].union_all(*selects[1:]) + u = union.subquery() + total = db.query(func.count()).select_from(u).scalar() or 0 + + if tsq is not None: + order = [u.c.rank.desc()] + else: + col = { + "title": func.lower(u.c.title), + "year": u.c.year, + "rating": u.c.rating, + "duration": u.c.duration_s, + "release": u.c.rel, + }.get(sort, u.c.added_at) + order = [(col.asc() if sort_dir == "asc" else col.desc()).nullslast()] + order.append(u.c.rk.desc()) + rows = db.query(u).order_by(*order).offset(offset).limit(limit).all() + + items = [] + for r in rows: + if r.kind == "movie": + items.append({ + "id": r.rk, "type": "movie", "title": r.title, "year": r.year, + "duration_seconds": r.duration_s, "thumb": f"/api/plex/image/{r.rk}", + "playable": r.playable, "status": r.status, "position_seconds": r.position_seconds, + }) + else: + items.append({ + "id": r.rk, "type": "show", "title": r.title, "year": r.year, + "thumb": f"/api/plex/image/{r.rk}", "season_count": r.season_count, "status": r.status, + }) + + episodes = [] + if tsq is not None and want_shows: + ep_st = aliased(PlexState) + eps = ( + db.query(PlexItem, ep_st, PlexShow.title.label("show_title")) + .outerjoin(ep_st, and_(ep_st.item_id == PlexItem.id, ep_st.user_id == user.id)) + .outerjoin(PlexShow, PlexShow.id == PlexItem.show_id) + .filter( + PlexItem.kind == "episode", + PlexItem.library_id.in_(show_lib_ids), + PlexItem.search_vector.op("@@")(tsq), + ) + .order_by(func.ts_rank(PlexItem.search_vector, tsq).desc()) + .limit(24) + .all() + ) + for e, s, show_title in eps: + card = _episode_card(e, s) + card["show_title"] = show_title + episodes.append(card) + + return {"scope": scope, "total": total, "offset": offset, "limit": limit, "items": items, "episodes": episodes} + + +@router.get("/facets") +def facets( + scope: str = "both", + user: User = Depends(current_user), + db: Session = Depends(get_db), +) -> dict: + """Available filter values for the unified library, scoped to movie|show|both: genres + content + ratings (with counts merged across the scope's libraries) and the year/rating/duration bounds, so + the sidebar only offers what the scope actually contains. Duration bounds are movie-only.""" empty = { "genres": [], "content_ratings": [], @@ -525,38 +752,56 @@ def facets( "duration_min": None, "duration_max": None, } - lib = db.query(PlexLibrary).filter_by(plex_key=str(library)).first() - if lib is None: + libs = db.query(PlexLibrary).filter_by(enabled=True).all() + movie_ids = [lb.id for lb in libs if lb.kind == "movie"] if scope in ("movie", "both") else [] + show_ids = [lb.id for lb in libs if lb.kind == "show"] if scope in ("show", "both") else [] + if not movie_ids and not show_ids: return empty - if lib.kind == "movie": - base = "FROM plex_items WHERE library_id = :lib AND kind = 'movie'" - dur_sel = "min(duration_s), max(duration_s)" - else: # show library — same columns on plex_shows, no per-row duration - base = "FROM plex_shows WHERE library_id = :lib" - dur_sel = "NULL, NULL" - genres = db.execute( - text( - f"SELECT g, count(*) AS c FROM (SELECT jsonb_array_elements_text(genres) AS g {base}) x " - "GROUP BY g ORDER BY c DESC, g" - ), - {"lib": lib.id}, - ).all() - crs = db.execute( - text(f"SELECT content_rating, count(*) AS c {base} AND content_rating IS NOT NULL GROUP BY content_rating ORDER BY c DESC"), - {"lib": lib.id}, - ).all() - b = db.execute( - text(f"SELECT min(year), max(year), max(rating), {dur_sel} {base}"), - {"lib": lib.id}, - ).first() + + genre_counts: dict[str, int] = {} + cr_counts: dict[str, int] = {} + years: list[int] = [] + ratings: list[float] = [] + durs: list[int] = [] + + def collect(table: str, ids: list[int], with_dur: bool) -> None: + if not ids: + return + base = f"FROM {table} WHERE library_id = ANY(:ids)" + for g, c in db.execute( + text(f"SELECT g, count(*) c FROM (SELECT jsonb_array_elements_text(genres) g {base}) x GROUP BY g"), + {"ids": ids}, + ).all(): + genre_counts[g] = genre_counts.get(g, 0) + c + for cr, c in db.execute( + text(f"SELECT content_rating, count(*) c {base} AND content_rating IS NOT NULL GROUP BY content_rating"), + {"ids": ids}, + ).all(): + cr_counts[cr] = cr_counts.get(cr, 0) + c + dur_sel = ", min(duration_s), max(duration_s)" if with_dur else "" + b = db.execute(text(f"SELECT min(year), max(year), max(rating){dur_sel} {base}"), {"ids": ids}).first() + if b[0] is not None: + years.append(b[0]) + if b[1] is not None: + years.append(b[1]) + if b[2] is not None: + ratings.append(float(b[2])) + if with_dur: + if b[3] is not None: + durs.append(b[3]) + if b[4] is not None: + durs.append(b[4]) + + collect("plex_items", movie_ids, with_dur=True) + collect("plex_shows", show_ids, with_dur=False) return { - "genres": [{"value": g, "count": c} for g, c in genres], - "content_ratings": [{"value": cr, "count": c} for cr, c in crs], - "year_min": b[0], - "year_max": b[1], - "rating_max": float(b[2]) if b[2] is not None else None, - "duration_min": b[3], - "duration_max": b[4], + "genres": [{"value": g, "count": c} for g, c in sorted(genre_counts.items(), key=lambda kv: (-kv[1], kv[0]))], + "content_ratings": [{"value": cr, "count": c} for cr, c in sorted(cr_counts.items(), key=lambda kv: -kv[1])], + "year_min": min(years) if years else None, + "year_max": max(years) if years else None, + "rating_max": max(ratings) if ratings else None, + "duration_min": min(durs) if durs else None, + "duration_max": max(durs) if durs else None, } @@ -1079,6 +1324,7 @@ def show_detail( "year": sh.year, "thumb": f"/api/plex/image/{sh.rating_key}", "art": f"/api/plex/image/{sh.rating_key}?variant=art", + "library": _lib_key(db, sh.library_id), "content_rating": sh.content_rating, "rating": sh.rating, "genres": sh.genres or [], @@ -1636,6 +1882,7 @@ def item_detail( "playable": it.playable, "thumb": f"/api/plex/image/{it.rating_key}", "art": f"/api/plex/image/{it.rating_key}?variant=art", + "library": _lib_key(db, it.library_id), "cast": rich.get("cast", []), "imdb_rating": rich.get("imdb_rating"), "imdb_id": rich.get("imdb_id"), diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 0a573e6..70297ba 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -246,7 +246,10 @@ export default function App() { const channelsView: ChannelsView = channelsViewRaw === "discovery" ? "discovery" : "subscribed"; // Plex module filters (its own left-sidebar filter section) — per-account persisted. - const [plexLib, setPlexLib] = useAccountPersistedState(LS.plexLibrary, ""); + // The former per-library picker is now a cross-library SCOPE: movie | show | both (unified library). + // (Reuses the old LS.plexLibrary key; an old stored library-id value falls back to "both".) + const [plexScopeRaw, setPlexScope] = useAccountPersistedState(LS.plexLibrary, "both"); + const plexScope = ["movie", "show", "both"].includes(plexScopeRaw) ? plexScopeRaw : "both"; const [plexShowFilter, setPlexShowFilter] = useAccountPersistedState(LS.plexShow, "all"); const [plexSort, setPlexSort] = useAccountPersistedState(LS.plexSort, "added"); const [plexPlaylistOpen, setPlexPlaylistOpen] = useState(null); // sidebar → open a playlist @@ -740,8 +743,8 @@ export default function App() { {page === "plex" && meQuery.data!.plex_enabled && ( setPlexQ("")} - library={plexLib} + scope={plexScope} + setScope={setPlexScope} show={plexShowFilter} sort={plexSort} filters={plexFilters} diff --git a/frontend/src/components/PlexBrowse.tsx b/frontend/src/components/PlexBrowse.tsx index f859d0b..46dee7e 100644 --- a/frontend/src/components/PlexBrowse.tsx +++ b/frontend/src/components/PlexBrowse.tsx @@ -1,17 +1,19 @@ -import { lazy, Suspense, useEffect, useLayoutEffect, useRef, useState, type CSSProperties } from "react"; +import { lazy, Suspense, useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode } from "react"; import { useTranslation } from "react-i18next"; -import { useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query"; +import { useInfiniteQuery, useQuery, useQueryClient, type InfiniteData } from "@tanstack/react-query"; import { ArrowLeft, Check, CheckCheck, CheckCircle2, + Film, Info, Layers, ListPlus, Play, RotateCcw, Star, + Tv2, type LucideIcon, } from "lucide-react"; import { @@ -21,8 +23,8 @@ import { type PlexCard, type PlexCastMember, type PlexFilters, - type PlexPerson, type PlexSeasonDetail, + type PlexUnifiedResult, } from "../lib/api"; import { useDebounced } from "../lib/useDebounced"; import { useHistorySubview } from "../lib/history"; @@ -51,7 +53,8 @@ type Sub = type Props = { q: string; onClearSearch: () => void; - library: string; + scope: string; // movie | show | both (unified cross-library scope) + setScope: (v: string) => void; show: string; sort: string; filters: PlexFilters; @@ -73,7 +76,8 @@ function dur(n?: number | null): string { export default function PlexBrowse({ q, onClearSearch, - library, + scope, + setScope, show, sort, filters, @@ -133,12 +137,12 @@ export default function PlexBrowse({ }, [sub]); const browseQ = useInfiniteQuery({ - queryKey: ["plex-browse", library, dq, sort, show, filters], - enabled: !!library && sub.view.kind === "grid", + queryKey: ["plex-library", scope, dq, sort, show, filters], + enabled: !!scope && sub.view.kind === "grid", initialPageParam: 0, queryFn: ({ pageParam }) => - api.plexBrowse({ - library, + api.plexLibrary({ + scope, q: dq || undefined, sort, show, @@ -154,21 +158,8 @@ export default function PlexBrowse({ const items = browseQ.data?.pages.flatMap((p) => p.items) ?? []; const total = browseQ.data?.pages[0]?.total ?? 0; - - // Cast/crew whose name matches the current search → virtual cards above the grid; clicking one - // adds that person to the filter. Only meaningful for movie libraries (the endpoint returns [] else). - const peopleQ = useQuery({ - queryKey: ["plex-people", library, dq], - queryFn: () => api.plexPeople(library, dq), - enabled: !!library && dq.length >= 2 && sub.view.kind === "grid", - }); - const people = peopleQ.data?.people ?? []; - function addPerson(p: PlexPerson) { - const key = p.kind === "director" ? "directors" : "actors"; - const cur = filters[key]; - if (!cur.includes(p.name)) setFilters({ ...filters, [key]: [...cur, p.name] }); - onClearSearch(); // switch from the name search to the person filter (clears the search box) - } + // Episode matches (grouped "Episodes" section) — search-only; same set on every page, take page 0. + const episodes = browseQ.data?.pages[0]?.episodes ?? []; // Infinite scroll: auto-load the next page when the sentinel scrolls into view. const sentinel = useRef(null); @@ -197,8 +188,40 @@ export default function PlexBrowse({ sub.open({ kind: "info", id: card.id }); } async function toggleWatched(card: PlexCard) { - await api.plexSetState(card.id, card.status === "watched" ? "new" : "watched"); - qc.invalidateQueries({ queryKey: ["plex-browse"] }); + const next = card.status === "watched" ? "new" : "watched"; + // Optimistically flip the card in every cached library page so the quick toggle reacts instantly + // and reliably BOTH ways (mark and un-mark), then reconcile with the server. + qc.setQueriesData>({ queryKey: ["plex-library"] }, (old) => + old + ? { + ...old, + pages: old.pages.map((pg) => ({ + ...pg, + items: pg.items.map((it) => (it.id === card.id ? { ...it, status: next } : it)), + })), + } + : old, + ); + await api.plexSetState(card.id, next).catch(() => {}); + qc.invalidateQueries({ queryKey: ["plex-library"] }); + } + // Apply a metadata filter (clicked on an info page / show hero / cast) then show the unified grid. + // Array filters (genres/people/studios) UNION with what's set; scalars replace. Clicking a person + // (cast/crew) widens to the 'both' scope so their movies AND shows show up together (mixed feed). + function applyFilter(patch: Partial) { + const merged = { ...filters } as unknown as Record; + for (const [k, v] of Object.entries(patch)) { + const cur = merged[k]; + if (Array.isArray(v) && Array.isArray(cur)) { + merged[k] = Array.from(new Set([...(cur as unknown[]), ...(v as unknown[])])); + } else { + merged[k] = v; + } + } + setFilters(merged as unknown as PlexFilters); + if (patch.actors?.length || patch.directors?.length) setScope("both"); + infoScrollRef.current = scroller()?.scrollTop ?? 0; // restore on Back to the info/show page + sub.open({ kind: "grid" }); } if (sub.view.kind === "player") { @@ -225,28 +248,10 @@ export default function PlexBrowse({ return ( sub.open({ kind: "player", id: infoId })} onPlayItem={(id) => sub.open({ kind: "player", id })} - onFilter={(patch) => { - // Clicking a metadata chip sets that filter and shows the filtered grid. Array filters - // (genres/people/studios) UNION with what's already set (so you can stack people); scalars - // replace. We push a fresh grid entry (not history.back) so browser Back returns to this - // info page instead of leaving the Plex module. - const merged = { ...filters } as unknown as Record; - for (const [k, v] of Object.entries(patch)) { - const cur = merged[k]; - if (Array.isArray(v) && Array.isArray(cur)) { - merged[k] = Array.from(new Set([...(cur as unknown[]), ...(v as unknown[])])); - } else { - merged[k] = v; - } - } - setFilters(merged as unknown as PlexFilters); - infoScrollRef.current = scroller()?.scrollTop ?? 0; // restore on Back to this info page - sub.open({ kind: "grid" }); - }} + onFilter={applyFilter} /> ); } @@ -255,11 +260,11 @@ export default function PlexBrowse({ return ( sub.open({ kind: "player", id: epRk, queue })} onOpenSeason={(seasonId) => sub.open({ kind: "season", showId, seasonId })} onOpenShow={(id) => sub.open({ kind: "show", id })} + onFilter={applyFilter} /> ); } @@ -281,48 +286,9 @@ export default function PlexBrowse({ {browseQ.isLoading ? " " : dq ? t("plex.searchCount", { count: total }) : t("plex.count", { count: total })}

- {/* Virtual person cards for a name search — click to add them to the filter. */} - {people.length > 0 && ( -
-

{t("plex.people.match")}

-
- {people.map((p) => { - const added = (p.kind === "director" ? filters.directors : filters.actors).includes(p.name); - return ( - - ); - })} -
-
- )} - {browseQ.isLoading ? (

{t("plex.loading")}

- ) : items.length === 0 ? ( + ) : items.length === 0 && episodes.length === 0 ? ( dq && plexFilterCount(filters) > 0 ? ( // A search that comes up empty WHILE filters are active is usually the filters, not the // query — say so and offer a one-click escape, instead of a bare "No matches". @@ -339,17 +305,38 @@ export default function PlexBrowse({

{dq ? t("plex.noMatches") : t("plex.empty")}

) ) : ( -
- {items.map((c) => ( - onCard(c)} - onInfo={() => onInfo(c)} - onToggleWatched={toggleWatched} - /> - ))} -
+ <> + {/* Titles grid — movies + shows mixed (visually tagged). */} + {items.length > 0 && ( + <> + {episodes.length > 0 && ( +

{t("plex.unified.titles")}

+ )} +
+ {items.map((c) => ( + onCard(c)} + onInfo={() => onInfo(c)} + onToggleWatched={toggleWatched} + /> + ))} +
+ + )} + {/* Episodes section (Proposal 3) — matching episodes on a search, kept out of the title grid. */} + {episodes.length > 0 && ( +
+

{t("plex.unified.episodes")}

+
+ {episodes.map((ep) => ( + onCard(ep)} /> + ))} +
+
+ )} + )}
@@ -407,16 +394,14 @@ function PlexPosterCard({ decoding="async" className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-200" /> - {/* Hover affordance: what a click does (play / resume / open show). */} + {/* Hover affordance: a play overlay on every card (movies/episodes play; a show opens). */}
- {isPlayable ? ( -
- - {inProgress ? t("plex.resume") : t("plex.play")} -
- ) : ( - {t("plex.openShow")} - )} +
+ + + {card.type === "show" ? t("plex.openShow") : inProgress ? t("plex.resume") : t("plex.play")} + +
{/* Quick watched toggle (movies/episodes), on hover. */} {isPlayable && ( @@ -467,13 +452,25 @@ function PlexPosterCard({ title={t(`plex.playable.${card.playable}`)} /> )} + {/* Type tag — tell a movie card from a show card at a glance (unified feed). */} + + {card.type === "show" ? : } + {pct > 0 && (
)}
-
{card.title}
+
+ {card.title} +
{[card.year, dur(card.duration_seconds)].filter(Boolean).join(" · ")}
); @@ -481,14 +478,12 @@ function PlexPosterCard({ function PlexInfoView({ id, - library, onBack, onPlay, onPlayItem, onFilter, }: { id: string; - library: string; onBack: () => void; onPlay: () => void; onPlayItem: (id: string) => void; @@ -514,7 +509,7 @@ function PlexInfoView({ void; className?: string; children: ReactNode }) { + if (!onClick) return {children}; + return ( + + ); +} + function BackBtn({ onBack, label }: { onBack: () => void; label: string }) { return ( + ) : ( +
+ {inner}
-
{c.name}
- {c.role &&
{c.role}
} -
- ))} + ); + })}
); @@ -666,7 +689,17 @@ function RelatedStrip({ related, onOpen }: { related: PlexCard[]; onOpen: (id: s ); } -function EpisodeCard({ ep, onPlay, onAdd }: { ep: PlexCard; onPlay: () => void; onAdd: () => void }) { +function EpisodeCard({ + ep, + onPlay, + onAdd, + withShowTitle, +}: { + ep: PlexCard; + onPlay: () => void; + onAdd?: () => void; + withShowTitle?: boolean; +}) { const { t } = useTranslation(); const inProgress = (ep.position_seconds ?? 0) > 0 && ep.status !== "watched"; const pct = @@ -701,20 +734,30 @@ function EpisodeCard({ ep, onPlay, onAdd }: { ep: PlexCard; onPlay: () => void;
+ {withShowTitle && ep.show_title && ( +
+ {ep.show_title} + {ep.season_number != null && ep.episode_number != null + ? ` · S${ep.season_number}·E${ep.episode_number}` + : ""} +
+ )}
- {ep.episode_number}. + {!withShowTitle && {ep.episode_number}.} {ep.title}
{dur(ep.duration_seconds)}
- + {onAdd && ( + + )}
); @@ -722,18 +765,18 @@ function EpisodeCard({ ep, onPlay, onAdd }: { ep: PlexCard; onPlay: () => void; function PlexShowView({ showId, - library, onBack, onPlay, onOpenSeason, onOpenShow, + onFilter, }: { showId: string; - library: string; onBack: () => void; onPlay: (epRk: string, queue: string[]) => void; onOpenSeason: (seasonId: string) => void; onOpenShow: (id: string) => void; + onFilter?: (patch: Partial) => void; }) { const { t } = useTranslation(); const qc = useQueryClient(); @@ -745,6 +788,7 @@ function PlexShowView({ const [busy, setBusy] = useState(false); const show = d?.show; + const showLib = show?.library ?? undefined; const allKeys = (d?.seasons ?? []).flatMap((se) => se.episodes.map((e) => e.id)); const watched = show?.status === "watched"; async function markAll(w: boolean) { @@ -755,7 +799,7 @@ function PlexShowView({ setBusy(false); } qc.invalidateQueries({ queryKey: ["plex-show", showId] }); - qc.invalidateQueries({ queryKey: ["plex-browse"] }); + qc.invalidateQueries({ queryKey: ["plex-library"] }); } return ( @@ -776,22 +820,37 @@ function PlexShowView({

{show.title}

- {show.year && {show.year}} - {show.content_rating && · {show.content_rating}} + {show.year != null && ( + onFilter({ yearMin: show.year, yearMax: show.year }) : undefined}> + {show.year} + + )} + {show.content_rating && ( + onFilter({ contentRatings: [show.content_rating!] }) : undefined}> + · {show.content_rating} + + )} {show.season_count != null && · {t("plex.seasons", { count: show.season_count })}} {show.imdb_rating != null && ( - + )}
{show.genres.length > 0 && (
{show.genres.map((g) => ( - + onFilter({ genres: [g] }) : undefined} + > {g} - + ))}
)} @@ -824,7 +883,7 @@ function PlexShowView({ label={t("plex.playlist.addShow")} /> )} - {isAdmin && library && ( + {isAdmin && showLib && ( setCollOpen(true)} icon={Layers} label={t("plex.series.addShowCollection")} /> )}
@@ -839,16 +898,16 @@ function PlexShowView({ ))} - {show.cast.length > 0 && } + {show.cast.length > 0 && } {d.related.length > 0 && } )} {addTarget && setAddTarget(null)} />} - {collOpen && show && ( + {collOpen && show && showLib && ( setCollOpen(false)} onChanged={() => qc.invalidateQueries({ queryKey: ["plex-show", showId] })} @@ -887,7 +946,7 @@ function PlexSeasonView({ setBusy(false); } qc.invalidateQueries({ queryKey: ["plex-show", showId] }); - qc.invalidateQueries({ queryKey: ["plex-browse"] }); + qc.invalidateQueries({ queryKey: ["plex-library"] }); } return ( diff --git a/frontend/src/components/PlexInfo.tsx b/frontend/src/components/PlexInfo.tsx index 248a8e8..8ae5878 100644 --- a/frontend/src/components/PlexInfo.tsx +++ b/frontend/src/components/PlexInfo.tsx @@ -143,7 +143,7 @@ export default function PlexInfo({ const setState = async (status: "new" | "watched") => { await api.plexSetState(detail.id, status).catch(() => {}); qc.invalidateQueries({ queryKey: ["plex-item", detail.id] }); - qc.invalidateQueries({ queryKey: ["plex-browse"] }); + qc.invalidateQueries({ queryKey: ["plex-library"] }); qc.invalidateQueries({ queryKey: ["plex-show"] }); onStateChange?.(); }; diff --git a/frontend/src/components/PlexSidebar.tsx b/frontend/src/components/PlexSidebar.tsx index a1333fe..f39a467 100644 --- a/frontend/src/components/PlexSidebar.tsx +++ b/frontend/src/components/PlexSidebar.tsx @@ -1,9 +1,8 @@ -import { useEffect, useState, type ReactNode } from "react"; +import { useState, type ReactNode } from "react"; import { useTranslation } from "react-i18next"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { ChevronRight, Film, Layers, ListMusic, Plus, SlidersHorizontal, Tv2, X } from "lucide-react"; import { api, EMPTY_PLEX_FILTERS, plexFilterCount, type PlexFilters } from "../lib/api"; -import { useDebounced } from "../lib/useDebounced"; // The Plex module's left filter column (mirrors the feed Sidebar's shell). Movie libraries get the // full metadata filter set (genre / rating / year / duration / added / content rating + the @@ -12,8 +11,8 @@ import { useDebounced } from "../lib/useDebounced"; // backend so the sidebar only offers what the library actually contains. type Props = { - library: string; - setLibrary: (v: string) => void; + scope: string; // movie | show | both (unified cross-library scope) + setScope: (v: string) => void; show: string; setShow: (v: string) => void; sort: string; @@ -39,8 +38,8 @@ const DURATION_BUCKETS: { key: string; min: number | null; max: number | null }[ ]; export default function PlexSidebar({ - library, - setLibrary, + scope, + setScope, show, setShow, sort, @@ -52,7 +51,6 @@ export default function PlexSidebar({ onToggleCollapse, }: Props) { const { t } = useTranslation(); - const libsQ = useQuery({ queryKey: ["plex-libraries"], queryFn: api.plexLibraries }); const playlistsQ = useQuery({ queryKey: ["plex-playlists"], queryFn: () => api.plexPlaylists() }); const [newPlaylist, setNewPlaylist] = useState(""); const qc = useQueryClient(); @@ -64,33 +62,17 @@ export default function PlexSidebar({ qc.invalidateQueries({ queryKey: ["plex-playlists"] }); onOpenPlaylist(pl.id); } - const libs = libsQ.data?.libraries ?? []; - const activeLib = libs.find((l) => l.key === library); - const isMovieLib = activeLib?.kind === "movie"; - + // Facet values (genres/ratings/bounds) for the current cross-library scope (movie|show|both). const facetsQ = useQuery({ - queryKey: ["plex-facets", library], - queryFn: () => api.plexFacets(library), - enabled: !!library, // facets now come for movie AND show libraries (0052) + queryKey: ["plex-facets", scope], + queryFn: () => api.plexFacets(scope), + enabled: !!scope, }); const facets = facetsQ.data; - // Collections picker (searchable; the list is only fetched when none is active). - const [collSearch, setCollSearch] = useState(""); - const collSearchDeb = useDebounced(collSearch.trim(), 300); - const collectionsQ = useQuery({ - queryKey: ["plex-collections", library, collSearchDeb], - queryFn: () => api.plexCollections(library, collSearchDeb || undefined), - enabled: !!library && !filters.collection, // collections apply to shows too - }); - const collections = collectionsQ.data?.collections ?? []; - - // Default to the first library once loaded (or if the stored one vanished). - useEffect(() => { - if (libs.length && !libs.some((l) => l.key === library)) setLibrary(libs[0].key); - }, [libs, library, setLibrary]); - - const fCount = plexFilterCount(filters); // shows carry the same filters now (0052) + // (Collection filtering: the active-collection chip is set from an item info page's "Browse + // collection"; there's no per-library picker in the unified cross-library scope.) + const fCount = plexFilterCount(filters); const activeCount = fCount + (show !== "all" ? 1 : 0) + (sort !== "added" ? 1 : 0); const anyActive = activeCount > 0; @@ -103,7 +85,8 @@ export default function PlexSidebar({ setSort("added"); }; - const sorts = isMovieLib ? MOVIE_SORTS : SHOW_SORTS; + // Movie-only scope offers the duration sort; mixed/show scopes drop it (a show has no runtime). + const sorts = scope === "movie" ? MOVIE_SORTS : SHOW_SORTS; const durBucketKey = DURATION_BUCKETS.find( (b) => (filters.durationMin ?? null) === b.min && (filters.durationMax ?? null) === b.max, )?.key; @@ -137,20 +120,19 @@ export default function PlexSidebar({ return (