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); } + }; }