From 882cd5f03ce71e21554af94918db4bd499ecaae1 Mon Sep 17 00:00:00 2001 From: rays Date: Sun, 22 Nov 2026 12:02:22 -0500 Subject: [PATCH] Now Playing lists an episode's chapters, and a tap plays from there (#477) Where they come from, in order: the chapters file an item names (, the Podcasting 2.0 namespace's JSON), stored on the item as entries.chapters and read when someone opens Now Playing; else the downloaded file's own chapters (ID3 CHAP frames, MP4 chapters), which ffprobe reads as it does for DeadAir. A chapter with toc false is only there to change the artwork and is left out. GET /api/enclosures/{id}/chapters answers for a file, since a file is what plays. With ?deadair=true the starts are moved into DeadAir's shortened clock with to_copy, as positions are, or a chapter would start late by every silence cut before it. A chapters file that cannot be read is an empty list: the player plays on without them, and the step's span says why. Items already stored get their chapters address when a scan next finds them told differently; feeds that answer 304 add it with their next items. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RqkrVBuJRne2JAhFpaDV2U --- crates/feed/src/parse.rs | 26 +++++++++ crates/ipx/CHANGELOG.md | 1 + crates/ipx/src/chapters.rs | 112 ++++++++++++++++++++++++++++++++++++ crates/ipx/src/db.rs | 37 ++++++++++-- crates/ipx/src/deadair.rs | 2 +- crates/ipx/src/entity.rs | 3 + crates/ipx/src/lib.rs | 1 + crates/ipx/src/web.rs | 49 ++++++++++++++++ crates/wire/proto/ipx.proto | 11 ++++ tests/ui/app.spec.ts | 7 +++ tests/ui/fixtures/serve.ts | 4 ++ tests/ui/fixtures/show.xml | 3 +- web/CHANGELOG.md | 1 + web/app.css | 6 ++ web/src/nowplaying.ts | 47 +++++++++++++++ web/src/types.ts | 7 +++ 16 files changed, 310 insertions(+), 7 deletions(-) create mode 100644 crates/ipx/src/chapters.rs diff --git a/crates/feed/src/parse.rs b/crates/feed/src/parse.rs index c392e2f..5a35235 100644 --- a/crates/feed/src/parse.rs +++ b/crates/feed/src/parse.rs @@ -46,6 +46,9 @@ pub struct Entry { pub duration: Option, pub episode: Option, pub season: Option, + /// Where its chapters are, ``: a JSON file of the Podcasting 2.0 + /// namespace's, read when someone plays it (#477). + pub chapters: Option, pub enclosures: Vec, } @@ -283,6 +286,7 @@ pub(crate) fn from_rss(ch: rss::Channel, bytes: &[u8]) -> ParsedFeed { duration: it.and_then(|i| i.duration()).and_then(parse_duration), episode: it.and_then(|i| i.episode()).and_then(|e| e.trim().parse().ok()), season: it.and_then(|i| i.season()).and_then(|e| e.trim().parse().ok()), + chapters: podcast_chapters(item), enclosures, }) }) @@ -348,6 +352,7 @@ pub(crate) fn from_atom(feed: atom_syndication::Feed) -> ParsedFeed { duration: None, episode: None, season: None, + chapters: None, enclosures, }) }) @@ -460,6 +465,12 @@ pub(crate) fn notes(content: Option<&str>, description: Option<&str>, markdown: /// /// shortcut: found by the `source` prefix the namespace's own docs and feeds use; a feed binding /// it to another prefix is not read, until one turns up. +/// ``, by the prefix feeds give it. +fn podcast_chapters(item: &rss::Item) -> Option { + let url = item.extensions().get("podcast")?.get("chapters")?.first()?.attrs().get("url")?.trim(); + (url.starts_with("http://") || url.starts_with("https://")).then(|| url.to_owned()) +} + pub(crate) fn source_markdown(item: &rss::Item) -> Option<&str> { item.extensions().get("source")?.get("markdown")?.first()?.value() } @@ -899,6 +910,21 @@ Some **bold** and [a link](https://x.example/). assert_eq!((p1.season, p1.episode), (Some(8), Some(1))); } + #[test] + fn an_items_chapters_are_where_podcast_chapters_says() { + let xml = br#" + + Showhttps://xd + Aa + + Bb + Cc + "#; + let feed = parse(xml).unwrap(); + let got: Vec<_> = feed.entries.iter().map(|e| e.chapters.as_deref()).collect(); + assert_eq!(got, [Some("https://x/a.json"), None, None], "only a web address, trimmed"); + } + #[test] fn an_item_may_carry_several_enclosures() { // The rss crate keeps only one per item -- the last -- so these come from the XML. diff --git a/crates/ipx/CHANGELOG.md b/crates/ipx/CHANGELOG.md index 1aada34..73937cc 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 +- An episode's chapters, from the chapters file its feed names (``) or else from the downloaded file itself, at `GET /api/enclosures/{id}/chapters`, in the clock of DeadAir's shortened copy when that is what plays (#477). - `GET /api/feeds/{id}/seasons` gives a podcast's seasons with how many episodes and unread each has, and a podcast's episodes can be asked for one season at a time, or for those naming none (`season=none`), and in its own order (`sort=episode`), season by season and episode by episode. `download-latest` takes a `season` to download all of it, first episode first (#482). - Smart playlists: `GET` and `POST /api/playlists`, `PATCH` and `DELETE /api/playlists/{id}`, and `GET /api/playlists/{id}/entries`, the episodes of the podcasts chosen in the playlist's order, those set to play first ahead of the rest (#476). - A feed in `/api/feeds` says whether it has audio or video (`podcast`), for the page's Podcasts shelf (#474). diff --git a/crates/ipx/src/chapters.rs b/crates/ipx/src/chapters.rs new file mode 100644 index 0000000..32d22f9 --- /dev/null +++ b/crates/ipx/src/chapters.rs @@ -0,0 +1,112 @@ +//! An episode's chapters (#477): from the JSON file its item names (``, the +//! Podcasting 2.0 namespace's), or else from the file itself once downloaded (ID3 `CHAP` frames, +//! MP4 chapters), which ffprobe reads as it does for DeadAir. + +use anyhow::{Context, Result}; +use serde::Serialize; +use std::path::Path; + +#[derive(Debug, PartialEq, Serialize)] +pub struct Chapter { + /// Seconds from the start of the original. + pub start: f64, + pub title: String, +} + +/// More than any list of chapters needs: a chapters file is a few KB. +const MAX: usize = 1 << 20; + +/// The namespace's chapters file: `{"chapters": [{"startTime": 0, "title": "..", "toc": false}]}`. +/// One with `toc` false is there to change the artwork, not to be listed. +pub fn from_json(body: &[u8]) -> Result> { + let v: serde_json::Value = serde_json::from_slice(body).context("reading the chapters file")?; + let list = v["chapters"].as_array().context("no chapters in the chapters file")?; + Ok(sorted( + list.iter() + .filter(|c| c["toc"] != false) + .filter_map(|c| Some(Chapter { start: c["startTime"].as_f64()?, title: text(&c["title"]) })) + .collect(), + )) +} + +/// ffprobe's `-show_chapters -of json`: `{"chapters": [{"start_time": "0.000000", "tags": {"title": ".."}}]}`. +pub fn from_ffprobe(out: &str) -> Result> { + let v: serde_json::Value = serde_json::from_str(out).context("reading ffprobe")?; + Ok(sorted( + v["chapters"] + .as_array() + .into_iter() + .flatten() + .filter_map(|c| { + Some(Chapter { start: c["start_time"].as_str()?.parse().ok()?, title: text(&c["tags"]["title"]) }) + }) + .collect(), + )) +} + +fn text(v: &serde_json::Value) -> String { + v.as_str().unwrap_or("").trim().to_owned() +} + +/// In order, and none before the start: the namespace does not promise either. +fn sorted(mut list: Vec) -> Vec { + list.retain(|c| c.start.is_finite() && c.start >= 0.0); + list.sort_by(|a, b| a.start.total_cmp(&b.start)); + list +} + +// ponytail: fetched each time someone opens Now Playing on an episode, which the page then keeps; +// keep them in the database if a chapters host turns out slow or many people play one episode. +pub async fn fetch(client: &reqwest::Client, url: &str) -> Result> { + let mut r = client.get(url).timeout(crate::feed::FEED_TIMEOUT).send().await?.error_for_status()?; + anyhow::ensure!(r.content_length().is_none_or(|n| n <= MAX as u64), "larger than {MAX} bytes"); + let mut body = Vec::new(); + while let Some(c) = r.chunk().await? { + body.extend_from_slice(&c); + anyhow::ensure!(body.len() <= MAX, "larger than {MAX} bytes"); + } + from_json(&body) +} + +pub async fn in_file(path: &Path) -> Result> { + let path = path.display().to_string(); + from_ffprobe(&crate::deadair::run_out("ffprobe", &["-v", "error", "-show_chapters", "-of", "json", &path]).await?) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_namespaces_file_is_read_in_order_without_its_artwork_only_chapters() { + let body = br#"{"version":"1.2.0","chapters":[ + {"startTime":95.5,"title":" Second "}, + {"startTime":0,"title":"Intro"}, + {"startTime":40,"img":"https://x/a.jpg","toc":false}, + {"title":"no start"}, + {"startTime":200}]}"#; + let got = from_json(body).unwrap(); + assert_eq!( + got, + [ + Chapter { start: 0.0, title: "Intro".into() }, + Chapter { start: 95.5, title: "Second".into() }, + Chapter { start: 200.0, title: "".into() }, + ] + ); + assert!(from_json(b"").is_err(), "a web page is not a chapters file"); + } + + #[test] + fn ffprobes_chapters_are_read_and_a_file_with_none_has_none() { + let out = r#"{"chapters":[ + {"id":1,"start_time":"61.250000","end_time":"120.000000","tags":{"title":"Two"}}, + {"id":0,"start_time":"0.000000","end_time":"61.250000","tags":{"title":"One"}}]}"#; + assert_eq!( + from_ffprobe(out).unwrap(), + [Chapter { start: 0.0, title: "One".into() }, Chapter { start: 61.25, title: "Two".into() }] + ); + assert_eq!(from_ffprobe(r#"{"chapters":[]}"#).unwrap(), []); + assert_eq!(from_ffprobe("{}").unwrap(), []); + } +} diff --git a/crates/ipx/src/db.rs b/crates/ipx/src/db.rs index 4758a9c..307d18c 100644 --- a/crates/ipx/src/db.rs +++ b/crates/ipx/src/db.rs @@ -121,6 +121,12 @@ async fn create_missing(orm: &DatabaseConnection) -> Result<()> { .await .context("adding entries.markdown")?; } + if orm.execute_unprepared("SELECT chapters FROM entries LIMIT 0").await.is_err() { + // Stored items get theirs as a scan finds them told differently, by this alone (#477). + orm.execute_unprepared("ALTER TABLE entries ADD COLUMN chapters TEXT") + .await + .context("adding entries.chapters")?; + } if orm.execute_unprepared("SELECT body_hash FROM feeds LIMIT 0").await.is_err() { for sql in ["ALTER TABLE feeds ADD COLUMN body_hash TEXT", "ALTER TABLE feeds ADD COLUMN same_since BIGINT"] { orm.execute_unprepared(sql).await.with_context(|| sql.to_owned())?; @@ -831,8 +837,8 @@ impl Db { .exec( "INSERT INTO entries (feed_id, guid, title, link, published, description, first_seen, - image, duration, episode, season, markdown, search_text) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) + image, duration, episode, season, markdown, search_text, chapters) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14) ON CONFLICT DO NOTHING", vec![ feed_id.into(), @@ -848,6 +854,7 @@ impl Db { e.season.into(), e.markdown.clone().into(), crate::search::search_text(e.title.as_deref(), e.description.as_deref()).into(), + e.chapters.clone().into(), ], ) .await?; @@ -861,6 +868,7 @@ impl Db { episode = coalesce($7, episode), season = coalesce($8, season), markdown = coalesce($9, markdown), + chapters = coalesce($10, chapters), -- Made again, by search.rs, when what it is made of has changed; the values -- here are the row's as it was. search_text = CASE WHEN title IS NOT DISTINCT FROM coalesce($3, title) @@ -877,6 +885,7 @@ impl Db { e.episode.into(), e.season.into(), e.markdown.clone().into(), + e.chapters.clone().into(), ], ) .await?; @@ -2704,6 +2713,14 @@ impl Db { .collect() } + /// Where an item's chapters are, when its feed says (#477). + pub async fn chapters_url(&self, feed_id: &str, guid: &str) -> Result> { + Ok(entries::Entity::find_by_id((feed_id.to_owned(), guid.to_owned())) + .one(&self.orm) + .await? + .and_then(|e| e.chapters)) + } + pub async fn enclosure(&self, id: i64) -> Result> { Ok(enclosures::Entity::find_by_id(id).one(&self.orm).await?.map(EncRow::from)) } @@ -2944,12 +2961,20 @@ impl Db { let feed = a.p(feed_id); let guids: Vec = entries.iter().map(|e| a.p(e.guid.clone())).collect(); let sql = format!( - "SELECT guid, title, description, image, duration, episode, season, markdown FROM entries + "SELECT guid, title, description, image, duration, episode, season, markdown, chapters FROM entries WHERE feed_id = {feed} AND guid IN ({})", guids.join(", ") ); - type Stored = - (Option, Option, Option, Option, Option, Option, Option); + type Stored = ( + Option, + Option, + Option, + Option, + Option, + Option, + Option, + Option, + ); let mut stored = std::collections::HashMap::::new(); for r in self.rows(&sql, a.0).await? { stored.insert( @@ -2962,6 +2987,7 @@ impl Db { r.try_get("", "episode")?, r.try_get("", "season")?, r.try_get("", "markdown")?, + r.try_get("", "chapters")?, ), ); } @@ -2979,6 +3005,7 @@ impl Db { || differs(&e.episode, &s.4) || differs(&e.season, &s.5) || differs(&e.markdown, &s.6) + || differs(&e.chapters, &s.7) }) }) .map(|e| e.guid.clone()) diff --git a/crates/ipx/src/deadair.rs b/crates/ipx/src/deadair.rs index 96ab418..399f136 100644 --- a/crates/ipx/src/deadair.rs +++ b/crates/ipx/src/deadair.rs @@ -590,7 +590,7 @@ async fn ffmpeg(args: &[&str]) -> Result { Ok(log) } -async fn run_out(prog: &str, args: &[&str]) -> Result { +pub(crate) async fn run_out(prog: &str, args: &[&str]) -> Result { let out = command(prog).args(args).output().await.with_context(|| format!("running {prog}"))?; if !out.status.success() { bail!("{prog} failed: {}", String::from_utf8_lossy(&out.stderr).trim()); diff --git a/crates/ipx/src/entity.rs b/crates/ipx/src/entity.rs index 7d018a8..c550111 100644 --- a/crates/ipx/src/entity.rs +++ b/crates/ipx/src/entity.rs @@ -86,6 +86,9 @@ pub mod entries { pub duration: Option, pub episode: Option, pub season: Option, + /// Where its chapters are, from `` (#477). + #[sea_orm(column_type = "Text", nullable)] + pub chapters: Option, /// The title and the text without markup, lowercased and cut short, which search reads /// (#459); none until search.rs makes it. #[sea_orm(column_type = "Text", nullable)] diff --git a/crates/ipx/src/lib.rs b/crates/ipx/src/lib.rs index 7708691..4ec3867 100644 --- a/crates/ipx/src/lib.rs +++ b/crates/ipx/src/lib.rs @@ -7,6 +7,7 @@ mod access; mod art; mod auth; mod catalogue; +mod chapters; mod cli; mod config; mod ctx; diff --git a/crates/ipx/src/web.rs b/crates/ipx/src/web.rs index 4e98821..19a8de9 100644 --- a/crates/ipx/src/web.rs +++ b/crates/ipx/src/web.rs @@ -77,6 +77,7 @@ const WIRE: ipx_wire::Routes = &[ ("POST", "/api/entries/{feed_id}/{guid}/flags", "ipx.Flags", "ipx.FeedRow"), ("POST", "/api/entries/{feed_id}/{guid}/position", "ipx.Position", ""), ("POST", "/api/entries/{feed_id}/{guid}/share", "ipx.ShareBody", "ipx.ShareLink"), + ("GET", "/api/enclosures/{id}/chapters", "", "ipx.Chapters"), ("POST", "/api/feeds/{id}/read-all", "", "ipx.Marked"), ("POST", "/api/read-all", "", "ipx.Marked"), ("POST", "/api/feeds/{id}/download-latest", "ipx.HowMany", "ipx.Queued"), @@ -128,6 +129,7 @@ pub fn router(state: WebState) -> Router { .route("/api/feeds/{id}/download-latest", post(download_latest)) .route("/api/enclosures/{id}/download", post(download_now)) .route("/api/enclosures/{id}", delete(delete_file)) + .route("/api/enclosures/{id}/chapters", get(chapters)) .route("/api/fetch", post(fetch_now)) .route("/api/opml", get(export_opml).post(import_opml)) .route("/api/settings", get(get_settings).patch(patch_settings)) @@ -2724,6 +2726,53 @@ struct Force { force: bool, } +#[derive(Deserialize)] +struct ChaptersAsked { + /// Played from DeadAir's shortened copy, whose clock the starts are then given in. + #[serde(default)] + deadair: bool, +} + +/// A file's chapters, for Now Playing (#477): from the file its item names, else from the file +/// itself once downloaded. None is an empty list, as is one that could not be read: the player +/// plays on without them, and the trace has why. +async fn chapters( + State(state): State, + Path(id): Path, + user: crate::db::User, + Query(q): Query, +) -> Result>, ApiError> { + let enc = state.ctx.db.enclosure(id).await?.ok_or_else(|| ApiError::not_found(format!("no file {id}")))?; + subscribed(&state, &user, &enc.feed_id).await?; + let mut list = Vec::new(); + if let Some(url) = state.ctx.db.chapters_url(&enc.feed_id, &enc.guid).await? { + match crate::chapters::fetch(&state.ctx.client, &url).instrument(db::step("chapters_fetch")).await { + Ok(l) => list = l, + Err(e) => { + tracing::debug!(url = %crate::feed::redact(&url), error = %format!("{e:#}"), "could not read the chapters") + } + } + } + if list.is_empty() + && let Some(path) = &enc.path + { + let file = crate::download::playable(std::path::Path::new(path)); + match crate::chapters::in_file(&file).instrument(db::step("chapters_file")).await { + Ok(l) => list = l, + Err(e) => tracing::debug!(error = %format!("{e:#}"), "could not read the file's chapters"), + } + } + if q.deadair + && !list.is_empty() + && let Some(plan) = crate::deadair::plan_for(&state.ctx, user.id, &enc.feed_id, id).await? + { + for c in &mut list { + c.start = crate::deadair::to_copy(&plan.cuts, (c.start * 1000.0) as i64) as f64 / 1000.0; + } + } + Ok(Json(list)) +} + async fn delete_file( State(state): State, Path(id): Path, diff --git a/crates/wire/proto/ipx.proto b/crates/wire/proto/ipx.proto index 029267d..3d2571e 100644 --- a/crates/wire/proto/ipx.proto +++ b/crates/wire/proto/ipx.proto @@ -289,6 +289,17 @@ message SeasonRows { repeated SeasonRow items = 1; } +// One chapter of a file in GET /api/enclosures/{id}/chapters (#477): its start in seconds, in +// the clock of what plays, and its title, which may be empty. +message Chapter { + double start = 1; + string title = 2; +} + +message Chapters { + repeated Chapter items = 1; +} + // POST /api/playlists, the answer. message PlaylistId { int64 id = 1; diff --git a/tests/ui/app.spec.ts b/tests/ui/app.spec.ts index 249ad1f..378966a 100644 --- a/tests/ui/app.spec.ts +++ b/tests/ui/app.spec.ts @@ -493,6 +493,13 @@ test('Now Playing opens from the player bar with the artwork, show notes and Up await expect(sheet.locator('h2')).toHaveText('Second Episode'); await expect(sheet.locator('.dbody')).toContainText('Notes for the second.'); await expect(sheet.locator('#nowqueue .childrow')).toHaveText([/First Episode/]); + // Its chapters, from the file its item names, in order; a tap plays from there (#477). + const chapters = sheet.locator('.chapters button'); + await expect(chapters).toHaveText([/0:00\s*Opening/, /0:01\s*The middle/]); + await chapters.nth(1).click(); + await expect.poll(() => page.evaluate(() => audio.currentTime)).toBeGreaterThanOrEqual(1.4); + await expect(chapters.nth(1)).toHaveAttribute('aria-current', 'true'); + await expect(chapters.nth(0)).not.toHaveAttribute('aria-current'); await page.keyboard.press('Escape'); await expect(sheet).toBeHidden(); // From the keyboard too, and the podcast's name opens its feed. diff --git a/tests/ui/fixtures/serve.ts b/tests/ui/fixtures/serve.ts index 382ef76..f0fe49d 100644 --- a/tests/ui/fixtures/serve.ts +++ b/tests/ui/fixtures/serve.ts @@ -124,6 +124,10 @@ http.createServer((req, res) => { // Where /flip.xml moves to for good. '/moved.xml': ['application/rss+xml', `Flip Show flip-1Flip one`], + // Second Episode's chapters (#477): one only for its artwork, which is not listed. + '/chapters.json': ['application/json+chapters', JSON.stringify({ version: '1.2.0', chapters: [ + { startTime: 1.5, title: 'The middle' }, { startTime: 0, title: 'Opening' }, { startTime: 1, img: `${at}/art.jpg`, toc: false }, + ] })], '/said.txt': ['text/plain', 'Unable to establish a DB connection'], '/long.txt': ['text/plain', 'This site is down for maintenance and will be back shortly, thank you for your patience while we work'], '/empty.xml': ['application/xml', ''], diff --git a/tests/ui/fixtures/show.xml b/tests/ui/fixtures/show.xml index d918c82..594ab6c 100644 --- a/tests/ui/fixtures/show.xml +++ b/tests/ui/fixtures/show.xml @@ -1,5 +1,5 @@ - + Test Showhttp://127.0.0.1:8792/A fixture feed. @@ -12,5 +12,6 @@ Mon, 08 Sep 2026 10:00:00 +0000 Notes for the second. 900 + \ No newline at end of file diff --git a/web/CHANGELOG.md b/web/CHANGELOG.md index 09c34bd..218ce4b 100644 --- a/web/CHANGELOG.md +++ b/web/CHANGELOG.md @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- Now Playing lists the episode's chapters, when its podcast has them, with the one playing in bold; a tap plays from there (#477). - A podcast told in seasons lists its episodes in its own order, season 1 episode 1 first, until a heading is clicked to sort it otherwise, with each season's start marked. A season picker under its tabs lists one season at a time, or the episodes in none, and a season picked can be downloaded whole (#482). - Smart playlists, in a folder of their own in the feed list: choose the podcasts, which of them play first, unplayed episodes only or all, newest or oldest first, and the playlist keeps itself up to date. Playing from one goes on through it once Up Next is empty (#476). - Now Playing: tap the player bar to see what is playing with its artwork large, its podcast (a tap opens it), its show notes and what follows in Up Next; Esc or the bar closes it (#475). diff --git a/web/app.css b/web/app.css index c07bd95..5bfeac4 100644 --- a/web/app.css +++ b/web/app.css @@ -711,6 +711,12 @@ body.scan-this .fhead [data-a=scan] .i,body.scan-any .fhead [data-a=scanall] .i, .nowmeta small{color:var(--dim);font-size:12.5px;font-variant-numeric:tabular-nums} #nowsheet h3{font-size:14px;font-weight:600;margin:22px 0 10px;color:var(--dim)} #nowqueue{display:flex;flex-direction:column;gap:6px} +/* Chapters (#477): a tap plays from there; the one playing reads bold. */ +.chapters{list-style:none;margin:0;padding:0;display:flex;flex-direction:column} +.chapters button{display:flex;gap:14px;width:100%;padding:8px 6px;border-radius:8px;text-align:left;font-size:14px} +.chapters button:hover{background:var(--raise)} +.chapters .ctime{min-width:4.5em;color:var(--dim);font-variant-numeric:tabular-nums} +.chapters button[aria-current]{font-weight:600} #pnow{cursor:pointer;border-radius:8px} @media (max-width:820px){ .nowhead{grid-template-columns:1fr;justify-items:center;text-align:center;gap:18px} diff --git a/web/src/nowplaying.ts b/web/src/nowplaying.ts index 3a45276..7ed5252 100644 --- a/web/src/nowplaying.ts +++ b/web/src/nowplaying.ts @@ -34,6 +34,7 @@ function drawNow(){ ${[dateOf(e.published),e.duration?clock(e.duration):''].filter(Boolean).join(', ')} +
${upNext.length?`

Up Next

`:''}

Show notes

${textOf(e)}
`; @@ -41,6 +42,52 @@ function drawNow(){ $('.nowshow',nowSheet).onclick=()=>{ closeNow(); selectFeed(e.feed_id); }; const q=$('#nowqueue'); for(const x of upNext) q?.appendChild(listenRow(x,'Remove from Up Next',()=>saveUpNext(upNext.filter(y=>entryKey(y)!==entryKey(x))))); + drawChapters(); } + +/// Chapters of what plays (#477), asked for once a file and clock: DeadAir's copy has its own +/// times. A failure is forgotten, so the next opening asks again. +const chapterLists=new Map>(); +let nowChapters: Chapter[]=[]; +function chaptersOf(enc: number, deadair: boolean): Promise { + const k=`${enc}${deadair?'d':''}`; + let got=chapterLists.get(k); + if(!got){ + got=api(`/api/enclosures/${enc}/chapters${deadair?'?deadair=true':''}`).catch(()=>{ chapterLists.delete(k); return []; }); + chapterLists.set(k,got); + } + return got; +} +function drawChapters(){ + const enc=player.enc; + nowChapters=[]; + if(enc==null) return; + chaptersOf(enc,!!player.src?.includes('/deadair')).then(cs=>{ + const box=$('#nowchaps'); + if(!box||!nowOpen()||player.enc!==enc||!cs.length) return; + nowChapters=cs; + box.innerHTML=`

Chapters

    ${cs.map((c,i)=> + `
  1. `).join('')}
`; + for(const b of $$('button',box)) b.onclick=()=>{ + audio.currentTime=cs[Number(b.dataset.i)]!.start; + // Marked now: a player still loading says nothing until it plays. + markChapter(); + if(audio.paused) audio.play(); + }; + markChapter(); + }); +} +/// The chapter playing now, marked as the one current. +function markChapter(){ + if(!nowChapters.length||!nowOpen()) return; + // A seek to a chapter's start can land a frame before it. + const t=audio.currentTime+.25; + let at=-1; + nowChapters.forEach((c,i)=>{ if(c.start<=t) at=i; }); + $$('#nowchaps button').forEach((b,i)=>{ + if(i===at) b.setAttribute('aria-current','true'); else b.removeAttribute('aria-current'); + }); +} +audio.addEventListener('timeupdate',markChapter); $('#pnow').onclick=()=>nowOpen()?closeNow():openNow(); $('#pnow').onkeydown=(ev: KeyboardEvent)=>{ if(ev.key==='Enter'||ev.key===' '){ ev.preventDefault(); $('#pnow').click(); } }; diff --git a/web/src/types.ts b/web/src/types.ts index f7c95e0..a8d35c0 100644 --- a/web/src/types.ts +++ b/web/src/types.ts @@ -151,6 +151,13 @@ interface State { sort: {col: string, dir: 'asc' | 'desc'}; } +/// One chapter of a file, `/api/enclosures/{id}/chapters` (chapters.rs Chapter, #477): its start +/// in seconds, in the clock of what plays. +interface Chapter { + start: number; + title: string; +} + /// One season of a podcast, `/api/feeds/{id}/seasons` (db.rs SeasonCount, #482). No season is /// the episodes that name none. interface SeasonCount {