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:
@@ -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.
|
||||
|
||||
@@ -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
112
crates/ipx/src/chapters.rs
Normal 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(), []);
|
||||
}
|
||||
}
|
||||
@@ -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())
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -7,6 +7,7 @@ mod access;
|
||||
mod art;
|
||||
mod auth;
|
||||
mod catalogue;
|
||||
mod chapters;
|
||||
mod cli;
|
||||
mod config;
|
||||
mod ctx;
|
||||
|
||||
@@ -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>,
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in New Issue
Block a user