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.