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
(<podcast:chapters url>, 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVBuJRne2JAhFpaDV2U
This commit is contained in:
2026-11-22 12:02:22 -05:00
parent f633f3d692
commit 882cd5f03c
16 changed files with 310 additions and 7 deletions

View File

@@ -46,6 +46,9 @@ pub struct Entry {
pub duration: Option<i64>,
pub episode: Option<i64>,
pub season: Option<i64>,
/// Where its chapters are, `<podcast:chapters url>`: a JSON file of the Podcasting 2.0
/// namespace's, read when someone plays it (#477).
pub chapters: Option<String>,
pub enclosures: Vec<Enclosure>,
}
@@ -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.
/// `<podcast:chapters url="..." type="application/json+chapters">`, by the prefix feeds give it.
fn podcast_chapters(item: &rss::Item) -> Option<String> {
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/).</description></item>
assert_eq!((p1.season, p1.episode), (Some(8), Some(1)));
}
#[test]
fn an_items_chapters_are_where_podcast_chapters_says() {
let xml = br#"<?xml version="1.0"?>
<rss version="2.0" xmlns:podcast="https://podcastindex.org/namespace/1.0">
<channel><title>Show</title><link>https://x</link><description>d</description>
<item><title>A</title><guid>a</guid>
<podcast:chapters url=" https://x/a.json " type="application/json+chapters"/></item>
<item><title>B</title><guid>b</guid><podcast:chapters url="file:///etc/passwd"/></item>
<item><title>C</title><guid>c</guid></item>
</channel></rss>"#;
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.

View File

@@ -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 (`<podcast:chapters>`) 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).

112
crates/ipx/src/chapters.rs Normal file
View File

@@ -0,0 +1,112 @@
//! An episode's chapters (#477): from the JSON file its item names (`<podcast:chapters>`, 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<Vec<Chapter>> {
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<Vec<Chapter>> {
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<Chapter>) -> Vec<Chapter> {
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<Vec<Chapter>> {
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<Vec<Chapter>> {
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"<html>").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(), []);
}
}

View File

@@ -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<Option<String>> {
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<Option<EncRow>> {
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<String> = 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<String>, Option<String>, Option<String>, Option<i64>, Option<i64>, Option<i64>, Option<String>);
type Stored = (
Option<String>,
Option<String>,
Option<String>,
Option<i64>,
Option<i64>,
Option<i64>,
Option<String>,
Option<String>,
);
let mut stored = std::collections::HashMap::<String, Stored>::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())

View File

@@ -590,7 +590,7 @@ async fn ffmpeg(args: &[&str]) -> Result<String> {
Ok(log)
}
async fn run_out(prog: &str, args: &[&str]) -> Result<String> {
pub(crate) async fn run_out(prog: &str, args: &[&str]) -> Result<String> {
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());

View File

@@ -86,6 +86,9 @@ pub mod entries {
pub duration: Option<i64>,
pub episode: Option<i64>,
pub season: Option<i64>,
/// Where its chapters are, from `<podcast:chapters>` (#477).
#[sea_orm(column_type = "Text", nullable)]
pub chapters: Option<String>,
/// 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)]

View File

@@ -7,6 +7,7 @@ mod access;
mod art;
mod auth;
mod catalogue;
mod chapters;
mod cli;
mod config;
mod ctx;

View File

@@ -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<WebState>,
Path(id): Path<i64>,
user: crate::db::User,
Query(q): Query<ChaptersAsked>,
) -> Result<Json<Vec<crate::chapters::Chapter>>, 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<WebState>,
Path(id): Path<i64>,

View File

@@ -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;

View File

@@ -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.

View File

@@ -124,6 +124,10 @@ http.createServer((req, res) => {
// Where /flip.xml moves to for good.
'/moved.xml': ['application/rss+xml', `<?xml version="1.0"?><rss version="2.0"><channel><title>Flip Show</title>
<item><guid>flip-1</guid><title>Flip one</title></item></channel></rss>`],
// 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', ''],

View File

@@ -1,5 +1,5 @@
<?xml version="1.0"?>
<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd">
<rss version="2.0" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:podcast="https://podcastindex.org/namespace/1.0">
<channel><title>Test Show</title><link>http://127.0.0.1:8792/</link><description>A fixture feed.</description>
<itunes:image href="http://127.0.0.1:8792/art.png"/>
<itunes:category text="Technology"/>
@@ -12,5 +12,6 @@
<pubDate>Mon, 08 Sep 2026 10:00:00 +0000</pubDate>
<description>Notes for the second.</description>
<itunes:duration>900</itunes:duration>
<podcast:chapters url="http://127.0.0.1:8792/chapters.json" type="application/json+chapters"/>
<enclosure url="http://127.0.0.1:8792/ep1.mp3?2" length="40000" type="audio/mpeg"/></item>
</channel></rss>

View File

@@ -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).

View File

@@ -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}

View File

@@ -34,6 +34,7 @@ function drawNow(){
<small>${[dateOf(e.published),e.duration?clock(e.duration):''].filter(Boolean).join(', ')}</small>
</div>
</div>
<div id="nowchaps"></div>
${upNext.length?`<h3>Up Next</h3><div class="childlist" id="nowqueue"></div>`:''}
<h3>Show notes</h3>
<div class="dbody">${textOf(e)}</div>`;
@@ -41,6 +42,52 @@ function drawNow(){
$<HTMLButtonElement>('.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<string,Promise<Chapter[]>>();
let nowChapters: Chapter[]=[];
function chaptersOf(enc: number, deadair: boolean): Promise<Chapter[]> {
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=`<h3>Chapters</h3><ol class="chapters">${cs.map((c,i)=>
`<li><button type="button" data-i="${i}"><span class="ctime">${clock(c.start)}</span><span>${esc(c.title)||`Chapter ${i+1}`}</span></button></li>`).join('')}</ol>`;
for(const b of $$<HTMLButtonElement>('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; });
$$<HTMLButtonElement>('#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(); } };

View File

@@ -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 {