From a57820a0781b02a8b0ee91d0b08734a4612e10a5 Mon Sep 17 00:00:00 2001 From: rays Date: Thu, 19 Nov 2026 09:04:57 -0500 Subject: [PATCH 1/4] A podcast told in seasons can be listed one season at a time (#482) GET /api/feeds/{id}/seasons counts a podcast's episodes and unread by season, from the same FROM as its list, so a count is what picking it shows; season= on its entries narrows the list to one, or to the episodes naming none. The page puts the seasons under the tabs, as the tabs' own track, when a podcast is told in them: two or more, holding most of its episodes. That leaves out Ken and Robin, whose "seasons" are years on a quarter of 767 episodes, and The Vintage RPG Podcast's 2 of 366. Listed all together by date, a heading marks where each season starts. A fixture podcast in seasons is in the browser suite, which now configures six feeds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy --- crates/ipx/CHANGELOG.md | 1 + crates/ipx/src/db.rs | 139 ++++++++++++++++++++++++++++++++-- crates/ipx/src/web.rs | 49 ++++++++++-- crates/wire/proto/ipx.proto | 12 +++ tests/page-unit.ts | 13 ++++ tests/ui/app.spec.ts | 26 ++++++- tests/ui/fixtures/seasons.xml | 13 ++++ tests/ui/global-setup.ts | 5 ++ web/CHANGELOG.md | 1 + web/app.css | 9 +++ web/build.mts | 2 +- web/src/feedpage.ts | 2 + web/src/feeds.ts | 2 +- web/src/items.ts | 14 +++- web/src/seasons.ts | 50 ++++++++++++ web/src/types.ts | 11 +++ web/src/util.ts | 2 +- 17 files changed, 329 insertions(+), 22 deletions(-) create mode 100644 tests/ui/fixtures/seasons.xml create mode 100644 web/src/seasons.ts diff --git a/crates/ipx/CHANGELOG.md b/crates/ipx/CHANGELOG.md index 301ba83..fcda89b 100644 --- a/crates/ipx/CHANGELOG.md +++ b/crates/ipx/CHANGELOG.md @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- `GET /api/feeds/{id}/seasons` gives a podcast's seasons with how many episodes and unread each has, and a podcast's episodes can be asked for one season at a time, or for those naming none (`season=none`) (#482). - Smart playlists: `GET` and `POST /api/playlists`, `PATCH` and `DELETE /api/playlists/{id}`, and `GET /api/playlists/{id}/entries`, the episodes of the podcasts chosen in the playlist's order, those set to play first ahead of the rest (#476). - A feed in `/api/feeds` says whether it has audio or video (`podcast`), for the page's Podcasts shelf (#474). - Up Next, a queue of episodes kept per account so every device shares it: `GET /api/queue` lists it in order, `PUT /api/queue` sets it, and an episode leaves it once it is 90% played (#473). diff --git a/crates/ipx/src/db.rs b/crates/ipx/src/db.rs index cea64a7..81c4596 100644 --- a/crates/ipx/src/db.rs +++ b/crates/ipx/src/db.rs @@ -1342,6 +1342,7 @@ fn entries_from( search: Option<&str>, guid: Option<&str>, signal: Option, + season: Season, pg: bool, ) -> String { let user = a.p(user_id); @@ -1381,6 +1382,11 @@ fn entries_from( if let Some(g) = guid { scope = format!("{scope} AND e.guid = {}", a.p(g)); } + match season { + Season::Any => {} + Season::Of(n) => scope = format!("{scope} AND e.season = {}", a.p(n)), + Season::Unnumbered => scope = format!("{scope} AND e.season IS NULL"), + } let search = match search.map(|q| q.trim().to_lowercase()).filter(|q| !q.is_empty()) { Some(q) => { // % and _ as typed, not as wildcards: "100%" matched anything starting 100 (#296). @@ -1495,6 +1501,23 @@ pub fn playlist_order(spec: &PlaylistSpec) -> String { format!("CASE WHEN e.feed_id IN ({ids}) THEN 0 ELSE 1 END, {by_date}") } +/// Which of a podcast's seasons a list is of (#482): every one, one by its number, or the episodes +/// that name none. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Season { + Any, + Of(i64), + Unnumbered, +} + +/// A season of a podcast, as its page offers it: None for the episodes that name none. +#[derive(Debug, PartialEq, Eq, serde::Serialize)] +pub struct SeasonCount { + pub season: Option, + pub episodes: i64, + pub unread: i64, +} + /// Which slice of a feed the UI is asking for. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Filter { @@ -1586,7 +1609,7 @@ impl Db { order: &str, ) -> Result> { let feeds = feed_id.as_ref().map(std::slice::from_ref); - self.entries_where(user_id, feeds, filter, search, None, None, offset, limit, order).await + self.entries_where(user_id, feeds, filter, search, None, None, Season::Any, offset, limit, order).await } /// As `entries_in`, for several feeds together (an OPML's shows, #283), or every subscribed @@ -1602,7 +1625,63 @@ impl Db { limit: i64, order: &str, ) -> Result> { - self.entries_where(user_id, feeds, filter, search, None, None, offset, limit, order).await + self.entries_where(user_id, feeds, filter, search, None, None, Season::Any, offset, limit, order).await + } + + /// As `entries_of`, for one season of the feeds (#482). + #[allow(clippy::too_many_arguments)] + pub async fn season_entries( + &self, + user_id: i64, + feeds: &[&str], + season: Season, + filter: Filter, + search: Option<&str>, + offset: i64, + limit: i64, + order: &str, + ) -> Result> { + self.entries_where(user_id, Some(feeds), filter, search, None, None, season, offset, limit, order).await + } + + /// As `count_of`, for one season of the feeds (#482). + pub async fn season_count( + &self, + user_id: i64, + feeds: &[&str], + season: Season, + filter: Filter, + search: Option<&str>, + ) -> Result { + self.count_where(user_id, Some(feeds), season, filter, search).await + } + + /// The seasons of the feeds, newest first and the episodes naming none last, each with how + /// many of its episodes the list holds and how many are unread: what the season picker offers + /// (#482). The same FROM as the lists, so a count is what picking it shows. + pub async fn seasons(&self, user_id: i64, feeds: &[&str]) -> Result> { + let count = |filter| { + let mut a = Args::default(); + let from = entries_from(&mut a, user_id, Some(feeds), filter, None, None, None, Season::Any, self.pg()); + (format!("SELECT e.season, count(*) AS n {from} GROUP BY e.season"), a.0) + }; + let read = |rows: Vec| -> Result, i64>> { + rows.iter().map(|r| Ok((r.try_get("", "season")?, r.try_get("", "n")?))).collect() + }; + let (all, unread) = (count(Filter::All), count(Filter::Unread)); + let all = read(self.rows(&all.0, all.1).await?)?; + let unread = read(self.rows(&unread.0, unread.1).await?)?; + let mut out: Vec = all + .into_iter() + .map(|(season, episodes)| SeasonCount { + season, + episodes, + unread: unread.get(&season).copied().unwrap_or(0), + }) + .collect(); + // Newest season first; None, the episodes naming none, sorts below every number. + out.sort_by_key(|s| std::cmp::Reverse(s.season)); + Ok(out) } /// The shows of an OPML (or a Patreon creator) this person subscribes to (#283). @@ -1631,14 +1710,14 @@ impl Db { limit: i64, order: &str, ) -> Result> { - self.entries_where(user_id, None, filter, search, None, Some(signal), offset, limit, order).await + self.entries_where(user_id, None, filter, search, None, Some(signal), Season::Any, offset, limit, order).await } pub async fn signal_count(&self, user_id: i64, signal: i64, filter: Filter, search: Option<&str>) -> Result { let mut a = Args::default(); let sql = format!( "SELECT count(*) AS n {}", - entries_from(&mut a, user_id, None, filter, search, None, Some(signal), self.pg()) + entries_from(&mut a, user_id, None, filter, search, None, Some(signal), Season::Any, self.pg()) ); let r = self.rows(&sql, a.0).await?; Ok(r.first().context("count(*) always returns a row")?.try_get("", "n")?) @@ -1649,7 +1728,7 @@ impl Db { pub async fn entry(&self, user_id: i64, feed_id: &str, guid: &str) -> Result> { let order = order_sql("published", "desc"); Ok(self - .entries_where(user_id, Some(&[feed_id]), Filter::All, None, Some(guid), None, 0, 1, &order) + .entries_where(user_id, Some(&[feed_id]), Filter::All, None, Some(guid), None, Season::Any, 0, 1, &order) .await? .pop()) } @@ -1663,12 +1742,13 @@ impl Db { search: Option<&str>, guid: Option<&str>, signal: Option, + season: Season, offset: i64, limit: i64, order: &str, ) -> Result> { let mut a = Args::default(); - let from = entries_from(&mut a, user_id, feeds, filter, search, guid, signal, self.pg()); + let from = entries_from(&mut a, user_id, feeds, filter, search, guid, signal, season, self.pg()); // The page's keys first, then its rows: the sort then needs only `entries_by_time`, not // every item's row, and the show notes are read for the page alone (#188). let (limit, offset) = (a.p(limit), a.p(offset)); @@ -1752,9 +1832,21 @@ impl Db { feeds: Option<&[&str]>, filter: Filter, search: Option<&str>, + ) -> Result { + self.count_where(user_id, feeds, Season::Any, filter, search).await + } + + async fn count_where( + &self, + user_id: i64, + feeds: Option<&[&str]>, + season: Season, + filter: Filter, + search: Option<&str>, ) -> Result { let mut a = Args::default(); - let sql = if filter == Filter::Unread && search.is_none() { + // The feed list's own count, feed by feed, knows nothing of seasons. + let sql = if filter == Filter::Unread && search.is_none() && season == Season::Any { // Feed by feed, as the feed list counts (#352); the same feeds as `entries_from`. let user = a.p(user_id); let scope = match feeds { @@ -1771,7 +1863,7 @@ impl Db { } else { format!( "SELECT count(*) AS n {}", - entries_from(&mut a, user_id, feeds, filter, search, None, None, self.pg()) + entries_from(&mut a, user_id, feeds, filter, search, None, None, season, self.pg()) ) }; let r = self.rows(&sql, a.0).await?; @@ -4093,6 +4185,37 @@ mod tests { assert!(guids(1).await.is_empty()); } + #[tokio::test] + async fn a_podcast_s_seasons_are_counted_and_listed_one_at_a_time() { + let db = Db::memory().await.unwrap(); + db.exec_for_test( + "INSERT INTO users (id, name, is_admin) VALUES (1,'ray',true); + INSERT INTO entries (feed_id, guid, title, published, first_seen, season) VALUES + ('f','a','S1E1',100,100,1),('f','b','S1E2',200,200,1),('f','c','S2E1',300,300,2), + ('f','d','Trailer',50,50,NULL),('g','e','Elsewhere',400,400,2);", + ) + .await + .unwrap(); + db.subscribe(1, "f").await.unwrap(); + db.set_entry_flag(1, "f", "a", EntryFlag::Read, true).await.unwrap(); + + // Newest first, the unnumbered last, each with its unread; another feed's season 2 is not in it. + let got = db.seasons(1, &["f"]).await.unwrap(); + let want = [(Some(2), 1, 1), (Some(1), 2, 1), (None, 1, 1)]; + assert_eq!(got.iter().map(|s| (s.season, s.episodes, s.unread)).collect::>(), want); + + let order = order_sql("published", "desc"); + let titles = async |season| { + let rows = db.season_entries(1, &["f"], season, Filter::All, None, 0, 50, &order).await.unwrap(); + assert_eq!(db.season_count(1, &["f"], season, Filter::All, None).await.unwrap(), rows.len() as i64); + rows.into_iter().map(|r| r.title.unwrap()).collect::>() + }; + assert_eq!(titles(Season::Of(1)).await, ["S1E2", "S1E1"]); + assert_eq!(titles(Season::Unnumbered).await, ["Trailer"]); + assert_eq!(titles(Season::Any).await.len(), 4); + assert_eq!(db.season_count(1, &["f"], Season::Of(1), Filter::Unread, None).await.unwrap(), 1); + } + #[tokio::test] async fn a_playlist_puts_its_priority_podcasts_first_and_is_its_owners_alone() { let db = Db::memory().await.unwrap(); diff --git a/crates/ipx/src/web.rs b/crates/ipx/src/web.rs index c0aeddc..112b5e3 100644 --- a/crates/ipx/src/web.rs +++ b/crates/ipx/src/web.rs @@ -60,6 +60,7 @@ const WIRE: ipx_wire::Routes = &[ ("POST", "/api/feeds", "ipx.NewFeed", "ipx.AddedFeed"), ("PATCH", "/api/feeds/{id}", "ipx.FeedPatch", ""), ("GET", "/api/feeds/{id}/entries", "", "ipx.EntryPage"), + ("GET", "/api/feeds/{id}/seasons", "", "ipx.SeasonRows"), ("GET", "/api/entries", "", "ipx.EntryPage"), ("GET", "/api/queue", "", "ipx.EntryPage"), ("PUT", "/api/queue", "ipx.QueueItems", "ipx.EntryPage"), @@ -108,6 +109,7 @@ pub fn router(state: WebState) -> Router { .route("/api/feeds", get(feeds).post(add_feed)) .route("/api/feeds/{id}", patch(patch_feed).delete(remove_feed)) .route("/api/feeds/{id}/entries", get(entries)) + .route("/api/feeds/{id}/seasons", get(seasons)) .route("/api/entries", get(all_entries)) .route("/api/queue", get(queue).put(set_queue)) .route("/api/playlists", get(list_playlists).post(add_playlist)) @@ -2042,6 +2044,9 @@ struct Page { sort: Option, #[serde(default)] dir: Option, + /// One season of a podcast's (#482): its number, or `none` for the episodes naming none. + #[serde(default)] + season: Option, } fn fifty() -> i64 { @@ -2069,6 +2074,20 @@ async fn entries( entry_page(&state, user.id, Some(&ids[..]), None, &page).await } +/// A podcast's seasons, for its page to offer one at a time (#482). An OPML's are its shows' +/// together, as its items are. +async fn seasons( + State(state): State, + Path(id): Path, + user: crate::db::User, +) -> Result>, ApiError> { + subscribed(&state, &user, &id).await?; + let mut ids = state.ctx.db.group_members(user.id, &id).await?; + ids.push(id); + let ids: Vec<&str> = ids.iter().map(String::as_str).collect(); + Ok(Json(state.ctx.db.seasons(user.id, &ids).await?)) +} + /// A feed's items and files are for the people who subscribe to it (#129). Anyone signed in /// could read any feed's by its id, a paid one's included, with its enclosure addresses, which /// can carry the subscriber's key, and fetch, queue or delete its files by theirs. A feed in @@ -2104,6 +2123,11 @@ async fn entry_page( let order = crate::db::order_sql(page.sort.as_deref().unwrap_or("published"), page.dir.as_deref().unwrap_or("desc")); let limit = page.limit.clamp(1, 200); + let season = match page.season.as_deref().map(str::trim) { + None | Some("") => db::Season::Any, + Some("none") => db::Season::Unnumbered, + Some(n) => db::Season::Of(n.parse().map_err(|_| ApiError::bad_request(format!("no season {n:?}")))?), + }; // Which list, so a slow one's trace says what was asked of it (#287). The search's words stay // out: they are the reader's own. let in_list = tracing::info_span!( @@ -2115,19 +2139,32 @@ async fn entry_page( offset = page.offset, limit, search = search.is_some(), + season = ?season, ); + // A season is of a podcast's own page; All Subscriptions and a Signal have none to pick. + let in_season = feeds.filter(|_| season != db::Season::Any); let list = async { - match signal { - Some(id) => { + match (signal, in_season) { + (Some(id), _) => { db.signal_entries(user_id, id, filter, search, page.offset, limit, &order).instrument(in_list).await } - None => db.entries_of(user_id, feeds, filter, search, page.offset, limit, &order).instrument(in_list).await, + (None, Some(fs)) => { + db.season_entries(user_id, fs, season, filter, search, page.offset, limit, &order) + .instrument(in_list) + .await + } + (None, None) => { + db.entries_of(user_id, feeds, filter, search, page.offset, limit, &order).instrument(in_list).await + } } }; let count = async { - match signal { - Some(id) => db.signal_count(user_id, id, filter, search).instrument(db::step("count_in")).await, - None => db.count_of(user_id, feeds, filter, search).instrument(db::step("count_in")).await, + match (signal, in_season) { + (Some(id), _) => db.signal_count(user_id, id, filter, search).instrument(db::step("count_in")).await, + (None, Some(fs)) => { + db.season_count(user_id, fs, season, filter, search).instrument(db::step("count_in")).await + } + (None, None) => db.count_of(user_id, feeds, filter, search).instrument(db::step("count_in")).await, } }; // The count beside the list, not after it: each waited on the other, about 40 and 24 ms on the diff --git a/crates/wire/proto/ipx.proto b/crates/wire/proto/ipx.proto index 014799f..6a8e149 100644 --- a/crates/wire/proto/ipx.proto +++ b/crates/wire/proto/ipx.proto @@ -275,6 +275,18 @@ message PlaylistRows { repeated PlaylistRow items = 1; } +// One season of a podcast in GET /api/feeds/{id}/seasons (#482): its number, unset for the +// episodes that name none, how many episodes it has and how many are unread. +message SeasonRow { + optional int64 season = 1; + int64 episodes = 2; + int64 unread = 3; +} + +message SeasonRows { + repeated SeasonRow items = 1; +} + // POST /api/playlists, the answer. message PlaylistId { int64 id = 1; diff --git a/tests/page-unit.ts b/tests/page-unit.ts index 047bd66..b4280be 100644 --- a/tests/page-unit.ts +++ b/tests/page-unit.ts @@ -37,6 +37,19 @@ test('names sort as a shelf files them, a leading The, A or An aside (#481)', () 'The Rest Is Science', 'science weekly', 'Theory of Everything']); }); +test('a podcast gets its seasons only when most of it is in two or more (#482)', () => { + const shown = (list: object) => run(`seasonsShown(${JSON.stringify(list)})`); + const s = (season: number | null, episodes: number) => ({ season, episodes, unread: 0 }); + assert.equal(shown([s(6, 25), s(5, 40), s(1, 30)]), true, 'Oxide and Friends'); + assert.equal(shown([s(7, 40), s(1, 30), s(null, 3)]), true, 'a few trailers aside'); + assert.equal(shown([s(232, 1), s(225, 1), s(null, 364)]), false, 'two numbered of 366'); + assert.equal(shown([s(2023, 150), s(12026, 44), s(null, 573)]), false, 'years on a quarter of them'); + assert.equal(shown([s(1, 40)]), false, 'one season is no choice'); + assert.equal(shown([{ episodes: 3, unread: 0 }, s(2, 2), s(1, 2)]), true, 'none sent as absent, as protobuf does'); + assert.equal(run('seasonName(null)'), 'Other episodes'); + assert.equal(run('seasonName(3)'), 'Season 3'); +}); + test('webUrl keeps only web addresses from a feed', () => { assert.equal(run(`webUrl('https://example.com/a')`), 'https://example.com/a'); assert.equal(run(`webUrl('HTTP://example.com/')`), 'HTTP://example.com/'); diff --git a/tests/ui/app.spec.ts b/tests/ui/app.spec.ts index 6ab2263..8376822 100644 --- a/tests/ui/app.spec.ts +++ b/tests/ui/app.spec.ts @@ -56,9 +56,9 @@ test.beforeEach(async ({ page }) => { test('the page loads and lists the configured feeds', async ({ page }) => { // Regression: a ReferenceError in the script left the shell rendered and the sidebar // empty, with every handler below the error dead. Server-side checks all passed. - // Four top-level feeds in the fixture config; the OPML's children are inside a closed folder. - // The Signals folder is above them, and no feed. - await expect(page.locator('.feed:not(.sigs):not(.plists)')).toHaveCount(5, { timeout: 15_000 }); + // Six top-level feeds in the fixture config, the season one's (#482) among them; the OPML's + // children are inside a closed folder. The Signals folder is above them, and no feed. + await expect(page.locator('.feed:not(.sigs):not(.plists)')).toHaveCount(6, { timeout: 15_000 }); await expect(page.locator('.feed', { hasText: 'Test Show' })).toBeVisible(); const errors: string[] = []; page.on('pageerror', e => errors.push(e.message)); @@ -3217,3 +3217,23 @@ test('a reap over the quota says what it would delete and, dry, deletes nothing' expect(ipx(['reap'])).toContain('deleted 0 old file(s), 0.0 MB'); expect(files()).toBe(before); }); + +test('a podcast told in seasons is listed one season at a time, or all with each season marked (#482)', async ({ page }) => { + await page.locator('#feedlist .feed', { hasText: 'Seasoned Show' }).click({ timeout: 20_000 }); + await page.locator('#content .tabs button[data-f="all"]').click(); + const picker = page.locator('#content .seasons'); + await expect(picker.locator('button')).toHaveText(['All seasons', 'Season 2', 'Season 1', 'Other']); + // Every season, newest first: where each starts is said above its first episode. + await expect(page.locator('#eps .sdiv')).toHaveText(['Season 2', 'Other episodes', 'Season 1']); + await picker.locator('button', { hasText: 'Season 1' }).click(); + await expect(page.locator('#eps .ep .t')).toHaveText(['The Pilot', 'Season One Close']); + await expect(page.locator('#eps .sdiv')).toHaveCount(0); + await expect(page.locator('#content .seasons button', { hasText: 'Season 1' })).toHaveAttribute('aria-pressed', 'true'); + await page.locator('#content .seasons button', { hasText: 'Other' }).click(); + await expect(page.locator('#eps .ep .t')).toHaveText(['A Bonus Between']); + // A podcast with one season has no picker, and opening it starts from every season again. + await page.locator('#feedlist .feed', { hasText: 'Test Show' }).first().click(); + await expect(page.locator('#content .seasons')).toHaveCount(0); + await page.locator('#feedlist .feed', { hasText: 'Seasoned Show' }).click(); + await expect(page.locator('#content .seasons button.on')).toHaveText('All seasons'); +}); diff --git a/tests/ui/fixtures/seasons.xml b/tests/ui/fixtures/seasons.xml new file mode 100644 index 0000000..e0a2383 --- /dev/null +++ b/tests/ui/fixtures/seasons.xml @@ -0,0 +1,13 @@ + + +Seasoned Showhttp://127.0.0.1:8792/A fixture podcast told in seasons (#482). +Season Two Finalesn-4Mon, 01 Jun 2026 10:00:00 +0000 + 22 +Season Two Openersn-3Mon, 25 May 2026 10:00:00 +0000 + 21 +A Bonus Betweensn-bMon, 18 May 2026 10:00:00 +0000 +The Pilotsn-1Mon, 11 May 2026 10:00:00 +0000 + 11 +Season One Closesn-2Mon, 04 May 2026 10:00:00 +0000 + 12 + diff --git a/tests/ui/global-setup.ts b/tests/ui/global-setup.ts index b0237ef..156911a 100644 --- a/tests/ui/global-setup.ts +++ b/tests/ui/global-setup.ts @@ -63,6 +63,11 @@ metrics_bind = "127.0.0.1:8799" url = "http://127.0.0.1:8792/show.xml" auto_download = true +# Told in seasons, with a bonus naming none between them: the season picker (#482). +[feeds.seasoned-show] +url = "http://127.0.0.1:8792/seasons.xml" +auto_download = false + # Downloads its image, so the UI has a file that is not playable to deal with. [feeds.picture-blog] url = "http://127.0.0.1:8792/pics.xml" diff --git a/web/CHANGELOG.md b/web/CHANGELOG.md index a153f58..30fb007 100644 --- a/web/CHANGELOG.md +++ b/web/CHANGELOG.md @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- A podcast told in seasons has a season picker under its tabs, to list one season at a time or the episodes in none, and listed all together, newest or oldest first, each season's start is marked (#482). - Smart playlists, in a folder of their own in the feed list: choose the podcasts, which of them play first, unplayed episodes only or all, newest or oldest first, and the playlist keeps itself up to date. Playing from one goes on through it once Up Next is empty (#476). - Now Playing: tap the player bar to see what is playing with its artwork large, its podcast (a tap opens it), its show notes and what follows in Up Next; Esc or the bar closes it (#475). - Podcasts: your podcasts as a shelf of their artwork, each with how many episodes are new; the search box narrows it, and a tap opens one (#474). diff --git a/web/app.css b/web/app.css index 6d613f3..d5aeb76 100644 --- a/web/app.css +++ b/web/app.css @@ -989,6 +989,13 @@ kbd{font:inherit;font-size:12px;color:var(--fg);background:var(--panel2);border: .tabs button.on{background:var(--raise);color:var(--fg);font-weight:500} .tabs a{padding:5px 12px;border-radius:7px;font-size:13px;color:var(--dim);text-decoration:none} .tabs a.on{background:var(--raise);color:var(--fg);font-weight:500} +/* A podcast's seasons (#482): the tabs' track, scrolled sideways when there are more than fit. */ +.tabs.seasons{max-width:100%;overflow-x:auto;scrollbar-width:none} +.tabs.seasons::-webkit-scrollbar{display:none} +.tabs.seasons button{white-space:nowrap;flex:none} +/* Where a season starts in the list of every season. */ +.sdiv{padding:14px 8px 5px;font-size:12px;font-weight:600;letter-spacing:.05em;text-transform:uppercase;color:var(--dim);border-bottom:1px solid var(--line)} +.sdiv:first-child{padding-top:4px} /* ---------- the admin page (admin.html) ---------- */ /* One column that scrolls under the same header, rather than the app's fixed panes. */ @@ -1539,6 +1546,8 @@ body:has(#player.on) #status{padding-bottom:3px} .tabs{flex:1 1 100%;border-radius:10px;padding:2px} .tabs button,.tabs a{flex:1;text-align:center;padding:7px 4px;border-radius:8px;font-size:14px} .tabs button.on,.tabs a.on{box-shadow:0 1px 3px rgba(0,0,0,.22)} + /* Seasons keep their own widths, scrolling past the edge, rather than squeezing eight into 390px. */ + .tabs.seasons button{flex:none;padding:7px 12px} /* Rows: taller, larger type, and a hairline between them that starts where the text does. */ .ep{padding:10px 8px;border-radius:10px;min-height:44px} diff --git a/web/build.mts b/web/build.mts index 9ff0002..cc4df29 100644 --- a/web/build.mts +++ b/web/build.mts @@ -29,7 +29,7 @@ const WEB_VERSION = JSON.parse(fs.readFileSync(path.join(here, '..', 'package.js // The files are one script, concatenated in this order, not modules: they share one top-level // scope, as the single inline script did, and code that runs at load needs what came before it. const PAGES: Record = { - 'index.html': { script: 'app.js', src: ['util', 'wire', 'theme', 'feeds', 'feedpage', 'items', 'player', 'upnext', 'nowplaying', 'dialogs', 'signals', 'playlists', 'gestures', 'offline', 'events', 'native'] }, + 'index.html': { script: 'app.js', src: ['util', 'wire', 'theme', 'feeds', 'feedpage', 'items', 'seasons', 'player', 'upnext', 'nowplaying', 'dialogs', 'signals', 'playlists', 'gestures', 'offline', 'events', 'native'] }, 'admin.html': { script: 'admin.js', src: ['util', 'wire', 'theme', 'admin'] }, 'login.html': { script: 'login.js', src: ['login'] }, }; diff --git a/web/src/feedpage.ts b/web/src/feedpage.ts index 475a720..5ed8a9e 100644 --- a/web/src/feedpage.ts +++ b/web/src/feedpage.ts @@ -99,6 +99,8 @@ function renderFeed(){ renderFeed(); loadEntries(); }); if(f) wireFailBanner(box,f); + // An OPML's page is many podcasts' episodes together, their seasons each their own. + if(f&&!kids.length) loadSeasons(f); } /// The item table's headings, each a button that sorts by its column. The first click goes the diff --git a/web/src/feeds.ts b/web/src/feeds.ts index 6539783..e517c4f 100644 --- a/web/src/feeds.ts +++ b/web/src/feeds.ts @@ -202,7 +202,7 @@ function renderFeeds(){ done(); } function selectFeed(id: string){ - S.feed=id; S.offset=0; S.sel=null; S.q=''; $('#epSearch').value=''; + S.feed=id; S.offset=0; S.sel=null; S.q=''; S.season=''; $('#epSearch').value=''; try{ localStorage.setItem('ipx.feed',id); }catch{} renderFeeds(); renderFeed(); loadEntries(); } diff --git a/web/src/items.ts b/web/src/items.ts index 404ea95..153cd58 100644 --- a/web/src/items.ts +++ b/web/src/items.ts @@ -14,10 +14,13 @@ const lists=new Map(); const LISTS_KEPT=40; /// Lists on their way, so a click on one already being fetched ahead waits for that answer. const fetching=new Map>(); -const listKey=(feed: string, filter=S.filter)=>[feed,filter,S.sort.col,S.sort.dir,S.q].join('\n'); +// A season is of the podcast open (#482): another feed's list, fetched ahead, is of every season. +const seasonFor=(feed: string)=>feed===S.feed?S.season:''; +const listKey=(feed: string, filter=S.filter)=>[feed,filter,S.sort.col,S.sort.dir,S.q,seasonFor(feed)].join('\n'); function listUrl(feed: string, filter=S.filter, offset=0){ const p=new URLSearchParams({offset:String(offset),limit:String(LIMIT),filter,sort:S.sort.col,dir:S.sort.dir}); if(S.q) p.set('q',S.q); + if(seasonFor(feed)) p.set('season',seasonFor(feed)); const sg=signalId(feed); return feed===':all' ? `/api/entries?${p}` : sg!==null ? `/api/signals/${sg}/entries?${p}` @@ -155,7 +158,14 @@ function renderEntries(){ else if(sg&&S.filter==='all') box.innerHTML='

Nothing has come through yet. New items are read as your feeds are checked.

'; return; } - for(const e of S.entries) box.appendChild(epEl(e)); + const breaks=seasonBreaks(); + let last: number|null|undefined; + S.entries.forEach((e,i)=>{ + if(breaks&&(i===0||(e.season??null)!==(last??null))) + box.insertAdjacentHTML('beforeend',`
${seasonName(e.season)}
`); + last=e.season; + box.appendChild(epEl(e)); + }); syncPlayButtons(); if(pane) pane.scrollTop=top; if(hasMore()){ diff --git a/web/src/seasons.ts b/web/src/seasons.ts new file mode 100644 index 0000000..bcac0f8 --- /dev/null +++ b/web/src/seasons.ts @@ -0,0 +1,50 @@ +/* ---------------- seasons (#482) ---------------- */ +/// A podcast's seasons, by feed id, as its page last fetched them, so going back to it draws its +/// picker at once while the counts are asked for again. +const seasonsOf=new Map(); +/// Whether a podcast is told in seasons: two or more of them, holding most of its episodes. A few +/// numbered among hundreds (The Vintage RPG Podcast's 2 of 366), or years given as seasons on a +/// quarter of them (Ken and Robin's), are no seasons worth a picker. +function seasonsShown(list: SeasonCount[]|undefined): boolean{ + if(!list) return false; + const numbered=list.filter(s=>s.season!=null); + const inOne=numbered.reduce((n,s)=>n+s.episodes,0), all=list.reduce((n,s)=>n+s.episodes,0); + return numbered.length>=2 && inOne*2>=all; +} +/// What the picker sends for a season: its number, or `none` for the episodes that name none. +const seasonKey=(s: SeasonCount)=>s.season==null?'none':String(s.season); +const seasonName=(s: number|null|undefined)=>s==null?'Other episodes':`Season ${s}`; +/// The picker, under the tabs: every season, one of them, or the episodes naming none. +function seasonsHTML(list: SeasonCount[]): string{ + const chip=(key: string,label: string,title: string)=> + ``; + return `
${chip('','All seasons','Every season')}${ + list.map(s=>chip(seasonKey(s),s.season==null?'Other':`Season ${s.season}`, + `${plural(s.episodes,'episode')}, ${s.unread} unread`)).join('')}
`; +} +function drawSeasons(f: Feed, list: SeasonCount[]|undefined){ + const bar=$('#content .toolbar'); if(!bar||S.feed!==f.id) return; + bar.querySelector('.seasons')?.remove(); + if(!list||!seasonsShown(list)) return; + bar.insertAdjacentHTML('beforeend',seasonsHTML(list)); + $$('.seasons button',bar).forEach(b=>b.onclick=()=>{ + S.season=b.dataset.season!; S.offset=0; + renderFeed(); loadEntries(); + }); + // The dividers in the list wait on knowing the podcast is told in seasons. + if(S.entries.length) renderEntries(); +} +/// A podcast's seasons onto its page: kept ones at once, then the server's. +async function loadSeasons(f: Feed){ + drawSeasons(f,seasonsOf.get(f.id)); + try{ + const got: SeasonCount[]=await api(`/api/feeds/${encodeURIComponent(f.id)}/seasons`); + seasonsOf.set(f.id,got); + drawSeasons(f,got); + }catch{} +} +/// Where a season starts in the list, said above its first episode: only for every season at +/// once, newest or oldest first, where the episodes run season by season. +function seasonBreaks(): boolean{ + return !S.season && S.sort.col==='published' && seasonsShown(seasonsOf.get(S.feed ?? '')); +} diff --git a/web/src/types.ts b/web/src/types.ts index 6d1a01d..f7c95e0 100644 --- a/web/src/types.ts +++ b/web/src/types.ts @@ -141,6 +141,9 @@ interface State { /// Whether the server has more after the last page it sent, by that answer's own numbers. more: boolean; filter: string; + /// One season of the open podcast (#482): its number, `none` for the episodes naming none, or + /// empty for every season. + season: string; q: string; /// The selected item's guid. sel: string | null; @@ -148,6 +151,14 @@ interface State { sort: {col: string, dir: 'asc' | 'desc'}; } +/// One season of a podcast, `/api/feeds/{id}/seasons` (db.rs SeasonCount, #482). No season is +/// the episodes that name none. +interface SeasonCount { + season?: number | null; + episodes: number; + unread: number; +} + /// A smart playlist, `/api/playlists` (db.rs PlaylistRow, #476). interface Playlist { id: number; diff --git a/web/src/util.ts b/web/src/util.ts index cedd55c..7aa84cb 100644 --- a/web/src/util.ts +++ b/web/src/util.ts @@ -345,7 +345,7 @@ const S: State = { feed:(()=>{ try{ return localStorage.getItem('ipx.feed'); }catch{ return null; } })(), entries:[], total:0, offset:0, more:false, filter:(()=>{ try{ return localStorage.getItem('ipx.filter'); }catch{ return null; } })()||'all', - q:'', sel:null, me:null, + season:'', q:'', sel:null, me:null, // The item table's order, kept across visits. The server sorts: a list arrives fifty at a time. sort:(()=>{ try{ return JSON.parse(localStorage.getItem('ipx.sort')??'null'); }catch{ return null; } })() ||{col:'published',dir:'desc'}, From 4eb6fbb28678609aecbdbe524d2a9d4409b0eeec Mon Sep 17 00:00:00 2001 From: rays Date: Thu, 19 Nov 2026 09:05:47 -0500 Subject: [PATCH 2/4] The app's wire code has the seasons' messages (#482) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy --- ios/Sources/Wire/ipx.pb.swift | 113 ++++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) diff --git a/ios/Sources/Wire/ipx.pb.swift b/ios/Sources/Wire/ipx.pb.swift index 44c81bc..15443c5 100644 --- a/ios/Sources/Wire/ipx.pb.swift +++ b/ios/Sources/Wire/ipx.pb.swift @@ -1151,6 +1151,45 @@ nonisolated struct Ipx_PlaylistRows: Sendable { init() {} } +/// One season of a podcast in GET /api/feeds/{id}/seasons (#482): its number, unset for the +/// episodes that name none, how many episodes it has and how many are unread. +nonisolated struct Ipx_SeasonRow: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + var season: Int64 { + get {_season ?? 0} + set {_season = newValue} + } + /// Returns true if `season` has been explicitly set. + var hasSeason: Bool {self._season != nil} + /// Clears the value of `season`. Subsequent reads from it will return its default value. + mutating func clearSeason() {self._season = nil} + + var episodes: Int64 = 0 + + var unread: Int64 = 0 + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} + + fileprivate var _season: Int64? = nil +} + +nonisolated struct Ipx_SeasonRows: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. + + var items: [Ipx_SeasonRow] = [] + + var unknownFields = SwiftProtobuf.UnknownStorage() + + init() {} +} + /// POST /api/playlists, the answer. nonisolated struct Ipx_PlaylistId: Sendable { // SwiftProtobuf.Message conformance is added in an extension below. See the @@ -3878,6 +3917,80 @@ nonisolated extension Ipx_PlaylistRows: SwiftProtobuf.Message, SwiftProtobuf._Me } } +nonisolated extension Ipx_SeasonRow: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".SeasonRow" + static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}season\0\u{1}episodes\0\u{1}unread\0") + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularInt64Field(value: &self._season) }() + case 2: try { try decoder.decodeSingularInt64Field(value: &self.episodes) }() + case 3: try { try decoder.decodeSingularInt64Field(value: &self.unread) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every if/case branch local when no optimizations + // are enabled. https://github.com/apple/swift-protobuf/issues/1034 and + // https://github.com/apple/swift-protobuf/issues/1182 + try { if let v = self._season { + try visitor.visitSingularInt64Field(value: v, fieldNumber: 1) + } }() + if self.episodes != 0 { + try visitor.visitSingularInt64Field(value: self.episodes, fieldNumber: 2) + } + if self.unread != 0 { + try visitor.visitSingularInt64Field(value: self.unread, fieldNumber: 3) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Ipx_SeasonRow, rhs: Ipx_SeasonRow) -> Bool { + if lhs._season != rhs._season {return false} + if lhs.episodes != rhs.episodes {return false} + if lhs.unread != rhs.unread {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + +nonisolated extension Ipx_SeasonRows: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { + static let protoMessageName: String = _protobuf_package + ".SeasonRows" + static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}items\0") + + mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeRepeatedMessageField(value: &self.items) }() + default: break + } + } + } + + func traverse(visitor: inout V) throws { + if !self.items.isEmpty { + try visitor.visitRepeatedMessageField(value: self.items, fieldNumber: 1) + } + try unknownFields.traverse(visitor: &visitor) + } + + static func ==(lhs: Ipx_SeasonRows, rhs: Ipx_SeasonRows) -> Bool { + if lhs.items != rhs.items {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } +} + nonisolated extension Ipx_PlaylistId: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".PlaylistId" static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}id\0") From c441215c628b8e46f145152494784430971e90d1 Mon Sep 17 00:00:00 2001 From: rays Date: Thu, 19 Nov 2026 09:21:50 -0500 Subject: [PATCH 3/4] A seasoned podcast runs in its own order, and a season downloads whole (#482) Asked for on the issue: lowest to highest, by season and then episode, and a way to download every episode of a season. sort=episode orders by season, episode, then date, with the episodes in none last either way round; a podcast told in seasons opens in it until a heading is clicked, and its seasons are offered lowest first. download-latest takes a season and queues every file of it not on iPX, first episode first, up to 300; the page asks first, since a season can be gigabytes. The picked season scrolls into view in the picker, and the count under the list is the season's. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy --- crates/ipx/CHANGELOG.md | 2 +- crates/ipx/src/db.rs | 56 +++++++++++++++++++++++++---------- crates/ipx/src/web.rs | 24 +++++++++++---- crates/wire/proto/ipx.proto | 2 ++ ios/Sources/Wire/ipx.pb.swift | 18 ++++++++++- tests/ui/app.spec.ts | 31 +++++++++++++++---- tests/ui/fixtures/seasons.xml | 12 +++++--- web/CHANGELOG.md | 2 +- web/src/feedpage.ts | 10 +++++-- web/src/feeds.ts | 2 +- web/src/items.ts | 6 ++-- web/src/seasons.ts | 47 +++++++++++++++++++++++++++-- 12 files changed, 168 insertions(+), 44 deletions(-) diff --git a/crates/ipx/CHANGELOG.md b/crates/ipx/CHANGELOG.md index fcda89b..9e92d23 100644 --- a/crates/ipx/CHANGELOG.md +++ b/crates/ipx/CHANGELOG.md @@ -14,7 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- `GET /api/feeds/{id}/seasons` gives a podcast's seasons with how many episodes and unread each has, and a podcast's episodes can be asked for one season at a time, or for those naming none (`season=none`) (#482). +- `GET /api/feeds/{id}/seasons` gives a podcast's seasons with how many episodes and unread each has, and a podcast's episodes can be asked for one season at a time, or for those naming none (`season=none`), and in its own order (`sort=episode`), season by season and episode by episode. `download-latest` takes a `season` to download all of it, first episode first (#482). - Smart playlists: `GET` and `POST /api/playlists`, `PATCH` and `DELETE /api/playlists/{id}`, and `GET /api/playlists/{id}/entries`, the episodes of the podcasts chosen in the playlist's order, those set to play first ahead of the rest (#476). - A feed in `/api/feeds` says whether it has audio or video (`podcast`), for the page's Podcasts shelf (#474). - Up Next, a queue of episodes kept per account so every device shares it: `GET /api/queue` lists it in order, `PUT /api/queue` sets it, and an episode leaves it once it is 90% played (#473). diff --git a/crates/ipx/src/db.rs b/crates/ipx/src/db.rs index 81c4596..d6948ec 100644 --- a/crates/ipx/src/db.rs +++ b/crates/ipx/src/db.rs @@ -1450,6 +1450,14 @@ fn not_hidden(user: &str) -> String { /// Pinned items are not lifted above the rest: sorting by the pin column, or the Pinned tab, does /// that when it is wanted, and lifting them always was undone (issues #35 and #36). pub fn order_sql(col: &str, dir: &str) -> String { + // A podcast told in seasons in its own order (#482): season by season, episode by episode, the + // episodes naming neither last whichever way round. + if col == "episode" { + let d = if dir == "desc" { "DESC" } else { "ASC" }; + return format!( + "e.season {d} NULLS LAST, e.episode {d} NULLS LAST, coalesce(e.published, e.first_seen) {d}, e.guid {d}" + ); + } let expr = match col { "kept" => "coalesce(s.flagged, false)", "title" => "lower(coalesce(e.title, ''))", @@ -1679,8 +1687,8 @@ impl Db { unread: unread.get(&season).copied().unwrap_or(0), }) .collect(); - // Newest season first; None, the episodes naming none, sorts below every number. - out.sort_by_key(|s| std::cmp::Reverse(s.season)); + // Lowest season first, as the podcast runs; the episodes naming none last. + out.sort_by_key(|s| (s.season.is_none(), s.season)); Ok(out) } @@ -2664,14 +2672,25 @@ impl Db { /// The next N enclosures with no file, newest entry first -- what "download latest" /// queues up. - pub async fn undownloaded(&self, feed_id: &str, limit: i64) -> Result> { + /// A feed's files not downloaded, newest first, or one season's in its own order (#482): what + /// Download latest, or Download this season, queues. + pub async fn undownloaded(&self, feed_id: &str, season: Season, limit: i64) -> Result> { + let mut a = Args::default(); + let (feed, limit) = (a.p(feed_id), a.p(limit)); + let (which, order) = match season { + Season::Any => (String::new(), order_sql("published", "desc")), + Season::Of(n) => (format!("AND e.season = {}", a.p(n)), order_sql("episode", "asc")), + Season::Unnumbered => ("AND e.season IS NULL".into(), order_sql("published", "asc")), + }; self.rows( - "SELECT x.id FROM enclosures x - JOIN entries e ON e.feed_id = x.feed_id AND e.guid = x.guid - WHERE x.feed_id = $1 AND x.path IS NULL AND x.state <> 'reaped' - ORDER BY coalesce(e.published, e.first_seen) DESC - LIMIT $2", - vec![feed_id.into(), limit.into()], + &format!( + "SELECT x.id FROM enclosures x + JOIN entries e ON e.feed_id = x.feed_id AND e.guid = x.guid + WHERE x.feed_id = {feed} AND x.path IS NULL AND x.state <> 'reaped' {which} + ORDER BY {order} + LIMIT {limit}" + ), + a.0, ) .await? .iter() @@ -4190,18 +4209,18 @@ mod tests { let db = Db::memory().await.unwrap(); db.exec_for_test( "INSERT INTO users (id, name, is_admin) VALUES (1,'ray',true); - INSERT INTO entries (feed_id, guid, title, published, first_seen, season) VALUES - ('f','a','S1E1',100,100,1),('f','b','S1E2',200,200,1),('f','c','S2E1',300,300,2), - ('f','d','Trailer',50,50,NULL),('g','e','Elsewhere',400,400,2);", + INSERT INTO entries (feed_id, guid, title, published, first_seen, season, episode) VALUES + ('f','a','S1E1',200,200,1,1),('f','b','S1E2',100,100,1,2),('f','c','S2E1',300,300,2,1), + ('f','d','Trailer',50,50,NULL,NULL),('g','e','Elsewhere',400,400,2,1);", ) .await .unwrap(); db.subscribe(1, "f").await.unwrap(); db.set_entry_flag(1, "f", "a", EntryFlag::Read, true).await.unwrap(); - // Newest first, the unnumbered last, each with its unread; another feed's season 2 is not in it. + // Lowest first, the unnumbered last, each with its unread; another feed's season 2 is not in it. let got = db.seasons(1, &["f"]).await.unwrap(); - let want = [(Some(2), 1, 1), (Some(1), 2, 1), (None, 1, 1)]; + let want = [(Some(1), 2, 1), (Some(2), 1, 1), (None, 1, 1)]; assert_eq!(got.iter().map(|s| (s.season, s.episodes, s.unread)).collect::>(), want); let order = order_sql("published", "desc"); @@ -4210,10 +4229,17 @@ mod tests { assert_eq!(db.season_count(1, &["f"], season, Filter::All, None).await.unwrap(), rows.len() as i64); rows.into_iter().map(|r| r.title.unwrap()).collect::>() }; - assert_eq!(titles(Season::Of(1)).await, ["S1E2", "S1E1"]); + // By date, newest first: S1E2 came out first, as a season's episodes sometimes do. + assert_eq!(titles(Season::Of(1)).await, ["S1E1", "S1E2"]); assert_eq!(titles(Season::Unnumbered).await, ["Trailer"]); assert_eq!(titles(Season::Any).await.len(), 4); assert_eq!(db.season_count(1, &["f"], Season::Of(1), Filter::Unread, None).await.unwrap(), 1); + // In the podcast's own order, season by season, the episodes in none last either way round. + let (up, down) = (order_sql("episode", "asc"), order_sql("episode", "desc")); + let all = db.season_entries(1, &["f"], Season::Any, Filter::All, None, 0, 50, &up).await.unwrap(); + assert_eq!(all.into_iter().map(|r| r.title.unwrap()).collect::>(), ["S1E1", "S1E2", "S2E1", "Trailer"]); + let back = db.season_entries(1, &["f"], Season::Any, Filter::All, None, 0, 50, &down).await.unwrap(); + assert_eq!(back.last().unwrap().title.as_deref(), Some("Trailer")); } #[tokio::test] diff --git a/crates/ipx/src/web.rs b/crates/ipx/src/web.rs index 112b5e3..4e98821 100644 --- a/crates/ipx/src/web.rs +++ b/crates/ipx/src/web.rs @@ -2074,6 +2074,16 @@ async fn entries( entry_page(&state, user.id, Some(&ids[..]), None, &page).await } +/// A season as the page sends it (#482): its number, `none` for the episodes naming none, or +/// nothing for every season. +fn season_of(s: Option<&str>) -> Result { + Ok(match s.map(str::trim) { + None | Some("") => db::Season::Any, + Some("none") => db::Season::Unnumbered, + Some(n) => db::Season::Of(n.parse().map_err(|_| ApiError::bad_request(format!("no season {n:?}")))?), + }) +} + /// A podcast's seasons, for its page to offer one at a time (#482). An OPML's are its shows' /// together, as its items are. async fn seasons( @@ -2123,11 +2133,7 @@ async fn entry_page( let order = crate::db::order_sql(page.sort.as_deref().unwrap_or("published"), page.dir.as_deref().unwrap_or("desc")); let limit = page.limit.clamp(1, 200); - let season = match page.season.as_deref().map(str::trim) { - None | Some("") => db::Season::Any, - Some("none") => db::Season::Unnumbered, - Some(n) => db::Season::Of(n.parse().map_err(|_| ApiError::bad_request(format!("no season {n:?}")))?), - }; + let season = season_of(page.season.as_deref())?; // Which list, so a slow one's trace says what was asked of it (#287). The search's words stay // out: they are the reader's own. let in_list = tracing::info_span!( @@ -3233,6 +3239,9 @@ async fn read_all_mine( struct HowMany { #[serde(default = "five")] count: i64, + /// One season, all of it, in place of the newest `count` (#482). + #[serde(default)] + season: Option, } fn five() -> i64 { @@ -3248,7 +3257,10 @@ async fn download_latest( Json(body): Json, ) -> Result, ApiError> { subscribed(&state, &user, &id).await?; - let ids = state.ctx.db.undownloaded(&id, body.count.clamp(1, 100)).await?; + let season = season_of(body.season.as_deref())?; + // A whole season, Oxide and Friends' longest 47 episodes; past 300 it is no season. + let most = if season == db::Season::Any { body.count.clamp(1, 100) } else { 300 }; + let ids = state.ctx.db.undownloaded(&id, season, most).await?; for enc in &ids { state.ctx.db.requeue(*enc).await?; state diff --git a/crates/wire/proto/ipx.proto b/crates/wire/proto/ipx.proto index 6a8e149..029267d 100644 --- a/crates/wire/proto/ipx.proto +++ b/crates/wire/proto/ipx.proto @@ -180,6 +180,8 @@ message FeedPatch { // POST /api/feeds/{id}/download-latest, the body. message HowMany { optional int64 count = 1; + // One season, all of it (#482): its number, or "none" for the episodes naming none. + optional string season = 2; } // POST /api/feeds/{id}/download-latest, the answer. diff --git a/ios/Sources/Wire/ipx.pb.swift b/ios/Sources/Wire/ipx.pb.swift index 15443c5..c872c73 100644 --- a/ios/Sources/Wire/ipx.pb.swift +++ b/ios/Sources/Wire/ipx.pb.swift @@ -780,11 +780,22 @@ nonisolated struct Ipx_HowMany: Sendable { /// Clears the value of `count`. Subsequent reads from it will return its default value. mutating func clearCount() {self._count = nil} + /// One season, all of it (#482): its number, or "none" for the episodes naming none. + var season: String { + get {_season ?? String()} + set {_season = newValue} + } + /// Returns true if `season` has been explicitly set. + var hasSeason: Bool {self._season != nil} + /// Clears the value of `season`. Subsequent reads from it will return its default value. + mutating func clearSeason() {self._season = nil} + var unknownFields = SwiftProtobuf.UnknownStorage() init() {} fileprivate var _count: Int64? = nil + fileprivate var _season: String? = nil } /// POST /api/feeds/{id}/download-latest, the answer. @@ -3353,7 +3364,7 @@ nonisolated extension Ipx_FeedPatch: SwiftProtobuf.Message, SwiftProtobuf._Messa nonisolated extension Ipx_HowMany: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { static let protoMessageName: String = _protobuf_package + ".HowMany" - static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}count\0") + static let _protobuf_nameMap = SwiftProtobuf._NameMap(bytecode: "\0\u{1}count\0\u{1}season\0") mutating func decodeMessage(decoder: inout D) throws { while let fieldNumber = try decoder.nextFieldNumber() { @@ -3362,6 +3373,7 @@ nonisolated extension Ipx_HowMany: SwiftProtobuf.Message, SwiftProtobuf._Message // enabled. https://github.com/apple/swift-protobuf/issues/1034 switch fieldNumber { case 1: try { try decoder.decodeSingularInt64Field(value: &self._count) }() + case 2: try { try decoder.decodeSingularStringField(value: &self._season) }() default: break } } @@ -3375,11 +3387,15 @@ nonisolated extension Ipx_HowMany: SwiftProtobuf.Message, SwiftProtobuf._Message try { if let v = self._count { try visitor.visitSingularInt64Field(value: v, fieldNumber: 1) } }() + try { if let v = self._season { + try visitor.visitSingularStringField(value: v, fieldNumber: 2) + } }() try unknownFields.traverse(visitor: &visitor) } static func ==(lhs: Ipx_HowMany, rhs: Ipx_HowMany) -> Bool { if lhs._count != rhs._count {return false} + if lhs._season != rhs._season {return false} if lhs.unknownFields != rhs.unknownFields {return false} return true } diff --git a/tests/ui/app.spec.ts b/tests/ui/app.spec.ts index 8376822..e4862c6 100644 --- a/tests/ui/app.spec.ts +++ b/tests/ui/app.spec.ts @@ -3218,20 +3218,39 @@ test('a reap over the quota says what it would delete and, dry, deletes nothing' expect(files()).toBe(before); }); -test('a podcast told in seasons is listed one season at a time, or all with each season marked (#482)', async ({ page }) => { +test('a podcast told in seasons runs in its own order, one season at a time or all, and a season downloads whole (#482)', async ({ page }) => { await page.locator('#feedlist .feed', { hasText: 'Seasoned Show' }).click({ timeout: 20_000 }); await page.locator('#content .tabs button[data-f="all"]').click(); const picker = page.locator('#content .seasons'); - await expect(picker.locator('button')).toHaveText(['All seasons', 'Season 2', 'Season 1', 'Other']); - // Every season, newest first: where each starts is said above its first episode. - await expect(page.locator('#eps .sdiv')).toHaveText(['Season 2', 'Other episodes', 'Season 1']); + await expect(picker.locator('button')).toHaveText(['All seasons', 'Season 1', 'Season 2', 'Other']); + // Every season, in the podcast's own order, season 1 episode 1 first: each season's start said. + await expect(page.locator('#eps .ep .t')).toHaveText(['The Pilot', 'Season One Close', 'Season Two Opener', 'Season Two Finale', 'A Bonus Between']); + await expect(page.locator('#eps .sdiv')).toHaveText(['Season 1', 'Season 2', 'Other episodes']); + // A heading clicked sorts by it, newest first, as on any other podcast. + await page.locator('.ephead [data-sort="published"]').click(); + await expect(page.locator('#eps .ep .t').first()).toHaveText('Season Two Finale'); + await picker.locator('button', { hasText: 'Season 1' }).click(); + await expect(page.locator('#content .seasons button', { hasText: 'Season 1' })).toHaveAttribute('aria-pressed', 'true'); await expect(page.locator('#eps .ep .t')).toHaveText(['The Pilot', 'Season One Close']); await expect(page.locator('#eps .sdiv')).toHaveCount(0); - await expect(page.locator('#content .seasons button', { hasText: 'Season 1' })).toHaveAttribute('aria-pressed', 'true'); + // The count under the list is the season's, as the server counts it. + const unread = await page.evaluate(async () => (await fetch('/api/feeds/seasoned-show/seasons').then(r => r.json())) + .find((s: { season?: number }) => s.season === 1).unread); + await expect(page.locator('#count')).toHaveText(`Seasoned Show: 2 items, ${unread} unread`); + // The whole season onto iPX, after asking, its first episode first. + await page.locator('#content .seasondl').click(); + await page.locator('#sgo').click(); + // By its words: each file's own toast follows at once on the fixtures' tiny files. + await expect(page.locator('.toast', { hasText: /Downloading 2 episodes of Season 1|All of Season 1 is on iPX already/ })).toBeAttached(); + await expect.poll(async () => page.evaluate(async () => (await fetch('/api/feeds/seasoned-show/entries?season=1').then(r => r.json())) + .entries.every((e: { enclosures: { path: string | null }[] }) => e.enclosures.every(x => x.path))), { timeout: 20_000 }).toBe(true); + expect(await page.evaluate(async () => (await fetch('/api/feeds/seasoned-show/entries?season=2').then(r => r.json())) + .entries.some((e: { enclosures: { path: string | null }[] }) => e.enclosures.some(x => x.path)))).toBe(false); + await page.locator('#content .seasons button', { hasText: 'Other' }).click(); await expect(page.locator('#eps .ep .t')).toHaveText(['A Bonus Between']); - // A podcast with one season has no picker, and opening it starts from every season again. + // A podcast with one season has no picker, and opening it again starts from every season. await page.locator('#feedlist .feed', { hasText: 'Test Show' }).first().click(); await expect(page.locator('#content .seasons')).toHaveCount(0); await page.locator('#feedlist .feed', { hasText: 'Seasoned Show' }).click(); diff --git a/tests/ui/fixtures/seasons.xml b/tests/ui/fixtures/seasons.xml index e0a2383..ff6dcec 100644 --- a/tests/ui/fixtures/seasons.xml +++ b/tests/ui/fixtures/seasons.xml @@ -2,12 +2,16 @@ Seasoned Showhttp://127.0.0.1:8792/A fixture podcast told in seasons (#482). Season Two Finalesn-4Mon, 01 Jun 2026 10:00:00 +0000 - 22 + 22 + Season Two Openersn-3Mon, 25 May 2026 10:00:00 +0000 - 21 + 21 + A Bonus Betweensn-bMon, 18 May 2026 10:00:00 +0000 The Pilotsn-1Mon, 11 May 2026 10:00:00 +0000 - 11 + 11 + Season One Closesn-2Mon, 04 May 2026 10:00:00 +0000 - 12 + 12 + diff --git a/web/CHANGELOG.md b/web/CHANGELOG.md index 30fb007..a5c8b2f 100644 --- a/web/CHANGELOG.md +++ b/web/CHANGELOG.md @@ -13,7 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- A podcast told in seasons has a season picker under its tabs, to list one season at a time or the episodes in none, and listed all together, newest or oldest first, each season's start is marked (#482). +- A podcast told in seasons lists its episodes in its own order, season 1 episode 1 first, until a heading is clicked to sort it otherwise, with each season's start marked. A season picker under its tabs lists one season at a time, or the episodes in none, and a season picked can be downloaded whole (#482). - Smart playlists, in a folder of their own in the feed list: choose the podcasts, which of them play first, unplayed episodes only or all, newest or oldest first, and the playlist keeps itself up to date. Playing from one goes on through it once Up Next is empty (#476). - Now Playing: tap the player bar to see what is playing with its artwork large, its podcast (a tap opens it), its show notes and what follows in Up Next; Esc or the bar closes it (#475). - Podcasts: your podcasts as a shelf of their artwork, each with how many episodes are new; the search box narrows it, and a tap opens one (#474). diff --git a/web/src/feedpage.ts b/web/src/feedpage.ts index 5ed8a9e..7fc0680 100644 --- a/web/src/feedpage.ts +++ b/web/src/feedpage.ts @@ -107,16 +107,20 @@ function renderFeed(){ /// natural way round (A to Z; newest, largest and kept first) and the next one reverses it. const COLS=[['kept','Pinned',ICON.pin],['title','Title'],['feed','Feed'],['type','File'],['size','Size'],['published','Published']]; function sortHead(){ + const now=sortFor(S.feed ?? ''); return '
'+COLS.map(([k,label,icon])=>{ - const on=S.sort.col===k; + const on=now.col===k; return ``; + `${on?`${ICON.caret}`:''}`; }).join('')+'
'; } function sortBy(col: string){ const first=['published','size','kept'].includes(col)?'desc':'asc'; - S.sort={col,dir:S.sort.col===col?(S.sort.dir==='asc'?'desc':'asc'):first}; + // From a seasoned podcast's own order (#482), the first click is that column's first way round. + const now=sortFor(S.feed ?? ''); + S.sort={col,dir:now.col===col?(now.dir==='asc'?'desc':'asc'):first}; + sortPicked=true; try{ localStorage.setItem('ipx.sort',JSON.stringify(S.sort)); }catch{} S.offset=0; renderFeed(); loadEntries(); } diff --git a/web/src/feeds.ts b/web/src/feeds.ts index e517c4f..bc2a7b6 100644 --- a/web/src/feeds.ts +++ b/web/src/feeds.ts @@ -202,7 +202,7 @@ function renderFeeds(){ done(); } function selectFeed(id: string){ - S.feed=id; S.offset=0; S.sel=null; S.q=''; S.season=''; $('#epSearch').value=''; + S.feed=id; S.offset=0; S.sel=null; S.q=''; S.season=''; sortPicked=false; $('#epSearch').value=''; try{ localStorage.setItem('ipx.feed',id); }catch{} renderFeeds(); renderFeed(); loadEntries(); } diff --git a/web/src/items.ts b/web/src/items.ts index 153cd58..b84a683 100644 --- a/web/src/items.ts +++ b/web/src/items.ts @@ -16,9 +16,9 @@ const LISTS_KEPT=40; const fetching=new Map>(); // A season is of the podcast open (#482): another feed's list, fetched ahead, is of every season. const seasonFor=(feed: string)=>feed===S.feed?S.season:''; -const listKey=(feed: string, filter=S.filter)=>[feed,filter,S.sort.col,S.sort.dir,S.q,seasonFor(feed)].join('\n'); +const listKey=(feed: string, filter=S.filter)=>[feed,filter,sortFor(feed).col,sortFor(feed).dir,S.q,seasonFor(feed)].join('\n'); function listUrl(feed: string, filter=S.filter, offset=0){ - const p=new URLSearchParams({offset:String(offset),limit:String(LIMIT),filter,sort:S.sort.col,dir:S.sort.dir}); + const p=new URLSearchParams({offset:String(offset),limit:String(LIMIT),filter,sort:sortFor(feed).col,dir:sortFor(feed).dir}); if(S.q) p.set('q',S.q); if(seasonFor(feed)) p.set('season',seasonFor(feed)); const sg=signalId(feed); @@ -146,7 +146,7 @@ function renderEntries(){ const f=S.feeds.find(x=>x.id===S.feed), v=VIEWS[S.feed ?? ''], sg=signalOf(S.feed); // An OPML's own row counts nothing: its shows do. const kids=f?S.feeds.filter(c=>c.group===f.id):[]; - const unread=kids.length?kids.reduce((n,x)=>n+x.unread,0):f?f.unread:sg?sg.unread:S.feeds.reduce((n,x)=>n+(x.unread||0),0); + const unread=kids.length?kids.reduce((n,x)=>n+x.unread,0):f?(seasonUnread(f.id)??f.unread):sg?sg.unread:S.feeds.reduce((n,x)=>n+(x.unread||0),0); $('#count').textContent= `${f?(f.title||f.id):sg?sg.name:v?v.title:''}: ${S.total} item${S.total===1?'':'s'}, ${unread} unread`; const pane=$('#list'), top=pane?pane.scrollTop:0; diff --git a/web/src/seasons.ts b/web/src/seasons.ts index bcac0f8..cff925c 100644 --- a/web/src/seasons.ts +++ b/web/src/seasons.ts @@ -24,9 +24,16 @@ function seasonsHTML(list: SeasonCount[]): string{ } function drawSeasons(f: Feed, list: SeasonCount[]|undefined){ const bar=$('#content .toolbar'); if(!bar||S.feed!==f.id) return; - bar.querySelector('.seasons')?.remove(); + bar.querySelector('.seasons')?.remove(); bar.querySelector('.seasondl')?.remove(); if(!list||!seasonsShown(list)) return; bar.insertAdjacentHTML('beforeend',seasonsHTML(list)); + if(S.season) bar.insertAdjacentHTML('beforeend',``); + bar.querySelector('.seasondl')?.addEventListener('click',()=>downloadSeason(f)); + // The one picked in view: on a phone Season 3 of six is past the edge, and the picker looked as + // if every season were still showing. + const track=bar.querySelector('.seasons'), on=track?.querySelector('.on'); + if(track&&on) track.scrollLeft+=on.getBoundingClientRect().left-track.getBoundingClientRect().left-(track.clientWidth-on.offsetWidth)/2; $$('.seasons button',bar).forEach(b=>b.onclick=()=>{ S.season=b.dataset.season!; S.offset=0; renderFeed(); loadEntries(); @@ -34,17 +41,51 @@ function drawSeasons(f: Feed, list: SeasonCount[]|undefined){ // The dividers in the list wait on knowing the podcast is told in seasons. if(S.entries.length) renderEntries(); } -/// A podcast's seasons onto its page: kept ones at once, then the server's. +/// A podcast's seasons onto its page: kept ones at once, then the server's. Told in seasons only +/// once the answer came, its list is asked for again in its own order. async function loadSeasons(f: Feed){ + const had=seasonsShown(seasonsOf.get(f.id)); drawSeasons(f,seasonsOf.get(f.id)); try{ const got: SeasonCount[]=await api(`/api/feeds/${encodeURIComponent(f.id)}/seasons`); seasonsOf.set(f.id,got); drawSeasons(f,got); + // Drawn again, so the headings say the order too. + if(!had&&seasonsShown(got)&&!sortPicked&&S.feed===f.id){ S.offset=0; renderFeed(); loadEntries(); } }catch{} } +/// Whether a heading was clicked to sort the podcast open: until one is, a podcast told in +/// seasons runs in its own order, season 1 episode 1 first, not by date (#482). +let sortPicked=false; +/// The order a list is asked for in: the page's, or a seasoned podcast's own. +function sortFor(feed: string): {col: string, dir: 'asc'|'desc'}{ + return feed===S.feed&&!sortPicked&&seasonsShown(seasonsOf.get(feed)) ? {col:'episode',dir:'asc'} : S.sort; +} +/// The unread of the season picked, for the count under the list; null for every season. +function seasonUnread(feed: string): number|null{ + if(!S.season) return null; + return seasonsOf.get(feed)?.find(s=>seasonKey(s)===S.season)?.unread ?? null; +} /// Where a season starts in the list, said above its first episode: only for every season at /// once, newest or oldest first, where the episodes run season by season. function seasonBreaks(): boolean{ - return !S.season && S.sort.col==='published' && seasonsShown(seasonsOf.get(S.feed ?? '')); + const feed=S.feed ?? '', col=sortFor(feed).col; + return !S.season && (col==='episode'||col==='published') && seasonsShown(seasonsOf.get(feed)); +} +/// Every episode of the season picked onto iPX, after asking: a season can be a few gigabytes. +function downloadSeason(f: Feed){ + const s=seasonsOf.get(f.id)?.find(x=>seasonKey(x)===S.season); if(!s) return; + const name=seasonName(s.season); + openModal(`

Download ${esc(name)}?

+

Every episode of ${esc(name)} of ${esc(f.title||f.id)} not on iPX yet, ${ + plural(s.episodes,'episode')} in all, is downloaded in order, the first episode first.

+
+
`); + $('#sgo').onclick=async()=>{ + try{ + const r=await api(`/api/feeds/${encodeURIComponent(f.id)}/download-latest`,{method:'POST',body:JSON.stringify({season:S.season})}); + closeModal(); + toast(r.queued?`Downloading ${plural(r.queued,'episode')} of ${name}`:`All of ${name} is on iPX already`); + }catch(e){ toast(why(e),true); } + }; } From 4421d1d0837ec6fd6677d88cafbb1841bbd431fa Mon Sep 17 00:00:00 2001 From: rays Date: Thu, 19 Nov 2026 09:24:21 -0500 Subject: [PATCH 4/4] A season's download sits on the picker's row (#482) On a phone, on a row of its own under the picker, it cost a line above the list for one button. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy --- web/app.css | 5 ++++- web/src/seasons.ts | 9 +++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/web/app.css b/web/app.css index d5aeb76..b5103bd 100644 --- a/web/app.css +++ b/web/app.css @@ -990,7 +990,8 @@ kbd{font:inherit;font-size:12px;color:var(--fg);background:var(--panel2);border: .tabs a{padding:5px 12px;border-radius:7px;font-size:13px;color:var(--dim);text-decoration:none} .tabs a.on{background:var(--raise);color:var(--fg);font-weight:500} /* A podcast's seasons (#482): the tabs' track, scrolled sideways when there are more than fit. */ -.tabs.seasons{max-width:100%;overflow-x:auto;scrollbar-width:none} +.seasonrow{display:flex;gap:8px;align-items:center;min-width:0;max-width:100%} +.tabs.seasons{min-width:0;overflow-x:auto;scrollbar-width:none} .tabs.seasons::-webkit-scrollbar{display:none} .tabs.seasons button{white-space:nowrap;flex:none} /* Where a season starts in the list of every season. */ @@ -1547,6 +1548,8 @@ body:has(#player.on) #status{padding-bottom:3px} .tabs button,.tabs a{flex:1;text-align:center;padding:7px 4px;border-radius:8px;font-size:14px} .tabs button.on,.tabs a.on{box-shadow:0 1px 3px rgba(0,0,0,.22)} /* Seasons keep their own widths, scrolling past the edge, rather than squeezing eight into 390px. */ + .seasonrow{flex:1 1 100%} + .seasonrow .tabs.seasons{flex:1 1 auto} .tabs.seasons button{flex:none;padding:7px 12px} /* Rows: taller, larger type, and a hairline between them that starts where the text does. */ diff --git a/web/src/seasons.ts b/web/src/seasons.ts index cff925c..396c7b7 100644 --- a/web/src/seasons.ts +++ b/web/src/seasons.ts @@ -24,11 +24,12 @@ function seasonsHTML(list: SeasonCount[]): string{ } function drawSeasons(f: Feed, list: SeasonCount[]|undefined){ const bar=$('#content .toolbar'); if(!bar||S.feed!==f.id) return; - bar.querySelector('.seasons')?.remove(); bar.querySelector('.seasondl')?.remove(); + bar.querySelector('.seasonrow')?.remove(); if(!list||!seasonsShown(list)) return; - bar.insertAdjacentHTML('beforeend',seasonsHTML(list)); - if(S.season) bar.insertAdjacentHTML('beforeend',``); + // The download beside the picker, on its row: on a phone, on a row of its own, it cost a line. + const picked=list.find(s=>seasonKey(s)===S.season); + bar.insertAdjacentHTML('beforeend',`
${seasonsHTML(list)}${picked?``:''}
`); bar.querySelector('.seasondl')?.addEventListener('click',()=>downloadSeason(f)); // The one picked in view: on a phone Season 3 of six is past the edge, and the picker looked as // if every season were still showing.