refactor: address code-review — layering + public API naming

Applies the three findings from the /code-review high pass on this stack:

1. to_tsquery_str moved from app.feedquery to app.utils — it's a generic
   tsquery sanitizer with no feed dependency; housing it in the feed
   read-model coupled the Plex browse module to the feed domain. Both feed
   and plex now import it from the neutral util module.

2. feedquery.decode_cursor no longer raises fastapi.HTTPException — it raises
   a plain ValueError, and routes/feed.get_feed translates it to the HTTP 400.
   The read-model no longer imports fastapi, matching its "no request state"
   docstring.

3. Dropped the leading underscore on the helpers that are now a cross-module
   public API: feedquery {filtered_query, sort_keys, order_by, keyset_predicate,
   encode_cursor, decode_cursor}; plex.query {TS_CONFIG, FIELD_COLUMNS,
   field_recheck, split_csv, added_cutoff, meta_filter_conds, apply_meta_filters,
   like_escape}; plex.cards {movie_card, show_card, episode_card, leaf_card}.
   Genuinely-internal helpers (_channel_url, _saved_expr, _ADDED_WINDOWS,
   _lib_key) keep their underscore.

Pure code motion + rename. DB-lane suite 287 passed / 2 skipped; ruff clean.
This commit is contained in:
2026-08-17 18:23:03 +02:00
parent e7b5b8e87f
commit 2ab188d873
6 changed files with 101 additions and 94 deletions
+28 -28
View File
@@ -42,22 +42,22 @@ from app.plex import detail as plex_detail
from app.plex import people as plex_people
from app.plex import rollup, subtitles
from app.plex import sync as plex_sync
from app.feedquery import to_tsquery_str
from app.plex.cards import _episode_card, _leaf_card, _movie_card, _show_card
from app.plex.cards import episode_card, leaf_card, movie_card, show_card
from app.plex.client import PlexClient, PlexError, PlexNotConfigured
from app.plex.lookups import by_rating_key
from app.plex.query import (
_FIELD_COLUMNS,
_TS_CONFIG,
FIELD_COLUMNS,
TS_CONFIG,
LibraryFilters,
_apply_meta_filters,
_csv,
_field_recheck,
_like_escape,
_meta_filter_conds,
apply_meta_filters,
field_recheck,
like_escape,
meta_filter_conds,
split_csv,
)
from app.routes._common import owned_or_404
from app.routes.plex._shared import item_or_404
from app.utils import to_tsquery_str
router = APIRouter(prefix="/api/plex", tags=["plex"])
@@ -130,14 +130,14 @@ def unified_library(
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
if field not in _FIELD_COLUMNS and field != "all":
tsq = func.to_tsquery(TS_CONFIG, ts) if ts else None
if field not in FIELD_COLUMNS and field != "all":
field = "all"
# `episode` scope targets episode rows only — the movie/show grid stays empty; the recheck for
# the specific title/people/summary fields is a strict narrowing on top of the GIN prefilter.
grid_field = field != "episode"
recheck = (
_field_recheck if tsq is not None and field not in ("all", "episode") else None
field_recheck if tsq is not None and field not in ("all", "episode") else None
)
selects = []
@@ -190,7 +190,7 @@ def unified_library(
)
else:
mq = mq.where(or_(st.status.is_(None), st.status != "hidden"))
mq = _apply_meta_filters(mq, PlexItem, p)
mq = apply_meta_filters(mq, PlexItem, p)
if f.duration_min is not None:
mq = mq.where(PlexItem.duration_s >= f.duration_min)
if f.duration_max is not None:
@@ -239,7 +239,7 @@ def unified_library(
sq = sq.where(or_(wat > 0, inp > 0), wat < tot)
elif show == "unwatched":
sq = sq.where(wat == 0, inp == 0)
sq = _apply_meta_filters(sq, PlexShow, p)
sq = apply_meta_filters(sq, PlexShow, p)
if tsq is not None:
sq = sq.where(PlexShow.search_vector.op("@@")(tsq))
if recheck is not None:
@@ -306,7 +306,7 @@ def unified_library(
if tsq is not None and want_shows and field in ("all", "episode"):
ep_st = aliased(PlexState)
ep_vec = (
func.to_tsvector(_TS_CONFIG, func.coalesce(PlexItem.title, ""))
func.to_tsvector(TS_CONFIG, func.coalesce(PlexItem.title, ""))
if field == "episode"
else PlexItem.search_vector
)
@@ -325,7 +325,7 @@ def unified_library(
.limit(24)
).all()
for e, s, show_title in eps:
card = _episode_card(e, s)
card = episode_card(e, s)
card["show_title"] = show_title
episodes.append(card)
@@ -373,7 +373,7 @@ def facets(
def wsq(query, model, ids, pp, kind_movie, with_dur):
"""Apply the (self-excluded) metadata filters + library scope + the per-user watch-state to a
facet aggregation query, so the facets reflect exactly the visible result set."""
query = query.where(model.library_id.in_(ids), *_meta_filter_conds(model, pp))
query = query.where(model.library_id.in_(ids), *meta_filter_conds(model, pp))
if kind_movie:
query = query.where(model.kind == "movie")
if with_dur and pp.get("duration_min") is not None:
@@ -514,7 +514,7 @@ def facets(
# be absent): the sidebar renders genres solely from this list and hides the whole genre section —
# chips AND the Any/All toggle — when it's empty, which would trap the user with no per-chip way to
# undo a zero-result selection. Count 0 is fine (genre chips don't display counts).
for g in _csv(f.genres):
for g in split_csv(f.genres):
genre_counts.setdefault(g, 0)
return {
"genres": [
@@ -588,7 +588,7 @@ def collections(
)
term = (q or "").strip()
if term:
query = query.where(PlexCollection.title.ilike(f"%{_like_escape(term)}%"))
query = query.where(PlexCollection.title.ilike(f"%{like_escape(term)}%"))
rows = db.execute(
query.order_by(
PlexCollection.child_count.desc().nullslast(),
@@ -898,7 +898,7 @@ def playlist_detail(
).scalars()
}
cards = [
_leaf_card(
leaf_card(
it,
states.get(it.id),
shows[it.show_id].title if it.show_id in shows else None,
@@ -1214,7 +1214,7 @@ def show_detail(
dict
] = [] # every episode, in season/episode order → show-level rollup
for e in eps:
card = _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.rollup(all_cards)
@@ -1226,7 +1226,7 @@ def show_detail(
related: list[dict] = []
try:
meta, related_raw = _show_enrichment(db, sh.rating_key)
related = _related_show_cards(db, user.id, related_raw, exclude=sh.id)
related = _relatedshow_cards(db, user.id, related_raw, exclude=sh.id)
if sh.people_enriched_at is None and meta:
plex_people.enrich_row_people(db, sh, plex_people.cast_from_meta(meta))
plex_detail.apply_rich_detail(sh, meta) # imdb/tagline/full_cast for future views
@@ -1289,7 +1289,7 @@ def _season_block(se: PlexSeason, cards: list[dict]) -> dict:
}
def _related_show_cards(
def _relatedshow_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),
@@ -1313,7 +1313,7 @@ def _related_show_cards(
if sh is None or rk in seen:
continue
seen.add(rk)
out.append(_show_card(sh, statuses.get(sh.id, "new")))
out.append(show_card(sh, statuses.get(sh.id, "new")))
if len(out) >= 20:
break
return out
@@ -1344,7 +1344,7 @@ def people_cards(
movies/shows (in the given scope) feature them. Photos come from the plex_people cache (populated
as items are rich-fetched — info-page view + the rich re-sync); counts are live against cast_names.
A name with no cached photo yet still returns a card (the UI shows a placeholder)."""
wanted = _csv(names)[:16]
wanted = split_csv(names)[:16]
if not wanted:
return {"people": []}
movie_lib_ids, show_lib_ids = _content_libs(db)
@@ -1429,7 +1429,7 @@ def person_detail(
)
).scalars()
}
movies = [_movie_card(it, states.get(it.id)) for it in items]
movies = [movie_card(it, states.get(it.id)) for it in items]
shows: list[dict] = []
if show_lib_ids:
@@ -1446,7 +1446,7 @@ def person_detail(
.limit(_PERSON_SECTION_MAX)
).scalars().all()
statuses = rollup.state_map(db, user.id, [s.id for s in show_rows])
shows = [_show_card(sh, statuses.get(sh.id, "new")) for sh in show_rows]
shows = [show_card(sh, statuses.get(sh.id, "new")) for sh in show_rows]
return {"name": name, "photo": photo, "movies": movies, "shows": shows}
@@ -1506,7 +1506,7 @@ def _collection_strips(db: Session, it: PlexItem, user_id: int) -> list[dict]:
"id": rk,
"title": col.title,
"source": _collection_source(col),
"items": [_movie_card(m, states.get(m.id)) for m in members],
"items": [movie_card(m, states.get(m.id)) for m in members],
}
)
return out