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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy
This commit is contained in:
2026-11-19 09:21:50 -05:00
parent 4eb6fbb286
commit c441215c62
12 changed files with 168 additions and 44 deletions

View File

@@ -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).

View File

@@ -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<Vec<i64>> {
/// 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<Vec<i64>> {
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::<Vec<_>>(), 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::<Vec<_>>()
};
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::<Vec<_>>(), ["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]

View File

@@ -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<db::Season, ApiError> {
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<String>,
}
fn five() -> i64 {
@@ -3248,7 +3257,10 @@ async fn download_latest(
Json(body): Json<HowMany>,
) -> Result<Json<serde_json::Value>, 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

View File

@@ -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.