diff --git a/CHANGELOG.md b/CHANGELOG.md
index d7a2606..dab3601 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,11 @@ What changed in each version of WhatsOn, newest first.
## Unreleased
+### Added
+- **Search finds episodes by their name.** Type an episode's title, like "Duck Duck Loon", and it shows in a new
+ Episodes row with its show and number, ready to play or open the show. Before, only movie and show names were
+ searched. A library refresh now also reads every episode's title, so on a big library it takes a little longer.
+
## 0.2.7 - 2026-11-10
### Changed
diff --git a/docs/adr/0030-search-episode-titles.md b/docs/adr/0030-search-episode-titles.md
new file mode 100644
index 0000000..9b0cfa5
--- /dev/null
+++ b/docs/adr/0030-search-episode-titles.md
@@ -0,0 +1,50 @@
+# 0030. Search finds episodes by their own titles
+
+- **Status:** Proposed
+- **Date:** 2026-11-10
+
+## Context
+
+The local copy of the library held movies and shows only, so search matched a show's name, summary, genres and cast, never
+an episode's title. A search for an episode such as "Duck, Duck, Loon!" found nothing even when the server had it, and the
+person had to know which show it belonged to. ADR 0029 makes sure the words as typed are searched for; without episode
+titles in the local copy there was still nothing for them to match. The live guide can't fill the gap either: guides fed
+from XMLTV through Plex arrive with no episode titles at all.
+
+## Decision
+
+WhatsOn keeps every library episode's title, season and number, and search matches episodes by their title.
+
+- `Source` gains `library_episodes()`, called right after `library()` on the same timer. Plex lists each TV section with
+ `type=4`, leaving out summaries, artwork and media details. Jellyfin lists items of type `Episode` for the configured user.
+- They're stored in `episodes` and indexed by title in `episodes_fts`, rebuilt on each library refresh and cleared when
+ switching server. If they fail to load, the library is still written and the previous episodes stay.
+- `search.run` returns them in `episodes` for text searches over the library: every word must be in the title, the show
+ must be in the library, at most 20 come back, and the show's genres, rating and year stand in for the episode's.
+- The results page shows them in an "Episodes" row, each with Play and Open the show. `/api/answer` sees them too.
+
+## Consequences
+
+- An episode can be found and played by its name alone.
+- A library refresh reads every episode, which is tens of thousands of items on a big library. On a test library of about
+ 44,000 episodes that's 23 pages and roughly 80 MB from Plex, about 15 seconds, every `LIBRARY_REFRESH_MINUTES` (6 hours
+ by default). The local database grows by a few megabytes.
+- Episodes don't carry watched status, so they show no tick, and they don't take part in suggestions or Trakt matching.
+- Episode summaries aren't searched, so describing an episode ("the one with the loon") still won't find it.
+- Every source must implement one more method.
+
+## Alternatives
+
+- **Ask the server's own search when a search runs.** No extra storage, but it's a network call on every search, Plex's
+ search missed this exact episode in testing, and search would stop working while the server is unreachable.
+- **Store episodes as `library` rows of kind `episode`.** One table, but suggestions, Trakt matching, the Library tab and
+ watched status all read `library` and assume movies and shows.
+- **Also index episode summaries.** Finds more, but one shared word in a summary would bring back pages of unrelated
+ episodes. Left for later.
+
+## Where it lives
+
+`library_episodes` in `whatson/sources/base.py`, `whatson/sources/plex.py` and `whatson/sources/jellyfin.py`;
+`write_episodes` and `Refresher.refresh_library` in `whatson/ingest.py`; `episodes` and `episodes_fts` in `whatson/db.py`;
+`search_episodes` in `whatson/search.py`; `episodeCard` in `whatson/static/js/cards.js` and `whatson/static/js/results.js`;
+`tests/test_episodes.py`. Builds on ADR 0005, ADR 0012 and ADR 0029.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 5418139..819dc75 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -81,3 +81,4 @@ Never rewrite an accepted ADR's reasoning. Fix a typo or add a link, but change
| [0027](0027-trakt-back-in-the-interface.md) | Trakt is back in the interface, as an optional section under More | Proposed |
| [0028](0028-sort-bare-guide-listings.md) | Sort bare guide listings from patterns across the guide | Proposed |
| [0029](0029-show-typed-matches-beside-the-ai-reading.md) | Show matches for the words as typed beside the AI's reading | Accepted |
+| [0030](0030-search-episode-titles.md) | Search finds episodes by their own titles | Proposed |
diff --git a/docs/api.md b/docs/api.md
index eeb2635..da061e1 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -36,7 +36,7 @@ serves generated schemas at `/docs` and `/openapi.json`.
| Route | What it does |
|---|---|
-| `GET /api/search` | Search. `q`, `scope`, `ai`, `on_now`, `kind`, or `filters` to replay edited chips. `device` shows watched status for that TV's Plex user. After an AI reading, `typed` holds the matches for the words as typed, or `null` |
+| `GET /api/search` | Search. `q`, `scope`, `ai`, `on_now`, `kind`, or `filters` to replay edited chips. `device` shows watched status for that TV's Plex user. `episodes` holds library episodes whose title has every word. After an AI reading, `typed` holds the matches for the words as typed, or `null` |
| `GET /api/answer` | One line answering `q` from the matches only. Empty when AI is off |
| `GET /api/suggest/live` | Picks for Live TV (`your_shows` is still returned; the page no longer shows it as a row) |
| `GET /api/suggest/library` | Up next, picks, and watchlist titles you don't have. `device` reads as that TV's Plex user |
diff --git a/docs/architecture.md b/docs/architecture.md
index ece78d3..3fc8d61 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -95,7 +95,8 @@ Default intervals: games 5 minutes (30 seconds while a followed team or league i
without saying more ([ADR 0028](adr/0028-sort-bare-guide-listings.md)). `link_games` matches sports and placeholder listings to games
([ADR 0014](adr/0014-match-espn-games-to-listings.md)), and `write_guide` replaces the tables and search index in one
transaction.
-4. Load the library the same way.
+4. Load the library the same way, then its episode titles ([ADR 0030](adr/0030-search-episode-titles.md)). If the
+ episodes fail to load, the library is still written and the previous episodes stay.
If the source was switched while a load was running, the result is thrown away.
@@ -103,7 +104,7 @@ If the source was switched while a load was running, the result is thrown away.
1. `GET /api/search` gets filters one of three ways: replayed from edited chips, read from the question by AI, or read
from keywords. See [ADR 0015](adr/0015-filters-are-the-search-contract.md).
-2. `search.run` queries games, the guide and the library over the local data. When AI read the question, it also searches the words as
+2. `search.run` queries games, the guide, the library and episode titles over the local data. When AI read the question, it also searches the words as
typed and returns those matches first, in `typed` ([ADR 0029](adr/0029-show-typed-matches-beside-the-ai-reading.md)).
3. When AI read the question, the front end then calls `GET /api/answer` for one line written from those matches only.
4. With Radarr or Sonarr set up, it also calls `GET /api/get/lookup` for titles you could get.
diff --git a/docs/data-model.md b/docs/data-model.md
index a01f3ae..b0500df 100644
--- a/docs/data-model.md
+++ b/docs/data-model.md
@@ -16,6 +16,8 @@ Safe to lose: the next refresh fills them again. Switching server clears all of
| `airings_fts` | Search index over airings. `extra` holds the linked game's team names, which is how a team finds its channel |
| `library` | Movies and shows. `rating_key` is the server's item id, whichever server that is |
| `library_fts` | Search index over the library |
+| `episodes` | Every library episode's title, season and number. `show_key` is its show's `rating_key` ([ADR 0030](adr/0030-search-episode-titles.md)) |
+| `episodes_fts` | Search index over episode titles |
| `games` | Games from ESPN, with teams, scores and networks. `state` is pre, in or post |
| `user_watched` | Watched status for Plex Home users other than the owner, refreshed as often as the library |
diff --git a/docs/frontend.md b/docs/frontend.md
index 2753d3a..135abdc 100644
--- a/docs/frontend.md
+++ b/docs/frontend.md
@@ -15,7 +15,7 @@ Plain JavaScript modules in `whatson/static/`, with no framework and no build st
| `whatson/static/js/core.js` | Shared helpers: `$`, `esc()`, `api()`, `store`, toasts, dialogs, formatting, placeholders |
| `whatson/static/js/cards.js` | Card renderers shared by the sections |
| `whatson/static/js/search.js` | The search box, filter chips and AI answer |
-| `whatson/static/js/results.js` | The search results page: matches for the words as typed first, then the AI's reading |
+| `whatson/static/js/results.js` | The search results page: matches for the words as typed first, then the AI's reading. Episodes get their own row |
| `whatson/static/js/player.js` | The TV picker, tuning, the now-playing bar, and the card it opens (listing, or a game's score and ESPN plays) |
| `whatson/static/js/live.js` | Live TV: suggestion rows, guide grid or now/next list, favorites |
| `whatson/static/js/library.js` | Library: poster grids, show pages, up next |
diff --git a/docs/testing.md b/docs/testing.md
index 7844523..e2c8e1f 100644
--- a/docs/testing.md
+++ b/docs/testing.md
@@ -17,6 +17,7 @@ scripts when Node.js is installed. CI also runs gitleaks over the whole history,
| `tests/test_guards.py` | The rules in `AGENTS.md` that a test can check. See [ADR 0021](adr/0021-rules-enforced-by-guard-tests.md) |
| `tests/test_docs.py` | ADR format and index, links and paths, and that the reference docs cover the code |
| `tests/test_core.py` | Linking games to listings, and search |
+| `tests/test_episodes.py` | Finding library episodes by their own titles |
| `tests/test_sources.py` | Plex and Jellyfin clients, and switching server |
| `tests/test_remote.py` | Remote tab, TV driver and app lists. The model for faking a TV |
| `tests/test_arr.py` | Radarr and Sonarr |
diff --git a/tests/test_core.py b/tests/test_core.py
index 29b878a..79a33b8 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -361,8 +361,8 @@ def test_typed_matches_are_not_repeated_or_added_without_ai(monkeypatch):
# A reading that finds the same things as the typed words leaves nothing extra in the AI's part.
out = search.run(make_db(), search.Filters(text="halloween"))
typed = search.split_typed(search.run(make_db(), search.basic_filters("halloween")), out)
- assert typed["library"] and out == {"games": [], "guide": [], "library": []}
- assert search.split_typed({"games": [], "guide": [], "library": []}, out) is None
+ assert typed["library"] and out == {"games": [], "guide": [], "library": [], "episodes": []}
+ assert search.split_typed({"games": [], "guide": [], "library": [], "episodes": []}, out) is None
def test_the_ai_answer_sees_the_typed_matches_first(monkeypatch):
diff --git a/tests/test_episodes.py b/tests/test_episodes.py
new file mode 100644
index 0000000..ce7a9bf
--- /dev/null
+++ b/tests/test_episodes.py
@@ -0,0 +1,140 @@
+"""Finding an episode by its own title (ADR 0030): the Plex and Jellyfin episode lists, storing them, and search."""
+
+import asyncio
+
+import httpx
+
+from whatson import db, search
+from whatson.ingest import Refresher, write_episodes, write_library
+from whatson.sources.base import Episode, LibraryItem
+from whatson.sources.jellyfin import Jellyfin
+from whatson.sources.plex import PlexClient
+
+SHOW_ID, EP1, EP2 = "b" * 32, "d" * 32, "e" * 32
+
+
+def run(coro):
+ return asyncio.run(coro)
+
+
+def library_db(rating: str = "TV-Y7") -> "db.sqlite3.Connection":
+ conn = db.connect(":memory:")
+ write_library(conn, [
+ LibraryItem("10", "show", "Critter Crew", 2011, "Two brothers meet animals", ["Kids"], content_rating=rating,
+ thumb="/library/metadata/10/thumb/1"),
+ LibraryItem("20", "movie", "Pond Life", 2001, "A documentary", ["Documentary"])])
+ write_episodes(conn, [
+ Episode("101", "10", "Critter Crew", 7, 15, "Goose, Goose, Heron!"),
+ Episode("102", "10", "Critter Crew", 7, 16, "Shapes of the Armadillo"),
+ Episode("901", "99", "Gone Show", 1, 1, "Goose, Goose, Heron!")]) # its show left the library
+ return conn
+
+
+def test_an_episode_is_found_by_its_own_title():
+ res = search.run(library_db(), search.basic_filters("Goose Goose Heron"))
+ assert res["library"] == [] # no show or movie has those words
+ [ep] = res["episodes"]
+ assert ep == {"type": "episode", "rating_key": "101", "show_key": "10", "show_title": "Critter Crew", "season": 7,
+ "index": 15, "title": "Goose, Goose, Heron!", "label": "S07E15 Goose, Goose, Heron!",
+ "thumb": "/library/metadata/10/thumb/1", "year": 2011}
+
+
+def test_episodes_follow_the_search_filters():
+ conn = library_db()
+ for f in (search.Filters(text="heron", kinds=["movie"]), search.Filters(text="heron", on_now=True),
+ search.Filters(text="heron", scope="guide"), search.Filters(text="heron", genres=["Horror"]),
+ search.Filters(text="")):
+ assert search.run(conn, f)["episodes"] == [], f
+ assert search.run(conn, search.Filters(text="heron", kinds=["episode"]))["episodes"]
+ assert search.run(conn, search.Filters(text="heron", audience="kids"))["episodes"]
+ assert not search.run(library_db(rating="TV-MA"), search.Filters(text="heron", audience="kids"))["episodes"]
+
+
+def test_an_episode_needs_every_word():
+ # One shared word isn't enough: "goose" alone matches, "goose armadillo" matches nothing.
+ conn = library_db()
+ assert [e["title"] for e in search.run(conn, search.Filters(text="goose"))["episodes"]] == ["Goose, Goose, Heron!"]
+ assert search.run(conn, search.Filters(text="goose armadillo"))["episodes"] == []
+
+
+def test_typed_episode_matches_are_not_repeated_in_the_ai_part():
+ conn = library_db()
+ out = search.run(conn, search.Filters(text="heron"))
+ typed = search.split_typed(search.run(conn, search.basic_filters("goose goose heron")), out)
+ assert [e["rating_key"] for e in typed["episodes"]] == ["101"] and out["episodes"] == []
+
+
+def test_switching_server_forgets_the_episodes():
+ conn = library_db()
+ db.clear_server_data(conn)
+ assert conn.execute("SELECT count(*) FROM episodes").fetchone()[0] == 0
+ assert search.run(conn, search.Filters(text="heron"))["episodes"] == []
+
+
+def test_plex_lists_episodes_of_show_sections_page_by_page(monkeypatch):
+ monkeypatch.setattr("whatson.sources.plex.PAGE", 2)
+ seen = []
+ eps = [{"ratingKey": 101, "grandparentRatingKey": 10, "grandparentTitle": "Critter Crew", "parentIndex": 7,
+ "index": 15, "title": "Goose, Goose, Heron!"},
+ {"ratingKey": 102, "grandparentRatingKey": 10, "grandparentTitle": "Critter Crew", "title": "Special"},
+ {"ratingKey": 103, "grandparentRatingKey": 10, "title": ""}] # no title: nothing to search for
+
+ def handler(req: httpx.Request) -> httpx.Response:
+ seen.append(req)
+ if req.url.path == "/library/sections":
+ return httpx.Response(200, json={"MediaContainer": {"Directory": [
+ {"key": "1", "type": "movie", "title": "Movies"}, {"key": "2", "type": "show", "title": "TV Shows"}]}})
+ start = int(req.headers["X-Plex-Container-Start"])
+ return httpx.Response(200, json={"MediaContainer": {"totalSize": 3, "Metadata": eps[start:start + 2]}})
+
+ plex = PlexClient("http://plex.example.com:32400", "t", http=httpx.AsyncClient(transport=httpx.MockTransport(handler)))
+ out = run(plex.library_episodes())
+ assert out == [Episode("101", "10", "Critter Crew", 7, 15, "Goose, Goose, Heron!"),
+ Episode("102", "10", "Critter Crew", None, None, "Special")]
+ lists = [r for r in seen if r.url.path != "/library/sections"]
+ assert [r.url.path for r in lists] == ["/library/sections/2/all"] * 2 # the movie section isn't asked
+ assert lists[0].url.params["type"] == "4" and "summary" in lists[0].url.params["excludeFields"]
+
+
+def test_jellyfin_lists_episodes_for_its_user():
+ seen = []
+
+ def handler(req: httpx.Request) -> httpx.Response:
+ seen.append(req)
+ return httpx.Response(200, json={"Items": [
+ {"Id": EP1, "SeriesId": SHOW_ID, "SeriesName": "Critter Crew", "ParentIndexNumber": 7, "IndexNumber": 15,
+ "Name": "Goose, Goose, Heron!"},
+ {"Id": EP2, "Name": "No show"}]})
+
+ jf = Jellyfin("http://jf.example.com:8096", "k3y", httpx.AsyncClient(transport=httpx.MockTransport(handler)), "u1")
+ assert run(jf.library_episodes()) == [Episode(EP1, SHOW_ID, "Critter Crew", 7, 15, "Goose, Goose, Heron!")]
+ assert seen[0].url.params["IncludeItemTypes"] == "Episode" and seen[0].url.params["userId"] == "u1"
+
+
+class FakeSource:
+ name, label, configured = "plex", "Plex", True
+
+ def __init__(self, episodes):
+ self.episodes = episodes
+
+ async def library(self):
+ return [LibraryItem("10", "show", "Critter Crew", 2011, "")]
+
+ async def library_episodes(self):
+ if isinstance(self.episodes, Exception):
+ raise self.episodes
+ return self.episodes
+
+
+def test_a_library_refresh_stores_the_episodes():
+ conn = db.connect(":memory:")
+ refresher = Refresher(object(), conn, FakeSource([Episode("101", "10", "Critter Crew", 7, 15, "Goose, Goose, Heron!")]))
+ run(refresher.refresh_library())
+ assert [e["label"] for e in search.run(conn, search.Filters(text="heron"))["episodes"]] == ["S07E15 Goose, Goose, Heron!"]
+
+
+def test_episodes_failing_to_load_keeps_the_library_and_the_old_episodes():
+ conn = library_db()
+ run(Refresher(object(), conn, FakeSource(httpx.ConnectError("down"))).refresh_library())
+ assert conn.execute("SELECT count(*) FROM library").fetchone()[0] == 1 # the new library was written
+ assert search.run(conn, search.Filters(text="heron"))["episodes"]
diff --git a/whatson/db.py b/whatson/db.py
index 825cce4..7b206c8 100644
--- a/whatson/db.py
+++ b/whatson/db.py
@@ -60,6 +60,19 @@
title, summary, genres, people, tokenize = 'unicode61 remove_diacritics 2'
);
+CREATE TABLE IF NOT EXISTS episodes (
+ rating_key TEXT PRIMARY KEY,
+ show_key TEXT NOT NULL, -- the show's rating_key in library
+ show_title TEXT NOT NULL DEFAULT '',
+ season INTEGER,
+ idx INTEGER, -- episode number in the season
+ title TEXT NOT NULL
+);
+
+CREATE VIRTUAL TABLE IF NOT EXISTS episodes_fts USING fts5 (
+ title, tokenize = 'unicode61 remove_diacritics 2'
+);
+
CREATE TABLE IF NOT EXISTS games (
id TEXT PRIMARY KEY,
league TEXT NOT NULL,
@@ -176,7 +189,8 @@ def connect(path: Path | str) -> sqlite3.Connection:
def clear_server_data(conn: sqlite3.Connection) -> None:
"""Everything tied to one server's ids, for when WhatsOn moves to another. Favorite channels go too:
the other server's channels have different ids."""
- for table in ("channels", "airings", "airings_fts", "library", "library_fts", "fav_channels", "user_watched"):
+ for table in ("channels", "airings", "airings_fts", "library", "library_fts", "episodes", "episodes_fts",
+ "fav_channels", "user_watched"):
conn.execute(f"DELETE FROM {table}")
for key in ("machine_id", "guide_refreshed", "library_refreshed"):
conn.execute("DELETE FROM meta WHERE key = ?", (key,))
diff --git a/whatson/ingest.py b/whatson/ingest.py
index 8f5b784..48b54c6 100644
--- a/whatson/ingest.py
+++ b/whatson/ingest.py
@@ -14,7 +14,7 @@
from . import db
from .config import Settings
from .sources import espn
-from .sources.base import Airing, Channel, LibraryItem, Source
+from .sources.base import Airing, Channel, Episode, LibraryItem, Source
log = logging.getLogger(__name__)
GAME_SLOT_MIN_VCN = 1000 # Dispatcharr-style per-event channels; ranked after real networks
@@ -174,6 +174,23 @@ def write_library(conn: sqlite3.Connection, items: list[LibraryItem]) -> None:
raise
+def write_episodes(conn: sqlite3.Connection, episodes: list[Episode]) -> None:
+ conn.execute("BEGIN")
+ try:
+ conn.execute("DELETE FROM episodes")
+ conn.execute("DELETE FROM episodes_fts")
+ for e in episodes:
+ cur = conn.execute(
+ "INSERT OR IGNORE INTO episodes (rating_key, show_key, show_title, season, idx, title) "
+ "VALUES (?, ?, ?, ?, ?, ?)", (e.rating_key, e.show_key, e.show_title, e.season, e.index, e.title))
+ if cur.rowcount:
+ conn.execute("INSERT INTO episodes_fts (rowid, title) VALUES (?, ?)", (cur.lastrowid, e.title))
+ conn.execute("COMMIT")
+ except Exception:
+ conn.execute("ROLLBACK")
+ raise
+
+
class Refresher:
def __init__(self, settings: Settings, conn: sqlite3.Connection, source: Source):
self.s, self.conn, self.source = settings, conn, source
@@ -208,6 +225,16 @@ async def refresh_library(self) -> None:
write_library(self.conn, items)
db.set_meta(self.conn, "library_refreshed", str(int(time.time())))
log.info("library: %d items", len(items))
+ # Episode titles are extra: if they can't be read, the movies and shows above still stand.
+ try:
+ episodes = await source.library_episodes()
+ except Exception as exc: # the old episode list stays until the next refresh
+ log.warning("library episodes: %s", exc)
+ return
+ if source is not self.source:
+ return
+ write_episodes(self.conn, episodes)
+ log.info("library: %d episodes", len(episodes))
def kick(self) -> None:
"""The server changed: look it up again and reload its guide and library now."""
diff --git a/whatson/routes.py b/whatson/routes.py
index 77b3f10..9dd064a 100644
--- a/whatson/routes.py
+++ b/whatson/routes.py
@@ -106,6 +106,8 @@ def _match_lines(res: dict) -> list[str]:
for li in res["library"][:8]:
lines.append(f"Library {li['kind']}: {li['title']} ({li['year']}) | {round((li['duration'] or 0) / 60000)} min"
f" | {li['genres']} | {li['content_rating']}{' | watched' if li['watched'] else ''}")
+ for e in res["episodes"][:8]:
+ lines.append(f"Library episode: {e['show_title']} {e['label']}")
return lines
diff --git a/whatson/search.py b/whatson/search.py
index db56984..6086cd1 100644
--- a/whatson/search.py
+++ b/whatson/search.py
@@ -286,6 +286,50 @@ def search_library(conn: sqlite3.Connection, f: Filters) -> list[dict]:
return [library_item(r) for r in rows]
+EPISODE_LIMIT = 20 # a one-word search can match hundreds of episode titles
+
+
+def search_episodes(conn: sqlite3.Connection, f: Filters) -> list[dict]:
+ """Episodes whose own title has every search word, so "duck duck loon" finds that episode of a show whose
+ name shares none of those words (ADR 0030). Only for text searches; the show's genres, rating and year
+ stand in for the episode's."""
+ q = fts_query(f.text)
+ if not q or (f.kinds and not {"show", "episode"} & set(f.kinds)):
+ return []
+ where, args = ["episodes_fts MATCH ?"], [q]
+ for g in f.genres:
+ where.append("l.genres LIKE ?")
+ args.append(f"%{g}%")
+ if f.year_from:
+ where.append("l.year >= ?")
+ args.append(f.year_from)
+ if f.year_to:
+ where.append("l.year <= ?")
+ args.append(f.year_to)
+ if f.audience in ("kids", "family"):
+ allowed = KIDS_RATINGS if f.audience == "kids" else FAMILY_RATINGS
+ where.append(f"l.content_rating IN ({','.join('?' * len(allowed))})")
+ args += list(allowed)
+ rows = conn.execute(
+ "SELECT e.*, l.title AS l_title, l.thumb AS l_thumb, l.year AS l_year FROM episodes_fts "
+ "JOIN episodes e ON e.rowid = episodes_fts.rowid JOIN library l ON l.rating_key = e.show_key WHERE "
+ + " AND ".join(where) + " ORDER BY bm25(episodes_fts), e.show_title, e.season, e.idx LIMIT ?",
+ args + [min(f.limit, EPISODE_LIMIT)]).fetchall()
+ return [episode_item(r) for r in rows]
+
+
+def episode_label(season: int | None, index: int | None, title: str) -> str:
+ """"S07E15 Duck, Duck, Loon!", or just the title when the numbers are missing."""
+ return (f"S{season:02d}E{index:02d} " if season is not None and index is not None else "") + title
+
+
+def episode_item(r: sqlite3.Row) -> dict:
+ return {"type": "episode", "rating_key": r["rating_key"], "show_key": r["show_key"],
+ "show_title": r["l_title"] or r["show_title"], "season": r["season"], "index": r["idx"],
+ "title": r["title"], "label": episode_label(r["season"], r["idx"], r["title"]),
+ "thumb": r["l_thumb"], "year": r["l_year"]}
+
+
def library_item(r: sqlite3.Row) -> dict:
return {"type": "library", "rating_key": r["rating_key"], "kind": r["kind"], "title": r["title"],
"year": r["year"], "summary": r["summary"], "genres": r["genres"], "thumb": r["thumb"],
@@ -342,14 +386,16 @@ def _guide_key(a: dict) -> tuple:
def split_typed(typed: dict, res: dict) -> dict | None:
"""Matches for the words as typed come first, so an AI misreading can't hide them (ADR 0029). Takes anything
they found out of `res`, the AI's reading, and returns them, or None when the typed words found nothing."""
- if not (typed["games"] or typed["guide"] or typed["library"]):
+ if not (typed["games"] or typed["guide"] or typed["library"] or typed["episodes"]):
return None
games = {g["id"] for g in typed["games"]}
guide = {_guide_key(a) for a in typed["guide"]}
library = {li["rating_key"] for li in typed["library"]}
+ episodes = {e["rating_key"] for e in typed["episodes"]}
res["games"] = [g for g in res["games"] if g["id"] not in games]
res["guide"] = [a for a in res["guide"] if _guide_key(a) not in guide]
res["library"] = [li for li in res["library"] if li["rating_key"] not in library]
+ res["episodes"] = [e for e in res["episodes"] if e["rating_key"] not in episodes]
return typed
@@ -357,4 +403,5 @@ def run(conn: sqlite3.Connection, f: Filters) -> dict:
guide = search_guide(conn, f) if f.scope in ("all", "guide") else []
library = search_library(conn, f) if f.scope in ("all", "library") and not f.on_now else []
games = search_games(conn, f) if f.scope in ("all", "guide") else []
- return {"games": games, "guide": guide, "library": library}
+ episodes = search_episodes(conn, f) if f.scope in ("all", "library") and not f.on_now else []
+ return {"games": games, "guide": guide, "library": library, "episodes": episodes}
diff --git a/whatson/sources/base.py b/whatson/sources/base.py
index cfc72c4..1136174 100644
--- a/whatson/sources/base.py
+++ b/whatson/sources/base.py
@@ -63,6 +63,17 @@ class LibraryItem:
guids: list[str] = field(default_factory=list)
+@dataclass
+class Episode:
+ """One episode of a show in the library, kept so search can find an episode by its own title (ADR 0030)."""
+ rating_key: str
+ show_key: str # the show's rating_key in the library
+ show_title: str
+ season: int | None
+ index: int | None
+ title: str
+
+
@dataclass
class Session:
player_title: str
@@ -114,6 +125,10 @@ async def load_guide(self, start: int, end: int) -> tuple[list[Channel], list[Ai
async def library(self) -> list[LibraryItem]:
"""Every movie and show. Called on a slow timer; the result replaces the local copy."""
+ async def library_episodes(self) -> list[Episode]:
+ """Every episode's title, season and number, for search. Called right after library(); the result replaces
+ the local copy. Keep each request light: this can be tens of thousands of episodes."""
+
async def playing(self) -> list[Session]:
"""What's playing now. The busy check relies on this, so it must say which TV each session is on."""
diff --git a/whatson/sources/jellyfin.py b/whatson/sources/jellyfin.py
index 7bc0263..48d0d00 100644
--- a/whatson/sources/jellyfin.py
+++ b/whatson/sources/jellyfin.py
@@ -14,7 +14,7 @@
import httpx
-from .base import Airing, Channel, LibraryItem, Session, classify
+from .base import Airing, Channel, Episode, LibraryItem, Session, classify
TICKS_PER_MS = 10_000
COMMANDS = {"PlayPause", "Pause", "Unpause", "Stop", "NextTrack", "PreviousTrack", "Seek"}
@@ -191,6 +191,13 @@ async def library(self) -> list[LibraryItem]:
**self._user())
return [_library_item(m) for m in rows]
+ async def library_episodes(self) -> list[Episode]:
+ rows = await self._pages("/Items", Recursive="true", IncludeItemTypes="Episode", EnableImages="false",
+ EnableUserData="false", **self._user())
+ return [Episode(rating_key=m["Id"], show_key=m["SeriesId"], show_title=m.get("SeriesName") or "",
+ season=m.get("ParentIndexNumber"), index=m.get("IndexNumber"), title=m["Name"])
+ for m in rows if m.get("Id") and m.get("SeriesId") and m.get("Name")]
+
async def sessions(self) -> list[JellyfinSession]:
out = []
for s in await self._call("GET", "/Sessions", params={"activeWithinSeconds": 900}) or []:
diff --git a/whatson/sources/plex.py b/whatson/sources/plex.py
index adf3c70..8400804 100644
--- a/whatson/sources/plex.py
+++ b/whatson/sources/plex.py
@@ -12,9 +12,10 @@
import httpx
-from .base import Airing, Channel, LibraryItem, Session, classify
+from .base import Airing, Channel, Episode, LibraryItem, Session, classify
PAGE = 2000
+EPISODE_TRIM = "excludeFields=summary,thumb,art&excludeElements=Media,Image,UltraBlurColors,Guid"
# Only exact Plex artwork paths, so /api/thumb can't be used to reach anything else on the server.
THUMB_RE = re.compile(r"/library/metadata/\d+/(thumb|art)/\d+")
@@ -24,6 +25,13 @@ def _list(container: dict[str, Any], key: str) -> list[dict[str, Any]]:
return value if isinstance(value, list) else [value]
+def _int(value: Any) -> int | None:
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return None
+
+
class PlexNotConnected(Exception):
"""No Plex server is set up yet (Settings → Plex)."""
@@ -173,6 +181,28 @@ async def library(self) -> list[LibraryItem]:
break
return out
+ async def library_episodes(self) -> list[Episode]:
+ out: list[Episode] = []
+ for sec in _list(await self._get("/library/sections"), "Directory"):
+ if sec.get("type") != "show":
+ continue
+ offset = 0
+ while True:
+ # type=4 is episodes. Leave out what search doesn't use, which roughly halves each page.
+ mc = await self._get(f"/library/sections/{sec['key']}/all?type=4&{EPISODE_TRIM}", headers={
+ "X-Plex-Container-Start": str(offset), "X-Plex-Container-Size": str(PAGE)})
+ items = _list(mc, "Metadata")
+ for m in items:
+ if m.get("ratingKey") and m.get("grandparentRatingKey") and m.get("title"):
+ out.append(Episode(
+ rating_key=str(m["ratingKey"]), show_key=str(m["grandparentRatingKey"]),
+ show_title=m.get("grandparentTitle", "") or "", season=_int(m.get("parentIndex")),
+ index=_int(m.get("index")), title=m["title"]))
+ offset += len(items)
+ if not items or offset >= int(mc.get("totalSize") or mc.get("size") or 0):
+ break
+ return out
+
async def sessions(self) -> list[Session]:
out = []
for m in _list(await self._get("/status/sessions"), "Metadata"):
diff --git a/whatson/static/js/cards.js b/whatson/static/js/cards.js
index ed1ae6a..7dc41ca 100644
--- a/whatson/static/js/cards.js
+++ b/whatson/static/js/cards.js
@@ -43,6 +43,19 @@ export function airingCard(a) {
`;
}
+export function episodeCard(e) {
+ return `
+
Matches for “${esc(res.typed.text)}”
${rows(res.typed)}`