Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
50 changes: 50 additions & 0 deletions docs/adr/0030-search-episode-titles.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions docs/adr/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
2 changes: 1 addition & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
5 changes: 3 additions & 2 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,15 +95,16 @@ 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.

### Search

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.
Expand Down
2 changes: 2 additions & 0 deletions docs/data-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |

Expand Down
2 changes: 1 addition & 1 deletion docs/frontend.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
1 change: 1 addition & 0 deletions docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
4 changes: 2 additions & 2 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
140 changes: 140 additions & 0 deletions tests/test_episodes.py
Original file line number Diff line number Diff line change
@@ -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"]
16 changes: 15 additions & 1 deletion whatson/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,))
Expand Down
Loading
Loading