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 <noreply@anthropic.com>
This commit is contained in:
@@ -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).
|
||||
|
||||
@@ -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<Vec<EntryRow>> {
|
||||
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<sea_orm::Value>| 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::<Vec<_>>();
|
||||
|
||||
// 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();
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<WebState>, user: crate::db::User) -> Result<Json<EntryPage>, 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<WebState>,
|
||||
user: crate::db::User,
|
||||
Json(items): Json<Vec<QueueItem>>,
|
||||
) -> Result<Json<EntryPage>, 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<Json<EntryPage>, 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<WebState>,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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 {},
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -29,7 +29,7 @@ const WEB_VERSION = JSON.parse(fs.readFileSync(path.join(here, '..', 'package.js
|
||||
// The files are one script, concatenated in this order, not modules: they share one top-level
|
||||
// scope, as the single inline script did, and code that runs at load needs what came before it.
|
||||
const PAGES: Record<string, { script: string, src: string[] }> = {
|
||||
'index.html': { script: 'app.js', src: ['util', 'wire', 'theme', 'feeds', 'feedpage', 'items', 'player', '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'] },
|
||||
};
|
||||
|
||||
@@ -59,6 +59,7 @@
|
||||
<button class="iconbtn" id="pback" title="Back 15 seconds (←)" aria-label="Back 15 seconds" data-icon="back"></button>
|
||||
<button class="iconbtn" id="pplay" title="Play or pause (space)" aria-label="Play or pause" data-icon="play"></button>
|
||||
<button class="iconbtn" id="pfwd" title="Forward 30 seconds (→)" aria-label="Forward 30 seconds" data-icon="fwd"></button>
|
||||
<button class="iconbtn" id="pnext" hidden title="Play the next in Up Next" aria-label="Play the next in Up Next" data-icon="next"></button>
|
||||
</div>
|
||||
<div id="seekrow">
|
||||
<span id="pcur">0:00</span>
|
||||
|
||||
@@ -318,6 +318,7 @@ async function renderListed(v: {title: string, icon: string, url?: string, blurb
|
||||
</div>
|
||||
<div class="childlist" id="listening"></div>`;
|
||||
$('#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?`<p class="hint">Nothing you are listening to mentions “${esc(S.q)}”.</p>`
|
||||
:'<p class="hint">Nothing in progress. Episodes you start and do not finish show up here.</p>';
|
||||
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||'')+
|
||||
`<div class="txt"><b>${EQ}<span>${esc(entryName(e).text)}</span></b>`+
|
||||
`<small><span class="fd">${esc(feedName(e.feed_id))}</span><span class="left"></span></small></div>`+
|
||||
`<button class="iconbtn" data-a="play"></button>`+
|
||||
`<button class="iconbtn" data-a="remove" title="Remove from Currently Listening" aria-label="Remove from Currently Listening">${ICON.close}</button>`+
|
||||
`<div class="rail"><i></i></div>`;
|
||||
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||'')+
|
||||
`<div class="txt"><b>${EQ}<span>${esc(entryName(e).text)}</span></b>`+
|
||||
`<small><span class="fd">${esc(feedName(e.feed_id))}</span><span class="left"></span></small></div>`+
|
||||
`<button class="iconbtn" data-a="play"></button>`+
|
||||
`<button class="iconbtn" data-a="remove" title="${removeLabel}" aria-label="${removeLabel}">${ICON.close}</button>`+
|
||||
`<div class="rail"><i></i></div>`;
|
||||
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.
|
||||
|
||||
@@ -138,3 +138,4 @@ function offerReload(){
|
||||
}
|
||||
connect();
|
||||
loadFeeds().then(preloadLists).catch(()=>{});
|
||||
loadUpNext();
|
||||
|
||||
@@ -34,6 +34,8 @@ const VIEWS: Record<string,{title: string, icon: string, url?: string, blurb?: s
|
||||
':directory':{title:'Directory',icon:ICON.directory,url:'/api/directory'},
|
||||
':listening':{title:'Currently Listening',icon:ICON.audio,url:'/api/entries?filter=in_progress&limit=50',
|
||||
blurb:'Episodes you started and have not finished, across every feed you subscribe to. Pick one up where you left off.'},
|
||||
':upnext':{title:'Up Next',icon:ICON.queue,url:'/api/queue',
|
||||
blurb:'Episodes lined up to play, in order. Each one plays when the one before it ends.'},
|
||||
':all':{title:'All Subscriptions',icon:ICON.all},
|
||||
};
|
||||
/// Whether a feed's items are in All Subscriptions, or in Signals: not when it, or the OPML or
|
||||
@@ -116,7 +118,8 @@ function renderFeeds(){
|
||||
el.className='place'+(S.feed===id?' sel':'');
|
||||
el.tabIndex=0; el.dataset.id=id;
|
||||
el.innerHTML=`<span class="ico">${v.icon}</span><b>${v.title}</b>`+(id===':all'
|
||||
?`<span class="badge${unreadAll?'':' zero'}" title="${unreadAll} unread">${unreadAll>999?'999+':unreadAll}</span>`:'');
|
||||
?`<span class="badge${unreadAll?'':' zero'}" title="${unreadAll} unread">${unreadAll>999?'999+':unreadAll}</span>`
|
||||
:id===':upnext'&&upNext.length?`<span class="badge" title="${plural(upNext.length,'episode')}">${upNext.length}</span>`:'');
|
||||
asLink(el,S.feed===id);
|
||||
el.onclick=()=>{ selectFeed(id); nav(false); };
|
||||
el.onpointerenter=el.ontouchstart=()=>prefetch(id);
|
||||
|
||||
@@ -207,6 +207,7 @@ function epEl(e: Entry){
|
||||
<span class="size">${enc?mb(enc.length):''}</span>
|
||||
<span class="date">${dateOf(e.published)}</span>
|
||||
<div class="rowacts">
|
||||
${enc&&playsKind(enc)?queueButton(e):''}
|
||||
${playable?`<button class="iconbtn" data-a="play" title="Play" aria-label="Play">${ICON.play}</button>`:
|
||||
(enc&&!has?`<button class="iconbtn" data-a="get" title="Download this ${
|
||||
enc.state==='skipped'?kindOf(enc):'file'}">${ICON.download}</button>`:'')}
|
||||
@@ -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}</button>
|
||||
<button class="btn ico" data-a="flag" title="${e.flagged?'Pinned: never deleted. Unpin':'Pin, so it is never deleted'}"
|
||||
aria-label="${e.flagged?'Unpin':'Pin'}" aria-pressed="${!!e.flagged}">${e.flagged?ICON.pinOn:ICON.pin}</button>
|
||||
${e.enclosures.some(playsKind)?queueButton(e,'btn ico'):''}
|
||||
${webUrl(e.link)?`<a class="btn ico" href="${esc(webUrl(e.link))}" target="_blank" rel="noopener noreferrer"
|
||||
title="Open the original" aria-label="Open the original">${ICON.open}</a>
|
||||
<button class="btn ico" data-a="share" title="Share" aria-label="Share">${ICON.share}</button>`:''}</span>`;
|
||||
@@ -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(); }
|
||||
|
||||
@@ -115,6 +115,14 @@ function wireDeviceSettings(){
|
||||
$<HTMLButtonElement>('#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; }
|
||||
|
||||
@@ -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: Record<string,()=>void>={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();$<HTMLButtonElement>('#pplay').innerHTML=ICON.play});
|
||||
audio.addEventListener('ended',()=>{savePos();markPlayed();$<HTMLButtonElement>('#pplay').innerHTML=ICON.play;playNext()});
|
||||
// body.playing is what sets the EQ bars moving.
|
||||
audio.addEventListener('play',()=>{ $<HTMLButtonElement>('#pplay').innerHTML=ICON.pause; document.body.classList.add('playing'); });
|
||||
audio.addEventListener('pause',()=>{ $<HTMLButtonElement>('#pplay').innerHTML=ICON.play; document.body.classList.remove('playing'); });
|
||||
@@ -175,6 +177,7 @@ audio.addEventListener('error',()=>{ if(audio.error) report('player_error',{msg:
|
||||
$<HTMLButtonElement>('#pplay').onclick=()=>{haptic('tap');audio.paused?audio.play():audio.pause()};
|
||||
$<HTMLButtonElement>('#pback').onclick=()=>audio.currentTime-=15;
|
||||
$<HTMLButtonElement>('#pfwd').onclick=()=>audio.currentTime+=30;
|
||||
$<HTMLButtonElement>('#pnext').onclick=()=>{ if(!playNext()) toast('Nothing in Up Next is ready to play.'); };
|
||||
$<HTMLInputElement>('#seek').oninput=(e: Event)=>{const d=audio.duration;if(d)audio.currentTime=d*Number((e.target as HTMLInputElement).value)/1000};
|
||||
$<HTMLSelectElement>('#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<string,string>={a:':all',d:':directory',l:':listening'};
|
||||
const GO: Record<string,string>={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: Record<string,()=>void>={
|
||||
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:()=>$<HTMLButtonElement>('#pnext').click(),
|
||||
// The toolbar's own buttons, so a key does exactly what the click does, and nothing while
|
||||
// they are disabled.
|
||||
o:()=>$<HTMLButtonElement>('#tbPlay').click(), m:()=>$<HTMLButtonElement>('#tbRead').click(), s:()=>$<HTMLButtonElement>('#tbFlag').click(),
|
||||
o:()=>$<HTMLButtonElement>('#tbPlay').click(),
|
||||
q:()=>{ const e=cur(); if(e) epAction('queue',e,null); }, Q:()=>{ const e=cur(); if(e) epAction('playnext',e,null); },
|
||||
m:()=>$<HTMLButtonElement>('#tbRead').click(), s:()=>$<HTMLButtonElement>('#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'],
|
||||
];
|
||||
|
||||
121
web/src/upnext.ts
Normal file
121
web/src/upnext.ts
Normal file
@@ -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 $$<HTMLButtonElement>('[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')=>`<button class="${cls}" data-a="queue" data-key="${esc(entryKey(e))}" aria-pressed="${queued(e)}"
|
||||
title="${queued(e)?'Remove from Up Next':'Add to Up Next'}" aria-label="${queued(e)?'Remove from Up Next':'Add to Up Next'}">${queued(e)?ICON.queued:ICON.queue}</button>`;
|
||||
|
||||
/// What plays after this one ends, or the next button is pressed.
|
||||
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);
|
||||
$<HTMLButtonElement>('#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?'':'<p class="hint">Nothing lined up. Add an episode with its Up Next button, and it plays when the one before it ends.</p>';
|
||||
for(const e of upNext){
|
||||
const el=listenRow(e,'Remove from Up Next',()=>saveUpNext(upNext.filter(x=>entryKey(x)!==entryKey(e))));
|
||||
el.insertAdjacentHTML('afterbegin',`<button class="iconbtn grip" title="Drag to move, or use the arrow keys" aria-label="Move ${esc(entryName(e).text)}">${ICON.grip}</button>`);
|
||||
box.appendChild(el);
|
||||
}
|
||||
for(const g of $$<HTMLButtonElement>('.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<HTMLElement>('.childrow')!;
|
||||
const save=()=>{
|
||||
const list=$$<HTMLElement & {entry?: Entry}>('.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=$$<HTMLElement>('.childrow',box).find(r=>r!==row&&m.clientY<r.getBoundingClientRect().bottom);
|
||||
if(over&&m.clientY>over.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(); };
|
||||
};
|
||||
}
|
||||
@@ -90,6 +90,12 @@ const ICON: Record<string,string>={
|
||||
left:fa('0 0 512 512','<path fill="currentColor" d="M9.4 233.4c-12.5 12.5-12.5 32.8 0 45.3l160 160c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L109.3 288 480 288c17.7 0 32-14.3 32-32s-14.3-32-32-32l-370.7 0 105.4-105.4c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0l-160 160z"/>'), // 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','<path fill="currentColor" d="M64 48l384 0c26.5 0 48 21.5 48 48l0 256c0 26.5-21.5 48-48 48l-56 0 0-56 48 0 0-240-368 0 0 240 48 0 0 56-56 0c-26.5 0-48-21.5-48-48L16 96c0-26.5 21.5-48 48-48zM256 288l144 176-288 0z"/>'),
|
||||
// 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','<path fill="currentColor" d="M32 96a32 32 0 0 1 32-32h384a32 32 0 0 1 0 64H64a32 32 0 0 1-32-32zm0 160a32 32 0 0 1 32-32h384a32 32 0 0 1 0 64H64a32 32 0 0 1-32-32zm32 128h160a32 32 0 0 1 0 64H64a32 32 0 0 1 0-64zm320-64a32 32 0 0 1 32 32v48h48a32 32 0 0 1 0 64h-48v48a32 32 0 0 1-64 0v-48h-48a32 32 0 0 1 0-64h48v-48a32 32 0 0 1 32-32z"/>'),
|
||||
queued:fa('0 0 512 512','<path fill="currentColor" d="M32 96a32 32 0 0 1 32-32h384a32 32 0 0 1 0 64H64a32 32 0 0 1-32-32zm0 160a32 32 0 0 1 32-32h384a32 32 0 0 1 0 64H64a32 32 0 0 1-32-32zm32 128h160a32 32 0 0 1 0 64H64a32 32 0 0 1 0-64z"/><path fill="none" stroke="currentColor" stroke-width="60" stroke-linecap="round" stroke-linejoin="round" d="M300 404l54 54 116-116"/>'),
|
||||
next:fa('0 0 320 512','<path fill="currentColor" d="M52.5 440.6c-9.5 7.9-22.8 9.7-34.1 4.4S0 428.4 0 416V96c0-12.4 7.2-23.7 18.4-29s24.5-3.6 34.1 4.4l192 160L256 241V96c0-17.7 14.3-32 32-32s32 14.3 32 32v320c0 17.7-14.3 32-32 32s-32-14.3-32-32V271l-11.5 9.6-192 160z"/>'),
|
||||
grip:fa('0 0 320 512','<path fill="currentColor" d="M40 352a40 40 0 1 1 0 80 40 40 0 1 1 0-80zm240 0a40 40 0 1 1 0 80 40 40 0 1 1 0-80zM40 216a40 40 0 1 1 0 80 40 40 0 1 1 0-80zm240 0a40 40 0 1 1 0 80 40 40 0 1 1 0-80zM40 80a40 40 0 1 1 0 80 40 40 0 1 1 0-80zm240 0a40 40 0 1 1 0 80 40 40 0 1 1 0-80z"/>'),
|
||||
subbed:fa('0 0 512 512','<path fill="currentColor" d="M256 512a256 256 0 1 1 0-512 256 256 0 1 1 0 512zM374 145.7c-10.7-7.8-25.7-5.4-33.5 5.3L221.1 315.2 169 263.1c-9.4-9.4-24.6-9.4-33.9 0s-9.4 24.6 0 33.9l72 72c5 5 11.8 7.5 18.8 7s13.4-4.1 17.5-9.8L379.3 179.2c7.8-10.7 5.4-25.7-5.3-33.5z"/>'), // solid/circle-check
|
||||
};
|
||||
// What is playing, as the icon's EQ bars; the stylesheet moves them.
|
||||
|
||||
Reference in New Issue
Block a user