From c65b80a06c206371f777fe1f2e74f950575d700a Mon Sep 17 00:00:00 2001 From: rays Date: Tue, 17 Nov 2026 14:31:40 +0000 Subject: [PATCH 1/9] Up Next: a queue that plays on by itself (#473) Playing was one episode at a time: when one ended nothing followed. Up Next is a per-account queue on the server (table `queue`, GET and PUT /api/queue), so the phone and the browser share it. The page adds to it from a row or the reader, reorders it by drag or arrow keys, and plays the next when one ends; what is playing leaves it as it starts, as Overcast's does. An episode 90% played leaves it on the server too, which covers the phone playing on while the page is frozen. The iOS app is told what follows (`{t:'next'}`, gated on the app saying it can) and starts it at the end of an episode; the page takes it up through nowPlaying as it does the car's pick. The Swift is not compiled here. The page stub answered every unknown address with [], whose `.entries` is Array.prototype.entries, so the queue read a function as its list; it now answers /api/queue as an entry list. Co-Authored-By: Claude Opus 5.5 --- crates/ipx/CHANGELOG.md | 1 + crates/ipx/src/db.rs | 89 ++++++++++++++++++++++++++ crates/ipx/src/entity.rs | 20 ++++++ crates/ipx/src/web.rs | 41 ++++++++++++ crates/wire/proto/ipx.proto | 11 ++++ ios/CHANGELOG.md | 1 + ios/Sources/Bridge.swift | 17 ++++- ios/Sources/Playback.swift | 9 +++ tests/dom-stub.ts | 2 +- tests/native-bridge.ts | 17 ++++- tests/page-unit.ts | 10 +++ tests/ui/app.spec.ts | 37 +++++++++++ web/CHANGELOG.md | 1 + web/app.css | 8 ++- web/build.mts | 2 +- web/index.html | 1 + web/src/dialogs.ts | 36 ++++++----- web/src/events.ts | 1 + web/src/feeds.ts | 5 +- web/src/items.ts | 3 + web/src/native.ts | 26 +++++--- web/src/player.ts | 21 ++++--- web/src/upnext.ts | 121 ++++++++++++++++++++++++++++++++++++ web/src/util.ts | 6 ++ 24 files changed, 445 insertions(+), 41 deletions(-) create mode 100644 web/src/upnext.ts diff --git a/crates/ipx/CHANGELOG.md b/crates/ipx/CHANGELOG.md index 1b91808..78860ae 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 +- 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). - Sharing an episode gives a link to its page on ipx-play, which anyone can open and play, set up in Admin, Directory, Sharing episodes; private and paid feeds still share their own address (#447). - The iOS app's icon count stays right with the app closed: with `[push]` set to an APNs key, ipx sends each registered phone (`POST /api/push/devices`, removed with `DELETE`) its All Subscriptions unread count through Apple's push service, within a minute of a change (#433). The push also wakes the app for a moment, for its widget to show the same count (#428). diff --git a/crates/ipx/src/db.rs b/crates/ipx/src/db.rs index cc4af3b..93cc075 100644 --- a/crates/ipx/src/db.rs +++ b/crates/ipx/src/db.rs @@ -73,6 +73,7 @@ async fn create_missing(orm: &DatabaseConnection) -> Result<()> { schema.create_table_from_entity(signals::Entity), schema.create_table_from_entity(signal_verdicts::Entity), schema.create_table_from_entity(push_devices::Entity), + schema.create_table_from_entity(queue::Entity), ] { orm.execute(table.if_not_exists()).await.context("creating the schema")?; } @@ -1750,6 +1751,64 @@ impl Db { vec![user_id.into(), feed_id.into(), guid.into(), secs.max(0).into(), duration.filter(|d| *d > 0).into()], ) .await?; + // A finished episode leaves Up Next (#473), at the 90% where the page calls it played, so + // every device agrees on what is next without each having to say so. + self.exec( + "DELETE FROM queue WHERE user_id = $1 AND feed_id = $2 AND guid = $3 AND EXISTS ( + SELECT 1 FROM entry_state s JOIN entries e ON e.feed_id = s.feed_id AND e.guid = s.guid + WHERE s.user_id = $1 AND s.feed_id = $2 AND s.guid = $3 + AND coalesce(s.duration, e.duration) > 0 + AND s.position * 10 >= coalesce(s.duration, e.duration) * 9)", + vec![user_id.into(), feed_id.into(), guid.into()], + ) + .await?; + Ok(()) + } + + /// Up Next (#473), in order, each episode as `entry` gives it. Only feeds still subscribed to, + /// and only episodes still there: retention may have taken one since it was queued. + // shortcut: one query per queued episode, fine for the tens a queue holds; join the queue into + // entries_where if queues ever run to hundreds. + pub async fn queue_of(&self, user_id: i64) -> Result> { + let keys = self + .rows( + "SELECT q.feed_id, q.guid FROM queue q + JOIN subscriptions s ON s.user_id = q.user_id AND s.feed_id = q.feed_id + WHERE q.user_id = $1 ORDER BY q.pos", + vec![user_id.into()], + ) + .await?; + let mut out = Vec::with_capacity(keys.len()); + for k in keys { + let (feed, guid): (String, String) = (k.try_get("", "feed_id")?, k.try_get("", "guid")?); + out.extend(self.entry(user_id, &feed, &guid).await?); + } + Ok(out) + } + + /// Puts Up Next in the order given, in one transaction. An episode that does not exist, or is + /// in a feed this person does not subscribe to, is left out; one given twice keeps its first + /// place. + // shortcut: the whole list replaced, so the last device to write wins; per-item adds and moves + // if two devices editing at once ever lose one's change. + pub async fn set_queue(&self, user_id: i64, items: &[(String, String)]) -> Result<()> { + use sea_orm::TransactionTrait; + let backend = self.orm.get_database_backend(); + let tx = self.orm.begin().await?; + let run = |sql: &str, v: Vec| Statement::from_sql_and_values(backend, sql, v); + tx.execute_raw(run("DELETE FROM queue WHERE user_id = $1", vec![user_id.into()])).await?; + for (pos, (feed, guid)) in items.iter().enumerate() { + tx.execute_raw(run( + "INSERT INTO queue (user_id, feed_id, guid, pos) + SELECT s.user_id, e.feed_id, e.guid, $4 FROM entries e + JOIN subscriptions s ON s.user_id = $1 AND s.feed_id = e.feed_id + WHERE e.feed_id = $2 AND e.guid = $3 + ON CONFLICT DO NOTHING", + vec![user_id.into(), feed.clone().into(), guid.clone().into(), (pos as i64).into()], + )) + .await?; + } + tx.commit().await?; Ok(()) } @@ -3881,6 +3940,36 @@ mod tests { assert_eq!(db.others_wanting(1, 3).await.unwrap(), (0, 0)); } + #[tokio::test] + async fn up_next_keeps_its_order_is_private_and_lets_go_of_what_is_finished() { + 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, first_seen, duration) VALUES + ('f','a','One',100,600),('f','b','Two',200,600),('g','c','Three',300,600);", + ) + .await + .unwrap(); + db.subscribe(1, "f").await.unwrap(); + db.subscribe(2, "f").await.unwrap(); + let key = |f: &str, g: &str| (f.to_owned(), g.to_owned()); + let guids = async |u| db.queue_of(u).await.unwrap().into_iter().map(|e| e.guid).collect::>(); + + // Not subscribed to g, an episode that is not there, and one given twice: left out. + let asked = [key("f", "b"), key("g", "c"), key("f", "zz"), key("f", "a"), key("f", "b")]; + db.set_queue(1, &asked).await.unwrap(); + assert_eq!(guids(1).await, ["b", "a"], "in the order given"); + assert!(guids(2).await.is_empty(), "sam's is their own"); + + db.set_position(1, "f", "b", 300, None).await.unwrap(); + assert_eq!(guids(1).await, ["b", "a"], "half way is not finished"); + db.set_position(1, "f", "b", 550, None).await.unwrap(); + assert_eq!(guids(1).await, ["a"], "past 90% it leaves"); + + db.set_queue(1, &[]).await.unwrap(); + assert!(guids(1).await.is_empty()); + } + #[tokio::test] async fn read_state_belongs_to_one_person() { let db = Db::memory().await.unwrap(); diff --git a/crates/ipx/src/entity.rs b/crates/ipx/src/entity.rs index 447997b..a607d72 100644 --- a/crates/ipx/src/entity.rs +++ b/crates/ipx/src/entity.rs @@ -270,6 +270,26 @@ pub mod entry_state { owned_by_user!(); } +/// Up Next (#473): the episodes someone has lined up to play, in order. Per person, and on the +/// server so the phone and the browser play through the same one. +pub mod queue { + use sea_orm::entity::prelude::*; + + #[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)] + #[sea_orm(table_name = "queue")] + pub struct Model { + #[sea_orm(primary_key, auto_increment = false)] + pub user_id: i64, + #[sea_orm(primary_key, auto_increment = false, column_type = "Text")] + pub feed_id: String, + #[sea_orm(primary_key, auto_increment = false, column_type = "Text")] + pub guid: String, + pub pos: 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. diff --git a/crates/ipx/src/web.rs b/crates/ipx/src/web.rs index d50e4bb..ded3a02 100644 --- a/crates/ipx/src/web.rs +++ b/crates/ipx/src/web.rs @@ -61,6 +61,8 @@ const WIRE: ipx_wire::Routes = &[ ("PATCH", "/api/feeds/{id}", "ipx.FeedPatch", ""), ("GET", "/api/feeds/{id}/entries", "", "ipx.EntryPage"), ("GET", "/api/entries", "", "ipx.EntryPage"), + ("GET", "/api/queue", "", "ipx.EntryPage"), + ("PUT", "/api/queue", "ipx.QueueItems", "ipx.EntryPage"), ("GET", "/api/signals", "", "ipx.SignalRows"), ("POST", "/api/signals", "ipx.SignalBody", "ipx.SignalId"), ("POST", "/api/signals/icon", "ipx.IconAsk", "ipx.Icon"), @@ -103,6 +105,7 @@ pub fn router(state: WebState) -> Router { .route("/api/feeds/{id}", patch(patch_feed).delete(remove_feed)) .route("/api/feeds/{id}/entries", get(entries)) .route("/api/entries", get(all_entries)) + .route("/api/queue", get(queue).put(set_queue)) .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)) @@ -2129,6 +2132,44 @@ async fn entry_page( Ok(Json(EntryPage { total, entries: rows })) } +/// One of Up Next's episodes, as the page names it. +#[derive(Deserialize)] +struct QueueItem { + feed_id: String, + guid: String, +} + +/// Up Next (#473): the episodes lined up to play, in order, as a page of entries. +async fn queue(State(state): State, user: crate::db::User) -> Result, ApiError> { + queue_page(&state, user.id).await +} + +/// Puts Up Next in the order sent, and answers with it as it now is: what was not yours to queue +/// is left out rather than refused, so a list one device held while another unsubscribed still +/// saves. +async fn set_queue( + State(state): State, + user: crate::db::User, + Json(items): Json>, +) -> Result, ApiError> { + if items.len() > 500 { + return Err(ApiError::bad_request("Up Next holds at most 500 episodes")); + } + let items: Vec<(String, String)> = items.into_iter().map(|i| (i.feed_id, i.guid)).collect(); + state.ctx.db.set_queue(user.id, &items).await?; + queue_page(&state, user.id).await +} + +async fn queue_page(state: &WebState, user_id: i64) -> Result, ApiError> { + let mut rows = state.ctx.db.queue_of(user_id).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: rows.len() as i64, entries: rows })) +} + /// One entry, in the clock of the file this person will play (`deadair::for_reader`). async fn one_entry( State(state): State, diff --git a/crates/wire/proto/ipx.proto b/crates/wire/proto/ipx.proto index 9e3bec3..3b91651 100644 --- a/crates/wire/proto/ipx.proto +++ b/crates/wire/proto/ipx.proto @@ -249,6 +249,17 @@ message EntryPage { repeated EntryRow entries = 2; } +// One of Up Next's episodes (#473). +message QueueItem { + string feed_id = 1; + string guid = 2; +} + +// PUT /api/queue, the body: Up Next in its new order. The answer is it as saved, an EntryPage. +message QueueItems { + repeated QueueItem items = 1; +} + // POST /api/entries/{feed_id}/{guid}/flags, the body. The answer is the feed's FeedRow, or JSON // null when the feed is not yours. message Flags { diff --git a/ios/CHANGELOG.md b/ios/CHANGELOG.md index b9ac38c..8b4b81c 100644 --- a/ios/CHANGELOG.md +++ b/ios/CHANGELOG.md @@ -6,6 +6,7 @@ The iOS app, `ios/`. Format: [Keep a Changelog](https://keepachangelog.com/en/1. ### Added +- Up Next plays on with the screen locked: the app is told what follows and starts it when an episode ends, without waiting for the page (#473). - iPX on the iPhone: the page in an app, playing through the phone's own player, so an episode plays on with the screen locked and the lock screen, Control Center and a car's buttons drive it (#418). - Player token (Settings, This device): an ipx API token, kept in the keychain, which the player, the badge and CarPlay send to `https://ipxapi.sdf1.net` instead of using the page's sign-in cookie, so playback does not stop when that cookie expires (#419). - The icon shows All Subscriptions' unread count, as the page's badge does: set when the app comes forward, after an item is marked read, and by a refresh iOS runs now and then while the app is closed, so it can be hours behind (#421). Reading in the app and new items arriving while it is open set it at once, and while an episode plays it is checked every quarter of an hour. diff --git a/ios/Sources/Bridge.swift b/ios/Sources/Bridge.swift index b036d14..0fa5b7c 100644 --- a/ios/Sources/Bridge.swift +++ b/ios/Sources/Bridge.swift @@ -122,7 +122,7 @@ final class Bridge: NSObject, WKScriptMessageHandler { if let r = m["rate"] as? Double { playback.setRate(Float(r)) } if let v = m["volume"] as? Double { playback.setVolume(Float(v)) } // What this build can do, so a newer page offers nothing it would ask for in vain. - send(["t": "host", "can": ["sleep", "route", "settings"]]) + send(["t": "host", "can": ["sleep", "route", "settings", "next"]]) sendAppSettings() // A page reloaded while the timer runs is told how long is left. if let at = playback.sleepAt { send(["t": "sleep", "left": max(0, at.timeIntervalSinceNow)]) } @@ -139,6 +139,21 @@ final class Bridge: NSObject, WKScriptMessageHandler { feedTitle: m["feedTitle"] as? String ?? "", artwork: m["artwork"] as? String, duration: m["duration"] as? Int)) + case "next": + // Without an episode it says nothing follows. + guard let path = m["url"] as? String, let url = Server.resolveForPlayer(path), + let enc = m["enc"] as? Int, + let feedId = m["feedId"] as? String, let guid = m["guid"] as? String else { + playback.next = nil + return + } + let at = m["position"] as? Double ?? 0 + playback.next = (.init( + url: url, enc: enc, feedId: feedId, guid: guid, + title: m["title"] as? String ?? "", + feedTitle: m["feedTitle"] as? String ?? "", + artwork: m["artwork"] as? String, + duration: m["duration"] as? Int), at > 5 ? at : nil) case "play": playback.play() case "pause": playback.pause() case "stop": playback.stop() diff --git a/ios/Sources/Playback.swift b/ios/Sources/Playback.swift index d9b2fc3..292cc57 100644 --- a/ios/Sources/Playback.swift +++ b/ios/Sources/Playback.swift @@ -32,6 +32,9 @@ final class Playback: NSObject { var onSlept: (() -> Void)? /// Something the page did not choose is loaded now: the car's pick (#420). var onChosen: (() -> Void)? + /// What plays when this one ends: the first in Up Next (#473), and where in it to start, as + /// the page last said. Here, not in the page, which is frozen while the screen is locked. + var next: (item: Item, startAt: Double?)? private let session: URLSession = { let cfg = URLSessionConfiguration.default @@ -306,6 +309,12 @@ final class Playback: NSObject { s.playing = false } markRead() + // Up Next goes on, and the page takes it up from nowPlaying as it does the car's pick. + if let n = next { + next = nil + playChosen(n.item, startAt: n.startAt) + return + } onState?(false) onEnded?() updateNowPlaying() diff --git a/tests/dom-stub.ts b/tests/dom-stub.ts index f0e0872..8e9ada7 100644 --- a/tests/dom-stub.ts +++ b/tests/dom-stub.ts @@ -75,7 +75,7 @@ function makeContext(html: string, script: string, { media = false } = {}) { : /\/api\/(popular|directory)/.test(String(url)) ? [{ id: 'f', title: 'A Feed', image: null, subscribers: 2, subscribed: true }, { id: 'g', title: null, image: null, subscribers: 1, subscribed: false }] - : /entries/.test(String(url)) ? { total: 0, entries: [] } : []), + : /entries|\/api\/queue/.test(String(url)) ? { total: 0, entries: [] } : []), }), EventSource: class { close() {} }, MediaMetadata: class {}, diff --git a/tests/native-bridge.ts b/tests/native-bridge.ts index 19ffdf5..b40cd6a 100644 --- a/tests/native-bridge.ts +++ b/tests/native-bridge.ts @@ -230,6 +230,21 @@ ctx.window.ipxNative.on({ t: 'nowPlaying', feedId: 'f', guid: 'g2', enc: 7, titl playing: false, cur: 130 }); ok(audio.paused === true && audio.currentTime === 130, 'told again on coming forward, the bar did not follow'); +// Up Next (#473): the app is told what follows, to play it with the screen locked, and taking it +// up from nowPlaying takes it out of Up Next. +const queued = { feed_id: 'f', guid: 'n1', title: 'Next One', position: 0, duration: 60, image: null, + enclosures: [{ id: 9, mime: 'audio/mpeg', path: '/n.mp3', url: 'http://x/n.mp3' }] }; +since(); +vm.runInContext(`upNext=[${JSON.stringify(queued)}]; hostNext()`, ctx); +ok(!last('next'), 'an app that never said it can was told what follows'); +ctx.window.ipxNative.on({ t: 'host', can: ['next'] }); +ok(last('next')?.guid === 'n1' && last('next')?.enc === 9 && last('next')?.url === '/media/9', 'the app was not told what plays next'); +ctx.window.ipxNative.on({ t: 'nowPlaying', feedId: 'f', guid: 'n1', enc: 9, title: 'Next One', feedTitle: 'A Feed', + playing: true, cur: 0, dur: 60 }); +ok(vm.runInContext('player.guid', ctx) === 'n1', 'the bar did not take up the next one'); +ok(vm.runInContext('upNext.length', ctx) === 0, 'the one under way is still in Up Next'); +ok(!!last('next') && !last('next')?.guid, 'the app was not told nothing follows'); + if (failed) { console.error(`\n${failed} failed`); process.exit(1); } -console.log('OK: native-bridge: the host takes playback, keeping, the sleep timer and haptics, and the page follows it'); +console.log('OK: native-bridge: the host takes playback, keeping, the sleep timer, haptics and Up Next, and the page follows it'); process.exit(0); diff --git a/tests/page-unit.ts b/tests/page-unit.ts index f678b5b..938d5bb 100644 --- a/tests/page-unit.ts +++ b/tests/page-unit.ts @@ -389,3 +389,13 @@ test('wireDecode reads protobuf into what the JSON would have been (#470)', () = assert.equal(run(`wireType('application/x-protobuf; messageType=ipx.FeedRows')`), 'ipx.FeedRows'); assert.equal(run(`wireType('application/json')`), undefined); }); + +test('nextUp is the first in Up Next that can play, passing over the one playing', () => { + const ep = (guid: string, path: string | null) => + ({ feed_id: 'f', guid, enclosures: [{ id: 1, mime: 'audio/mpeg', path, url: 'http://x/a.mp3' }] }); + const list = JSON.stringify([ep('a', '/a.mp3'), ep('b', null), ep('c', '/c.mp3')]); + assert.equal(run(`nextUp(${list}, null)?.guid`), 'a'); + assert.equal(run(`nextUp(${list}, 'f\\na')?.guid`), 'c', 'b is not downloaded yet'); + assert.equal(run(`nextUp(${list}, 'f\\nc')?.guid`), 'a'); + assert.equal(run(`nextUp([], null)`), undefined); +}); diff --git a/tests/ui/app.spec.ts b/tests/ui/app.spec.ts index d9a9796..96552a5 100644 --- a/tests/ui/app.spec.ts +++ b/tests/ui/app.spec.ts @@ -425,6 +425,43 @@ test('Currently Listening, its own place below the Directory, resumes an episode await expect(row.locator('.eq')).toBeHidden(); }); +test('Up Next lines episodes up, moves them, and plays the next when one ends (#473)', async ({ page }) => { + await page.evaluate(() => saveUpNext([])); + await page.locator('.feed', { hasText: 'Test Show' }).click(); + for (const name of ['First Episode', 'Second Episode']) { + const ep = page.locator('#eps .ep', { hasText: name }); + await ep.hover(); + await ep.locator('[data-a=queue]').click(); + await expect(ep.locator('[data-a=queue]')).toHaveAttribute('aria-pressed', 'true'); + } + const place = page.locator('#feedlist .place', { hasText: 'Up Next' }); + await expect(place.locator('.badge')).toHaveText('2'); + + await place.click(); + const rows = page.locator('#listening .childrow .txt b'); + await expect(rows).toHaveText(['First Episode', 'Second Episode']); + // Moved by its handle's arrow keys, and kept so on the server. + await page.locator('#listening .childrow', { hasText: 'Second Episode' }).locator('.grip').press('ArrowUp'); + await expect(rows).toHaveText(['Second Episode', 'First Episode']); + await expect.poll(() => page.evaluate(async () => (await api('/api/queue')).entries.map((e: Entry) => e.guid))) + .toEqual(['ui-2', 'ui-1']); + + // Playing one takes it out; the end of it plays the next. + await page.locator('#listening .childrow', { hasText: 'Second Episode' }).click(); + await expect(page.locator('#ptitle')).toHaveText('Second Episode'); + await expect(rows).toHaveText(['First Episode']); + await expect(page.locator('#pnext')).toBeVisible(); + // The fixture files are not real audio, so the end is said rather than played to. + await page.evaluate(() => audio.dispatchEvent(new Event('ended'))); + await expect(page.locator('#ptitle')).toHaveText('First Episode', { timeout: 20_000 }); + await expect(page.locator('#listening')).toContainText('Nothing lined up'); + await expect(page.locator('#pnext')).toBeHidden(); + + await page.locator('#pclose').click(); + await page.evaluate(() => api('/api/entries/test-show/ui-1/position', { method: 'POST', body: JSON.stringify({ secs: 0 }) })); + await page.evaluate(() => api('/api/entries/test-show/ui-2/position', { method: 'POST', body: JSON.stringify({ secs: 0 }) })); +}); + 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 diff --git a/web/CHANGELOG.md b/web/CHANGELOG.md index e204b35..52dcd2c 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 +- 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). - The page reads ipx's answers in protobuf, with a decoder of its own and no library, and in JSON from a server that has none; offline, a kept answer still shows what was read offline (#470). - On a phone, back and the item's actions (read, pin, open, share) float over the text as it scrolls, so they are at hand anywhere in a long post without scrolling back to the top; pressing one there keeps your place (#456). - Share on an episode offers Share link, Share from where you are, and Copy link, with a link to the episode's page on ipx-play that anyone can play; an episode of a private feed offers its own page in the same menu, never its file, which a paid feed signs for you, and says why there is no page anyone can play. An admin sets ipx-play up in Admin, Directory (#447, #452, #454, #455). diff --git a/web/app.css b/web/app.css index 8823c61..cc1a423 100644 --- a/web/app.css +++ b/web/app.css @@ -696,6 +696,10 @@ body.scan-this .fhead [data-a=scan] .i,body.scan-any .fhead [data-a=scanall] .i, #listening .txt small .fd{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} #listening .txt small .left{flex:none;color:var(--dim)} #listening .childrow:not(.now) .eq{display:none} +/* 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} +#listening .childrow.dragging{border-color:var(--accent);cursor:grabbing} #listening .rail{position:absolute;left:0;right:0;bottom:0;height:3px;background:var(--raise)} #listening .rail i{display:block;height:100%;width:0;background:var(--faint);transition:width .25s linear} #listening .now{border-color:color-mix(in srgb,var(--accent2) 60%,var(--line))} @@ -1011,7 +1015,7 @@ body.adminpage #logbox{height:calc(100dvh - 230px);min-height:240px} /* A table, as the original's was: unread, kept, title, feed, file, size, published. */ .ephead,.ep{ display:grid;gap:8px;align-items:center; - grid-template-columns:22px 22px minmax(120px,1fr) minmax(0,160px) 56px minmax(0,72px) minmax(0,92px) 64px; + grid-template-columns:22px 22px minmax(120px,1fr) minmax(0,160px) 56px minmax(0,72px) minmax(0,92px) 96px; } /* A pixel more side padding than a row's: a row has a 1px border the heading has not, and without it every heading sat a pixel left of its column. */ @@ -1081,7 +1085,7 @@ body.playing .eq i:nth-child(3){animation-delay:-.6s} .ep .file .dlbar{position:absolute;left:0;right:0;bottom:-5px;margin:0} .ep .rowacts{justify-content:flex-end} /* One feed's own table has no need of a Feed column; All Subscriptions does. */ -#split.one .ephead,#split.one .ep{grid-template-columns:22px 22px minmax(120px,1fr) 56px minmax(0,72px) minmax(0,92px) 64px} +#split.one .ephead,#split.one .ep{grid-template-columns:22px 22px minmax(120px,1fr) 56px minmax(0,72px) minmax(0,92px) 96px} #split.one .h-fd,#split.one .ep .fd{display:none} .dot{width:3px;height:3px;border-radius:50%;background:var(--faint);flex:none} .ep .rowacts{display:flex;gap:2px;align-items:flex-start;opacity:0;transition:opacity .12s} diff --git a/web/build.mts b/web/build.mts index 2eab2ae..172cb56 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', 'dialogs', 'signals', 'gestures', 'offline', 'events', 'native'] }, + 'index.html': { script: 'app.js', src: ['util', 'wire', 'theme', 'feeds', 'feedpage', 'items', 'player', 'upnext', 'dialogs', 'signals', '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/index.html b/web/index.html index 10dcaaa..c77b936 100644 --- a/web/index.html +++ b/web/index.html @@ -59,6 +59,7 @@ +
0:00 diff --git a/web/src/dialogs.ts b/web/src/dialogs.ts index 0846d76..f4a99c4 100644 --- a/web/src/dialogs.ts +++ b/web/src/dialogs.ts @@ -318,6 +318,7 @@ async function renderListed(v: {title: string, icon: string, url?: string, blurb
`; $('#count').textContent=v.title; + if(v===VIEWS[':upnext']){ drawUpNext(); return; } // The search box looks through these too, title and text, as it does a feed's items (#127). await renderListening(S.q?`${v.url}&q=${encodeURIComponent(S.q)}`:v.url!,$('#listening',box), n=>{ if(VIEWS[S.feed ?? '']===v) $('#count').textContent=`${v.title}: ${plural(n,'episode')}`; }); @@ -342,22 +343,25 @@ async function renderListening(url: string,box: HTMLElement,counted: (n: number) function drawListening(box: HTMLElement,rows: Entry[]){ box.innerHTML=rows.length?'':S.q?`

Nothing you are listening to mentions “${esc(S.q)}”.

` :'

Nothing in progress. Episodes you start and do not finish show up here.

'; - for(const e of rows){ - // Carries its episode, for paintListenRow to repaint as the player moves. - const el: HTMLDivElement & {entry?: Entry}=document.createElement('div'); - el.className='childrow'; - el.entry=e; - el.innerHTML=artHTML(e.image||feedArt(e.feed_id),e.title||'')+ - `
${EQ}${esc(entryName(e).text)}`+ - `${esc(feedName(e.feed_id))}
`+ - ``+ - ``+ - `
`; - el.onclick=ev=>(ev.target as Element).closest('[data-a=remove]')?forget(e) - :el.classList.contains('now')&&!audio.paused?audio.pause():play(e); - paintListenRow(el); - box.appendChild(el); - } + for(const e of rows) box.appendChild(listenRow(e,'Remove from Currently Listening',()=>forget(e))); +} +/// An episode's row in Currently Listening and Up Next: its art, how far in, play, and a button +/// to take it out of the list, which `remove` does. +function listenRow(e: Entry,removeLabel: string,remove: ()=>void){ + // Carries its episode, for paintListenRow to repaint as the player moves. + const el: HTMLDivElement & {entry?: Entry}=document.createElement('div'); + el.className='childrow'; + el.entry=e; + el.innerHTML=artHTML(e.image||feedArt(e.feed_id),e.title||'')+ + `
${EQ}${esc(entryName(e).text)}`+ + `${esc(feedName(e.feed_id))}
`+ + ``+ + ``+ + `
`; + el.onclick=ev=>(ev.target as Element).closest('[data-a=remove]')?remove() + :el.classList.contains('now')&&!audio.paused?audio.pause():play(e); + paintListenRow(el); + return el; } /// One row's time left, progress and play button, taken from the player when it is the one in it. diff --git a/web/src/events.ts b/web/src/events.ts index 8696637..e245bde 100644 --- a/web/src/events.ts +++ b/web/src/events.ts @@ -138,3 +138,4 @@ function offerReload(){ } connect(); loadFeeds().then(preloadLists).catch(()=>{}); +loadUpNext(); diff --git a/web/src/feeds.ts b/web/src/feeds.ts index 3f22106..7660082 100644 --- a/web/src/feeds.ts +++ b/web/src/feeds.ts @@ -34,6 +34,8 @@ const VIEWS: Record${v.icon}${v.title}`+(id===':all' - ?`${unreadAll>999?'999+':unreadAll}`:''); + ?`${unreadAll>999?'999+':unreadAll}` + :id===':upnext'&&upNext.length?`${upNext.length}`:''); asLink(el,S.feed===id); el.onclick=()=>{ selectFeed(id); nav(false); }; el.onpointerenter=el.ontouchstart=()=>prefetch(id); diff --git a/web/src/items.ts b/web/src/items.ts index d2226a2..cb7731b 100644 --- a/web/src/items.ts +++ b/web/src/items.ts @@ -207,6 +207,7 @@ function epEl(e: Entry){ ${enc?mb(enc.length):''} ${dateOf(e.published)}
+ ${enc&&playsKind(enc)?queueButton(e):''} ${playable?``: (enc&&!has?``:'')} @@ -439,6 +440,7 @@ function detailHtml(e: Entry){ aria-label="Mark ${e.read?'unread':'read'}" aria-pressed="${!!e.read}">${e.read?ICON.check:ICON.unread} + ${e.enclosures.some(playsKind)?queueButton(e,'btn ico'):''} ${webUrl(e.link)?`${ICON.open} `:''}`; @@ -626,6 +628,7 @@ async function epAction(a: string, e: Entry, el: HTMLElement|null, encId?: numbe try{ if(a==='play'){ haptic('tap'); play(e, encId!=null ? enc : undefined); } if(a==='offline' && enc) await toggleKept(enc, entryName(e).text); + if(a==='queue'||a==='playnext'){ haptic('tap'); await toggleQueued(e, a==='playnext'); } if(a==='share') await shareEpisode(e, encId??null); if(a==='flag'){ e.flagged=!e.flagged; await api(path+'/flags',{method:'POST',body:JSON.stringify({flagged:e.flagged})}); haptic('tap'); redraw(); } if(a==='read'){ await setRead(e,!e.read); haptic(e.read?'done':'tap'); redraw(); } diff --git a/web/src/native.ts b/web/src/native.ts index 1499690..5c791de 100644 --- a/web/src/native.ts +++ b/web/src/native.ts @@ -115,6 +115,14 @@ function wireDeviceSettings(){ $('#sptokenclear').onclick=()=>host({t:'clearToken'}); } +/// An episode as the phone's player takes it, to play now (`load`) or after this one (`next`). +function hostItem(e: Entry|null, enc: {id: number}, url: string){ + return {url, enc:enc.id, feedId:e?.feed_id ?? player.feed, guid:e?.guid ?? player.guid, + title:e ? entryName(e).text : '', feedTitle:feedName(e?.feed_id ?? player.feed), + artwork:(e && e.image) || feedArt(e?.feed_id ?? player.feed) || null, + position:(e && e.position) || 0, duration:(e && e.duration) || null}; +} + function installNativePlayback(){ const post = ipxHost!; const M = HTMLMediaElement.prototype; @@ -165,15 +173,10 @@ function installNativePlayback(){ realPause.call(audio); realRemoveAttribute('src'); realLoad.call(audio); - const e = player.entry, f = player.feed; - post({t:'load', url:v, enc:player.enc, feedId:f, guid:player.guid, - title:e ? entryName(e).text : '', feedTitle:feedName(f), - artwork:(e && e.image) || feedArt(f) || null, - // Where the host starts is not this: the seek to where you left off is player.ts's, on - // loadedmetadata, so one piece of code decides it. This is for the host's now-playing - // display before the file has loaded. - position:(e && e.position) || 0, duration:(e && e.duration) || null, - rate:audio.playbackRate, volume:audio.volume}); + // Where the host starts is not the position in it: the seek to where you left off is + // player.ts's, on loadedmetadata, so one piece of code decides it. That is for the host's + // now-playing display before the file has loaded. + post({t:'load', ...hostItem(player.entry, {id:player.enc!}, v), rate:audio.playbackRate, volume:audio.volume}); }, }); @@ -222,6 +225,9 @@ function installNativePlayback(){ // Not moved: nothing here played it, so there is no place of the page's own to save. player.guid=m.guid; player.feed=m.feedId; player.entry=e; player.enc=m.enc; player.src=enc?mediaSrc(enc):undefined; player.moved=false; player.marked=false; player.saveAt=m.cur||0; + // The phone went on to the next in Up Next by itself (#473): it is under way, so out of it. + const was=upNext.find(x=>x.guid===m.guid&&x.feed_id===m.feedId); + if(was){ player.entry=e||was; startedPlaying(was); } $('#partwrap').innerHTML=artHTML(m.artwork||feedArt(m.feedId),feedName(m.feedId)); $('#ptitle').textContent=m.title||''; $('#pfeed').textContent=m.feedTitle||''; @@ -262,7 +268,7 @@ function installNativePlayback(){ // Not playback's, so not gated on it: the app says what it keeps whether or not it plays. if(m.t==='kept'||m.t==='keepFailed'){ hostKept(m); return; } // Sent at ready, so a page newer than the app offers only what the app can do. - if(m.t==='host'){ hostCan.clear(); for(const c of m.can||[]) hostCan.add(c); paintRoute(); return; } + if(m.t==='host'){ hostCan.clear(); for(const c of m.can||[]) hostCan.add(c); paintRoute(); hostNext(); return; } if(m.t==='sleep'||m.t==='slept'){ hostSleep(m); return; } if(m.t==='push'){ hostPush(m); return; } if(m.t==='appSettings'){ hostAppSettings(m); return; } diff --git a/web/src/player.ts b/web/src/player.ts index da5c69b..5fdedc4 100644 --- a/web/src/player.ts +++ b/web/src/player.ts @@ -85,6 +85,8 @@ function play(e: Entry,enc=e.enclosures.find(isPlayable)){ mediaSession(e,f); player.marked=false; paintDead(); + startedPlaying(e); + hostNext(); } const go=()=>audio.play().catch(playFailed); if(wait) wait.then(go,playFailed); else go(); @@ -97,7 +99,7 @@ function mediaSession(e: Entry,f: Feed|undefined){ artwork:(e.image||(f&&f.image))?[{src:artSrc((e.image||f?.image)!),sizes:'512x512'}]:[], }); const h: Recordvoid>={play:()=>audio.play(),pause:()=>audio.pause(), - seekbackward:()=>audio.currentTime-=15,seekforward:()=>audio.currentTime+=30}; + seekbackward:()=>audio.currentTime-=15,seekforward:()=>audio.currentTime+=30,nexttrack:playNext}; for(const k in h){ try{navigator.mediaSession.setActionHandler(k as MediaSessionAction,h[k])}catch{} } } audio.addEventListener('timeupdate',()=>{ @@ -136,7 +138,7 @@ function savePos(){ deadair:player.src?.includes('/deadair')?player.enc:undefined})],{type:'application/json'})); } audio.addEventListener('pause',savePos); -audio.addEventListener('ended',()=>{savePos();markPlayed();$('#pplay').innerHTML=ICON.play}); +audio.addEventListener('ended',()=>{savePos();markPlayed();$('#pplay').innerHTML=ICON.play;playNext()}); // body.playing is what sets the EQ bars moving. audio.addEventListener('play',()=>{ $('#pplay').innerHTML=ICON.pause; document.body.classList.add('playing'); }); audio.addEventListener('pause',()=>{ $('#pplay').innerHTML=ICON.play; document.body.classList.remove('playing'); }); @@ -175,6 +177,7 @@ audio.addEventListener('error',()=>{ if(audio.error) report('player_error',{msg: $('#pplay').onclick=()=>{haptic('tap');audio.paused?audio.play():audio.pause()}; $('#pback').onclick=()=>audio.currentTime-=15; $('#pfwd').onclick=()=>audio.currentTime+=30; +$('#pnext').onclick=()=>{ if(!playNext()) toast('Nothing in Up Next is ready to play.'); }; $('#seek').oninput=(e: Event)=>{const d=audio.duration;if(d)audio.currentTime=d*Number((e.target as HTMLInputElement).value)/1000}; $('#rate').onchange=(e: Event)=>{audio.playbackRate=+(e.target as HTMLSelectElement).value;localStorage.setItem('ipx.rate',(e.target as HTMLSelectElement).value)}; /// What the app said it can do itself (`{t:'host', can}`, native.ts): empty in a browser, and in @@ -301,7 +304,7 @@ document.addEventListener('keydown',ev=>{ // Feedly's keys, vim's j and k among them: a letter to move through items or feeds, g and a // letter to go somewhere, ? to list them. None fire with Ctrl, Alt or Cmd held, so the browser's // own shortcuts still work, or while a dialog is open. -const GO: Record={a:':all',d:':directory',l:':listening'}; +const GO: Record={a:':all',d:':directory',l:':listening',u:':upnext'}; let gAt=0; function stepEntry(by: number){ if(VIEWS[S.feed ?? '']?.url||!S.entries.length) return; @@ -318,10 +321,12 @@ function stepFeed(by: number){ } const KEYS: Recordvoid>={ j:()=>stepEntry(1), n:()=>stepEntry(1), k:()=>stepEntry(-1), p:()=>stepEntry(-1), - J:()=>stepFeed(1), K:()=>stepFeed(-1), + J:()=>stepFeed(1), K:()=>stepFeed(-1), N:()=>$('#pnext').click(), // The toolbar's own buttons, so a key does exactly what the click does, and nothing while // they are disabled. - o:()=>$('#tbPlay').click(), m:()=>$('#tbRead').click(), s:()=>$('#tbFlag').click(), + o:()=>$('#tbPlay').click(), + q:()=>{ const e=cur(); if(e) epAction('queue',e,null); }, Q:()=>{ const e=cur(); if(e) epAction('playnext',e,null); }, + m:()=>$('#tbRead').click(), s:()=>$('#tbFlag').click(), v:()=>{ const u=webUrl(cur()?.link); if(u) window.open(u,'_blank','noopener'); }, A:()=>$('#content .fhead [data-a="read"], #content .fhead [data-a="readall"]')?.click(), r:async()=>{ await loadFeeds(true); if(S.feed){ renderFeed(); loadEntries(); } }, @@ -343,17 +348,17 @@ function keysModal(){ const rows=[ ['Go to'], [g('a'),'All Subscriptions'],[g('d'),'Directory'], - [g('l'),'Currently Listening'],[g('s'),'Settings'], + [g('u'),'Up Next'],[g('l'),'Currently Listening'],[g('s'),'Settings'], [k('Shift')+' '+k('J'),'Next feed'],[k('Shift')+' '+k('K'),'Previous feed'], [k('/'),'Search items, Currently Listening or the Directory'],[k('r'),'Refresh'],[k('['),'Show or hide the feed list'], ['Items'], [k('j')+' or '+k('n'),'Next item'],[k('k')+' or '+k('p'),'Previous item'], [k('Shift')+' '+k('A'),'Mark all read'], ['The selected item'], - [k('o'),'Play it'],[k('m'),'Mark it read or unread'],[k('s'),'Pin it, or unpin it'], + [k('o'),'Play it'],[k('q'),'Add it to Up Next, or take it out'],[k('Shift')+' '+k('Q'),'Play it next'],[k('m'),'Mark it read or unread'],[k('s'),'Pin it, or unpin it'], [k('v'),'Open the original in a new tab'], ['The player'], - [k('Space'),'Play or pause'],[k('←')+' '+k('→'),'Back 15 seconds, forward 30'], + [k('Space'),'Play or pause'],[k('←')+' '+k('→'),'Back 15 seconds, forward 30'],[k('Shift')+' '+k('N'),'Play the next in Up Next'], ['Anywhere'], [k('?'),'This list'],[k('Esc'),'Close a dialog'], ]; diff --git a/web/src/upnext.ts b/web/src/upnext.ts new file mode 100644 index 0000000..5566f37 --- /dev/null +++ b/web/src/upnext.ts @@ -0,0 +1,121 @@ +/* ---------------- Up Next ---------------- */ +/// Up Next (#473): the episodes lined up to play, kept on the server so the phone and the browser +/// share one. What is playing is not in it: an episode leaves Up Next as it starts, as Overcast's +/// does, so the first one in it is always the one that follows. +let upNext: Entry[]=[]; + +/// The next one in the list that can play now, the one playing aside. One not downloaded yet is +/// passed over, to wait in the list until it is. +const nextUp=(list: Entry[], playing: string|null)=>list.find(e=>entryKey(e)!==playing&&e.enclosures.some(isPlayable)); +const queued=(e: Entry)=>upNext.some(x=>entryKey(x)===entryKey(e)); + +function loadUpNext(){ + api('/api/queue').then((r: ListPage)=>{ upNext=r.entries; upNextChanged(); }).catch(()=>{}); +} +/// Saves Up Next in this order and takes the server's answer, which leaves out what was not +/// yours to queue. Drawn at once from what was asked, so a drag lands where it was dropped. +async function saveUpNext(list: Entry[]){ + upNext=list; upNextChanged(); + try{ + const r: ListPage=await api('/api/queue',{method:'PUT',body:JSON.stringify(list.map(e=>({feed_id:e.feed_id,guid:e.guid})))}); + upNext=r.entries; + }catch(err){ toast(why(err),true); loadUpNext(); return; } + upNextChanged(); +} +function upNextChanged(){ + renderFeeds(); + if(S.feed===':upnext') drawUpNext(); + // The rows' and the reader's buttons say whether each is in it. + for(const b of $$('[data-a=queue]')) paintQueueButton(b); + hostNext(); +} + +/// Adds an episode at the end, or first with `next`, or takes it out if it is in already and +/// neither was asked. A file still on the feed's server is fetched now, so it is here by its turn. +async function toggleQueued(e: Entry, next=false){ + const rest=upNext.filter(x=>entryKey(x)!==entryKey(e)); + if(queued(e)&&!next){ await saveUpNext(rest); toast('Removed from Up Next'); return; } + const enc=e.enclosures.find(isPlayable)||e.enclosures.find(playsKind); + if(!enc){ toast('There is nothing to play in this item.',true); return; } + await saveUpNext(next?[e,...rest]:[...rest,e]); + if(!enc.path){ + await api(`/api/enclosures/${enc.id}/download`,{method:'POST'}).catch(()=>{}); + enc.state='pending'; + } + toast((next?'Plays next':'Added to Up Next')+(enc.path?'':'. Downloading it first.')); +} +function paintQueueButton(b: HTMLButtonElement){ + const key=b.dataset.key, on=!!key&&upNext.some(x=>entryKey(x)===key); + const label=on?'Remove from Up Next':'Add to Up Next'; + b.setAttribute('aria-pressed',String(on)); b.title=label; b.setAttribute('aria-label',label); + b.innerHTML=on?ICON.queued:ICON.queue; +} +/// The toggle on a row or in the reader, drawn with its state. +const queueButton=(e: Entry,cls='iconbtn')=>``; + +/// What plays after this one ends, or the next button is pressed. +function playNext(){ + const e=nextUp(upNext,player.guid?player.feed+'\n'+player.guid:null); + if(e) play(e); + return !!e; +} +/// Playing takes an episode out of Up Next: it is under way, and Currently Listening has it now. +function startedPlaying(e: Entry){ + if(queued(e)) saveUpNext(upNext.filter(x=>entryKey(x)!==entryKey(e))); +} + +/// 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); + $('#pnext').hidden=!next; + try{ + if(!ipxHost||!hostCan.has('next')) return; + const e=next, enc=e?.enclosures.find(isPlayable); + ipxHost(e&&enc?{t:'next',...hostItem(e,enc,mediaSrc(enc))}:{t:'next'}); + }catch{} +} + +/// Up Next's place: the list, a handle on each row to drag it up or down (or its arrow keys), +/// and a button to take it out. +function drawUpNext(){ + const box=$('#listening'); if(!box) return; + $('#count').textContent=`Up Next: ${plural(upNext.length,'episode')}`; + box.innerHTML=upNext.length?'':'

Nothing lined up. Add an episode with its Up Next button, and it plays when the one before it ends.

'; + for(const e of upNext){ + const el=listenRow(e,'Remove from Up Next',()=>saveUpNext(upNext.filter(x=>entryKey(x)!==entryKey(e)))); + el.insertAdjacentHTML('afterbegin',``); + box.appendChild(el); + } + for(const g of $$('.grip',box)) grip(g,box); +} +/// One row's handle. A drag moves the row among the others as the pointer goes, and saves where +/// it is let go; Up and Down move it one place, for a keyboard. +function grip(g: HTMLButtonElement,box: HTMLElement){ + const row=g.closest('.childrow')!; + const save=()=>{ + const list=$$('.childrow',box).map(r=>r.entry!); + if(list.some((e,i)=>e!==upNext[i])) saveUpNext(list); + }; + g.onclick=ev=>ev.stopPropagation(); + g.onkeydown=ev=>{ + const [up,down]=[row.previousElementSibling,row.nextElementSibling]; + if(ev.key==='ArrowUp'&&up) box.insertBefore(row,up); + else if(ev.key==='ArrowDown'&&down) box.insertBefore(down,row); + else return; + ev.preventDefault(); g.focus(); save(); + }; + g.onpointerdown=ev=>{ + ev.preventDefault(); ev.stopPropagation(); + g.setPointerCapture(ev.pointerId); + row.classList.add('dragging'); + g.onpointermove=m=>{ + const over=$$('.childrow',box).find(r=>r!==row&&m.clientYover.getBoundingClientRect().top+over.offsetHeight/2) box.insertBefore(row,over.nextElementSibling); + else if(over) box.insertBefore(row,over); + else box.appendChild(row); + }; + g.onpointerup=g.onpointercancel=()=>{ g.onpointermove=null; row.classList.remove('dragging'); save(); }; + }; +} diff --git a/web/src/util.ts b/web/src/util.ts index 3af443a..6467caf 100644 --- a/web/src/util.ts +++ b/web/src/util.ts @@ -90,6 +90,12 @@ const ICON: Record={ left:fa('0 0 512 512',''), // solid/arrow-left // Drawn here: Font Awesome's free set has no AirPlay. A screen with a triangle under it, as Apple's. airplay:fa('0 0 512 512',''), + // Up Next (#473): a list, with a plus to add to it or a tick once in it, the state in the + // shape. Drawn here, so the two are the same list and differ only in that mark. + queue:fa('0 0 512 512',''), + queued:fa('0 0 512 512',''), + next:fa('0 0 320 512',''), + grip:fa('0 0 320 512',''), subbed:fa('0 0 512 512',''), // solid/circle-check }; // What is playing, as the icon's EQ bars; the stylesheet moves them. From 1fb1edd6b0b0cd95eafbb8bb00899f10457162fa Mon Sep 17 00:00:00 2001 From: rays Date: Tue, 17 Nov 2026 14:37:53 +0000 Subject: [PATCH 2/9] Podcasts shelf: your podcasts as their artwork (#474) A place beside Up Next listing every feed with audio or video as a grid of its artwork, with how many episodes are new, as Overcast's home screen does. It is drawn from the feed list the page already holds; the feed list gains `podcast`, an EXISTS per subscription over enclosures, which stops at a podcast's first episode and is one index probe for a feed with no files. Its cost on production's database is not measured: the EXPLAIN was not run. The iOS app's generated messages (ios/Sources/Wire) are not regenerated: there is no protoc here. Nothing in the app reads the new fields, and a proto3 reader skips a field it does not know. Co-Authored-By: Claude Opus 5.5 --- crates/ipx/CHANGELOG.md | 1 + crates/ipx/src/db.rs | 23 ++++++++++++++++++++--- crates/ipx/src/web.rs | 6 +++++- crates/wire/proto/ipx.proto | 2 ++ tests/ui/app.spec.ts | 13 +++++++++++++ web/CHANGELOG.md | 1 + web/app.css | 8 ++++++++ web/src/dialogs.ts | 22 +++++++++++++++++++++- web/src/feeds.ts | 2 ++ web/src/types.ts | 2 ++ web/src/util.ts | 2 ++ 11 files changed, 77 insertions(+), 5 deletions(-) diff --git a/crates/ipx/CHANGELOG.md b/crates/ipx/CHANGELOG.md index 78860ae..2e9ee62 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 +- 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). - Sharing an episode gives a link to its page on ipx-play, which anyone can open and play, set up in Admin, Directory, Sharing episodes; private and paid feeds still share their own address (#447). diff --git a/crates/ipx/src/db.rs b/crates/ipx/src/db.rs index 93cc075..c77903c 100644 --- a/crates/ipx/src/db.rs +++ b/crates/ipx/src/db.rs @@ -611,6 +611,16 @@ impl Db { ), vec![user_id.into(), one()], ); + // Whether a feed has any audio or video, for the Podcasts shelf (#474). EXISTS, so a podcast + // stops at its first episode, and a feed with no files is one probe of enclosures_entry. + let media = counts( + "media", + "SELECT sub.feed_id, CAST(1 AS BIGINT) AS n FROM subscriptions sub + WHERE sub.user_id = $1 AND (CAST($2 AS TEXT) IS NULL OR sub.feed_id = $2) + AND EXISTS (SELECT 1 FROM enclosures x WHERE x.feed_id = sub.feed_id + AND (lower(x.mime) LIKE 'audio/%' OR lower(x.mime) LIKE 'video/%'))", + vec![user_id.into(), one()], + ); let blocked = Instrument::instrument( blocklists::Entity::find().filter(blocklists::Column::UserId.eq(user_id)).all(&self.orm), step("blocked"), @@ -620,10 +630,11 @@ impl Db { rows = rows.filter(feeds::Column::Id.eq(id)); } let rows = Instrument::instrument(rows.all(&self.orm), step("feeds")); - let (entries, downloaded, unread, blocked, rows) = tokio::try_join!( + let (entries, downloaded, unread, media, blocked, rows) = tokio::try_join!( entries, downloaded, unread, + media, async { blocked.await.map_err(anyhow::Error::from) }, async { rows.await.map_err(anyhow::Error::from) }, )?; @@ -649,6 +660,7 @@ impl Db { ttl_mins: f.ttl_mins.map(|t| t.max(0) as u64), blocked: blocked.remove(&id).unwrap_or_default(), unread: unread.get(&id).copied().unwrap_or(0), + podcast: media.contains_key(&id), }; (id, listing) }) @@ -663,6 +675,8 @@ pub struct FeedListing { pub ttl_mins: Option, pub blocked: Vec, pub unread: i64, + /// It has an audio or video file, so it is on the Podcasts shelf (#474). + pub podcast: bool, } /// Everything `fetch` needs to decide whether to poll a feed, and how. @@ -3639,12 +3653,15 @@ mod tests { INSERT INTO entries (feed_id, guid, first_seen) VALUES ('f','a',0),('f','b',0),('f','c',0),('g','d',0),('h','e',0); INSERT INTO entry_state (user_id, feed_id, guid, read) VALUES (1,'f','a',true),(2,'f','b',true); INSERT INTO hidden (user_id, feed_id, guid) VALUES (1,'f','c'); - INSERT INTO enclosures (id, feed_id, guid, url, path, state) VALUES - (1,'f','a','u1','/tmp/a','done'),(2,'f','b','u2',null,'pending'); + INSERT INTO enclosures (id, feed_id, guid, url, path, state, mime) VALUES + (1,'f','a','u1','/tmp/a','done','Audio/MPEG'),(2,'f','b','u2',null,'pending',null), + (3,'g','d','u3',null,'skipped','image/jpeg'); INSERT INTO blocklists (user_id, feed_id, words) VALUES (1,'g','[\"spoiler\"]');", ).await .unwrap(); let list = db.feed_list(1, None).await.unwrap(); + // On the Podcasts shelf by having sound, whatever the case of its type; a picture is not (#474). + assert!(list["f"].podcast && !list["g"].podcast); let g = db.feed_list(1, Some("g")).await.unwrap(); assert_eq!(g.keys().collect::>(), ["g"]); assert_eq!( diff --git a/crates/ipx/src/web.rs b/crates/ipx/src/web.rs index ded3a02..18f48a4 100644 --- a/crates/ipx/src/web.rs +++ b/crates/ipx/src/web.rs @@ -1004,6 +1004,8 @@ struct FeedRow { private: bool, /// Private whatever it is marked, for a login or an address with a key in it. private_by_address: bool, + /// Has an audio or video file: on the Podcasts shelf (#474). + podcast: bool, } #[derive(Serialize)] @@ -1052,7 +1054,8 @@ async fn feed_rows(state: &WebState, user: &crate::db::User, only: Option<&str>) let up = feed.group.as_deref().and_then(|g| mine.get(g)); let Some(mine) = mine.get(id) else { continue }; // A feed not scanned yet has no row: blank, as feed_summary gave it. - let crate::db::FeedListing { summary: s, ttl_mins, blocked, unread } = listed.remove(id).unwrap_or_default(); + let crate::db::FeedListing { summary: s, ttl_mins, blocked, unread, podcast } = + listed.remove(id).unwrap_or_default(); out.push(FeedRow { private: feed.private, private_by_address: crate::directory::looks_private(&crate::config::Feed { @@ -1115,6 +1118,7 @@ async fn feed_rows(state: &WebState, user: &crate::db::User, only: Option<&str>) kept: kept.contains(id), hide_from_all: hidden.contains(id), hide_from_signals: quiet.contains(id), + podcast, }); } Ok(out) diff --git a/crates/wire/proto/ipx.proto b/crates/wire/proto/ipx.proto index 3b91651..610c7bc 100644 --- a/crates/wire/proto/ipx.proto +++ b/crates/wire/proto/ipx.proto @@ -134,6 +134,8 @@ message FeedRow { bool hide_from_signals = 32; bool private = 33; bool private_by_address = 34; + // Has an audio or video file: on the Podcasts shelf (#474). + bool podcast = 35; } // GET /api/feeds. diff --git a/tests/ui/app.spec.ts b/tests/ui/app.spec.ts index 96552a5..197f699 100644 --- a/tests/ui/app.spec.ts +++ b/tests/ui/app.spec.ts @@ -462,6 +462,19 @@ test('Up Next lines episodes up, moves them, and plays the next when one ends (# await page.evaluate(() => api('/api/entries/test-show/ui-2/position', { method: 'POST', body: JSON.stringify({ secs: 0 }) })); }); +test('the Podcasts shelf shows the feeds with episodes, as their artwork, and opens one (#474)', async ({ page }) => { + await page.locator('#feedlist .place', { hasText: 'Podcasts' }).click(); + const shows = page.locator('#content .shelf .show'); + await expect(shows.filter({ hasText: 'Test Show' })).toBeVisible(); + // A blog of pictures has files, and no episodes. + await expect(shows.filter({ hasText: 'Picture Blog' })).toHaveCount(0); + await page.locator('#epSearch').fill('multi'); + await expect(shows).toHaveText([/Multi Show/]); + await page.locator('#epSearch').fill(''); + await shows.filter({ hasText: 'Test Show' }).click(); + await expect(page.locator('#eps .ep', { hasText: 'First Episode' })).toBeVisible(); +}); + 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 diff --git a/web/CHANGELOG.md b/web/CHANGELOG.md index 52dcd2c..ce1d801 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 +- 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). - The page reads ipx's answers in protobuf, with a decoder of its own and no library, and in JSON from a server that has none; offline, a kept answer still shows what was read offline (#470). - On a phone, back and the item's actions (read, pin, open, share) float over the text as it scrolls, so they are at hand anywhere in a long post without scrolling back to the top; pressing one there keeps your place (#456). diff --git a/web/app.css b/web/app.css index cc1a423..1e24887 100644 --- a/web/app.css +++ b/web/app.css @@ -696,6 +696,14 @@ body.scan-this .fhead [data-a=scan] .i,body.scan-any .fhead [data-a=scanall] .i, #listening .txt small .fd{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} #listening .txt small .left{flex:none;color:var(--dim)} #listening .childrow:not(.now) .eq{display:none} +/* The Podcasts shelf (#474): the artwork is the podcast, as on a shelf of records, so nothing + frames it: no card, no shadow, the name and its new episodes under it. */ +.shelf{display:grid;grid-template-columns:repeat(auto-fill,minmax(112px,1fr));gap:20px 14px;padding:4px 2px 24px} +.shelf .show{display:flex;flex-direction:column;gap:6px;min-width:0;text-align:left;cursor:pointer;border-radius:10px} +.shelf .show .art{width:100%;height:auto;aspect-ratio:1;border-radius:10px;font-size:26px} +.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}} /* 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} diff --git a/web/src/dialogs.ts b/web/src/dialogs.ts index f4a99c4..c091e68 100644 --- a/web/src/dialogs.ts +++ b/web/src/dialogs.ts @@ -310,6 +310,7 @@ async function renderListed(v: {title: string, icon: string, url?: string, blurb await renderDirectory(v.url!,$('#directory'),n=>{ if(VIEWS[S.feed ?? '']===v) $('#count').textContent=`${v.title}: ${plural(n,'feed')}`; }); return; } + if(v===VIEWS[':podcasts']){ drawShelf(box); return; } $('#epSearch').setAttribute('aria-label','Search items'); box.innerHTML=`
@@ -324,6 +325,25 @@ async function renderListed(v: {title: string, icon: string, url?: string, blurb n=>{ if(VIEWS[S.feed ?? '']===v) $('#count').textContent=`${v.title}: ${plural(n,'episode')}`; }); } +/// The Podcasts shelf (#474): every feed with audio or video, as its artwork, with how many of its +/// episodes are new. A tap opens it. The search box narrows it by name. +function drawShelf(box: HTMLElement){ + $('#epSearch').setAttribute('aria-label','Search podcasts'); + const q=S.q.trim().toLowerCase(); + const shows=S.feeds.filter(f=>f.podcast&&(!q||(f.title||f.id).toLowerCase().includes(q))); + $('#count').textContent=`Podcasts: ${plural(shows.length,'podcast')}`; + box.innerHTML=shows.length?'
' + :`

${q?`No podcast is called “${esc(S.q)}”.`:'No podcasts yet. Add a feed with episodes in it, and it shows here.'}

`; + const shelf=$('.shelf',box); + for(const f of shows){ + const name=f.title||f.id, b=document.createElement('button'); + b.type='button'; b.className='show'; + b.innerHTML=`${artHTML(f.image,name)}${esc(name)}${f.unread?`${f.unread} new`:''}`; + b.onclick=()=>selectFeed(f.id); + shelf.appendChild(b); + } +} + /// Currently Listening: episodes you started and have not finished, across every feed you /// subscribe to. A row resumes the episode in the player bar on click -- a shortcut back to /// where you left off, not another way to browse. The one in the player pauses instead. @@ -410,7 +430,7 @@ $('#epSearch').oninput=(ev: Event)=>{ clearTimeout(searchT); // server (#126, #127). searchT=setTimeout(()=>{ S.q=(ev.target as HTMLInputElement).value; S.offset=0; if(S.feed===':directory'){ dirShow=null; drawDirectory(); } - else if(S.feed===':listening') renderListed(VIEWS[':listening']); + else if(S.feed===':listening'||S.feed===':podcasts') renderListed(VIEWS[S.feed]); else loadEntries(); },250); }; // Crossing the phone breakpoint moves the files between their pane and the text. window.matchMedia?.('(max-width:820px)')?.addEventListener?.('change',()=>{ const e=cur(); if(e) showDetail(e); }); diff --git a/web/src/feeds.ts b/web/src/feeds.ts index 7660082..bc3c3d3 100644 --- a/web/src/feeds.ts +++ b/web/src/feeds.ts @@ -36,6 +36,8 @@ const VIEWS: Record={ // shape. Drawn here, so the two are the same list and differ only in that mark. queue:fa('0 0 512 512',''), queued:fa('0 0 512 512',''), + // Font Awesome's podcast, for the Podcasts shelf (#474). + podcasts:fa('0 0 448 512',''), next:fa('0 0 320 512',''), grip:fa('0 0 320 512',''), subbed:fa('0 0 512 512',''), // solid/circle-check From 2faca684da937b6a874f33530c0805ea7c0e3eb9 Mon Sep 17 00:00:00 2001 From: rays Date: Tue, 17 Nov 2026 14:40:02 +0000 Subject: [PATCH 3/9] Now Playing: a full view of what is playing (#475) Tapping the player bar, or Enter on it, opens a sheet over the feeds and the list: the episode's artwork large, its podcast, its show notes and Up Next. The bar stays below it with the controls, so there is one set of them rather than a second kept in step. Chapters are left for #477: nothing reads them. Co-Authored-By: Claude Opus 5.5 --- tests/ui/app.spec.ts | 32 +++++++++++++++++++++++++++ web/CHANGELOG.md | 1 + web/app.css | 50 ++++++++++++++++++++++++++++++------------- web/build.mts | 2 +- web/index.html | 3 ++- web/src/dialogs.ts | 2 +- web/src/native.ts | 1 + web/src/nowplaying.ts | 46 +++++++++++++++++++++++++++++++++++++++ web/src/player.ts | 5 +++-- web/src/upnext.ts | 1 + 10 files changed, 123 insertions(+), 20 deletions(-) create mode 100644 web/src/nowplaying.ts diff --git a/tests/ui/app.spec.ts b/tests/ui/app.spec.ts index 197f699..4403682 100644 --- a/tests/ui/app.spec.ts +++ b/tests/ui/app.spec.ts @@ -475,6 +475,38 @@ test('the Podcasts shelf shows the feeds with episodes, as their artwork, and op await expect(page.locator('#eps .ep', { hasText: 'First Episode' })).toBeVisible(); }); +test('Now Playing opens from the player bar with the artwork, show notes and Up Next (#475)', async ({ page }) => { + await page.evaluate(() => saveUpNext([])); + await page.locator('.feed', { hasText: 'Test Show' }).click(); + const first = page.locator('#eps .ep', { hasText: 'First Episode' }); + await first.hover(); + await first.locator('[data-a=queue]').click(); + const second = page.locator('#eps .ep', { hasText: 'Second Episode' }); + await second.hover(); + await second.locator('[data-a=play]').click(); + await expect(page.locator('#ptitle')).toHaveText('Second Episode'); + + const sheet = page.locator('#nowsheet'); + await page.locator('#pnow').click(); + await expect(sheet).toBeVisible(); + await expect(page.locator('#pnow')).toHaveAttribute('aria-expanded', 'true'); + await expect(sheet.locator('h2')).toHaveText('Second Episode'); + await expect(sheet.locator('.dbody')).toContainText('Notes for the second.'); + await expect(sheet.locator('#nowqueue .childrow')).toHaveText([/First Episode/]); + await page.keyboard.press('Escape'); + await expect(sheet).toBeHidden(); + // From the keyboard too, and the podcast's name opens its feed. + await page.locator('#pnow').focus(); + await page.keyboard.press('Enter'); + await sheet.locator('.nowshow').click(); + await expect(sheet).toBeHidden(); + await expect(page.locator('#eps .ep', { hasText: 'Second Episode' })).toBeVisible(); + + await page.locator('#pclose').click(); + await page.evaluate(() => saveUpNext([])); + await page.evaluate(() => api('/api/entries/test-show/ui-2/position', { method: 'POST', body: JSON.stringify({ secs: 0 }) })); +}); + 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 diff --git a/web/CHANGELOG.md b/web/CHANGELOG.md index ce1d801..9f52c02 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 +- 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). - The page reads ipx's answers in protobuf, with a decoder of its own and no library, and in JSON from a server that has none; offline, a kept answer still shows what was read offline (#470). diff --git a/web/app.css b/web/app.css index 1e24887..8baf5cf 100644 --- a/web/app.css +++ b/web/app.css @@ -688,14 +688,34 @@ body.scan-this .fhead [data-a=scan] .i,body.scan-any .fhead [data-a=scanall] .i, /* Currently Listening: how far into each episode you are, as a rail along the foot of its row. The one in the player is marked as it is everywhere else, by the amber EQ bars, and its rail and time left move as it plays. The rest stay neutral, so that one is what stands out. */ -#listening .childrow{position:relative;overflow:hidden;gap:12px;padding:10px 10px 13px} -#listening .childrow .art{width:44px;height:44px;font-size:13px} -#listening .txt b{display:flex;align-items:center;gap:7px} -#listening .txt b span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} -#listening .txt small{display:flex;gap:12px;margin-top:3px;color:var(--faint);font-size:11.5px} -#listening .txt small .fd{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} -#listening .txt small .left{flex:none;color:var(--dim)} -#listening .childrow:not(.now) .eq{display:none} +#listening .childrow,#nowqueue .childrow{position:relative;overflow:hidden;gap:12px;padding:10px 10px 13px} +#listening .childrow .art,#nowqueue .childrow .art{width:44px;height:44px;font-size:13px} +#listening .txt b,#nowqueue .txt b{display:flex;align-items:center;gap:7px} +#listening .txt b span,#nowqueue .txt b span{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +#listening .txt small,#nowqueue .txt small{display:flex;gap:12px;margin-top:3px;color:var(--faint);font-size:11.5px} +#listening .txt small .fd,#nowqueue .txt small .fd{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +#listening .txt small .left,#nowqueue .txt small .left{flex:none;color:var(--dim)} +#listening .childrow:not(.now) .eq,#nowqueue .childrow:not(.now) .eq{display:none} +/* Now Playing (#475): over the feeds and the list, above the player bar, which keeps the + controls. The artwork is the one large thing on the page. */ +#nowsheet{grid-row:1;grid-column:1/-1;z-index:30;overflow:auto;background:var(--bg); + padding:22px max(16px,calc((100% - 720px)/2)) 32px;position:relative} +#nowclose{position:absolute;top:14px;right:max(12px,calc((100% - 720px)/2 - 44px))} +.nowhead{display:grid;grid-template-columns:minmax(0,280px) minmax(0,1fr);gap:24px;align-items:end;margin:10px 0 26px} +.nowhead .nowart{width:100%;height:auto;aspect-ratio:1;border-radius:14px;font-size:56px} +.nowmeta{display:flex;flex-direction:column;gap:6px;min-width:0} +.nowmeta h2{margin:0;font-size:24px;line-height:1.2;text-wrap:balance} +.nowshow{align-self:flex-start;color:var(--accent);font-size:15px;font-weight:500;text-align:left} +.nowmeta small{color:var(--dim);font-size:12.5px;font-variant-numeric:tabular-nums} +#nowsheet h3{font-size:14px;font-weight:600;margin:22px 0 10px;color:var(--dim)} +#nowqueue{display:flex;flex-direction:column;gap:6px} +#pnow{cursor:pointer;border-radius:8px} +@media (max-width:820px){ + .nowhead{grid-template-columns:1fr;justify-items:center;text-align:center;gap:18px} + .nowhead .nowart{max-width:300px} + .nowmeta{align-items:center} + .nowshow{align-self:center;text-align:center} +} /* The Podcasts shelf (#474): the artwork is the podcast, as on a shelf of records, so nothing frames it: no card, no shadow, the name and its new episodes under it. */ .shelf{display:grid;grid-template-columns:repeat(auto-fill,minmax(112px,1fr));gap:20px 14px;padding:4px 2px 24px} @@ -708,14 +728,14 @@ body.scan-this .fhead [data-a=scan] .i,body.scan-any .fhead [data-a=scanall] .i, #listening .grip{width:22px;margin-left:-4px;color:var(--faint);cursor:grab;touch-action:none} #listening .grip svg{width:12px;height:12px} #listening .childrow.dragging{border-color:var(--accent);cursor:grabbing} -#listening .rail{position:absolute;left:0;right:0;bottom:0;height:3px;background:var(--raise)} -#listening .rail i{display:block;height:100%;width:0;background:var(--faint);transition:width .25s linear} -#listening .now{border-color:color-mix(in srgb,var(--accent2) 60%,var(--line))} -#listening .now .eq,#listening .now .left{color:var(--accent2)} -#listening .now .rail i{background:var(--accent2)} +#listening .rail,#nowqueue .rail{position:absolute;left:0;right:0;bottom:0;height:3px;background:var(--raise)} +#listening .rail i,#nowqueue .rail i{display:block;height:100%;width:0;background:var(--faint);transition:width .25s linear} +#listening .now,#nowqueue .now{border-color:color-mix(in srgb,var(--accent2) 60%,var(--line))} +#listening .now .eq,#nowqueue .now .eq,#listening .now .left,#nowqueue .now .left{color:var(--accent2)} +#listening .now .rail i,#nowqueue .now .rail i{background:var(--accent2)} /* Quiet buttons: a filled one on every row outshouted the row that is playing. */ -#listening [data-a=play]{color:var(--accent)} -#listening [data-a=remove]{color:var(--faint)} +#listening [data-a=play],#nowqueue [data-a=play]{color:var(--accent)} +#listening [data-a=remove],#nowqueue [data-a=remove]{color:var(--faint)} /* The Directory, laid out as Apple's is: a large title, then sections. Every page carries what kind of feed (.tabs, as the item filters are) in its title row. */ .dhead{margin-bottom:6px} diff --git a/web/build.mts b/web/build.mts index 172cb56..03d717b 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', 'dialogs', 'signals', 'gestures', 'offline', 'events', 'native'] }, + 'index.html': { script: 'app.js', src: ['util', 'wire', 'theme', 'feeds', 'feedpage', 'items', 'player', 'upnext', 'nowplaying', 'dialogs', 'signals', '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/index.html b/web/index.html index c77b936..98b2041 100644 --- a/web/index.html +++ b/web/index.html @@ -46,11 +46,12 @@
+
-
+ diff --git a/web/src/dialogs.ts b/web/src/dialogs.ts index c091e68..17bd00e 100644 --- a/web/src/dialogs.ts +++ b/web/src/dialogs.ts @@ -401,7 +401,7 @@ function paintListenRow(el: HTMLElement & {entry?: Entry}){ } /// Keeps the list in step with the player. Only a row that is, or was, the one in it changes. function syncListening(){ - for(const el of $$('#listening .childrow')) + for(const el of $$('#listening .childrow, #nowqueue .childrow')) if(el.entry&&(el.classList.contains('now')||inPlayer(el.entry))) paintListenRow(el); } diff --git a/web/src/native.ts b/web/src/native.ts index 5c791de..2d7a130 100644 --- a/web/src/native.ts +++ b/web/src/native.ts @@ -241,6 +241,7 @@ function installNativePlayback(){ fire(m.playing ? 'play' : 'pause'); renderEntries(); syncListening(); + drawNow(); } function stop(){ diff --git a/web/src/nowplaying.ts b/web/src/nowplaying.ts new file mode 100644 index 0000000..3a45276 --- /dev/null +++ b/web/src/nowplaying.ts @@ -0,0 +1,46 @@ +/* ---------------- Now Playing ---------------- */ +/// Now Playing (#475): what is playing, opened from the player bar. Its artwork large, the +/// podcast it is from, its show notes and what follows in Up Next. The bar stays below it with +/// the controls, so there is one set of them, not a second to keep in step. +const nowSheet=$('#nowsheet'); +const nowOpen=()=>!nowSheet.hidden; + +function openNow(){ + if(!player.guid) return; + nowSheet.hidden=false; + $('#pnow').setAttribute('aria-expanded','true'); + drawNow(); + $('#nowclose').focus(); +} +function closeNow(){ + if(!nowOpen()) return; + nowSheet.hidden=true; + $('#pnow').setAttribute('aria-expanded','false'); + $('#pnow').focus(); +} +/// Drawn again whenever what plays or what follows changes, while it is open. +function drawNow(){ + const e=player.entry; + if(!nowOpen()) return; + if(!e||!player.guid){ closeNow(); return; } + const name=entryName(e).text, show=feedName(e.feed_id); + nowSheet.innerHTML=` + +
+ ${artHTML(e.image||feedArt(e.feed_id),show,'nowart')} +
+

${esc(name)}

+ + ${[dateOf(e.published),e.duration?clock(e.duration):''].filter(Boolean).join(', ')} +
+
+ ${upNext.length?`

Up Next

`:''} +

Show notes

+
${textOf(e)}
`; + $('#nowclose').onclick=closeNow; + $('.nowshow',nowSheet).onclick=()=>{ closeNow(); selectFeed(e.feed_id); }; + const q=$('#nowqueue'); + for(const x of upNext) q?.appendChild(listenRow(x,'Remove from Up Next',()=>saveUpNext(upNext.filter(y=>entryKey(y)!==entryKey(x))))); +} +$('#pnow').onclick=()=>nowOpen()?closeNow():openNow(); +$('#pnow').onkeydown=(ev: KeyboardEvent)=>{ if(ev.key==='Enter'||ev.key===' '){ ev.preventDefault(); $('#pnow').click(); } }; diff --git a/web/src/player.ts b/web/src/player.ts index 5fdedc4..2736954 100644 --- a/web/src/player.ts +++ b/web/src/player.ts @@ -87,6 +87,7 @@ function play(e: Entry,enc=e.enclosures.find(isPlayable)){ paintDead(); startedPlaying(e); hostNext(); + drawNow(); } const go=()=>audio.play().catch(playFailed); if(wait) wait.then(go,playFailed); else go(); @@ -279,7 +280,7 @@ async function switchVersion(){ if(was) (wait||Promise.resolve()).then(()=>audio.play()).catch(()=>{}); return true; } -$('#pclose').onclick=()=>{if(sleepAt)sleepIn(0);savePos();audio.pause();dropHls();audio.removeAttribute('src');player.guid=null;$('#player').classList.remove('on');document.body.classList.remove('has-video');renderEntries(); +$('#pclose').onclick=()=>{closeNow();if(sleepAt)sleepIn(0);savePos();audio.pause();dropHls();audio.removeAttribute('src');player.guid=null;$('#player').classList.remove('on');document.body.classList.remove('has-video');renderEntries(); // Called here, not left to the pause event: closing a player already paused fires none. syncListening()}; (function restore(){ @@ -291,7 +292,7 @@ $('#pclose').onclick=()=>{if(sleepAt)sleepIn(0);savePos();aud document.addEventListener('keydown',ev=>{ // Escape leaves a dialog even from inside one of its boxes. It used to sit below the check // that follows, so Add feed, which opens with the cursor in its URL box, ignored it. - if(ev.key==='Escape'){closeModal();nav(false);return} + if(ev.key==='Escape'){closeModal();nav(false);closeNow();return} // The rest are single keys that would otherwise eat what you type. if(/^(INPUT|TEXTAREA|SELECT)$/.test((ev.target as Element).tagName)) return; if(ev.key===' '&&player.guid){ev.preventDefault();audio.paused?audio.play():audio.pause()} diff --git a/web/src/upnext.ts b/web/src/upnext.ts index 5566f37..4b864ca 100644 --- a/web/src/upnext.ts +++ b/web/src/upnext.ts @@ -25,6 +25,7 @@ async function saveUpNext(list: Entry[]){ function upNextChanged(){ renderFeeds(); if(S.feed===':upnext') drawUpNext(); + drawNow(); // The rows' and the reader's buttons say whether each is in it. for(const b of $$('[data-a=queue]')) paintQueueButton(b); hostNext(); From 02ee6d74c1642f265a38ea7be2110fc72fdd83f3 Mon Sep 17 00:00:00 2001 From: rays Date: Tue, 17 Nov 2026 14:54:19 +0000 Subject: [PATCH 4/9] 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 --- crates/ipx/CHANGELOG.md | 1 + crates/ipx/src/db.rs | 153 ++++++++++++++++++++++++++++++++- crates/ipx/src/entity.rs | 27 ++++++ crates/ipx/src/web.rs | 95 +++++++++++++++++++++ crates/wire/proto/ipx.proto | 29 +++++++ tests/ui/app.spec.ts | 43 +++++++++- web/CHANGELOG.md | 1 + web/app.css | 6 ++ web/build.mts | 2 +- web/src/events.ts | 1 + web/src/feedpage.ts | 3 + web/src/feeds.ts | 3 +- web/src/items.ts | 2 +- web/src/player.ts | 1 + web/src/playlists.ts | 163 ++++++++++++++++++++++++++++++++++++ web/src/types.ts | 12 +++ web/src/upnext.ts | 9 +- 17 files changed, 540 insertions(+), 11 deletions(-) create mode 100644 web/src/playlists.ts diff --git a/crates/ipx/CHANGELOG.md b/crates/ipx/CHANGELOG.md index 2e9ee62..8914139 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 +- 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). diff --git a/crates/ipx/src/db.rs b/crates/ipx/src/db.rs index c77903c..0408b04 100644 --- a/crates/ipx/src/db.rs +++ b/crates/ipx/src/db.rs @@ -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, + #[serde(default)] + pub priority: Vec, + #[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::>().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> { + let mine: std::collections::HashSet = + 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> { + 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, spec: &PlaylistSpec) -> Result> { + 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 { + 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 { 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::>() + }; + 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(); diff --git a/crates/ipx/src/entity.rs b/crates/ipx/src/entity.rs index a607d72..7d018a8 100644 --- a/crates/ipx/src/entity.rs +++ b/crates/ipx/src/entity.rs @@ -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. diff --git a/crates/ipx/src/web.rs b/crates/ipx/src/web.rs index 18f48a4..77f0564 100644 --- a/crates/ipx/src/web.rs +++ b/crates/ipx/src/web.rs @@ -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, 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 { + 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 = + 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, + user: crate::db::User, +) -> Result>, ApiError> { + Ok(Json(state.ctx.db.playlists(user.id).await?)) +} + +async fn add_playlist( + State(state): State, + user: crate::db::User, + Json(spec): Json, +) -> Result, 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, + Path(id): Path, + user: crate::db::User, + Json(spec): Json, +) -> Result { + 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, + Path(id): Path, + user: crate::db::User, +) -> Result { + 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, + Path(id): Path, + user: crate::db::User, + Query(page): Query, +) -> Result, 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, diff --git a/crates/wire/proto/ipx.proto b/crates/wire/proto/ipx.proto index 610c7bc..014799f 100644 --- a/crates/wire/proto/ipx.proto +++ b/crates/wire/proto/ipx.proto @@ -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; diff --git a/tests/ui/app.spec.ts b/tests/ui/app.spec.ts index 4403682..69a7143 100644 --- a/tests/ui/app.spec.ts +++ b/tests/ui/app.spec.ts @@ -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(); diff --git a/web/CHANGELOG.md b/web/CHANGELOG.md index 9f52c02..ed1d64b 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 +- 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). diff --git a/web/app.css b/web/app.css index 8baf5cf..ba4b8c9 100644 --- a/web/app.css +++ b/web/app.css @@ -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} diff --git a/web/build.mts b/web/build.mts index 03d717b..9ff0002 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', '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'] }, }; diff --git a/web/src/events.ts b/web/src/events.ts index e245bde..08c733e 100644 --- a/web/src/events.ts +++ b/web/src/events.ts @@ -139,3 +139,4 @@ function offerReload(){ connect(); loadFeeds().then(preloadLists).catch(()=>{}); loadUpNext(); +loadPlaylists(); diff --git a/web/src/feedpage.ts b/web/src/feedpage.ts index f3d72bb..475a720 100644 --- a/web/src/feedpage.ts +++ b/web/src/feedpage.ts @@ -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); $('#tbRemove').disabled=!f; diff --git a/web/src/feeds.ts b/web/src/feeds.ts index bc3c3d3..a6b57d5 100644 --- a/web/src/feeds.ts +++ b/web/src/feeds.ts @@ -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','

No feeds.

'); return done(); } diff --git a/web/src/items.ts b/web/src/items.ts index cb7731b..404ea95 100644 --- a/web/src/items.ts +++ b/web/src/items.ts @@ -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. diff --git a/web/src/player.ts b/web/src/player.ts index 2736954..1e034db 100644 --- a/web/src/player.ts +++ b/web/src/player.ts @@ -72,6 +72,7 @@ function play(e: Entry,enc=e.enclosures.find(isPlayable)){ let wait: Promise|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; diff --git a/web/src/playlists.ts b/web/src/playlists.ts new file mode 100644 index 0000000..5a76c44 --- /dev/null +++ b/web/src/playlists.ts @@ -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:`, +/// 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', + ``+ + `
${ICON.queue}
Playlists${playlists.length?plural(playlists.length,'playlist'):'Episodes from the podcasts you choose'}
`, + ()=>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', + `${playlistArt(p)}
${esc(p.name)}${plural(p.feeds.length,'podcast')}
`+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')}`; + $('#tbRemove').disabled=true; + syncTools(null); + const box=$('#content'); + box.classList.add('plain'); + box.innerHTML=` +
+
${ICON.queue}
+

Playlists

Episodes from the podcasts you choose, kept up to date as new ones come.
+
+
+
`; + $('#content .acts [data-a="new"]').onclick=()=>playlistModal(); + const list=$('#plists'); + if(!playlists.length){ list.innerHTML='

No playlists yet. Make one from the podcasts you want to hear in a row.

'; return; } + for(const p of playlists){ + const el=document.createElement('div'); + el.className='childrow'; + el.innerHTML=playlistArt(p)+`
${esc(p.name)}${plural(p.feeds.length,'podcast')}
`+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){ + $('#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=` +
+ ${playlistArt(p)} +

${esc(p.name)}

${how}, from ${plural(p.feeds.length,'podcast')}
+
+ + +
+
+
`; + $('#content .acts [data-a="edit"]').onclick=()=>playlistModal(p); + $('#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=`

${esc(why(e))}

`; return; } + if(!list.isConnected) return; + $('#count').textContent=`${p.name}: ${plural(p.items,'episode')}`; + list.innerHTML=rows.length?'':'

Nothing here yet. Episodes show up as your podcasts publish them.

'; + 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 `
${artHTML(f.image,f.title||f.id)} + +
`; + }; + openModal(`

${p?'Edit playlist':'New playlist'}

+
+
+
+ ${shows.length?`
${shows.map(row).join('')}
`:'

Subscribe to a podcast first.

'} + Episodes of those set to play first come before the rest.
+
+ +
+
+
`); + // Play first means something only for a podcast in the playlist. + for(const box of $$('[data-in]')) box.onchange=()=>{ + const first=$(`[data-first="${CSS.escape(box.dataset.in!)}"]`); + first.disabled=!box.checked; if(!box.checked) first.checked=false; + }; + $('#plname').focus(); + $('#plsave').onclick=async()=>{ + const name=$('#plname').value.trim(); + const feeds=$$('[data-in]').filter(b=>b.checked).map(b=>b.dataset.in!); + if(!name){ $('#plname').focus(); return; } + if(!feeds.length){ toast('Choose at least one podcast.',true); return; } + const body=JSON.stringify({name,feeds,priority:$$('[data-first]').filter(b=>b.checked).map(b=>b.dataset.first!), + only_unplayed:$('#plunplayed').checked,oldest_first:$('#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); } + }; +} diff --git a/web/src/types.ts b/web/src/types.ts index 0887a6c..6d1a01d 100644 --- a/web/src/types.ts +++ b/web/src/types.ts @@ -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; diff --git a/web/src/upnext.ts b/web/src/upnext.ts index 4b864ca..ca7a87c 100644 --- a/web/src/upnext.ts +++ b/web/src/upnext.ts @@ -56,10 +56,13 @@ const queueButton=(e: Entry,cls='iconbtn')=>``; /// 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(); $('#pnext').hidden=!next; try{ if(!ipxHost||!hostCan.has('next')) return; From bd7452db8f1f6b5dab6030d863a08dae68e0d217 Mon Sep 17 00:00:00 2001 From: rays Date: Tue, 17 Nov 2026 14:57:38 +0000 Subject: [PATCH 5/9] Now Playing covers the feeds and the list, not a row above them (#475) As a grid item of #shell the sheet took a row of its own and pushed the sidebar and the list into a second one; it is laid over the shell instead. Co-Authored-By: Claude Opus 5.5 --- web/app.css | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/web/app.css b/web/app.css index ba4b8c9..1f4ae82 100644 --- a/web/app.css +++ b/web/app.css @@ -509,7 +509,7 @@ a{color:var(--accent)} ::-webkit-scrollbar-track{background:transparent} /* ---------- shell ---------- */ -#shell{display:grid;grid-template-columns:290px 1fr;min-height:0;min-width:0;overflow:hidden} +#shell{display:grid;grid-template-columns:290px 1fr;min-height:0;min-width:0;overflow:hidden;position:relative} /* [ hides the feed list. A phone slides it over the page instead, so this is for wider screens. */ @media (min-width:821px){ body.nosb #shell{grid-template-columns:minmax(0,1fr)} @@ -698,9 +698,9 @@ body.scan-this .fhead [data-a=scan] .i,body.scan-any .fhead [data-a=scanall] .i, #listening .childrow:not(.now) .eq,#nowqueue .childrow:not(.now) .eq{display:none} /* Now Playing (#475): over the feeds and the list, above the player bar, which keeps the controls. The artwork is the one large thing on the page. */ -#nowsheet{grid-row:1;grid-column:1/-1;z-index:30;overflow:auto;background:var(--bg); - padding:22px max(16px,calc((100% - 720px)/2)) 32px;position:relative} -#nowclose{position:absolute;top:14px;right:max(12px,calc((100% - 720px)/2 - 44px))} +#nowsheet{position:absolute;inset:0;z-index:30;overflow:auto;background:var(--bg); + padding:22px max(16px,calc((100% - 720px)/2)) 32px} +#nowclose{position:sticky;float:right;top:0;margin:-8px -4px 0 0;right:max(12px,calc((100% - 720px)/2 - 44px))} .nowhead{display:grid;grid-template-columns:minmax(0,280px) minmax(0,1fr);gap:24px;align-items:end;margin:10px 0 26px} .nowhead .nowart{width:100%;height:auto;aspect-ratio:1;border-radius:14px;font-size:56px} .nowmeta{display:flex;flex-direction:column;gap:6px;min-width:0} From 7a3e3b4c63f44f10f724dd102c2ba48ec8dcd10d Mon Sep 17 00:00:00 2001 From: rays Date: Thu, 19 Nov 2026 07:30:49 -0500 Subject: [PATCH 6/9] The media handler's impossible error is matched as one (#479) rustc 1.100 knows serving a file cannot fail (the error is Infallible) and called e.to_string() an unreachable call, which -D warnings made the pre-commit hook refuse for every commit touching ipx's Rust. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy --- crates/ipx/src/web.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ipx/src/web.rs b/crates/ipx/src/web.rs index 77f0564..c0aeddc 100644 --- a/crates/ipx/src/web.rs +++ b/crates/ipx/src/web.rs @@ -2945,7 +2945,7 @@ async fn serve_media(state: WebState, id: i64, user: crate::db::User, req: Reque } r.into_response() } - Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(), + Err(e) => match e {}, } } From 02d485cd10238511300de6861d01722311300f9f Mon Sep 17 00:00:00 2001 From: rays Date: Thu, 19 Nov 2026 07:30:52 -0500 Subject: [PATCH 7/9] A feed an OPML drops takes its subscriptions and is not scanned again (#478) On 2026-11-18 a scan's OPML sync dropped sciencedaily-latest-science-news. drop_managed deleted the feed and its items but left its subscriptions, and the scan, which had the feed in its list of feeds due, read it again later in the same run and stored 60 items. The feed was then in no catalogue but still subscribed to: All Subscriptions, which reads subscriptions, listed its items, while the feed list, which reads the catalogue, left it out, so the page had no name to put beside them and sharing one answered 404. drop_managed now deletes the feed's subscriptions too, and sync_group returns the ids it dropped so the scan skips them. 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 | 2 ++ crates/ipx/src/lists.rs | 21 +++++++++++++++++++-- crates/ipx/src/scan.rs | 14 +++++++++++--- 4 files changed, 33 insertions(+), 5 deletions(-) diff --git a/crates/ipx/CHANGELOG.md b/crates/ipx/CHANGELOG.md index 8914139..643a9c4 100644 --- a/crates/ipx/CHANGELOG.md +++ b/crates/ipx/CHANGELOG.md @@ -35,6 +35,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- A feed an OPML stops listing leaves All Subscriptions with it, rather than its items staying there with no feed name beside them: the scan no longer reads it again after the list drops it, and its subscriptions go with it (#478). - Searching All Subscriptions answers in a fraction of a second, not five: a search reads each item's title and text without its markup, indexed on Postgres, and still finds part of a word. It no longer matches words inside the HTML's tags, such as a link's address. Text past the first 4,000 characters of a very long post is not searched (#459, #472). - Artwork that cannot be shown is asked for again a day later rather than every hour: one too large is refused on its stated size before it is read, and a refusal from the publisher or one ipx makes (too large, not an image) is remembered for a day; JPEG XL pictures sent without a type are shown (#448). - `ipx reap --dry-run` says "would delete" of each file and of the total, rather than "deleted", word for word a real reap, of files it kept (#461). diff --git a/crates/ipx/src/db.rs b/crates/ipx/src/db.rs index 0408b04..cea64a7 100644 --- a/crates/ipx/src/db.rs +++ b/crates/ipx/src/db.rs @@ -2708,6 +2708,8 @@ impl Db { self.exec("DELETE FROM feeds WHERE id = $1 AND managed", vec![id.into()]).await?; self.exec("DELETE FROM entries WHERE feed_id = $1", vec![id.into()]).await?; self.exec("DELETE FROM enclosures WHERE feed_id = $1 AND path IS NULL", vec![id.into()]).await?; + // Left behind, All Subscriptions listed the items of a feed no list had a name for (#478). + self.exec("DELETE FROM subscriptions WHERE feed_id = $1", vec![id.into()]).await?; Ok(()) } diff --git a/crates/ipx/src/lists.rs b/crates/ipx/src/lists.rs index 13c6ead..b42cdf8 100644 --- a/crates/ipx/src/lists.rs +++ b/crates/ipx/src/lists.rs @@ -182,7 +182,7 @@ pub(crate) async fn sync_group(ctx: &Arc, parent_id: &str, listed: &[(Strin .await?; // Anything in this group the OPML no longer lists. - let mut removed = 0; + let mut removed = vec![]; let mut kept = 0; let parent = ctx.cfg().feeds.get(parent_id).cloned(); async { @@ -203,7 +203,7 @@ pub(crate) async fn sync_group(ctx: &Arc, parent_id: &str, listed: &[(Strin tracing::info!(feed = %m.id, "dropped from the OPML but has downloads; keeping it"); } else { ctx.db.drop_managed(&m.id).await?; - removed += 1; + removed.push(m.id.clone()); tracing::info!(feed = %m.id, "dropped from the OPML with nothing downloaded; removed"); } } @@ -291,4 +291,21 @@ mod tests { assert!(ctx.db.subscription(me, "b").await.unwrap().is_some()); assert!(ctx.db.subscription(you, "b").await.unwrap().is_none()); } + + #[tokio::test] + async fn a_feed_the_list_drops_takes_its_subscriptions_with_it() { + let mut cfg = config::Config::default(); + cfg.feeds.insert("opml".into(), feed()); + let ctx = Arc::new(test_ctx(cfg).await); + let me = ctx.db.create_user("me", None, false).await.unwrap(); + ctx.db.upsert_managed("a", "http://x/a.xml", "a", "opml").await.unwrap(); + ctx.db.subscribe(me, "opml").await.unwrap(); + ctx.db.subscribe(me, "a").await.unwrap(); + + // Left subscribed, All Subscriptions listed a's items with no feed to name them (#478). + let Outcome::Opml { removed, .. } = sync_group(&ctx, "opml", &[]).await.unwrap() else { panic!("a list") }; + assert_eq!(removed, ["a"], "the scan is told, so it does not read a again"); + assert!(ctx.db.subscription(me, "a").await.unwrap().is_none()); + assert!(ctx.db.subscription(me, "opml").await.unwrap().is_some()); + } } diff --git a/crates/ipx/src/scan.rs b/crates/ipx/src/scan.rs index 92b6fb4..73eb244 100644 --- a/crates/ipx/src/scan.rs +++ b/crates/ipx/src/scan.rs @@ -5,6 +5,7 @@ use crate::ctx::Ctx; use crate::ipc::Event; use crate::{catalogue, cli, config, db, download, feed, lists, metrics, signals, torrent}; use anyhow::Result; +use std::collections::HashSet; use std::path::Path; use std::path::PathBuf; use std::sync::Arc; @@ -23,6 +24,8 @@ pub(crate) async fn fetch(ctx: &Arc, only: Option<&str>, force: bool, scope let subscribed = ctx.db.subscriber_counts().await?; let mut scanned = 0; let mut fresh: Vec = vec![]; + // Feeds a list read earlier in this run dropped: still in `due`, scanned they came back (#478). + let mut dropped: HashSet = HashSet::new(); let in_scope = |s: &Sub| scope.is_empty() || scope.contains(&s.id) || s.cfg.group.as_ref().is_some_and(|g| scope.contains(g)); let mut states = ctx.db.http_states().await?; @@ -95,6 +98,9 @@ pub(crate) async fn fetch(ctx: &Arc, only: Option<&str>, force: bool, scope let (id, feed_cfg) = (&sub.id, &sub.cfg); // A task that panicked has no body; scan_one then fetches it itself. let fetched = futures_util::StreamExt::next(&mut bodies).await.and_then(|j| j.ok()).flatten(); + if dropped.contains(id) { + continue; + } scanned += 1; ctx.out.emit(Event::FeedStart { feed: id.clone() }); match scan_one(ctx, id, feed_cfg, state, force, fetched).await { @@ -113,10 +119,12 @@ pub(crate) async fn fetch(ctx: &Arc, only: Option<&str>, force: bool, scope ctx.out.emit(Event::FeedSkip { feed: id.clone(), reason: format!( - "{total} feed(s) listed, {} added, {removed} unsubscribed, {kept} kept without a listing", - added.len() + "{total} feed(s) listed, {} added, {} unsubscribed, {kept} kept without a listing", + added.len(), + removed.len() ), }); + dropped.extend(removed); // Read them in the same pass, as the original did, rather than making // the user wait a whole interval for a newly listed show. fresh.extend(added); @@ -247,7 +255,7 @@ pub(crate) enum Outcome { /// The URL is a list of feeds rather than a feed: an OPML, or a Patreon creator's shows. Opml { added: Vec, - removed: usize, + removed: Vec, kept: usize, total: usize, }, From c19135744273a1a49bca4d8da1dda55cf53dd60c Mon Sep 17 00:00:00 2001 From: rays Date: Thu, 19 Nov 2026 07:33:53 -0500 Subject: [PATCH 8/9] ipx rm takes a feed's subscriptions with it (#478) Removing a feed from the catalogue left whoever subscribed to it subscribed, the same leftover a list's dropped feed made: All Subscriptions listed its items with no feed to name them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy --- crates/ipx/src/catalogue.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/ipx/src/catalogue.rs b/crates/ipx/src/catalogue.rs index 1bfe71c..c175a53 100644 --- a/crates/ipx/src/catalogue.rs +++ b/crates/ipx/src/catalogue.rs @@ -136,6 +136,10 @@ pub(crate) async fn rm(ctx: &Ctx, feed: &str) -> Result<()> { return Ok(()); }; ctx.store_cfg(cfg).await?; + // Left subscribed, All Subscriptions listed its items with no feed to name them (#478). + for (user, _) in ctx.db.subscribers_of(feed).await? { + ctx.db.unsubscribe(user, feed).await?; + } // State and files stay: re-adding the feed should not re-download its back catalogue. println!("removed {feed}; downloads and history kept"); retire_group(ctx, feed, Some(&parent)).await?; From d5037fb76d3b47577abbcb5ac926a4d8c22a37b1 Mon Sep 17 00:00:00 2001 From: rays Date: Thu, 19 Nov 2026 07:39:00 -0500 Subject: [PATCH 9/9] Subscriptions to a feed no longer in the catalogue are dropped at start (#478) The ways a feed leaves the catalogue now take its subscriptions with it, but any path missed now or added later would leave the same leftover: items in All Subscriptions with no feed to name them. Each start now unsubscribes everyone from a feed the catalogue does not have, after retire_stranded, unless the catalogue is empty, which is likelier a fault than a server with no feeds. The 41 already in production (all from the Hacker News top feeds OPML, which drops feeds daily) were deleted by hand on 2026-11-19. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RqkrVAJFkEgz9cXG3jG1Zy --- crates/ipx/CHANGELOG.md | 2 +- crates/ipx/src/catalogue.rs | 36 ++++++++++++++++++++++++++++++++++++ crates/ipx/src/daemon.rs | 6 ++++++ 3 files changed, 43 insertions(+), 1 deletion(-) diff --git a/crates/ipx/CHANGELOG.md b/crates/ipx/CHANGELOG.md index 643a9c4..301ba83 100644 --- a/crates/ipx/CHANGELOG.md +++ b/crates/ipx/CHANGELOG.md @@ -35,7 +35,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed -- A feed an OPML stops listing leaves All Subscriptions with it, rather than its items staying there with no feed name beside them: the scan no longer reads it again after the list drops it, and its subscriptions go with it (#478). +- A feed an OPML stops listing leaves All Subscriptions with it, rather than its items staying there with no feed name beside them: the scan no longer reads it again after the list drops it, and its subscriptions go with it, as they do when a feed is removed with `ipx rm`. Any left from before are removed when ipx starts (#478). - Searching All Subscriptions answers in a fraction of a second, not five: a search reads each item's title and text without its markup, indexed on Postgres, and still finds part of a word. It no longer matches words inside the HTML's tags, such as a link's address. Text past the first 4,000 characters of a very long post is not searched (#459, #472). - Artwork that cannot be shown is asked for again a day later rather than every hour: one too large is refused on its stated size before it is read, and a refusal from the publisher or one ipx makes (too large, not an image) is remembered for a day; JPEG XL pictures sent without a type are shown (#448). - `ipx reap --dry-run` says "would delete" of each file and of the total, rather than "deleted", word for word a real reap, of files it kept (#461). diff --git a/crates/ipx/src/catalogue.rs b/crates/ipx/src/catalogue.rs index c175a53..1d38af6 100644 --- a/crates/ipx/src/catalogue.rs +++ b/crates/ipx/src/catalogue.rs @@ -481,6 +481,27 @@ pub(crate) async fn retire_stranded(ctx: &Ctx) -> Result { Ok(before.len() - ctx.db.managed_feeds().await?.len()) } +/// Unsubscribes everyone from feeds the catalogue no longer has, and returns how many feeds that +/// was. Removing a feed once left its subscriptions behind, 41 of them by 2026-11-19, and All +/// Subscriptions listed their items with no feed to name them (#478). +pub(crate) async fn drop_stray_subscriptions(ctx: &Ctx) -> Result { + let known: std::collections::HashSet = subscriptions(ctx).await?.into_iter().map(|s| s.id).collect(); + // A catalogue that came back empty is more likely a fault than a server with no feeds, and + // taking it at its word would unsubscribe everyone from everything. + if known.is_empty() { + return Ok(0); + } + let mut dropped = 0; + for feed in ctx.db.subscriber_counts().await?.into_keys().filter(|f| !known.contains(f)) { + for (user, _) in ctx.db.subscribers_of(&feed).await? { + ctx.db.unsubscribe(user, &feed).await?; + } + tracing::info!(feed = %feed, "unsubscribed everyone from a feed no longer in the catalogue"); + dropped += 1; + } + Ok(dropped) +} + /// Puts each feed no longer derived in the group its catalogue entry says, and returns how many /// moved. Made a feed of its own before #358, a show kept its list's group in the database, and /// hiding the list from All Subscriptions hid it too. @@ -716,6 +737,21 @@ mod tests { assert_eq!(regroup_unmanaged(&ctx).await.unwrap(), 0, "nothing left to move"); } + #[tokio::test] + async fn a_subscription_to_a_feed_not_in_the_catalogue_is_dropped() { + let mut cfg = config::Config::default(); + cfg.feeds.insert("opml".into(), feed()); + let ctx = test_ctx(cfg).await; + let me = ctx.db.create_user("me", None, false).await.unwrap(); + ctx.db.upsert_managed("listed", "http://x/l.xml", "Listed", "opml").await.unwrap(); + for id in ["opml", "listed", "gone"] { + ctx.db.subscribe(me, id).await.unwrap(); + } + assert_eq!(drop_stray_subscriptions(&ctx).await.unwrap(), 1); + let mine: Vec = ctx.db.subscriptions_for(me).await.unwrap().into_iter().map(|s| s.feed_id).collect(); + assert!(mine.contains(&"opml".into()) && mine.contains(&"listed".into()) && !mine.contains(&"gone".into())); + } + #[tokio::test] async fn a_stranded_group_is_retired_but_a_promoted_feed_keeps_its_entries() { // davewiner: the OPML left config before retire_group existed, and 11 of its feeds diff --git a/crates/ipx/src/daemon.rs b/crates/ipx/src/daemon.rs index 1ac84f4..6c2db7e 100644 --- a/crates/ipx/src/daemon.rs +++ b/crates/ipx/src/daemon.rs @@ -97,6 +97,12 @@ pub(crate) async fn daemon( Ok(n) => tracing::info!(feeds = n, "retired feeds whose OPML is no longer in config"), Err(e) => tracing::warn!(error = %format!("{e:#}"), "could not retire feeds whose OPML is no longer in config"), } + // After retire_stranded, which drops feeds whose subscriptions this then finds. + match catalogue::drop_stray_subscriptions(&ctx).instrument(db::step("drop_stray_subscriptions")).await { + Ok(0) => {} + Ok(n) => tracing::info!(feeds = n, "unsubscribed everyone from feeds no longer in the catalogue"), + Err(e) => tracing::warn!(error = %format!("{e:#}"), "could not drop subscriptions to feeds no longer in the catalogue"), + } match catalogue::regroup_unmanaged(&ctx).instrument(db::step("regroup_unmanaged")).await { Ok(0) => {} Ok(n) => tracing::info!(feeds = n, "took feeds of their own out of their old list's group"),