Smart playlists (#476)

A playlist is the episodes of the podcasts chosen, those set to play first
ahead of the rest, newest or oldest first, unplayed only or all, kept up to
date by itself (table `playlists`, /api/playlists). It sits in a folder of its
own in the feed list, as Signals do. Played from one, an episode goes on to
the playlist's next once Up Next has nothing.

The priority ids are written into the ORDER BY, which the page query uses
twice, so they are quoted there rather than bound; they are also only ever
feed ids this person subscribes to.

The folder row first borrowed Signals' `sigs` class, which the tests use to
mean Signals' folder; four Signals tests failed until it had its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 14:54:19 +00:00
parent 2faca684da
commit 02ee6d74c1
17 changed files with 540 additions and 11 deletions

View File

@@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- 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).
- The API answers in protobuf as well as JSON: a client that sends `Accept: application/x-protobuf` gets protobuf, and one that sends `Content-Type: application/x-protobuf` may send its body so; JSON stays the default for a client that does not ask, and an answer of null stays JSON. The messages are in `crates/wire/proto/ipx.proto`. ipx's own calls to the directory and ipx-play go in protobuf too, so both need their protobuf releases first. Answers and those calls go through structs generated from the `.proto` files, about four times quicker to read than the JSON (#465, #470).

View File

@@ -2,8 +2,8 @@
//! per-feed .ipxd plists, history.dat and qmcache.dat.
use crate::entity::{
api_tokens, blocklists, catalogue, deadair_prefs, enclosures, entries, feeds, hidden, push_devices, sessions,
settings, signal_verdicts, signals, subscriptions, users,
api_tokens, blocklists, catalogue, deadair_prefs, enclosures, entries, feeds, hidden, playlists, push_devices,
sessions, settings, signal_verdicts, signals, subscriptions, users,
};
use anyhow::{Context, Result};
use sea_orm::sea_query::{Expr, Func};
@@ -74,6 +74,7 @@ async fn create_missing(orm: &DatabaseConnection) -> Result<()> {
schema.create_table_from_entity(signal_verdicts::Entity),
schema.create_table_from_entity(push_devices::Entity),
schema.create_table_from_entity(queue::Entity),
schema.create_table_from_entity(playlists::Entity),
] {
orm.execute(table.if_not_exists()).await.context("creating the schema")?;
}
@@ -1459,6 +1460,41 @@ pub fn order_sql(col: &str, dir: &str) -> String {
format!("{expr} {dir}, coalesce(e.published, e.first_seen) DESC, e.guid DESC")
}
/// A smart playlist as it is made and kept (#476): which podcasts, which of them come first, and
/// which of their episodes.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct PlaylistSpec {
pub name: String,
pub feeds: Vec<String>,
#[serde(default)]
pub priority: Vec<String>,
#[serde(default)]
pub only_unplayed: bool,
#[serde(default)]
pub oldest_first: bool,
}
/// A playlist in the list, with how many episodes it holds now.
#[derive(Debug, serde::Serialize)]
pub struct PlaylistRow {
pub id: i64,
#[serde(flatten)]
pub spec: PlaylistSpec,
pub items: i64,
}
/// A playlist's order: its priority podcasts' episodes first, then by date, newest or oldest
/// first. The ids are written into the SQL, so each is quoted; they are feed ids this person
/// subscribes to, slugs, but the quoting does not rely on that.
pub fn playlist_order(spec: &PlaylistSpec) -> String {
let by_date = order_sql("published", if spec.oldest_first { "asc" } else { "desc" });
if spec.priority.is_empty() {
return by_date;
}
let ids = spec.priority.iter().map(|f| format!("'{}'", f.replace('\'', "''"))).collect::<Vec<_>>().join(", ");
format!("CASE WHEN e.feed_id IN ({ids}) THEN 0 ELSE 1 END, {by_date}")
}
/// Which slice of a feed the UI is asking for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Filter {
@@ -3248,6 +3284,74 @@ impl Db {
Ok(true)
}
/// This person's smart playlists (#476), by name, each with its count. A podcast unsubscribed
/// from since is left out of it, here and in its episodes.
pub async fn playlists(&self, user_id: i64) -> Result<Vec<PlaylistRow>> {
let mine: std::collections::HashSet<String> =
self.subscriptions_for(user_id).await?.into_iter().map(|s| s.feed_id).collect();
let rows = playlists::Entity::find()
.filter(playlists::Column::UserId.eq(user_id))
.order_by_asc(playlists::Column::Name)
.all(&self.orm)
.await?;
let mut out = Vec::with_capacity(rows.len());
for p in rows {
let mut spec = PlaylistSpec {
name: p.name,
feeds: serde_json::from_str(&p.feeds)?,
priority: serde_json::from_str(&p.priority)?,
only_unplayed: p.only_unplayed,
oldest_first: p.oldest_first,
};
spec.feeds.retain(|f| mine.contains(f));
spec.priority.retain(|f| spec.feeds.contains(f));
let feeds: Vec<&str> = spec.feeds.iter().map(String::as_str).collect();
let filter = if spec.only_unplayed { Filter::Unread } else { Filter::All };
let items = self.count_of(user_id, Some(&feeds), filter, None).await?;
out.push(PlaylistRow { id: p.id, spec, items });
}
Ok(out)
}
pub async fn playlist(&self, user_id: i64, id: i64) -> Result<Option<PlaylistRow>> {
Ok(self.playlists(user_id).await?.into_iter().find(|p| p.id == id))
}
/// Makes a playlist, or with `id` changes one of this person's: its id, or None when that one
/// is not theirs.
pub async fn save_playlist(&self, user_id: i64, id: Option<i64>, spec: &PlaylistSpec) -> Result<Option<i64>> {
let mut m = playlists::ActiveModel {
user_id: Set(user_id),
name: Set(spec.name.clone()),
feeds: Set(serde_json::to_string(&spec.feeds)?),
priority: Set(serde_json::to_string(&spec.priority)?),
only_unplayed: Set(spec.only_unplayed),
oldest_first: Set(spec.oldest_first),
..Default::default()
};
let Some(id) = id else {
m.created = Set(now());
return Ok(Some(m.insert(&self.orm).await?.id));
};
let theirs = playlists::Entity::find_by_id(id).one(&self.orm).await?.is_some_and(|p| p.user_id == user_id);
if !theirs {
return Ok(None);
}
m.id = Set(id);
m.update(&self.orm).await?;
Ok(Some(id))
}
pub async fn remove_playlist(&self, user_id: i64, id: i64) -> Result<bool> {
let n = playlists::Entity::delete_many()
.filter(playlists::Column::Id.eq(id))
.filter(playlists::Column::UserId.eq(user_id))
.exec(&self.orm)
.await?
.rows_affected;
Ok(n > 0)
}
pub async fn typesafe_key_set(&self, user_id: i64) -> Result<bool> {
Ok(users::Entity::find_by_id(user_id).one(&self.orm).await?.is_some_and(|u| u.typesafe_key.is_some()))
}
@@ -3987,6 +4091,51 @@ mod tests {
assert!(guids(1).await.is_empty());
}
#[tokio::test]
async fn a_playlist_puts_its_priority_podcasts_first_and_is_its_owners_alone() {
let db = Db::memory().await.unwrap();
db.exec_for_test(
"INSERT INTO users (id, name, is_admin) VALUES (1,'ray',true),(2,'sam',false);
INSERT INTO entries (feed_id, guid, title, published, first_seen) VALUES
('f','f1','F old',100,100),('f','f2','F new',300,300),('g','g1','G mid',200,200),('h','h1','H',400,400);",
)
.await
.unwrap();
for f in ["f", "g", "h"] {
db.subscribe(1, f).await.unwrap();
}
let spec = |priority: &[&str], oldest_first| PlaylistSpec {
name: "Commute".into(),
feeds: vec!["f".into(), "g".into()],
priority: priority.iter().map(|p| p.to_string()).collect(),
only_unplayed: false,
oldest_first,
};
let id = db.save_playlist(1, None, &spec(&[], false)).await.unwrap().unwrap();
let guids = async |s: &PlaylistSpec| {
let feeds: Vec<&str> = s.feeds.iter().map(String::as_str).collect();
let rows = db.entries_of(1, Some(&feeds), Filter::All, None, 0, 50, &playlist_order(s)).await.unwrap();
rows.into_iter().map(|e| e.guid).collect::<Vec<_>>()
};
assert_eq!(guids(&spec(&[], false)).await, ["f2", "g1", "f1"], "newest first, h not in it");
assert_eq!(guids(&spec(&[], true)).await, ["f1", "g1", "f2"], "oldest first");
assert_eq!(guids(&spec(&["g"], false)).await, ["g1", "f2", "f1"], "g first");
assert_eq!(guids(&spec(&["it's"], false)).await, ["f2", "g1", "f1"], "a quote is quoted");
let mine = db.playlists(1).await.unwrap();
assert_eq!((mine.len(), mine[0].items), (1, 3));
assert!(db.playlists(2).await.unwrap().is_empty(), "sam has none");
assert_eq!(db.save_playlist(2, Some(id), &spec(&[], true)).await.unwrap(), None, "not sam's to change");
assert!(!db.remove_playlist(2, id).await.unwrap(), "nor to remove");
db.exec_for_test("DELETE FROM subscriptions WHERE user_id = 1 AND feed_id = 'g'").await.unwrap();
let p = db.playlist(1, id).await.unwrap().unwrap();
assert_eq!((p.spec.feeds.as_slice(), p.items), (&["f".to_string()][..], 2), "g unsubscribed from");
assert!(db.remove_playlist(1, id).await.unwrap());
assert!(db.playlists(1).await.unwrap().is_empty());
}
#[tokio::test]
async fn read_state_belongs_to_one_person() {
let db = Db::memory().await.unwrap();

View File

@@ -290,6 +290,33 @@ pub mod queue {
owned_by_user!();
}
/// Smart playlists (#476): episodes of the podcasts chosen, kept up to date by themselves. The
/// priority podcasts' episodes come first.
pub mod playlists {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "playlists")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
pub user_id: i64,
#[sea_orm(column_type = "Text")]
pub name: String,
/// JSON array of feed ids.
#[sea_orm(column_type = "Text")]
pub feeds: String,
/// JSON array of feed ids, of those in `feeds`.
#[sea_orm(column_type = "Text")]
pub priority: String,
pub only_unplayed: bool,
pub oldest_first: bool,
pub created: i64,
}
owned_by_user!();
}
/// Words someone never wants to see: an item whose title or text has one is hidden from them and
/// not downloaded on their account (issue #47). `feed_id` is empty for the list that applies to
/// every feed they read.

View File

@@ -63,6 +63,10 @@ const WIRE: ipx_wire::Routes = &[
("GET", "/api/entries", "", "ipx.EntryPage"),
("GET", "/api/queue", "", "ipx.EntryPage"),
("PUT", "/api/queue", "ipx.QueueItems", "ipx.EntryPage"),
("GET", "/api/playlists", "", "ipx.PlaylistRows"),
("POST", "/api/playlists", "ipx.PlaylistSpec", "ipx.PlaylistId"),
("PATCH", "/api/playlists/{id}", "ipx.PlaylistSpec", ""),
("GET", "/api/playlists/{id}/entries", "", "ipx.EntryPage"),
("GET", "/api/signals", "", "ipx.SignalRows"),
("POST", "/api/signals", "ipx.SignalBody", "ipx.SignalId"),
("POST", "/api/signals/icon", "ipx.IconAsk", "ipx.Icon"),
@@ -106,6 +110,9 @@ pub fn router(state: WebState) -> Router {
.route("/api/feeds/{id}/entries", get(entries))
.route("/api/entries", get(all_entries))
.route("/api/queue", get(queue).put(set_queue))
.route("/api/playlists", get(list_playlists).post(add_playlist))
.route("/api/playlists/{id}", patch(patch_playlist).delete(remove_playlist))
.route("/api/playlists/{id}/entries", get(playlist_entries))
.route("/api/signals", get(list_signals).post(add_signal))
.route("/api/signals/icon", post(pick_signal_icon))
.route("/api/signals/{id}", patch(patch_signal).delete(remove_signal))
@@ -2174,6 +2181,94 @@ async fn queue_page(state: &WebState, user_id: i64) -> Result<Json<EntryPage>, A
Ok(Json(EntryPage { total: rows.len() as i64, entries: rows }))
}
/// A playlist as sent, made fit to keep: a name, the podcasts this person subscribes to, the
/// priority ones among them.
async fn playlist_spec(
state: &WebState,
user: &crate::db::User,
mut spec: crate::db::PlaylistSpec,
) -> Result<crate::db::PlaylistSpec, ApiError> {
spec.name = spec.name.trim().to_owned();
if spec.name.is_empty() || spec.name.chars().count() > 100 {
return Err(ApiError::bad_request("a playlist needs a name of up to 100 characters"));
}
let mine: std::collections::HashSet<String> =
state.ctx.db.subscriptions_for(user.id).await?.into_iter().map(|s| s.feed_id).collect();
let mut seen = std::collections::HashSet::new();
spec.feeds.retain(|f| mine.contains(f) && seen.insert(f.clone()));
if spec.feeds.is_empty() {
return Err(ApiError::bad_request("a playlist needs at least one podcast you subscribe to"));
}
spec.priority.retain(|f| spec.feeds.contains(f));
spec.priority.dedup();
Ok(spec)
}
/// Smart playlists (#476).
async fn list_playlists(
State(state): State<WebState>,
user: crate::db::User,
) -> Result<Json<Vec<crate::db::PlaylistRow>>, ApiError> {
Ok(Json(state.ctx.db.playlists(user.id).await?))
}
async fn add_playlist(
State(state): State<WebState>,
user: crate::db::User,
Json(spec): Json<crate::db::PlaylistSpec>,
) -> Result<Json<serde_json::Value>, ApiError> {
let spec = playlist_spec(&state, &user, spec).await?;
let id = state.ctx.db.save_playlist(user.id, None, &spec).await?;
Ok(Json(serde_json::json!({ "id": id })))
}
async fn patch_playlist(
State(state): State<WebState>,
Path(id): Path<i64>,
user: crate::db::User,
Json(spec): Json<crate::db::PlaylistSpec>,
) -> Result<StatusCode, ApiError> {
let spec = playlist_spec(&state, &user, spec).await?;
match state.ctx.db.save_playlist(user.id, Some(id), &spec).await? {
Some(_) => Ok(StatusCode::NO_CONTENT),
None => Err(ApiError::not_found("no such playlist")),
}
}
async fn remove_playlist(
State(state): State<WebState>,
Path(id): Path<i64>,
user: crate::db::User,
) -> Result<StatusCode, ApiError> {
if !state.ctx.db.remove_playlist(user.id, id).await? {
return Err(ApiError::not_found("no such playlist"));
}
Ok(StatusCode::NO_CONTENT)
}
/// A playlist's episodes, in its own order: the page's sort does not apply.
async fn playlist_entries(
State(state): State<WebState>,
Path(id): Path<i64>,
user: crate::db::User,
Query(page): Query<Page>,
) -> Result<Json<EntryPage>, ApiError> {
let Some(p) = state.ctx.db.playlist(user.id, id).await? else {
return Err(ApiError::not_found("no such playlist"));
};
let feeds: Vec<&str> = p.spec.feeds.iter().map(String::as_str).collect();
let filter = if p.spec.only_unplayed { crate::db::Filter::Unread } else { crate::db::Filter::All };
let order = crate::db::playlist_order(&p.spec);
let limit = page.limit.clamp(1, 200);
let mut rows = state.ctx.db.entries_of(user.id, Some(&feeds), filter, None, page.offset, limit, &order).await?;
let mut sanitizer = feed_sanitizer();
for row in &mut rows {
clean_row(&mut sanitizer, row);
}
crate::deadair::for_reader(&state.ctx, user.id, &mut rows).await?;
Ok(Json(EntryPage { total: p.items, entries: rows }))
}
/// One entry, in the clock of the file this person will play (`deadair::for_reader`).
async fn one_entry(
State(state): State<WebState>,

View File

@@ -251,6 +251,35 @@ message EntryPage {
repeated EntryRow entries = 2;
}
// POST /api/playlists and PATCH /api/playlists/{id}, the body: a smart playlist (#476).
message PlaylistSpec {
string name = 1;
repeated string feeds = 2;
repeated string priority = 3;
bool only_unplayed = 4;
bool oldest_first = 5;
}
// A playlist in GET /api/playlists, with how many episodes it holds now.
message PlaylistRow {
int64 id = 1;
string name = 2;
repeated string feeds = 3;
repeated string priority = 4;
bool only_unplayed = 5;
bool oldest_first = 6;
int64 items = 7;
}
message PlaylistRows {
repeated PlaylistRow items = 1;
}
// POST /api/playlists, the answer.
message PlaylistId {
int64 id = 1;
}
// One of Up Next's episodes (#473).
message QueueItem {
string feed_id = 1;