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;

View File

@@ -58,7 +58,7 @@ test('the page loads and lists the configured feeds', async ({ page }) => {
// 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)')).toHaveCount(5, { timeout: 15_000 });
await expect(page.locator('.feed:not(.sigs):not(.plists)')).toHaveCount(5, { timeout: 15_000 });
await expect(page.locator('.feed', { hasText: 'Test Show' })).toBeVisible();
const errors: string[] = [];
page.on('pageerror', e => errors.push(e.message));
@@ -507,6 +507,43 @@ test('Now Playing opens from the player bar with the artwork, show notes and Up
await page.evaluate(() => api('/api/entries/test-show/ui-2/position', { method: 'POST', body: JSON.stringify({ secs: 0 }) }));
});
test('a smart playlist puts its first podcasts ahead and plays on through itself (#476)', async ({ page }) => {
await page.evaluate(() => saveUpNext([]));
await page.locator('#feedlist .feed', { hasText: 'Playlists' }).click();
await page.locator('#content .acts [data-a="new"]').click();
await page.locator('#plname').fill('Commute');
await page.locator('[data-in="test-show"]').check();
await page.locator('[data-in="multi-show"]').check();
await page.locator('[data-first="multi-show"]').check();
await page.locator('#plunplayed').uncheck();
await page.locator('#plsave').click();
const rows = page.locator('#listening .childrow .txt b');
await expect(rows).toHaveText(['Two Files', 'Second Episode', 'First Episode']);
await expect(page.locator('#feedlist .feed.child', { hasText: 'Commute' }).locator('.badge')).toHaveText('3');
// Both of Test Show's files here, whatever ran before: only a downloaded one plays next.
const missing = async () => (await page.evaluate(() => api('/api/feeds/test-show/entries')) as ListPage).entries
.flatMap(e => e.enclosures).filter(x => !x.path).map(x => x.id);
for (const id of await missing()) await page.evaluate(id => api(`/api/enclosures/${id}/download`, { method: 'POST' }), id);
await expect.poll(missing, { timeout: 20_000 }).toEqual([]);
await page.locator('#feedlist .feed.child', { hasText: 'Commute' }).click();
// Played from the playlist, the end of one plays the next in it.
await page.locator('#listening .childrow', { hasText: 'Second Episode' }).click();
await expect(page.locator('#ptitle')).toHaveText('Second Episode');
await expect(page.locator('#pnext')).toBeVisible();
await page.evaluate(() => audio.dispatchEvent(new Event('ended')));
await expect(page.locator('#ptitle')).toHaveText('First Episode');
await page.locator('#pclose').click();
await page.locator('#content .acts [data-a="rm"]').click();
await answer(page);
await expect(page.locator('#feedlist .feed.child', { hasText: 'Commute' })).toHaveCount(0);
for (const g of ['ui-1', 'ui-2'])
await page.evaluate(g => api(`/api/entries/test-show/${g}/position`, { method: 'POST', body: JSON.stringify({ secs: 0 }) }), g);
});
test('a player nobody has played since it last saved does not save again', async ({ page }) => {
// A tab left paused at 41:15 saved that as it reloaded, over the 32:48 another had reached,
// and the episode dropped out of Currently Listening. The fixture audio does not decode, so
@@ -611,7 +648,7 @@ test('an OPML subscription is a collapsible folder', async ({ page }) => {
const chev = page.locator('.feed.group .chev');
await expect(chev).toBeVisible({ timeout: 20_000 });
// The Signals folder is a folder too (#255).
await expect(page.locator('.feed:not(.group):not(.sigs) .chev')).toHaveCount(0);
await expect(page.locator('.feed:not(.group):not(.sigs):not(.plists) .chev')).toHaveCount(0);
await expect(chev).toHaveAttribute('aria-expanded', 'false');
// Closed by default: the children are not listed until the folder is opened.
@@ -2412,7 +2449,7 @@ test.describe('an item with no files, on a phone', () => {
test('a pinned feed, even one from inside a folder, goes to the top of the list', async ({ page }) => {
// The Signals folder is first, under All Subscriptions (#256), and no feed.
const rows = page.locator('#feedlist .feed:not(.sigs)');
const rows = page.locator('#feedlist .feed:not(.sigs):not(.plists)');
const group = page.locator('.feed.group').first();
if ((await group.locator('.chev').getAttribute('aria-expanded')) !== 'true') await group.locator('.chev').click();
const child = page.locator('.feed.child').first();

View File

@@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- 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).
- Up Next: line episodes up with the list button on a row or in the reader (`q`, or `Shift Q` to play one next), move them by their handles, and each plays when the one before it ends. The player has a Next button while something is lined up, and the lock screen's next-track button does the same (#473).

View File

@@ -724,6 +724,12 @@ body.scan-this .fhead [data-a=scan] .i,body.scan-any .fhead [data-a=scanall] .i,
.shelf .show b{font-weight:500;font-size:13px;line-height:1.3;color:var(--fg);display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
.shelf .show small{color:var(--dim);font-size:11.5px;min-height:1em;margin-top:-3px}
@media (hover:hover){.shelf .show:hover .art{outline:2px solid var(--accent);outline-offset:2px}}
/* A playlist's podcasts in its dialog: each one in or out, and whether it plays first. */
.plshows{display:flex;flex-direction:column;gap:2px;max-height:min(46vh,360px);overflow:auto;margin-top:4px}
.plshow{display:grid;grid-template-columns:28px minmax(0,1fr) auto;gap:10px;align-items:center;padding:4px 2px}
.plshow .art{width:28px;height:28px;font-size:10px}
.plshow .check{margin:0;min-width:0}
.plshow .first{color:var(--dim);font-size:12.5px}
/* Up Next's handle: dragged, it takes the pointer, so the list does not scroll under the finger. */
#listening .grip{width:22px;margin-left:-4px;color:var(--faint);cursor:grab;touch-action:none}
#listening .grip svg{width:12px;height:12px}

View File

@@ -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<string, { script: string, src: string[] }> = {
'index.html': { script: 'app.js', src: ['util', 'wire', 'theme', 'feeds', 'feedpage', 'items', 'player', 'upnext', 'nowplaying', 'dialogs', 'signals', 'gestures', 'offline', 'events', 'native'] },
'index.html': { script: 'app.js', src: ['util', 'wire', 'theme', 'feeds', 'feedpage', 'items', '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'] },
};

View File

@@ -139,3 +139,4 @@ function offerReload(){
connect();
loadFeeds().then(preloadLists).catch(()=>{});
loadUpNext();
loadPlaylists();

View File

@@ -23,6 +23,9 @@ function renderFeed(){
const v=VIEWS[S.feed ?? ''];
if(v&&v.url) return renderListed(v);
if(S.feed===SIGNALS) return renderSignals();
if(S.feed===PLAYLISTS) return renderPlaylists();
const pl=playlistOf(S.feed);
if(pl) return renderPlaylist(pl);
const f=v?null:S.feeds.find(x=>x.id===S.feed);
const sg=signalOf(S.feed);
$<HTMLButtonElement>('#tbRemove').disabled=!f;

View File

@@ -20,7 +20,7 @@ async function loadFeeds(keepSel?: boolean){
// All Subscriptions rather than picking one alphabetically. Nothing to land on at all (a
// brand new account) leaves S.feed alone, so the empty state's own message shows instead.
if(!keepSel && S.feeds.length){
const known = S.feed && (VIEWS[S.feed] || S.feed===SIGNALS || signalOf(S.feed) || S.feeds.some(f=>f.id===S.feed));
const known = S.feed && (VIEWS[S.feed] || S.feed===SIGNALS || signalOf(S.feed) || S.feed===PLAYLISTS || playlistOf(S.feed) || S.feeds.some(f=>f.id===S.feed));
selectFeed(known ? S.feed! : ':all');
}
}
@@ -129,6 +129,7 @@ function renderFeeds(){
}
list.appendChild(places);
signalFolder(list,q);
playlistFolder(list,q);
const shown=S.feeds.filter(f=>!q||(f.title||f.id).toLowerCase().includes(q));
if(!shown.length){ list.insertAdjacentHTML('beforeend','<p class="empty" style="padding:20px 8px">No feeds.</p>'); return done(); }

View File

@@ -78,7 +78,7 @@ function preloadLists(){
/// `quiet` for a refresh nobody asked for (a live update): not a wait anyone sees, so not timed.
async function loadEntries(append?: boolean, quiet?: boolean){
// The Directory lists feeds, and Currently Listening draws its own episodes.
if(!S.feed || VIEWS[S.feed]?.url || S.feed===SIGNALS) return;
if(!S.feed || VIEWS[S.feed]?.url || S.feed===SIGNALS || S.feed===PLAYLISTS || playlistOf(S.feed)) return;
const feed=S.feed, key=listKey(feed), asked=performance.now(), seq=++loadSeq;
// From asking to the list drawn: what someone waits for after a click, under that click's trace
// (#246). Once, when the list first shows: from what is kept, at once.

View File

@@ -72,6 +72,7 @@ function play(e: Entry,enc=e.enclosures.find(isPlayable)){
let wait: Promise<void>|null=null;
if(!resuming){
player.guid=e.guid; player.feed=e.feed_id; player.entry=e; player.enc=enc.id; player.moved=false;
playingFrom=null;
document.body.classList.toggle('has-video', kindOf(enc)==='video');
wait=setSrc(player.src=mediaSrc(enc));
audio.currentTime=0;

163
web/src/playlists.ts Normal file
View File

@@ -0,0 +1,163 @@
/* ---------------- smart playlists ---------------- */
/// Smart playlists (#476): the episodes of the podcasts chosen, those marked to play first ahead of
/// the rest, newest or oldest first, unplayed only or all. A playlist is a place, `:playlist:<id>`,
/// in a folder of their own in the feed list, as Signals are.
const PLAYLISTS=':playlists';
let playlists: Playlist[]=[];
/// The playlist the episode playing was started from, which goes on to its next when it ends, once
/// Up Next has nothing.
let playingFrom: Entry[]|null=null;
function playlistOf(view: string|null){
const m=/^:playlist:(\d+)$/.exec(view||'');
return m ? playlists.find(p=>p.id===Number(m[1])) : undefined;
}
function loadPlaylists(){
return api('/api/playlists').then((r: Playlist[])=>{ playlists=r; renderFeeds(); }).catch(()=>{});
}
/// The playlist's own art: its podcasts' artwork, four together, as a folder's is.
const playlistArt=(p: Playlist)=>folderArt({id:'',title:p.name,image:null} as Feed,S.feeds.filter(f=>p.feeds.includes(f.id)));
function playlistFolder(list: HTMLElement, q: string){
const mine=playlists.filter(p=>!q||p.name.toLowerCase().includes(q));
if(q&&!mine.length) return;
const open=expanded.has(PLAYLISTS)||!!q;
list.appendChild(feedRow(PLAYLISTS,'plists',
`<button class="chev" aria-expanded="${open}" title="Show or hide your playlists" aria-label="Show or hide your playlists">${ICON.caret}</button>`+
`<span class="fart"><div class="art">${ICON.queue}</div></span><div class="txt"><b>Playlists</b><small>${playlists.length?plural(playlists.length,'playlist'):'Episodes from the podcasts you choose'}</small></div>`,
()=>selectFeed(PLAYLISTS)));
$('.chev',list.lastElementChild!).onclick=(ev: Event)=>{ ev.stopPropagation(); toggleGroup(PLAYLISTS); };
if(!open) return;
for(const p of mine)
list.appendChild(feedRow(':playlist:'+p.id,'child',
`<span class="fart">${playlistArt(p)}</span><div class="txt"><b>${esc(p.name)}</b><small>${plural(p.feeds.length,'podcast')}</small></div>`+badgeHTML(p.items),
()=>selectFeed(':playlist:'+p.id)));
}
/// The folder's page: every playlist, and New playlist.
function renderPlaylists(){
$('#count').textContent=`Playlists: ${plural(playlists.length,'playlist')}`;
$<HTMLButtonElement>('#tbRemove').disabled=true;
syncTools(null);
const box=$('#content');
box.classList.add('plain');
box.innerHTML=`
<div class="fhead slim">
<div class="art">${ICON.queue}</div>
<div class="meta"><h2>Playlists</h2><div class="sub">Episodes from the podcasts you choose, kept up to date as new ones come.</div></div>
<div class="acts"><button class="btn ico" data-a="new" title="New playlist" aria-label="New playlist">${ICON.plus}</button></div>
</div>
<div class="childlist" id="plists"></div>`;
$<HTMLButtonElement>('#content .acts [data-a="new"]').onclick=()=>playlistModal();
const list=$('#plists');
if(!playlists.length){ list.innerHTML='<p class="empty">No playlists yet. Make one from the podcasts you want to hear in a row.</p>'; return; }
for(const p of playlists){
const el=document.createElement('div');
el.className='childrow';
el.innerHTML=playlistArt(p)+`<div class="txt"><b>${esc(p.name)}</b><small class="meta">${plural(p.feeds.length,'podcast')}</small></div>`+badgeHTML(p.items);
el.onclick=()=>selectFeed(':playlist:'+p.id);
list.appendChild(el);
}
}
/// A playlist's page: its episodes in its order. Play goes on through it; the cross marks one
/// played, which takes it out of an unplayed-only playlist.
async function renderPlaylist(p: Playlist){
$<HTMLButtonElement>('#tbRemove').disabled=true;
syncTools(null);
const box=$('#content');
box.classList.add('plain');
const how=[p.only_unplayed?'Unplayed episodes':'Every episode',p.oldest_first?'oldest first':'newest first',
p.priority.length?`${plural(p.priority.length,'podcast')} first`:''].filter(Boolean).join(', ');
box.innerHTML=`
<div class="fhead slim">
${playlistArt(p)}
<div class="meta"><h2>${esc(p.name)}</h2><div class="sub">${how}, from ${plural(p.feeds.length,'podcast')}</div></div>
<div class="acts">
<button class="btn ico" data-a="edit" title="Edit this playlist" aria-label="Edit this playlist">${ICON.settings}</button>
<button class="btn ico danger" data-a="rm" title="Delete this playlist" aria-label="Delete this playlist">${ICON.trash}</button>
</div>
</div>
<div class="childlist" id="listening"></div>`;
$<HTMLButtonElement>('#content .acts [data-a="edit"]').onclick=()=>playlistModal(p);
$<HTMLButtonElement>('#content .acts [data-a="rm"]').onclick=async()=>{
if(!await ask(`Delete the playlist ${p.name}? Its episodes stay in their podcasts.`,'Delete')) return;
try{ await api(`/api/playlists/${p.id}`,{method:'DELETE'}); toast('Deleted'); await loadPlaylists(); selectFeed(PLAYLISTS); }
catch(e){ toast(why(e),true); }
};
const list=$('#listening');
listLoading(list);
let rows: Entry[];
// shortcut: the first 200 only, with no Load more; page it as feeds do if a playlist is listened
// through that far.
try{ rows=(await api(`/api/playlists/${p.id}/entries?limit=200`) as ListPage).entries; }
catch(e){ list.innerHTML=`<p class="hint">${esc(why(e))}</p>`; return; }
if(!list.isConnected) return;
$('#count').textContent=`${p.name}: ${plural(p.items,'episode')}`;
list.innerHTML=rows.length?'':'<p class="hint">Nothing here yet. Episodes show up as your podcasts publish them.</p>';
for(const e of rows){
const el=listenRow(e,'Mark played',async()=>{ try{ await setRead(e,true); }catch(err){ toast(why(err),true); } renderPlaylist(p); loadPlaylists(); });
el.onclick=ev=>{
if((ev.target as Element).closest('[data-a=remove]')) return;
if(el.classList.contains('now')&&!audio.paused){ audio.pause(); return; }
playFrom(rows,e);
};
list.appendChild(el);
}
}
/// Plays an episode of a list that goes on to the list's next.
function playFrom(list: Entry[],e: Entry){
play(e);
// After play, which forgets the list it came from, and has painted Next and told the phone
// what follows without it.
if(inPlayer(e)){ playingFrom=list; hostNext(); }
}
/// The next in the playlist after the one playing, if it was started from one.
function nextInPlaylist(){
if(!playingFrom) return undefined;
const i=playingFrom.findIndex(inPlayer);
return i<0 ? undefined : nextUp(playingFrom.slice(i+1),null);
}
/// Making a playlist, or changing one: a name, the podcasts in it and which play first, and which
/// of their episodes.
function playlistModal(p?: Playlist){
const shows=S.feeds.filter(f=>f.podcast);
const row=(f: Feed)=>{
const id=esc(f.id), inIt=!!p?.feeds.includes(f.id), first=!!p?.priority.includes(f.id);
return `<div class="plshow">${artHTML(f.image,f.title||f.id)}
<label class="check"><input type="checkbox" data-in="${id}"${inIt?' checked':''}> ${esc(f.title||f.id)}</label>
<label class="check first"><input type="checkbox" data-first="${id}"${first?' checked':''}${inIt?'':' disabled'}> Play first</label></div>`;
};
openModal(`<h3>${p?'Edit playlist':'New playlist'}</h3>
<div class="field"><label for="plname">Name</label>
<input type="text" id="plname" value="${esc(p?.name||'')}" placeholder="Morning commute"></div>
<div class="field"><label>Podcasts</label>
${shows.length?`<div class="plshows">${shows.map(row).join('')}</div>`:'<p class="hint">Subscribe to a podcast first.</p>'}
<span class="hint">Episodes of those set to play first come before the rest.</span></div>
<div class="field">
<label class="check"><input type="checkbox" id="plunplayed"${p?.only_unplayed??true?' checked':''}> Only episodes you have not played</label>
<label class="check"><input type="checkbox" id="ploldest"${p?.oldest_first?' checked':''}> Oldest first</label></div>
<div class="cardacts"><button class="btn ico" onclick="closeModal()" title="Cancel" aria-label="Cancel">${ICON.close}</button>
<button class="btn ico primary" id="plsave" title="${p?'Save':'Make playlist'}" aria-label="${p?'Save':'Make playlist'}">${p?ICON.check:ICON.plus}</button></div>`);
// Play first means something only for a podcast in the playlist.
for(const box of $$<HTMLInputElement>('[data-in]')) box.onchange=()=>{
const first=$<HTMLInputElement>(`[data-first="${CSS.escape(box.dataset.in!)}"]`);
first.disabled=!box.checked; if(!box.checked) first.checked=false;
};
$<HTMLInputElement>('#plname').focus();
$<HTMLButtonElement>('#plsave').onclick=async()=>{
const name=$<HTMLInputElement>('#plname').value.trim();
const feeds=$$<HTMLInputElement>('[data-in]').filter(b=>b.checked).map(b=>b.dataset.in!);
if(!name){ $<HTMLInputElement>('#plname').focus(); return; }
if(!feeds.length){ toast('Choose at least one podcast.',true); return; }
const body=JSON.stringify({name,feeds,priority:$$<HTMLInputElement>('[data-first]').filter(b=>b.checked).map(b=>b.dataset.first!),
only_unplayed:$<HTMLInputElement>('#plunplayed').checked,oldest_first:$<HTMLInputElement>('#ploldest').checked});
try{
const r=p ? await api(`/api/playlists/${p.id}`,{method:'PATCH',body}) : await api('/api/playlists',{method:'POST',body});
closeModal(); toast(p?'Saved':'Playlist made');
if(!expanded.has(PLAYLISTS)) toggleGroup(PLAYLISTS);
await loadPlaylists(); selectFeed(':playlist:'+(p?p.id:r.id));
}catch(e){ toast(why(e),true); }
};
}

View File

@@ -148,6 +148,18 @@ interface State {
sort: {col: string, dir: 'asc' | 'desc'};
}
/// A smart playlist, `/api/playlists` (db.rs PlaylistRow, #476).
interface Playlist {
id: number;
name: string;
feeds: string[];
priority: string[];
only_unplayed: boolean;
oldest_first: boolean;
/** How many episodes it holds now. */
items: number;
}
/// An account, `/api/users` (web.rs list_users).
interface Account {
id: number;

View File

@@ -56,10 +56,13 @@ const queueButton=(e: Entry,cls='iconbtn')=>`<button class="${cls}" data-a="queu
title="${queued(e)?'Remove from Up Next':'Add to Up Next'}" aria-label="${queued(e)?'Remove from Up Next':'Add to Up Next'}">${queued(e)?ICON.queued:ICON.queue}</button>`;
/// What plays after this one ends, or the next button is pressed.
/// Up Next first; with nothing in it, the next in the playlist the one playing came from.
function playNext(){
const e=nextUp(upNext,player.guid?player.feed+'\n'+player.guid:null);
if(e) play(e);
return !!e;
if(e){ play(e); return true; }
const n=nextInPlaylist();
if(n&&playingFrom){ playFrom(playingFrom,n); return true; }
return false;
}
/// Playing takes an episode out of Up Next: it is under way, and Currently Listening has it now.
function startedPlaying(e: Entry){
@@ -69,7 +72,7 @@ function startedPlaying(e: Entry){
/// The phone's player is told what follows (#473), so with the screen locked, when the page is
/// frozen and cannot answer the end of an episode, it goes on to the next by itself.
function hostNext(){
const next=nextUp(upNext,player.guid?player.feed+'\n'+player.guid:null);
const next=nextUp(upNext,player.guid?player.feed+'\n'+player.guid:null)??nextInPlaylist();
$<HTMLButtonElement>('#pnext').hidden=!next;
try{
if(!ipxHost||!hostCan.has('next')) return;