From 0da9862cf35e5f1a2cca50599dbee8af09104312 Mon Sep 17 00:00:00 2001 From: Sanapach Date: Mon, 16 Nov 2026 18:53:45 +0200 Subject: [PATCH] Add podcast RSS subscriptions with streaming playback (cherry picked from commit 20167c5b5e2a55b1965fe7f7a095b909ce2d9267) Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 3 + ARCHITECTURE.md | 23 + CHANGELOG.md | 12 + Cargo.lock | 2 + Cargo.toml | 4 + README.md | 27 + src/app/action.rs | 6 +- src/app/event.rs | 22 + src/app/mod.rs | 178 +++- src/app/podcast_runtime.rs | 489 ++++++++++ src/app/popup.rs | 47 +- src/app/state.rs | 185 +++- src/app/update.rs | 247 ++++- src/app/update_tests.rs | 251 ++++- src/config/default_keymap.toml | 11 +- src/config/keymap.rs | 2 + src/devices.rs | 22 +- src/devices/tests.rs | 51 + src/main.rs | 1 + src/player/mod.rs | 116 ++- src/podcasts/feed.rs | 1576 +++++++++++++++++++++++++++++++ src/podcasts/fetch.rs | 207 ++++ src/podcasts/mod.rs | 344 +++++++ src/podcasts/store.rs | 504 ++++++++++ src/podcasts/stream.rs | 794 ++++++++++++++++ src/podcasts/test_server.rs | 260 +++++ src/podcasts/tests.rs | 1620 ++++++++++++++++++++++++++++++++ src/ui/mod.rs | 17 +- src/ui/podcasts.rs | 493 ++++++++++ src/ui/popup.rs | 40 +- 30 files changed, 7479 insertions(+), 75 deletions(-) create mode 100644 src/app/podcast_runtime.rs create mode 100644 src/podcasts/feed.rs create mode 100644 src/podcasts/fetch.rs create mode 100644 src/podcasts/mod.rs create mode 100644 src/podcasts/store.rs create mode 100644 src/podcasts/stream.rs create mode 100644 src/podcasts/test_server.rs create mode 100644 src/podcasts/tests.rs create mode 100644 src/ui/podcasts.rs diff --git a/AGENTS.md b/AGENTS.md index 34b5e49..d517778 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -65,6 +65,9 @@ update it only when dependencies change. coordination. - `src/ui/` renders `AppState`; rendering code must not start background work or mutate persistence. +- `src/podcasts/` owns RSS parsing, podcast persistence, feed fetching and + the HTTP range-request stream reader; `src/app/podcast_runtime.rs` + schedules its work and folds results into `AppState`. - `src/media.rs` owns OS media controls. - `src/visualizer.rs` and `src/visualizations/` own the Rhai visualization host and bundled scripts. diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 06dbf21..de9bef4 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -377,6 +377,25 @@ timeouts are bounded; incompatible profiles are rejected. This direct peer-selection layer can later be replaced by DHT routing without changing local storage or ranking. +## Podcasts + +Podcasts are a separate local source beside the music library. A dedicated +SQLite store holds subscriptions and episode metadata keyed by +`(podcast, RSS GUID)`. A feed refresh upserts episodes and never deletes +ones that dropped out of the feed. Refreshes use conditional HTTP requests +and run in the background with bounded concurrency. The store is +independent of `furumi-library`, so podcast data cannot affect the music +catalog, its migrations or federation publishing. + +Episodes enter the queue as ordinary `TrackItem`s whose `file_path` is the +remote audio URL and whose ids sit in a reserved negative range. Playback +opens an HTTP range-request reader on the blocking pool. The reader buffers a +bounded window ahead of the decoder, and rodio uses coarse, byte-based +seeking for it, so a seek far into an episode fetches only the bytes it +needs. A sequence number discards a stream that finishes connecting after a +newer playback request. Episodes have no content id: listening history, +likes, playlists and cross-device handoff skip them. + ## Persistence boundaries Furumi stores different kinds of state according to their lifetime: @@ -387,6 +406,8 @@ Furumi stores different kinds of state according to their lifetime: | Device operation log and replicas | SQLite | Offline synchronization | | Versioned track embeddings | SQLite | Durable, locally rebuildable similarity data | | Federation catalog cache | SQLite/cache | Faster network browsing | +| Podcast subscriptions and episode metadata | SQLite (`podcasts.sqlite3`) | Durable local podcast catalog; refetchable from feeds | +| Podcast covers | Filesystem cache | Replaceable artwork | | Audio and artwork cache | Filesystem cache | Reusable fetched data | | Settings, keymap, identity | Platform config/data dirs | Node configuration | | Queue and playback snapshots | Application/device sync state | Continuity and handoff | @@ -423,6 +444,8 @@ The source tree follows the architectural responsibilities: - `devices.rs` owns trusted-device replication and playback coordination; - `app/` owns state transitions and runtime orchestration; - `ui/` renders the TUI; +- `podcasts/` owns RSS parsing, the podcast store, feed fetching and the + HTTP range-request stream reader; - `media.rs` integrates platform media controls; - `visualizer.rs` hosts programmable Rhai visualizations. diff --git a/CHANGELOG.md b/CHANGELOG.md index 3145a1d..280abfa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- A Podcasts tab (key `6`) for RSS subscriptions: add a feed by URL, browse + the episode catalog with title search and date sorting, and play an episode + through the regular player and queue. +- Episodes stream over HTTP with range-request seeking; only feed metadata + is stored locally, in `podcasts.sqlite3`, with covers in the cache + directory. +- Background refresh of stale feeds (conditional requests, GUID + deduplication) and a `RefreshPodcasts` action (`Shift+R` in the + `podcasts` key context). + ## [0.2.8] - 2026-09-02 ### Added diff --git a/Cargo.lock b/Cargo.lock index 51d9a33..8ee1615 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1724,6 +1724,7 @@ dependencies = [ "crokey", "crossterm", "directories", + "encoding_rs", "flate2", "fs2", "furumi-library", @@ -1733,6 +1734,7 @@ dependencies = [ "lofty", "music-dht", "object", + "quick-xml", "ratatui", "reqwest 0.12.28", "rhai", diff --git a/Cargo.toml b/Cargo.toml index 0c76128..7a7ce2e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,6 +26,8 @@ blake3 = "1" crokey = "1.4.0" crossterm = { version = "0.29.0", features = ["event-stream"] } directories = "6.0.0" +# Podcast feeds: non-UTF-8 XML declarations (windows-1251, koi8-r, ...). +encoding_rs = "0.8.35" futures-util = "0.3.32" furumi-library = "0.2.0" image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp", "gif", "bmp"] } @@ -33,6 +35,8 @@ lofty = "0.22" # P2P federation: library index in a shared DHT + audio streaming between # peers (same protocol as furumi-fd). music-dht = "0.5.0" +# Podcast RSS/Atom parsing. +quick-xml = "0.41.0" ratatui = "0.30.1" reqwest = { version = "0.12.28", default-features = false, features = ["rustls-tls", "stream", "blocking"] } rhai = { version = "1", features = ["sync"] } diff --git a/README.md b/README.md index 6a2cd17..15c9d64 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,33 @@ The first selectable model is downloaded on demand and is licensed separately by MTG under CC BY-NC-SA 4.0 (a proprietary license is also available from MTG); Furumi itself remains WTFPL. +## Podcasts + +The **Podcasts** tab (key `6`) subscribes to podcast RSS feeds and plays +episodes through the same player, queue and media keys as your music. + +- Choose **Add podcast** and paste the feed URL, for example + `https://podster.fm/rss.xml?pid=778`. Furumi stores the feed's metadata + only: titles, notes, dates and durations. Audio files are never + downloaded in bulk. +- Press `Enter` on a podcast to open its episode list. `/` searches episode + titles as you type, `v` switches between newest-first and oldest-first, + and `Shift+R` checks for new episodes. +- `Enter` on an episode plays it right away, ahead of the rest of your + queue. `a` / `Shift+A` queue it like a track. The episode streams over HTTP + and seeks with range requests, so jumping into a long episode does not + download everything before that point. +- Subscriptions are checked for new episodes in the background. A feed is + fetched again only after 30 minutes, and the request is conditional, so + an unchanged feed costs almost nothing. Episodes are matched by their RSS + GUID, so each one is listed once. +- `Shift+D` on a podcast in the list unsubscribes from it. + +Subscriptions live in Furumi's data directory (`podcasts.sqlite3`). Covers are +kept in the cache directory. Podcasts are local to each device: they are not +yet synchronized between trusted devices or shared through federation, and +playback position is not remembered. + ## Install ### macOS diff --git a/src/app/action.rs b/src/app/action.rs index ec21964..fbeb126 100644 --- a/src/app/action.rs +++ b/src/app/action.rs @@ -57,6 +57,8 @@ pub enum Action { OpenSearch, EditSelected, DeleteSelected, + /// Podcasts: check the opened (or every) subscription for new episodes. + RefreshPodcasts, } /// Help-window sections, in display order. @@ -138,7 +140,8 @@ impl Action { Action::EditSelected | Action::DeleteSelected | Action::CycleSourceMode - | Action::OpenLibraryFilters => Category::Library, + | Action::OpenLibraryFilters + | Action::RefreshPodcasts => Category::Library, Action::OpenSearch | Action::OpenCommandLine => Category::Search, Action::ToggleHelp | Action::Quit => Category::System, } @@ -215,6 +218,7 @@ impl Action { Action::OpenSearch => "Search artists, releases, tracks".into(), Action::EditSelected => "Edit the selected item".into(), Action::DeleteSelected => "Delete the selected item".into(), + Action::RefreshPodcasts => "Podcasts: check for new episodes".into(), } } } diff --git a/src/app/event.rs b/src/app/event.rs index 54feb60..297a11e 100644 --- a/src/app/event.rs +++ b/src/app/event.rs @@ -206,4 +206,26 @@ pub enum AppEvent { JamInvite(Result), /// Result of joining a Jam capability. JamJoined(Result), + /// Podcast subscriptions (re)loaded from the podcast store. + PodcastsLoaded(Result, String>), + /// The stored episode catalog of one podcast. + PodcastEpisodesLoaded { + podcast_id: i64, + result: Result, String>, + }, + /// A new subscription was stored (its id) or rejected. + PodcastSubscribed(Result), + /// One feed refresh finished. + PodcastRefreshed { + podcast_id: i64, + result: Result, + /// Background sweep: report errors in the log, not the status bar. + quiet: bool, + }, + PodcastUnsubscribed { + podcast_id: i64, + result: Result<(), String>, + }, + /// Periodic timer: refresh subscriptions whose feed went stale. + PodcastAutoRefreshDue, } diff --git a/src/app/mod.rs b/src/app/mod.rs index 9c4517a..a4721ed 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -4,6 +4,7 @@ pub mod command; mod enrichment; pub mod event; pub mod input; +mod podcast_runtime; pub(crate) mod popup; pub mod state; pub mod update; @@ -73,10 +74,18 @@ pub struct Runtime { pub search_seq: Arc, pub player: player::Controller, pub player_start_pending: bool, + /// Pause or seek requested while a start was pending; those commands + /// reached a stopped output and are re-applied once audio starts. + pub start_intent_changed: bool, pub media_tx: std::sync::mpsc::Sender, pub last_media_push: Option, pub status_publisher: crate::status::Publisher, pub status_visualizer: crate::visualizer::status::Renderer, + /// Podcast store and feed client; `None` when the store cannot open. + pub podcasts: Option, + /// Bumped by every playback start or stop, so a remote stream that + /// finishes connecting late does not start over a newer request. + pub playback_seq: Arc, } #[derive(Debug, Clone, Copy)] @@ -439,6 +448,16 @@ pub async fn run( state.device_playback.active_device_id = Some(device_id); state.device_playback.active_device_name = Some(device_name); } + let podcasts = match podcast_runtime::open().await { + Ok(podcasts) => Some(podcasts), + Err(err) => { + tracing::warn!(%err, "podcast storage unavailable"); + state.podcasts.list = Some(state::Loadable::Failed(format!( + "podcast storage is unavailable: {err}" + ))); + None + } + }; let player_events = event_tx.clone(); let mut runtime = Runtime { event_tx, @@ -471,11 +490,18 @@ pub async fn run( let _ = player_events.send(AppEvent::Player(event)); }), player_start_pending: false, + start_intent_changed: false, media_tx, last_media_push: None, status_publisher: crate::status::Publisher::spawn(), status_visualizer: crate::visualizer::status::Renderer::default(), + podcasts, + playback_seq: Arc::new(std::sync::atomic::AtomicU64::new(0)), }; + if runtime.podcasts.is_some() { + podcast_runtime::load_list(&runtime); + podcast_runtime::spawn_auto_refresh_timer(runtime.event_tx.clone()); + } spawn_content_id_backfill(&runtime); if state.similarity.settings.enabled { runtime.similarity.start(); @@ -699,6 +725,32 @@ fn playback_track_to_ui( wire.to_track_item() } +/// Stop local audio and invalidate any playback start still in flight (a +/// podcast or federated stream that is connecting), so it cannot begin +/// after this stop. +fn stop_player(runtime: &Runtime) { + runtime + .playback_seq + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + runtime.player.stop(); +} + +/// Jam participants are not trusted devices: they may echo the host's own +/// podcast episodes back, but must not make the host fetch arbitrary URLs. +fn sanitize_jam_stream_urls(state: &AppState, wire: &mut crate::devices::PlaybackStateWire) { + for track in &mut wire.queue { + if crate::podcasts::is_remote_url(&track.file_path) + && !state + .player + .queue + .iter() + .any(|queued| queued.file_path == track.file_path) + { + track.file_path.clear(); + } + } +} + fn track_playback_key(track: &crate::library::models::TrackItem) -> String { state::track_key(track) } @@ -842,7 +894,7 @@ pub(crate) fn become_control_device( ) { runtime.player.set_playback_allowed(false); if state.device_playback.is_audio_owner() { - runtime.player.stop(); + stop_player(runtime); publish_inactive_playback_snapshot(state, runtime); } state.device_playback.role = state::DevicePlaybackRole::Control; @@ -1307,6 +1359,14 @@ fn maintenance(state: &mut AppState, runtime: &mut Runtime) { } } } + if state.active_tab == state::Tab::Podcasts + && let Some(path) = state + .podcasts + .current_podcast() + .and_then(|podcast| podcast.cover_path.clone()) + { + wanted.push((path, header.0, header.1)); + } for (path, width, height) in wanted { let key = crate::art::cache_key(&path, width, height); if state.art.contains_key(&key) { @@ -1588,6 +1648,7 @@ fn perform_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) { push_media_update(state, runtime, true); } Effect::TogglePause => { + runtime.start_intent_changed |= runtime.player_start_pending; if state.player.paused { runtime.player.pause(); } else { @@ -1597,10 +1658,11 @@ fn perform_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) { } Effect::StopPlayback => { runtime.player_start_pending = false; - runtime.player.stop(); + stop_player(runtime); push_media_update(state, runtime, true); } Effect::SeekBy(delta) => { + runtime.start_intent_changed |= runtime.player_start_pending; let target = (state.player.position_secs + delta as f64).max(0.0); state.player.position_secs = target; runtime @@ -1679,6 +1741,10 @@ fn perform_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) { } }); } + Effect::PodcastLoadEpisodes(id) => podcast_runtime::open_episodes(state, runtime, id), + Effect::PodcastSubscribe(url) => podcast_runtime::subscribe(state, runtime, url), + Effect::PodcastRefresh(ids) => podcast_runtime::refresh(state, runtime, ids), + Effect::PodcastUnsubscribe(id) => podcast_runtime::unsubscribe(state, runtime, id), Effect::LoadListenHistory => { let library = Arc::clone(&runtime.library); let devices = Arc::clone(&runtime.devices); @@ -2032,7 +2098,7 @@ fn perform_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) { } => { if stop { runtime.player_start_pending = false; - runtime.player.stop(); + stop_player(runtime); push_media_update(state, runtime, true); } else if let Some(paused) = restart_paused { start_current_audio(state, runtime, 0.0, paused); @@ -2167,7 +2233,11 @@ fn start_current_audio( let Some(mut track) = state.player.queue.get(state.player.queue_pos).cloned() else { return; }; - if track_file_missing(&track) { + runtime + .playback_seq + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let remote = crate::podcasts::is_remote_url(&track.file_path); + if !remote && track_file_missing(&track) { if let Some(local) = local_track_for_playback(runtime, &track) { state.player.queue[state.player.queue_pos] = local.clone(); track = local; @@ -2187,7 +2257,8 @@ fn start_current_audio( state.player.listen_id = Some(runtime.devices.new_listen_id()); state.player.prefetched_pos = None; runtime.player_start_pending = true; - runtime.player.stop(); + runtime.start_intent_changed = false; + stop_player(runtime); state.status_message = Some(format!( "federation: locating \"{}\" for this device…", track.title @@ -2246,10 +2317,17 @@ fn start_current_audio( state.status_message = Some(format!("▶ {} — {}", track.title, track.artist_line())); runtime.player_start_pending = true; + runtime.start_intent_changed = false; + if remote { + // Podcast episode: stream it over HTTP instead of opening a file. + state.status_message = Some(format!("podcast: connecting to \"{}\"…", track.title)); + podcast_runtime::start_stream(runtime, track, state.player.volume, position_secs, paused); + return; + } if track.is_fed_pending() { // A federated track that is not on disk yet: silence the previous // audio, download it and resume through FedTrackResolved. - runtime.player.stop(); + stop_player(runtime); state.status_message = Some(format!("federation: fetching \"{}\"…", track.title)); spawn_fed_resolve( runtime, @@ -2264,7 +2342,7 @@ fn start_current_audio( } if track_file_missing(&track) { runtime.player_start_pending = false; - runtime.player.stop(); + stop_player(runtime); state.player.playing = false; state.player.paused = false; state.status_message = Some(format!( @@ -2405,6 +2483,11 @@ fn report_history( let Some(listen_id) = listen_id else { return; }; + // Listening history is keyed by audio content ids, which streamed + // podcast episodes do not have. + if crate::podcasts::is_remote_url(&track.file_path) { + return; + } let Some(event) = runtime.devices.listen_event_for_track( listen_id.to_string(), track, @@ -2572,6 +2655,12 @@ fn spawn_fed_resolve( let tx = runtime.event_tx.clone(); let controller = runtime.player.clone(); let streaming = Arc::clone(&runtime.fed_streaming); + // The playback request this resolve belongs to; a newer start or stop + // makes a stream that connects later stay silent. + let start_seq = runtime + .playback_seq + .load(std::sync::atomic::Ordering::SeqCst); + let current_seq = Arc::clone(&runtime.playback_seq); tokio::spawn(async move { let progress = download_progress_sender(tx.clone(), title.clone()); let result = if let Some(playback) = @@ -2588,6 +2677,10 @@ fn spawn_fed_resolve( return; } started = true; + if current_seq.load(std::sync::atomic::Ordering::SeqCst) != start_seq { + tracing::debug!(title = %stream_title, "federated stream superseded before start"); + return; + } stream_markers .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) @@ -2644,6 +2737,12 @@ fn spawn_content_id_resolve( let tx = runtime.event_tx.clone(); let controller = runtime.player.clone(); let streaming = Arc::clone(&runtime.fed_streaming); + // The playback request this resolve belongs to; a newer start or stop + // makes a stream that connects later stay silent. + let start_seq = runtime + .playback_seq + .load(std::sync::atomic::Ordering::SeqCst); + let current_seq = Arc::clone(&runtime.playback_seq); tokio::spawn(async move { let result = match fed.track_by_content_id(&content_id, Some(&label)).await { Ok(fed_track) => { @@ -2668,6 +2767,10 @@ fn spawn_content_id_resolve( return; } started = true; + if current_seq.load(std::sync::atomic::Ordering::SeqCst) != start_seq { + tracing::debug!(title = %stream_title, "federated stream superseded before start"); + return; + } stream_markers .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) @@ -3095,7 +3198,7 @@ fn apply_queue_refresh( if state.player.queue.is_empty() { if state.player.playing { runtime.player_start_pending = false; - runtime.player.stop(); + stop_player(runtime); } state.player = state::PlayerBar::default(); state.queue_tab.cursor = 0; @@ -3139,7 +3242,7 @@ fn apply_queue_refresh( (Some(_), _) => { // The playing track was deleted from the library. runtime.player_start_pending = false; - runtime.player.stop(); + stop_player(runtime); state.player.queue_pos = refreshed_queue_pos.min(state.player.queue.len() - 1); state.player.current = None; state.player.playing = false; @@ -3166,14 +3269,14 @@ fn reconcile_personal_playback(state: &mut AppState, runtime: &mut Runtime) { Ok(owner) => owner, Err(error) => { runtime.player.set_playback_allowed(false); - runtime.player.stop(); + stop_player(runtime); state.status_message = Some(format!("playback coordination: {error}")); return; } }; let Some(owner) = owner else { runtime.player.set_playback_allowed(false); - runtime.player.stop(); + stop_player(runtime); runtime.player_start_pending = false; state.device_playback.role = state::DevicePlaybackRole::Control; state.device_playback.active_device_id = None; @@ -3192,7 +3295,7 @@ fn reconcile_personal_playback(state: &mut AppState, runtime: &mut Runtime) { } } else { runtime.player.set_playback_allowed(false); - runtime.player.stop(); + stop_player(runtime); runtime.player_start_pending = false; state.device_playback.role = state::DevicePlaybackRole::Control; state.device_playback.active_device_id = Some(owner); @@ -3232,7 +3335,7 @@ fn handle_playback_command( .set_volume(player::amplitude(state.player.volume)); if !state.player.playing { runtime.player_start_pending = false; - runtime.player.stop(); + stop_player(runtime); push_media_update(state, runtime, true); publish_playback_snapshot(state, runtime); return; @@ -3298,11 +3401,21 @@ fn handle_playback_command( } fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent) { + let Some(event) = podcast_runtime::handle_event(state, runtime, event) else { + return; + }; match event { AppEvent::StatusVisualizationReady(ready) => { runtime.status_visualizer.busy = false; state.status_visualizer.apply(ready); } + // Folded into the state by podcast_runtime::handle_event above. + AppEvent::PodcastsLoaded(_) + | AppEvent::PodcastEpisodesLoaded { .. } + | AppEvent::PodcastSubscribed(_) + | AppEvent::PodcastRefreshed { .. } + | AppEvent::PodcastUnsubscribed { .. } + | AppEvent::PodcastAutoRefreshDue => {} AppEvent::UpdateChecked(result) => { state.updater.busy = false; state.updater.message = match result { @@ -3473,7 +3586,7 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent } crate::jam::JamRole::Participant => { if state.device_playback.is_audio_owner() { - runtime.player.stop(); + stop_player(runtime); runtime.player_start_pending = false; } state.device_playback.role = state::DevicePlaybackRole::Jam; @@ -3505,6 +3618,7 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent seek, } => { wire.volume = state.player.volume; + sanitize_jam_stream_urls(state, &mut wire); crate::devices::PlaybackCommand::SetState { state: wire, seek } } crate::devices::PlaybackCommand::ActiveChanged { .. } => { @@ -3729,7 +3843,7 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent runtime.player_start_pending = false; state.player.playing = false; state.player.current = None; - runtime.player.stop(); + stop_player(runtime); } } } @@ -4000,7 +4114,7 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent runtime.player_start_pending = false; // A background decoder may finish after ownership was handed off. // Ignoring Started alone would leave its obsolete audio playing. - runtime.player.stop(); + stop_player(runtime); tracing::debug!( ?event, "ignored local player event while controlling remote playback" @@ -4008,6 +4122,36 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent } AppEvent::Player(player::PlayerEvent::Started) => { runtime.player_start_pending = false; + let intent_changed = std::mem::take(&mut runtime.start_intent_changed); + if let Some(track) = &state.player.current + && crate::podcasts::is_remote_url(&track.file_path) + { + // A stream connects for seconds; pause, seek and volume + // changes made meanwhile hit a stopped output. Re-apply them + // (these commands queue behind the stream's own start-up ones). + runtime + .player + .set_volume(player::amplitude(state.player.volume)); + if intent_changed && state.player.position_secs > 0.0 { + runtime + .player + .seek(Duration::from_secs_f64(state.player.position_secs)); + } + if state.player.paused { + runtime.player.pause(); + } else { + runtime.player.resume(); + } + // Replace the "connecting" notice. + if state + .status_message + .as_deref() + .is_some_and(|message| message.starts_with("podcast: connecting")) + { + state.status_message = + Some(format!("▶ {} — {}", track.title, track.artist_line())); + } + } } AppEvent::Player(player::PlayerEvent::TrackFinished { has_next }) => { // The finished track gets a full-duration, completed entry. @@ -4262,7 +4406,7 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent if state.device_playback.is_control() { record_control_playback_state(state, runtime, false); } else { - runtime.player.stop(); + stop_player(runtime); push_media_update(state, runtime, true); } return; diff --git a/src/app/podcast_runtime.rs b/src/app/podcast_runtime.rs new file mode 100644 index 0000000..bbbb4fc --- /dev/null +++ b/src/app/podcast_runtime.rs @@ -0,0 +1,489 @@ +//! Runtime side of the Podcasts tab: opening the podcast store, running feed +//! fetches and SQLite work off the UI thread, and folding their results back +//! into `AppState`. Only RSS metadata is persisted; episode audio is streamed +//! on demand by `start_stream`. + +use std::sync::Arc; +use std::sync::atomic::Ordering; +use std::time::Duration; + +use super::event::AppEvent; +use super::state::{AppState, Loadable, OpenedPodcast}; +use super::update::PODCAST_STALE_SECS; +use super::{Runtime, err_string, now_epoch_seconds}; + +/// How often the background sweep looks for stale feeds. Each feed is only +/// fetched when it was last checked more than `PODCAST_STALE_SECS` ago. +const AUTO_REFRESH_INTERVAL: Duration = Duration::from_secs(5 * 60); +/// Delay before the first sweep, so startup work is not slowed down. +const AUTO_REFRESH_FIRST_DELAY: Duration = Duration::from_secs(20); +/// Feeds fetched at the same time; protects slow links and podcast hosts. +const MAX_CONCURRENT_REFRESHES: usize = 4; + +/// Store and HTTP client shared by podcast background tasks. +pub struct PodcastRuntime { + pub store: Arc, + pub fetcher: Arc, + refresh_slots: Arc, +} + +/// Open the podcast store beside the library data and the cover cache in +/// the platform cache directory. Failure disables only the Podcasts tab. +pub async fn open() -> Result { + let dirs = crate::config::project_dirs() + .ok_or_else(|| "no home directory for podcast data".to_string())?; + let db_path = dirs.data_dir().join("podcasts.sqlite3"); + let covers_dir = dirs.cache_dir().join("podcasts").join("covers"); + let store = tokio::task::spawn_blocking(move || crate::podcasts::Store::open(&db_path)) + .await + .map_err(|err| err.to_string())? + .map_err(err_string)?; + let fetcher = crate::podcasts::Fetcher::new(covers_dir).map_err(err_string)?; + Ok(PodcastRuntime { + store: Arc::new(store), + fetcher: Arc::new(fetcher), + refresh_slots: Arc::new(tokio::sync::Semaphore::new(MAX_CONCURRENT_REFRESHES)), + }) +} + +/// Ticks `PodcastAutoRefreshDue`; the handler decides which feeds are stale. +pub fn spawn_auto_refresh_timer(tx: tokio::sync::mpsc::UnboundedSender) { + tokio::spawn(async move { + let start = tokio::time::Instant::now() + AUTO_REFRESH_FIRST_DELAY; + let mut interval = tokio::time::interval_at(start, AUTO_REFRESH_INTERVAL); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + loop { + interval.tick().await; + if tx.send(AppEvent::PodcastAutoRefreshDue).is_err() { + return; + } + } + }); +} + +fn unavailable(state: &mut AppState) { + state.status_message = Some("podcasts are unavailable (see the Podcasts tab)".into()); +} + +pub fn load_list(runtime: &Runtime) { + let Some(podcasts) = &runtime.podcasts else { + return; + }; + let store = Arc::clone(&podcasts.store); + let tx = runtime.event_tx.clone(); + tokio::task::spawn_blocking(move || { + let result = store.list_podcasts().map_err(err_string); + let _ = tx.send(AppEvent::PodcastsLoaded(result)); + }); +} + +fn load_episodes(runtime: &Runtime, podcast_id: i64) { + let Some(podcasts) = &runtime.podcasts else { + return; + }; + let store = Arc::clone(&podcasts.store); + let tx = runtime.event_tx.clone(); + tokio::task::spawn_blocking(move || { + let result = store.episodes(podcast_id).map_err(err_string); + let _ = tx.send(AppEvent::PodcastEpisodesLoaded { podcast_id, result }); + }); +} + +/// Effect::PodcastLoadEpisodes: read the stored catalog, and fetch the feed +/// in the background when it has not been checked recently. +pub fn open_episodes(state: &mut AppState, runtime: &Runtime, podcast_id: i64) { + if runtime.podcasts.is_none() { + state.podcasts.episodes = Some(( + podcast_id, + Loadable::Failed("podcast storage is unavailable".into()), + )); + return; + } + load_episodes(runtime, podcast_id); + let stale = state + .podcasts + .podcast(podcast_id) + .is_some_and(|podcast| is_stale(podcast.last_checked_at, now_epoch_seconds())); + if stale && !state.podcasts.refreshing.contains(&podcast_id) { + state.podcasts.refreshing.insert(podcast_id); + spawn_refresh(runtime, vec![podcast_id], true); + } +} + +fn is_stale(last_checked_at: Option, now: i64) -> bool { + last_checked_at.is_none_or(|checked| now.saturating_sub(checked) >= PODCAST_STALE_SECS) +} + +pub fn subscribe(state: &mut AppState, runtime: &Runtime, url: String) { + let Some(podcasts) = &runtime.podcasts else { + return unavailable(state); + }; + if state.podcasts.subscribing { + state.status_message = Some("podcasts: a subscription is already being added".into()); + return; + } + state.podcasts.subscribing = true; + state.status_message = Some(format!("podcasts: reading feed {url}…")); + let store = Arc::clone(&podcasts.store); + let fetcher = Arc::clone(&podcasts.fetcher); + let tx = runtime.event_tx.clone(); + tokio::spawn(async move { + let result = crate::podcasts::subscribe(store, &fetcher, &url, now_epoch_seconds()) + .await + .map_err(err_string); + let _ = tx.send(AppEvent::PodcastSubscribed(result)); + }); +} + +/// Effect::PodcastRefresh / the periodic sweep. Callers have already put the +/// ids into `state.podcasts.refreshing`. +pub fn spawn_refresh(runtime: &Runtime, ids: Vec, quiet: bool) { + let Some(podcasts) = &runtime.podcasts else { + return; + }; + for podcast_id in ids { + let store = Arc::clone(&podcasts.store); + let fetcher = Arc::clone(&podcasts.fetcher); + let slots = Arc::clone(&podcasts.refresh_slots); + let tx = runtime.event_tx.clone(); + tokio::spawn(async move { + let Ok(_permit) = slots.acquire_owned().await else { + return; + }; + let result = crate::podcasts::refresh(store, &fetcher, podcast_id, now_epoch_seconds()) + .await + .map_err(err_string); + let _ = tx.send(AppEvent::PodcastRefreshed { + podcast_id, + result, + quiet, + }); + }); + } +} + +pub fn refresh(state: &mut AppState, runtime: &Runtime, ids: Vec) { + if runtime.podcasts.is_none() { + for id in &ids { + state.podcasts.refreshing.remove(id); + } + return unavailable(state); + } + spawn_refresh(runtime, ids, false); +} + +pub fn unsubscribe(state: &mut AppState, runtime: &Runtime, podcast_id: i64) { + let Some(podcasts) = &runtime.podcasts else { + return unavailable(state); + }; + let store = Arc::clone(&podcasts.store); + let tx = runtime.event_tx.clone(); + tokio::task::spawn_blocking(move || { + let result = store + .remove_podcast(podcast_id) + .map(|cover_path| { + // Covers are replaceable cache; a leftover file is harmless. + if let Some(path) = cover_path + && let Err(err) = std::fs::remove_file(&path) + && err.kind() != std::io::ErrorKind::NotFound + { + tracing::debug!(%err, path, "podcast cover cleanup failed"); + } + }) + .map_err(err_string); + let _ = tx.send(AppEvent::PodcastUnsubscribed { podcast_id, result }); + }); +} + +/// The periodic sweep: refresh every subscription not checked recently. +pub fn auto_refresh(state: &mut AppState, runtime: &Runtime) { + if runtime.podcasts.is_none() { + return; + } + let now = now_epoch_seconds(); + state.podcasts.last_auto_refresh = Some(now); + let ids: Vec = state + .podcasts + .podcasts() + .iter() + .filter(|podcast| is_stale(podcast.last_checked_at, now)) + .map(|podcast| podcast.id) + .filter(|id| !state.podcasts.refreshing.contains(id)) + .collect(); + if ids.is_empty() { + return; + } + tracing::debug!(count = ids.len(), "podcasts: refreshing stale feeds"); + state.podcasts.refreshing.extend(ids.iter().copied()); + spawn_refresh(runtime, ids, true); +} + +/// Fold a podcast `AppEvent` into the state; any other event is handed back. +pub fn handle_event(state: &mut AppState, runtime: &Runtime, event: AppEvent) -> Option { + match event { + AppEvent::PodcastsLoaded(result) => { + let selected_id = selected_podcast_id(state); + match result { + Ok(list) => state.podcasts.list = Some(Loadable::Ready(list)), + Err(err) => { + tracing::warn!(%err, "podcast list load failed"); + if matches!(state.podcasts.list, Some(Loadable::Ready(_))) { + // A failed reload keeps the visible subscriptions. + state.status_message = Some(format!("podcasts: {err}")); + } else { + state.podcasts.list = Some(Loadable::Failed(err)); + } + } + } + restore_list_cursor(state, selected_id); + // A podcast that disappeared (unsubscribed elsewhere) closes. + if let Some(opened) = state.podcasts.opened + && matches!(state.podcasts.list, Some(Loadable::Ready(_))) + && state.podcasts.podcast(opened.id).is_none() + { + state.podcasts.opened = None; + state.podcasts.episodes = None; + state.podcasts.filter.clear(); + } + } + AppEvent::PodcastEpisodesLoaded { podcast_id, result } => { + // Only the catalog slot this load was issued for may take it: a + // slow read for a podcast the user already left must not replace + // the one now open (each open re-keys the slot first). + if !episodes_result_is_current(state, podcast_id) { + return None; + } + // Keep the cursor on the same episode when new ones arrive above. + let selected_episode = state + .podcasts + .selected_episode() + .filter(|episode| episode.podcast_id == podcast_id) + .map(|episode| episode.id); + match result { + Ok(episodes) => { + state.podcasts.episodes = Some((podcast_id, Loadable::Ready(episodes))); + } + Err(err) => { + tracing::warn!(%err, podcast_id, "podcast episodes load failed"); + // A failed reload keeps an already visible catalog. + let keep = matches!( + &state.podcasts.episodes, + Some((id, Loadable::Ready(_))) if *id == podcast_id + ); + if keep { + state.status_message = Some(format!("podcasts: {err}")); + } else { + state.podcasts.episodes = Some((podcast_id, Loadable::Failed(err))); + } + } + } + if let (Some(episode_id), Some(opened)) = (selected_episode, state.podcasts.opened) + && opened.id == podcast_id + && let Some(episodes) = state.podcasts.opened_episodes() + { + let visible = state.podcasts.visible_episode_indices(); + if let Some(cursor) = visible + .iter() + .position(|&index| episodes[index].id == episode_id) + { + state.podcasts.opened = Some(OpenedPodcast { + id: podcast_id, + cursor, + }); + } + } + } + AppEvent::PodcastSubscribed(result) => { + state.podcasts.subscribing = false; + match result { + Ok(podcast_id) => { + state.status_message = Some("podcasts: subscribed".into()); + // Select the new row once the reloaded list arrives. + state.podcasts.opened = None; + state.podcasts.filter.clear(); + state.podcasts.pending_select = Some(podcast_id); + load_list(runtime); + } + Err(err) => { + state.status_message = Some(format!("podcasts: cannot subscribe: {err}")); + } + } + } + AppEvent::PodcastRefreshed { + podcast_id, + result, + quiet, + } => { + state.podcasts.refreshing.remove(&podcast_id); + let title = state + .podcasts + .podcast(podcast_id) + .map(|podcast| podcast.title.clone()) + .unwrap_or_else(|| "podcast".to_string()); + match result { + Ok(summary) => { + if summary.new_episodes > 0 { + state.status_message = Some(format!( + "podcasts: {} new episode(s) in {title}", + summary.new_episodes + )); + } else if !quiet && state.podcasts.refreshing.is_empty() { + state.status_message = Some("podcasts: no new episodes".into()); + } + if state + .podcasts + .opened + .is_some_and(|opened| opened.id == podcast_id) + && (summary.new_episodes > 0 || summary.updated_episodes > 0) + { + load_episodes(runtime, podcast_id); + } + } + Err(err) => { + tracing::warn!(%err, podcast_id, "podcast refresh failed"); + if !quiet { + state.status_message = + Some(format!("podcasts: {title}: refresh failed: {err}")); + } + } + } + // Counts, check time and errors live on the list rows. + load_list(runtime); + } + AppEvent::PodcastUnsubscribed { podcast_id, result } => match result { + Ok(()) => { + if state + .podcasts + .opened + .is_some_and(|opened| opened.id == podcast_id) + { + state.podcasts.opened = None; + state.podcasts.filter.clear(); + } + if matches!(&state.podcasts.episodes, Some((id, _)) if *id == podcast_id) { + state.podcasts.episodes = None; + } + state.status_message = Some("podcasts: unsubscribed".into()); + load_list(runtime); + } + Err(err) => { + state.status_message = Some(format!("podcasts: unsubscribe failed: {err}")); + } + }, + AppEvent::PodcastAutoRefreshDue => auto_refresh(state, runtime), + other => return Some(other), + } + None +} + +fn episodes_result_is_current(state: &AppState, podcast_id: i64) -> bool { + matches!(&state.podcasts.episodes, Some((id, _)) if *id == podcast_id) +} + +fn selected_podcast_id(state: &AppState) -> Option { + if state.podcasts.opened.is_some() { + return None; + } + state.podcasts.current_podcast().map(|podcast| podcast.id) +} + +/// After a list reload, keep the cursor on the same podcast (or on a newly +/// subscribed one) even when rows above it were added or removed. +fn restore_list_cursor(state: &mut AppState, previous: Option) { + let target = state.podcasts.pending_select.take().or(previous); + let rows = state.podcasts.list_rows().len(); + if let Some(id) = target + && let Some(index) = state + .podcasts + .podcasts() + .iter() + .position(|podcast| podcast.id == id) + { + state.podcasts.selected = index + super::state::PODCAST_ACTION_ROWS; + } + state.podcasts.selected = state.podcasts.selected.min(rows.saturating_sub(1)); +} + +/// Start playing a remote episode URL. Opening the HTTP stream may take a +/// few seconds, so it runs on the blocking pool; a newer playback request +/// started meanwhile wins (`playback_seq`). +pub fn start_stream( + runtime: &Runtime, + track: crate::library::models::TrackItem, + volume: u8, + position_secs: f64, + paused: bool, +) { + let seq = runtime.playback_seq.load(Ordering::SeqCst); + let current_seq = Arc::clone(&runtime.playback_seq); + let controller = runtime.player.clone(); + let tx = runtime.event_tx.clone(); + let volume = crate::player::amplitude(volume); + // Silence the previous track while the stream connects. This must not + // bump `playback_seq`: the request captured above is the current one. + runtime.player.stop(); + tokio::task::spawn_blocking(move || { + // Connect and probe the container here, not on the audio thread: + // both wait on the network, and a stalled host must not block + // pause/stop of whatever plays next. + let decoded = crate::podcasts::stream::open(&track.file_path).and_then(|opened| { + let coarse_seek = opened.seekable && opened.byte_len.is_some(); + crate::player::decode_source_with( + Box::new(opened.reader), + opened.byte_len, + opened.mime_type.as_deref(), + opened.seekable, + coarse_seek, + ) + .map_err(|err| anyhow::anyhow!("cannot decode the episode audio: {err}")) + }); + // A newer start or stop happened meanwhile: neither play nor report. + if current_seq.load(Ordering::SeqCst) != seq { + tracing::debug!(title = %track.title, "podcast stream superseded before start"); + return; + } + match decoded { + Ok(source) => { + controller.play_source(source, volume); + if position_secs > 0.0 { + controller.seek(Duration::from_secs_f64(position_secs)); + } + if paused { + controller.pause(); + } + } + Err(err) => { + tracing::warn!(title = %track.title, url = %track.file_path, err = %format!("{err:#}"), "podcast stream failed"); + let _ = tx.send(AppEvent::Player(crate::player::PlayerEvent::Failed( + format!("cannot stream \"{}\": {err:#}", track.title), + ))); + } + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn late_episode_loads_for_another_podcast_are_ignored() { + let mut state = AppState::default(); + state.podcasts.opened = Some(OpenedPodcast { id: 7, cursor: 0 }); + state.podcasts.episodes = Some((7, Loadable::Loading)); + assert!(episodes_result_is_current(&state, 7)); + assert!(!episodes_result_is_current(&state, 3)); + state.podcasts.episodes = None; + assert!(!episodes_result_is_current(&state, 7)); + } + + #[test] + fn staleness_uses_last_check_time() { + let now = 1_000_000; + assert!(is_stale(None, now)); + assert!(is_stale(Some(now - PODCAST_STALE_SECS), now)); + assert!(!is_stale(Some(now - PODCAST_STALE_SECS + 1), now)); + // A clock that moved backwards does not trigger a refresh storm. + assert!(!is_stale(Some(now + 60), now)); + } +} diff --git a/src/app/popup.rs b/src/app/popup.rs index 1d82205..ddd8c95 100644 --- a/src/app/popup.rs +++ b/src/app/popup.rs @@ -557,7 +557,11 @@ fn handle_fed_input( key: KeyEvent, ) { match key.code { - KeyCode::Esc => {} + KeyCode::Esc => { + if field == FedInputField::PodcastFilter { + crate::app::update::podcasts_set_filter(state, String::new()); + } + } KeyCode::Enter => { let value = input.trim().to_string(); match field { @@ -662,10 +666,28 @@ fn handle_fed_input( ); } } + FedInputField::PodcastFeedUrl => { + if value.is_empty() { + state.status_message = Some("podcast feed URL is empty".into()); + } else { + super::perform_effect( + state, + runtime, + crate::app::update::Effect::PodcastSubscribe(value), + ); + } + } + // The filter is already applied live; Enter just keeps it. + FedInputField::PodcastFilter => { + crate::app::update::podcasts_set_filter(state, value); + } } } _ => { input.handle_key(key); + if field == FedInputField::PodcastFilter { + crate::app::update::podcasts_set_filter(state, input.to_string()); + } state.popup = Some(Popup::FedInput { field, input }); } } @@ -787,9 +809,15 @@ fn handle_device_leave(state: &mut AppState, runtime: &mut Runtime, key: KeyEven /// Pasted text goes into the focused text field when one is open. pub fn handle_paste(state: &mut AppState, pasted: &str) { let cleaned: String = pasted.chars().filter(|c| !c.is_control()).collect(); + let mut filter = None; match &mut state.popup { Some(Popup::NewPlaylist { input, busy, .. }) if !*busy => input.insert_str(&cleaned), - Some(Popup::FedInput { input, .. }) => input.insert_str(&cleaned), + Some(Popup::FedInput { field, input }) => { + input.insert_str(&cleaned); + if *field == FedInputField::PodcastFilter { + filter = Some(input.to_string()); + } + } Some(Popup::Edit { fields, focus, .. }) => { if let Some(field) = fields.get_mut(*focus) { field.value.insert_str(&cleaned); @@ -797,6 +825,9 @@ pub fn handle_paste(state: &mut AppState, pasted: &str) { } _ => {} } + if let Some(filter) = filter { + crate::app::update::podcasts_set_filter(state, filter); + } } // --------------------------------------------------------------------------- @@ -969,13 +1000,22 @@ fn save_edit( fn handle_confirm_delete( state: &mut AppState, - runtime: &Runtime, + runtime: &mut Runtime, target: DeleteTarget, label: String, key: KeyEvent, ) { match key.code { KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('q') => {} + KeyCode::Enter | KeyCode::Char('y') if matches!(target, DeleteTarget::Podcast(_)) => { + if let DeleteTarget::Podcast(id) = target { + super::perform_effect( + state, + runtime, + crate::app::update::Effect::PodcastUnsubscribe(id), + ); + } + } KeyCode::Enter | KeyCode::Char('y') => { let library = Arc::clone(&runtime.library); let result = match target { @@ -989,6 +1029,7 @@ fn handle_confirm_delete( library.delete_playlist(id) } }, + DeleteTarget::Podcast(_) => unreachable!("handled by the guarded arm above"), }; match result { Ok(()) => { diff --git a/src/app/state.rs b/src/app/state.rs index 811d46e..caacdec 100644 --- a/src/app/state.rs +++ b/src/app/state.rs @@ -695,6 +695,8 @@ pub enum DeleteTarget { Release(i64), Artist(i64), Playlist(i64), + /// Unsubscribe: drops the feed's stored metadata and cached cover. + Podcast(i64), } /// One text field of an edit form. @@ -899,6 +901,9 @@ pub enum FedInputField { DeviceName, ConnectInvite, JamInvite, + PodcastFeedUrl, + /// Live episode-title filter of the opened podcast. + PodcastFilter, } impl FedInputField { @@ -913,6 +918,8 @@ impl FedInputField { FedInputField::DeviceName => "Device name", FedInputField::ConnectInvite => "Connect device (paste frid://i invite)", FedInputField::JamInvite => "Join Jam (paste frid://j invite)", + FedInputField::PodcastFeedUrl => "Add podcast (RSS feed URL)", + FedInputField::PodcastFilter => "Search episodes by title", } } @@ -945,6 +952,12 @@ impl FedInputField { FedInputField::JamInvite => { "Paste a frid://j capability to control the host player for this Jam only." } + FedInputField::PodcastFeedUrl => { + "Paste the podcast's RSS feed URL. Only the episode list is stored; audio streams when you play an episode." + } + FedInputField::PodcastFilter => { + "Type words from the episode title; the list updates as you type. Enter keeps the filter, Esc clears it." + } } } } @@ -1469,15 +1482,19 @@ pub enum Tab { Queue, Federation, Logs, + Podcasts, } impl Tab { - pub const ALL: [Tab; 5] = [ + /// Display and `GoToTab` index order. Podcasts is appended so the + /// existing number keys (and user keymaps) keep their meaning. + pub const ALL: [Tab; 6] = [ Tab::Global, Tab::Playlists, Tab::Queue, Tab::Federation, Tab::Logs, + Tab::Podcasts, ]; pub fn title(self) -> &'static str { @@ -1487,6 +1504,7 @@ impl Tab { Tab::Queue => "Queue", Tab::Federation => "Settings", Tab::Logs => "Logs", + Tab::Podcasts => "Podcasts", } } @@ -1513,6 +1531,7 @@ impl Tab { Tab::Queue => KeyContext::Queue, Tab::Federation => KeyContext::Federation, Tab::Logs => KeyContext::Logs, + Tab::Podcasts => KeyContext::Podcasts, } } } @@ -1646,6 +1665,169 @@ impl DevicePlaybackState { } } +/// Podcasts tab: subscriptions list, or the episode catalog of one opened +/// podcast. Only RSS metadata lives here; audio streams on demand. +#[derive(Debug, Default)] +pub struct PodcastsTab { + /// Subscriptions; `None` until the first load is requested. + pub list: Option>>, + /// Cursor over `podcast_list_rows` (action rows first, then podcasts). + pub selected: usize, + pub opened: Option, + /// Episodes of the opened podcast, keyed by its id so a late result for + /// a podcast that is no longer open is ignored. + pub episodes: Option<(i64, Loadable>)>, + /// Case-insensitive episode title filter; every word must match. + pub filter: String, + pub sort: EpisodeSort, + /// Feeds with a refresh in flight (spinner + dedup of requests). + pub refreshing: HashSet, + pub subscribing: bool, + /// Wall-clock seconds of the last automatic refresh sweep. + pub last_auto_refresh: Option, + /// Newly subscribed podcast to select once the reloaded list arrives. + pub pending_select: Option, +} + +/// "Add podcast" and "Check for new episodes" rows above the podcasts. +pub const PODCAST_ACTION_ROWS: usize = 2; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct OpenedPodcast { + pub id: i64, + /// Index into `visible_episode_indices`. + pub cursor: usize, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum EpisodeSort { + #[default] + NewestFirst, + OldestFirst, +} + +impl EpisodeSort { + pub fn toggle(self) -> Self { + match self { + EpisodeSort::NewestFirst => EpisodeSort::OldestFirst, + EpisodeSort::OldestFirst => EpisodeSort::NewestFirst, + } + } + + pub fn label(self) -> &'static str { + match self { + EpisodeSort::NewestFirst => "newest first", + EpisodeSort::OldestFirst => "oldest first", + } + } +} + +/// One row of the podcast subscriptions list. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PodcastListRow { + Add, + RefreshAll, + /// Index into the loaded podcast list. + Podcast(usize), +} + +impl PodcastsTab { + pub fn podcasts(&self) -> &[crate::podcasts::Podcast] { + match &self.list { + Some(Loadable::Ready(list)) => list, + _ => &[], + } + } + + pub fn podcast(&self, id: i64) -> Option<&crate::podcasts::Podcast> { + self.podcasts().iter().find(|podcast| podcast.id == id) + } + + pub fn list_rows(&self) -> Vec { + let mut rows = vec![PodcastListRow::Add, PodcastListRow::RefreshAll]; + rows.extend((0..self.podcasts().len()).map(PodcastListRow::Podcast)); + rows + } + + /// The podcast under the list cursor (list view) or the opened one. + pub fn current_podcast(&self) -> Option<&crate::podcasts::Podcast> { + if let Some(opened) = self.opened { + return self.podcast(opened.id); + } + match self.list_rows().get(self.selected)? { + PodcastListRow::Podcast(index) => self.podcasts().get(*index), + _ => None, + } + } + + /// Episodes of the opened podcast, when loaded. + pub fn opened_episodes(&self) -> Option<&[crate::podcasts::Episode]> { + let opened = self.opened?; + match &self.episodes { + Some((id, Loadable::Ready(episodes))) if *id == opened.id => Some(episodes), + _ => None, + } + } + + /// Indices into `opened_episodes()` after the title filter and sort. + pub fn visible_episode_indices(&self) -> Vec { + let Some(episodes) = self.opened_episodes() else { + return Vec::new(); + }; + visible_episode_indices(episodes, &self.filter, self.sort) + } + + pub fn selected_episode(&self) -> Option<&crate::podcasts::Episode> { + let opened = self.opened?; + let episodes = self.opened_episodes()?; + let visible = visible_episode_indices(episodes, &self.filter, self.sort); + visible + .get(opened.cursor.min(visible.len().saturating_sub(1))) + .and_then(|&index| episodes.get(index)) + } +} + +/// Filter by title (every whitespace-separated term, case-insensitively) +/// and order by publication date; undated episodes always go last. +pub fn visible_episode_indices( + episodes: &[crate::podcasts::Episode], + filter: &str, + sort: EpisodeSort, +) -> Vec { + let terms: Vec = filter.split_whitespace().map(str::to_lowercase).collect(); + let mut indices: Vec = episodes + .iter() + .enumerate() + .filter(|(_, episode)| { + if terms.is_empty() { + return true; + } + let title = episode.title.to_lowercase(); + terms.iter().all(|term| title.contains(term.as_str())) + }) + .map(|(index, _)| index) + .collect(); + indices.sort_by(|&a, &b| { + let (a_ep, b_ep) = (&episodes[a], &episodes[b]); + match (a_ep.published_at, b_ep.published_at) { + (Some(x), Some(y)) => match sort { + EpisodeSort::NewestFirst => y.cmp(&x), + EpisodeSort::OldestFirst => x.cmp(&y), + }, + (Some(_), None) => std::cmp::Ordering::Less, + (None, Some(_)) => std::cmp::Ordering::Greater, + (None, None) => std::cmp::Ordering::Equal, + } + // Stable sort keeps the store order (newest id first) for ties; + // reverse it for oldest-first so ties follow the same direction. + .then_with(|| match sort { + EpisodeSort::NewestFirst => a.cmp(&b), + EpisodeSort::OldestFirst => b.cmp(&a), + }) + }); + indices +} + /// Single source of truth for the UI. Mutated only by `update()` and the /// event handlers in the main loop; views render from `&AppState`. #[derive(Debug, Default)] @@ -1698,6 +1880,7 @@ pub struct AppState { pub queue_tab: QueueTab, pub federation: FederationTab, pub similarity: SimilarityTab, + pub podcasts: PodcastsTab, /// The one federated artist card being viewed (name + loading state); /// opening another card replaces it. pub fed_artist_view: Option<(String, Loadable)>, diff --git a/src/app/update.rs b/src/app/update.rs index 2fab271..71f8f5f 100644 --- a/src/app/update.rs +++ b/src/app/update.rs @@ -106,6 +106,13 @@ pub enum Effect { }, /// Load qualified listening history without blocking the UI thread. LoadListenHistory, + /// Load the episode catalog of one podcast (and refresh it when stale). + PodcastLoadEpisodes(i64), + /// Fetch an RSS feed and store it as a new subscription. + PodcastSubscribe(String), + /// Check these subscriptions for new episodes. + PodcastRefresh(Vec), + PodcastUnsubscribe(i64), } pub fn update(state: &mut AppState, action: Action) -> Option { @@ -283,6 +290,7 @@ pub fn update(state: &mut AppState, action: Action) -> Option { state.logs.selected_seq = None; state.logs.follow = true; } + Tab::Podcasts => podcasts_toggle_sort(state), _ => {} } None @@ -311,6 +319,15 @@ pub fn update(state: &mut AppState, action: Action) -> Option { state.cmdline.begin_history_navigation(); None } + Action::OpenSearch + if state.active_tab == Tab::Podcasts && state.podcasts.opened.is_some() => + { + state.popup = Some(super::state::Popup::FedInput { + field: super::state::FedInputField::PodcastFilter, + input: crate::app::input::LineEdit::new(state.podcasts.filter.clone()), + }); + None + } Action::OpenSearch => { // The command line opens pre-filled with "/": typing continues // the live search, exactly as if `:` then `/` were pressed. @@ -423,6 +440,10 @@ pub fn update(state: &mut AppState, action: Action) -> Option { state.popup = Some(super::state::Popup::AddToPlaylist { target, cursor: 0 }); state.track_selection.clear(); } + None if state.active_tab == Tab::Podcasts => { + state.status_message = + Some("podcast episodes cannot be added to playlists".into()); + } None => state.status_message = Some("no track selected".into()), } None @@ -470,11 +491,16 @@ pub fn update(state: &mut AppState, action: Action) -> Option { None } } + Action::EditSelected if state.active_tab == Tab::Podcasts => { + state.status_message = Some("podcast metadata comes from the RSS feed".into()); + None + } Action::EditSelected => { open_edit_popup(state); None } Action::DeleteSelected => delete_selected(state), + Action::RefreshPodcasts => podcasts_refresh(state), } } @@ -551,14 +577,22 @@ fn selected_playlist_target( return Some(super::state::PlaylistAddTarget::Fed(fed)); } - let local = selected_tracks(state); + // Playlists hold library rows; streamed podcast episodes have none. + let local: Vec = selected_tracks(state) + .into_iter() + .filter(|track| !crate::podcasts::is_remote_url(&track.file_path)) + .collect(); if !local.is_empty() { return Some(super::state::PlaylistAddTarget::Local(local)); } + if state.active_tab == Tab::Podcasts { + return None; + } include_current .then(|| state.player.current.clone()) .flatten() + .filter(|track| !crate::podcasts::is_remote_url(&track.file_path)) .map(|track| super::state::PlaylistAddTarget::Local(vec![track])) } @@ -691,6 +725,9 @@ fn delete_selected(state: &mut AppState) -> Option { if state.active_tab == Tab::Queue { return remove_selected_from_queue(state); } + if state.active_tab == Tab::Podcasts { + return podcasts_confirm_unsubscribe(state); + } if state.active_tab == Tab::Playlists { match state.playlists.opened { None => { @@ -1016,7 +1053,7 @@ fn current_track_list_context(state: &AppState) -> Option<(TrackSelectionScope, state.queue_tab.cursor, state.player.queue.len(), )), - Tab::Federation | Tab::Logs => None, + Tab::Federation | Tab::Logs | Tab::Podcasts => None, } } @@ -1070,11 +1107,14 @@ fn current_track_list(state: &AppState) -> Option<(TrackSelectionScope, usize, V state.queue_tab.cursor, state.player.queue.clone(), )), - Tab::Federation | Tab::Logs => None, + Tab::Federation | Tab::Logs | Tab::Podcasts => None, } } pub fn selected_tracks(state: &AppState) -> Vec { + if state.active_tab == Tab::Podcasts { + return selected_episode_track(state).into_iter().collect(); + } if state.active_tab == Tab::Global && state.search.similarity_source.is_some() && let Some(GlobalView::Search { cursor }) = state.global.stack.last() @@ -1371,7 +1411,7 @@ pub fn selected_track(state: &AppState) -> Option { .map(|track| (*track).clone()) } Tab::Queue => state.player.queue.get(state.queue_tab.cursor).cloned(), - Tab::Federation | Tab::Logs => None, + Tab::Federation | Tab::Logs | Tab::Podcasts => None, } } @@ -1775,6 +1815,10 @@ fn page_step(state: &AppState) -> isize { } fn move_selection(state: &mut AppState, dx: isize, dy: isize) { + if state.active_tab == Tab::Podcasts { + podcasts_move(state, dy); + return; + } if state.active_tab == Tab::Federation { if dy != 0 { let last = settings_rows(state).len() as isize - 1; @@ -2169,6 +2213,10 @@ fn jump_selection(state: &mut AppState, first: bool) { state.settings_cursor = if first { 0 } else { last }; return; } + if state.active_tab == Tab::Podcasts { + podcasts_move(state, if first { isize::MIN } else { isize::MAX }); + return; + } if state.active_tab == Tab::Logs { if first { let level = super::state::LOG_LEVELS[state.logs.level_index]; @@ -2259,6 +2307,9 @@ fn select_current(state: &mut AppState) -> Option { if state.active_tab == Tab::Federation { return federation_select(state); } + if state.active_tab == Tab::Podcasts { + return podcasts_select(state); + } // Queue: jump playback to the track under the cursor. Earlier tracks // stay in the queue as "played"; picking one of them just moves the // playing position back. @@ -3197,6 +3248,7 @@ fn go_back(state: &mut AppState) { Tab::Playlists => { state.playlists.opened = None; } + Tab::Podcasts => podcasts_close(state), Tab::Global => { // Esc on a view opened by Shift-J from another tab goes back to // that tab, not down the Global stack. @@ -3251,9 +3303,196 @@ fn reset_tab(state: &mut AppState, tab: Tab) { state.logs.selected_seq = None; } Tab::Queue => {} + Tab::Podcasts => podcasts_close(state), } } +// --------------------------------------------------------------------------- +// Podcasts tab +// --------------------------------------------------------------------------- + +/// How long a feed counts as fresh: opening it or the periodic sweep only +/// re-fetches feeds checked longer ago than this. +pub const PODCAST_STALE_SECS: i64 = 30 * 60; + +fn podcasts_move(state: &mut AppState, dy: isize) { + let tab = &mut state.podcasts; + let (cursor, len) = match tab.opened { + Some(opened) => (opened.cursor, tab.visible_episode_indices().len()), + None => (tab.selected, tab.list_rows().len()), + }; + if len == 0 { + return; + } + let target = (cursor as isize) + .saturating_add(dy) + .clamp(0, len as isize - 1) as usize; + match &mut tab.opened { + Some(opened) => opened.cursor = target, + None => tab.selected = target, + } +} + +fn podcasts_toggle_sort(state: &mut AppState) { + let tab = &mut state.podcasts; + tab.sort = tab.sort.toggle(); + if let Some(opened) = &mut tab.opened { + opened.cursor = 0; + } + state.status_message = Some(format!("episodes: {}", state.podcasts.sort.label())); +} + +/// Esc: episode catalog → subscriptions list. The filter belongs to the +/// catalog it was typed in, so it is dropped as well. +fn podcasts_close(state: &mut AppState) { + let tab = &mut state.podcasts; + if let Some(opened) = tab.opened.take() + && let Some(index) = tab.podcasts().iter().position(|p| p.id == opened.id) + { + tab.selected = index + super::state::PODCAST_ACTION_ROWS; + } + tab.filter.clear(); +} + +/// Called whenever the filter text changes: keep the cursor on the first +/// match so the list does not appear empty below a stale cursor. +pub fn podcasts_set_filter(state: &mut AppState, filter: String) { + // Caret movement and Enter on an unchanged filter keep the cursor. + if state.podcasts.filter == filter { + return; + } + state.podcasts.filter = filter; + if let Some(opened) = &mut state.podcasts.opened { + opened.cursor = 0; + } +} + +fn podcasts_select(state: &mut AppState) -> Option { + use super::state::PodcastListRow; + + if state.podcasts.opened.is_some() { + return play_selected_episode(state); + } + match state + .podcasts + .list_rows() + .get(state.podcasts.selected) + .copied()? + { + PodcastListRow::Add => { + if state.podcasts.subscribing { + state.status_message = + Some("podcasts: a subscription is already being added".into()); + return None; + } + state.popup = Some(super::state::Popup::FedInput { + field: super::state::FedInputField::PodcastFeedUrl, + input: crate::app::input::LineEdit::default(), + }); + None + } + PodcastListRow::RefreshAll => podcasts_refresh(state), + PodcastListRow::Podcast(index) => { + let id = state.podcasts.podcasts().get(index)?.id; + state.podcasts.opened = Some(super::state::OpenedPodcast { id, cursor: 0 }); + state.podcasts.filter.clear(); + if !matches!(&state.podcasts.episodes, Some((loaded, Loadable::Ready(_))) if *loaded == id) + { + state.podcasts.episodes = Some((id, Loadable::Loading)); + } + Some(Effect::PodcastLoadEpisodes(id)) + } + } +} + +/// Shift-R: the opened podcast, or every subscription from the list. +fn podcasts_refresh(state: &mut AppState) -> Option { + if state.active_tab != Tab::Podcasts { + return None; + } + let ids: Vec = match state.podcasts.opened { + Some(opened) => vec![opened.id], + None => state.podcasts.podcasts().iter().map(|p| p.id).collect(), + }; + let ids: Vec = ids + .into_iter() + .filter(|id| !state.podcasts.refreshing.contains(id)) + .collect(); + if ids.is_empty() { + state.status_message = Some(if state.podcasts.podcasts().is_empty() { + "podcasts: no subscriptions yet".into() + } else { + "podcasts: already checking for new episodes".into() + }); + return None; + } + state.podcasts.refreshing.extend(ids.iter().copied()); + state.status_message = Some(format!( + "podcasts: checking {} feed(s) for new episodes…", + ids.len() + )); + Some(Effect::PodcastRefresh(ids)) +} + +fn podcasts_confirm_unsubscribe(state: &mut AppState) -> Option { + if state.podcasts.opened.is_some() { + state.status_message = + Some("podcasts: go back to the podcast list (esc) to unsubscribe".into()); + return None; + } + let Some(podcast) = state.podcasts.current_podcast() else { + state.status_message = Some("podcasts: select a podcast to unsubscribe".into()); + return None; + }; + state.popup = Some(super::state::Popup::ConfirmDelete { + target: super::state::DeleteTarget::Podcast(podcast.id), + label: format!("podcast \"{}\"", podcast.title), + }); + None +} + +/// The queueable track for the episode under the cursor. +fn selected_episode_track(state: &AppState) -> Option { + let opened = state.podcasts.opened?; + let podcast = state.podcasts.podcast(opened.id)?; + let episode = state.podcasts.selected_episode()?; + Some(crate::podcasts::episode_track(podcast, episode)) +} + +/// Enter on an episode: play it right now without discarding the queue. It +/// is inserted after the current track and becomes the current track. +fn play_selected_episode(state: &mut AppState) -> Option { + let Some(track) = selected_episode_track(state) else { + state.status_message = Some(match state.podcasts.opened_episodes() { + Some(_) if !state.podcasts.filter.is_empty() => "no episode matches the filter".into(), + Some(_) => "this podcast has no episodes".into(), + None => "episodes are still loading".into(), + }); + return None; + }; + Some(play_track_now(state, track)) +} + +pub fn play_track_now(state: &mut AppState, track: TrackItem) -> Effect { + let player = &mut state.player; + let insert_at = if player.current.is_some() { + (player.queue_pos + 1).min(player.queue.len()) + } else { + player.queue_pos.min(player.queue.len()) + }; + player.queue.insert(insert_at, track); + if let Some(end) = player.play_next_end.as_mut() + && *end >= insert_at + { + *end += 1; + } + player.queue_pos = insert_at; + player.prefetched_pos = None; + normalize_play_next_block(player); + state.track_selection.clear(); + Effect::PlayCurrent +} + fn not_yet(state: &mut AppState, what: &str) { state.status_message = Some(format!("{what}: coming in a later milestone")); } diff --git a/src/app/update_tests.rs b/src/app/update_tests.rs index 8f57a03..02b5fb7 100644 --- a/src/app/update_tests.rs +++ b/src/app/update_tests.rs @@ -181,7 +181,7 @@ fn expired_quit_confirmation_rearms() { fn tab_cycling_wraps() { let mut state = AppState::default(); update(&mut state, Action::PrevTab); - assert_eq!(state.active_tab, Tab::Logs); + assert_eq!(state.active_tab, Tab::Podcasts); update(&mut state, Action::NextTab); assert_eq!(state.active_tab, Tab::Global); } @@ -1346,3 +1346,252 @@ fn card_refresh_animates_while_previous_results_stay_visible() { assert!(!render_enrichment_card(&state).contains("searching peers")); } } + +// --------------------------------------------------------------------------- +// Podcasts +// --------------------------------------------------------------------------- + +fn podcast(id: i64, title: &str) -> crate::podcasts::Podcast { + crate::podcasts::Podcast { + id, + feed_url: format!("https://example.test/{id}.xml"), + title: title.into(), + author: None, + description: None, + link: None, + image_url: None, + cover_path: None, + episode_count: 0, + latest_published_at: None, + last_checked_at: None, + last_error: None, + } +} + +fn episode(id: i64, title: &str, published_at: Option) -> crate::podcasts::Episode { + crate::podcasts::Episode { + id, + podcast_id: 7, + guid: format!("guid-{id}"), + title: title.into(), + description: None, + published_at, + duration_seconds: Some(60.0), + audio_url: format!("https://cdn.example.test/{id}.mp3"), + mime_type: Some("audio/mpeg".into()), + byte_len: None, + link: None, + image_url: None, + } +} + +/// Podcasts tab with podcast 7 opened and three episodes loaded in store +/// order (newest first) plus one undated episode. +fn podcasts_state() -> AppState { + use crate::app::state::OpenedPodcast; + let mut state = AppState { + active_tab: Tab::Podcasts, + ..AppState::default() + }; + state.podcasts.list = Some(Loadable::Ready(vec![ + podcast(3, "Another show"), + podcast(7, "Vivat"), + ])); + state.podcasts.opened = Some(OpenedPodcast { id: 7, cursor: 0 }); + state.podcasts.episodes = Some(( + 7, + Loadable::Ready(vec![ + episode(30, "Выпуск 3: Рим", Some(3_000)), + episode(20, "Выпуск 2: Греция", Some(2_000)), + episode(10, "Выпуск 1: Египет", Some(1_000)), + episode(5, "Бонус без даты", None), + ]), + )); + state +} + +#[test] +fn podcast_tab_is_reachable_by_number_without_shifting_other_tabs() { + let mut state = AppState::default(); + update(&mut state, Action::GoToTab(2)); + assert_eq!(state.active_tab, Tab::Queue); + update(&mut state, Action::GoToTab(5)); + assert_eq!(state.active_tab, Tab::Podcasts); +} + +#[test] +fn podcast_episode_filter_matches_every_word_case_insensitively() { + let mut state = podcasts_state(); + let titles = |state: &AppState| -> Vec { + let episodes = state.podcasts.opened_episodes().unwrap(); + state + .podcasts + .visible_episode_indices() + .into_iter() + .map(|index| episodes[index].title.clone()) + .collect() + }; + assert_eq!(titles(&state).len(), 4); + podcasts_set_filter(&mut state, "ВЫПУСК рим".into()); + assert_eq!(titles(&state), vec!["Выпуск 3: Рим"]); + podcasts_set_filter(&mut state, "nothing".into()); + assert!(titles(&state).is_empty()); + assert!(update(&mut state, Action::Select).is_none()); + assert_eq!( + state.status_message.as_deref(), + Some("no episode matches the filter") + ); +} + +#[test] +fn podcast_sort_toggles_and_keeps_undated_episodes_last() { + let mut state = podcasts_state(); + let ids = |state: &AppState| -> Vec { + let episodes = state.podcasts.opened_episodes().unwrap(); + state + .podcasts + .visible_episode_indices() + .into_iter() + .map(|index| episodes[index].id) + .collect() + }; + assert_eq!(ids(&state), vec![30, 20, 10, 5]); + state.podcasts.opened.as_mut().unwrap().cursor = 2; + update(&mut state, Action::ToggleViewMode); + assert_eq!(ids(&state), vec![10, 20, 30, 5]); + assert_eq!(state.podcasts.opened.unwrap().cursor, 0); +} + +#[test] +fn podcast_search_key_opens_the_episode_filter_not_library_search() { + use crate::app::state::{FedInputField, Popup}; + let mut state = podcasts_state(); + update(&mut state, Action::OpenSearch); + assert_eq!(state.active_tab, Tab::Podcasts); + assert!(!state.cmdline.active); + assert!(matches!( + state.popup, + Some(Popup::FedInput { + field: FedInputField::PodcastFilter, + .. + }) + )); +} + +#[test] +fn enter_on_episode_plays_it_now_and_keeps_the_queue() { + let mut state = podcasts_state(); + state.player.queue = vec![test_track(1), test_track(2)]; + state.player.queue_pos = 0; + state.player.current = Some(test_track(1)); + state.podcasts.opened.as_mut().unwrap().cursor = 1; + + assert_eq!( + update(&mut state, Action::Select), + Some(Effect::PlayCurrent) + ); + assert_eq!(state.player.queue.len(), 3); + assert_eq!(state.player.queue_pos, 1); + let queued = &state.player.queue[1]; + assert_eq!(queued.title, "Выпуск 2: Греция"); + assert_eq!(queued.file_path, "https://cdn.example.test/20.mp3"); + assert_eq!(queued.release_title, "Vivat"); + assert_eq!( + crate::podcasts::episode_id_from_track_id(queued.id), + Some(20) + ); + // The music that was queued after the current track still follows. + assert_eq!(state.player.queue[2].id, 2); +} + +#[test] +fn episode_can_be_queued_with_the_regular_queue_keys() { + let mut state = podcasts_state(); + state.player.queue = vec![test_track(1)]; + state.player.current = Some(test_track(1)); + update(&mut state, Action::QueueAddLast); + assert_eq!(state.player.queue.len(), 2); + assert_eq!(state.player.queue[1].title, "Выпуск 3: Рим"); + assert_eq!(state.player.queue_pos, 0); +} + +#[test] +fn podcast_list_rows_open_add_refresh_and_podcasts() { + use crate::app::state::{FedInputField, PODCAST_ACTION_ROWS, Popup}; + let mut state = podcasts_state(); + update(&mut state, Action::Back); + assert!(state.podcasts.opened.is_none()); + // Esc returns to the row of the podcast that was open. + assert_eq!(state.podcasts.selected, PODCAST_ACTION_ROWS + 1); + + update(&mut state, Action::SelectFirst); + assert_eq!(state.podcasts.selected, 0); + assert!(update(&mut state, Action::Select).is_none()); + assert!(matches!( + state.popup, + Some(Popup::FedInput { + field: FedInputField::PodcastFeedUrl, + .. + }) + )); + state.popup = None; + + update(&mut state, Action::MoveDown); + assert_eq!( + update(&mut state, Action::Select), + Some(Effect::PodcastRefresh(vec![3, 7])) + ); + // A second request while those are running is not duplicated. + assert_eq!(update(&mut state, Action::RefreshPodcasts), None); + + update(&mut state, Action::MoveDown); + state.podcasts.episodes = None; + assert_eq!( + update(&mut state, Action::Select), + Some(Effect::PodcastLoadEpisodes(3)) + ); + assert_eq!(state.podcasts.opened.map(|opened| opened.id), Some(3)); + assert!(matches!( + state.podcasts.episodes, + Some((3, Loadable::Loading)) + )); +} + +#[test] +fn unsubscribe_asks_for_confirmation_from_the_list_only() { + use crate::app::state::{DeleteTarget, PODCAST_ACTION_ROWS, Popup}; + let mut state = podcasts_state(); + assert!(update(&mut state, Action::DeleteSelected).is_none()); + assert!(state.popup.is_none()); + + update(&mut state, Action::Back); + state.podcasts.selected = PODCAST_ACTION_ROWS; + update(&mut state, Action::DeleteSelected); + assert!(matches!( + state.popup, + Some(Popup::ConfirmDelete { + target: DeleteTarget::Podcast(3), + .. + }) + )); +} + +#[test] +fn podcast_cursor_stays_inside_the_filtered_list() { + let mut state = podcasts_state(); + update(&mut state, Action::SelectLast); + assert_eq!(state.podcasts.opened.unwrap().cursor, 3); + podcasts_set_filter(&mut state, "выпуск".into()); + assert_eq!(state.podcasts.opened.unwrap().cursor, 0); + update(&mut state, Action::PageDown); + assert_eq!(state.podcasts.opened.unwrap().cursor, 2); +} + +#[test] +fn unchanged_podcast_filter_keeps_the_episode_cursor() { + let mut state = podcasts_state(); + podcasts_set_filter(&mut state, "выпуск".into()); + state.podcasts.opened.as_mut().unwrap().cursor = 2; + podcasts_set_filter(&mut state, "выпуск".into()); + assert_eq!(state.podcasts.opened.unwrap().cursor, 2); +} diff --git a/src/config/default_keymap.toml b/src/config/default_keymap.toml index 06d62dd..e99210a 100644 --- a/src/config/default_keymap.toml +++ b/src/config/default_keymap.toml @@ -9,7 +9,7 @@ # command: an Action name, optionally with parameters: # command = { SeekForward = { seconds = 30 } } # context: optional view filter — global (default), library, search, -# playlists, queue, logs. +# playlists, queue, settings, logs, podcasts. [[keymaps]] key_sequence = "q" @@ -51,6 +51,10 @@ command = { GoToTab = 3 } key_sequence = "5" command = { GoToTab = 4 } +[[keymaps]] +key_sequence = "6" +command = { GoToTab = 5 } + [[keymaps]] key_sequence = "y" command = "DownloadSelected" @@ -255,3 +259,8 @@ command = "OpenCommandLine" [[keymaps]] key_sequence = "/" command = "OpenSearch" + +[[keymaps]] +key_sequence = "shift-r" +command = "RefreshPodcasts" +context = "podcasts" diff --git a/src/config/keymap.rs b/src/config/keymap.rs index 444b1e2..d21362f 100644 --- a/src/config/keymap.rs +++ b/src/config/keymap.rs @@ -23,6 +23,7 @@ pub enum KeyContext { #[serde(rename = "settings", alias = "federation")] Federation, Logs, + Podcasts, } impl KeyContext { @@ -35,6 +36,7 @@ impl KeyContext { KeyContext::Queue => "queue", KeyContext::Federation => "settings", KeyContext::Logs => "logs", + KeyContext::Podcasts => "podcasts", } } } diff --git a/src/devices.rs b/src/devices.rs index 60259c1..684123a 100644 --- a/src/devices.rs +++ b/src/devices.rs @@ -131,6 +131,12 @@ pub struct PlaybackTrack { pub fed: Option, } +/// The part of a track's `file_path` that may cross devices: only http(s) +/// stream URLs (podcast episodes), never local filesystem paths. +fn portable_remote_url(file_path: &str) -> Option { + crate::podcasts::is_remote_url(file_path).then(|| file_path.to_string()) +} + impl PlaybackTrack { fn portable_placeholder_id(&self) -> i64 { let key = self @@ -183,7 +189,9 @@ impl PlaybackTrack { release_id: track.release_id, release_title: track.release_title.clone(), release_year: track.release_year, - file_path: String::new(), + // Local paths stay private; a streamed podcast episode's URL is + // the only way another device can play it. + file_path: portable_remote_url(&track.file_path).unwrap_or_default(), content_id: track .content_id .clone() @@ -208,8 +216,16 @@ impl PlaybackTrack { }) .collect() }; + // A podcast episode keeps its episode-range id and stream URL, so the + // queue entry stays the same track across devices and round trips. + let episode_url = portable_remote_url(&self.file_path) + .filter(|_| crate::podcasts::episode_id_from_track_id(self.id).is_some()); TrackItem { - id: self.portable_placeholder_id(), + id: if episode_url.is_some() { + self.id + } else { + self.portable_placeholder_id() + }, title: self.title.clone(), track_number: self.track_number, disc_number: self.disc_number, @@ -219,7 +235,7 @@ impl PlaybackTrack { release_id: self.release_id, release_title: self.release_title.clone(), release_year: self.release_year, - file_path: String::new(), + file_path: episode_url.unwrap_or_default(), content_id: self.content_id.clone(), cover_path: None, audio_format: self.audio_format.clone(), diff --git a/src/devices/tests.rs b/src/devices/tests.rs index a47a0cc..f17d1d2 100644 --- a/src/devices/tests.rs +++ b/src/devices/tests.rs @@ -936,3 +936,54 @@ fn stale_synced_playlist_item_metadata_repairs_pending_fed_track() { assert!(detail.tracks[0].is_fed_pending()); assert_eq!(detail.tracks[0].title, fed.title); } + +#[test] +fn podcast_episode_survives_the_playback_wire_but_local_paths_do_not() { + let podcast = crate::podcasts::Podcast { + id: 1, + feed_url: "https://example.test/feed.xml".into(), + title: "Show".into(), + author: None, + description: None, + link: None, + image_url: None, + cover_path: Some("/home/user/.cache/cover.jpg".into()), + episode_count: 1, + latest_published_at: None, + last_checked_at: None, + last_error: None, + }; + let episode = crate::podcasts::Episode { + id: 42, + podcast_id: 1, + guid: "g".into(), + title: "Episode".into(), + description: None, + published_at: None, + duration_seconds: Some(60.0), + audio_url: "https://cdn.example.test/42.mp3".into(), + mime_type: Some("audio/mpeg".into()), + byte_len: None, + link: None, + image_url: None, + }; + let track = crate::podcasts::episode_track(&podcast, &episode); + let round_trip = PlaybackTrack::from_track(&track).to_track_item(); + assert_eq!(round_trip.id, track.id); + assert_eq!(round_trip.file_path, episode.audio_url); + assert_eq!( + crate::app::state::track_key(&round_trip), + crate::app::state::track_key(&track) + ); + + // Local files never leak their path; a URL without an episode id is + // not trusted as a stream either. + let mut local = track.clone(); + local.id = 7; + local.file_path = "/home/user/Music/a.flac".into(); + assert!(PlaybackTrack::from_track(&local).file_path.is_empty()); + local.file_path = "https://cdn.example.test/other.mp3".into(); + let wire = PlaybackTrack::from_track(&local); + assert_eq!(wire.file_path, "https://cdn.example.test/other.mp3"); + assert!(wire.to_track_item().file_path.is_empty()); +} diff --git a/src/main.rs b/src/main.rs index a540345..097eef3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,6 +7,7 @@ mod jam; mod library; mod media; mod player; +mod podcasts; mod share; mod similarity; mod status; diff --git a/src/player/mod.rs b/src/player/mod.rs index f25d167..5724a95 100644 --- a/src/player/mod.rs +++ b/src/player/mod.rs @@ -51,6 +51,12 @@ enum Command { seekable: bool, volume: f32, }, + /// Play a source that was already probed and decoded off this thread + /// (remote podcast streams, whose probing waits on the network). + PlaySource { + source: DecodedSource, + volume: f32, + }, /// Append the next track behind the current one without interrupting /// playback — rodio switches sources back to back (gapless-ish). Enqueue { @@ -122,6 +128,12 @@ impl Controller { }); } + /// Play an already decoded source, built with `decode_source_with` + /// outside the audio thread. + pub fn play_source(&self, source: DecodedSource, volume: f32) { + let _ = self.tx.send(Command::PlaySource { source, volume }); + } + pub fn enqueue(&self, reader: TrackReader, byte_len: Option) { let _ = self.tx.send(Command::Enqueue { reader, byte_len }); } @@ -186,7 +198,10 @@ fn run( if !playback_allowed.load(Ordering::Acquire) && matches!( command, - Command::Play { .. } | Command::Enqueue { .. } | Command::Resume + Command::Play { .. } + | Command::PlaySource { .. } + | Command::Enqueue { .. } + | Command::Resume ) { continue; @@ -236,43 +251,21 @@ fn handle( seekable, volume, } => { - // The device is opened lazily on first playback so the app works - // on machines with no audio output until you actually press play. - if output.is_none() { - match DeviceSinkBuilder::open_default_sink() { - Ok(device) => { - let player = Player::connect_new(device.mixer()); - *output = Some(Output { - _device: device, - player, - }); - } - Err(err) => { - on_event(PlayerEvent::Failed(format!("no audio device: {err}"))); - return; - } - } - } - let out = output.as_ref().expect("output opened above"); - + let Some(out) = ensure_output(output, on_event) else { + return; + }; match decode_source(reader, byte_len, mime_type.as_deref(), seekable) { - Ok(source) => { - shared.analysis.clear(); - out.player.stop(); - out.player.set_volume(volume); - out.player.append(analyzer::AnalyzedSource::new( - source, - Arc::clone(&shared.analysis), - )); - out.player.play(); - *track_loaded = true; - on_event(PlayerEvent::Started); - } + Ok(source) => start_source(out, source, volume, shared, track_loaded, on_event), Err(err) => { on_event(PlayerEvent::Failed(format!("cannot decode track: {err}"))); } } } + Command::PlaySource { source, volume } => { + if let Some(out) = ensure_output(output, on_event) { + start_source(out, source, volume, shared, track_loaded, on_event); + } + } Command::Enqueue { reader, byte_len } => { let Some(out) = output.as_ref() else { return; @@ -322,13 +315,71 @@ fn handle( } } +/// The device is opened lazily on first playback so the app works on +/// machines with no audio output until you actually press play. +fn ensure_output<'a>( + output: &'a mut Option, + on_event: &impl Fn(PlayerEvent), +) -> Option<&'a Output> { + if output.is_none() { + match DeviceSinkBuilder::open_default_sink() { + Ok(device) => { + let player = Player::connect_new(device.mixer()); + *output = Some(Output { + _device: device, + player, + }); + } + Err(err) => { + on_event(PlayerEvent::Failed(format!("no audio device: {err}"))); + return None; + } + } + } + output.as_ref() +} + +/// Replace whatever is playing with `source`. +fn start_source( + out: &Output, + source: DecodedSource, + volume: f32, + shared: &Shared, + track_loaded: &mut bool, + on_event: &impl Fn(PlayerEvent), +) { + shared.analysis.clear(); + out.player.stop(); + out.player.set_volume(volume); + out.player.append(analyzer::AnalyzedSource::new( + source, + Arc::clone(&shared.analysis), + )); + out.player.play(); + *track_loaded = true; + on_event(PlayerEvent::Started); +} + pub(crate) type DecodedSource = Box; pub(crate) fn decode_source( + reader: TrackReader, + byte_len: Option, + mime_type: Option<&str>, + seekable: bool, +) -> Result { + decode_source_with(reader, byte_len, mime_type, seekable, false) +} + +/// `decode_source` with optional coarse (byte-estimate) seeking, which +/// remote streams need: an accurate MP3 seek decodes every frame before the +/// target, i.e. downloads it. +pub(crate) fn decode_source_with( mut reader: TrackReader, byte_len: Option, mime_type: Option<&str>, seekable: bool, + coarse_seek: bool, ) -> Result { let mime_is_opus = mime_type.is_some_and(|mime| { let mime = mime.to_ascii_lowercase(); @@ -344,6 +395,7 @@ pub(crate) fn decode_source( let mut builder = Decoder::builder() .with_data(reader) .with_seekable(seekable) + .with_coarse_seek(coarse_seek) .with_gapless(true); if let Some(len) = byte_len { builder = builder.with_byte_len(len); diff --git a/src/podcasts/feed.rs b/src/podcasts/feed.rs new file mode 100644 index 0000000..7b531c8 --- /dev/null +++ b/src/podcasts/feed.rs @@ -0,0 +1,1576 @@ +//! Tolerant RSS 2.0 / RSS 1.0 / Atom parser for podcast feeds. +//! +//! Real-world feeds are frequently sloppy: undeclared namespace prefixes, +//! HTML entities that XML does not define, mismatched closing tags, legacy +//! single-byte encodings and creative date formats. The parser is a single +//! iterative pass over `quick-xml` events (no recursion), keeps only the +//! fields Furumi needs and never panics on malformed input. + +use std::borrow::Cow; +use std::collections::HashSet; + +use anyhow::{Result, bail}; +use quick_xml::events::{BytesStart, Event}; +use quick_xml::reader::Reader; +use reqwest::Url; + +/// Upper bound on episodes taken from a single feed document. +pub const MAX_EPISODES: usize = 20_000; +/// Upper bound (in characters) for plain-text descriptions. +pub const MAX_DESCRIPTION_CHARS: usize = 4000; +/// Upper bound (in characters) for titles and other short fields. +const MAX_SHORT_CHARS: usize = 1000; +/// Raw text captured for one element is capped to keep memory bounded on +/// hostile or broken documents. +const MAX_CAPTURE_BYTES: usize = 512 * 1024; +/// Elements nested deeper than this are skipped (their events are ignored). +const MAX_DEPTH: usize = 256; +const UNTITLED_EPISODE: &str = "Untitled episode"; +const UNTITLED_PODCAST: &str = "Untitled podcast"; + +#[derive(Debug, Clone, PartialEq)] +pub struct ParsedFeed { + pub title: String, + pub author: Option, + pub description: Option, + pub link: Option, + pub image_url: Option, + pub episodes: Vec, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct ParsedEpisode { + pub guid: String, + pub title: String, + pub description: Option, + pub published_at: Option, + pub duration_seconds: Option, + pub audio_url: String, + pub mime_type: Option, + pub byte_len: Option, + pub link: Option, + pub image_url: Option, +} + +/// Parses an RSS or Atom document. Fails for documents that are not feeds +/// (for example an HTML page) with "not an RSS or Atom feed". +/// +/// Without a base URL, relative media URLs cannot be resolved and such +/// episodes are dropped; prefer [`parse_feed_with_base`] when the feed URL is +/// known. +#[cfg(test)] +pub fn parse_feed(bytes: &[u8]) -> Result { + parse_feed_with_base(bytes, None) +} + +/// [`parse_feed`] resolving relative enclosure and image URLs against +/// `base_url` (the final URL the feed was fetched from). Episodes whose audio +/// URL does not resolve to an absolute `http`/`https` URL are dropped, so a +/// feed can never point playback at a local file. +pub fn parse_feed_with_base(bytes: &[u8], base_url: Option<&str>) -> Result { + let text = decode_document(bytes); + let parser = Parser { + base: base_url.and_then(|base| Url::parse(base).ok()), + ..Parser::default() + }; + parser.run(&text) +} + +// --------------------------------------------------------------------------- +// Character encoding + +/// Decodes the raw document to UTF-8. A BOM wins; otherwise an ASCII-compatible +/// encoding named in the XML declaration (windows-1251, koi8-r, ...) is +/// honoured; everything else is decoded as lossy UTF-8. +fn decode_document(bytes: &[u8]) -> Cow<'_, str> { + if let Some((encoding, bom_len)) = encoding_rs::Encoding::for_bom(bytes) { + let (text, _) = encoding.decode_without_bom_handling(&bytes[bom_len..]); + return text; + } + if let Some(encoding) = declared_encoding(bytes).and_then(encoding_rs::Encoding::for_label) + && encoding != encoding_rs::UTF_8 + && encoding.is_ascii_compatible() + { + let (text, _) = encoding.decode_without_bom_handling(bytes); + return text; + } + String::from_utf8_lossy(bytes) +} + +/// The `encoding="..."` label of a leading XML declaration, if any. +fn declared_encoding(bytes: &[u8]) -> Option<&[u8]> { + let head = &bytes[..bytes.len().min(512)]; + let start = head.iter().position(|b| !b.is_ascii_whitespace())?; + let head = &head[start..]; + if !head.starts_with(b"")?; + let decl = &head[..end]; + let at = find(decl, b"encoding")? + b"encoding".len(); + let rest = &decl[at..]; + let rest = &rest[rest.iter().position(|b| !b.is_ascii_whitespace())?..]; + let rest = rest.strip_prefix(b"=")?; + let rest = &rest[rest.iter().position(|b| !b.is_ascii_whitespace())?..]; + let quote = *rest.first()?; + if quote != b'"' && quote != b'\'' { + return None; + } + let rest = &rest[1..]; + let len = rest.iter().position(|&b| b == quote)?; + Some(&rest[..len]) +} + +fn find(haystack: &[u8], needle: &[u8]) -> Option { + haystack + .windows(needle.len()) + .position(|window| window == needle) +} + +// --------------------------------------------------------------------------- +// Namespaces + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Ns { + /// No namespace, or the RSS 0.9x/1.0 namespace. + Plain, + Atom, + Itunes, + Content, + Media, + Dc, + Other, +} + +fn classify_uri(uri: &str) -> Ns { + let uri = uri.trim().to_ascii_lowercase(); + if uri.is_empty() { + Ns::Plain + } else if uri.contains("w3.org/2005/atom") { + Ns::Atom + } else if uri.contains("itunes.com/dtds/podcast") { + Ns::Itunes + } else if uri.contains("purl.org/rss/1.0/modules/content") { + Ns::Content + } else if uri.contains("search.yahoo.com/mrss") { + Ns::Media + } else if uri.contains("purl.org/dc/elements") { + Ns::Dc + } else if uri.contains("purl.org/rss/1.0") + || uri.contains("my.netscape.com/rdf") + || uri.contains("backend.userland.com/rss") + { + Ns::Plain + } else { + Ns::Other + } +} + +/// Classification of a prefix nobody declared (common in sloppy feeds). +fn classify_prefix(prefix: &str) -> Ns { + match prefix.to_ascii_lowercase().as_str() { + "" => Ns::Plain, + "itunes" => Ns::Itunes, + "content" => Ns::Content, + "media" => Ns::Media, + "dc" => Ns::Dc, + "atom" | "atom10" => Ns::Atom, + _ => Ns::Other, + } +} + +// --------------------------------------------------------------------------- +// Parser state + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Kind { + Rss, + Atom, +} + +#[derive(Debug)] +struct Elem { + ns: Ns, + /// ASCII-lowercased local name. + local: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Field { + FeedTitle, + FeedDescription, + FeedItunesSummary, + FeedLink, + FeedItunesAuthor, + FeedAtomAuthor, + FeedDcCreator, + FeedManagingEditor, + FeedImageUrl, + FeedLogo, + FeedIcon, + ItemTitle, + ItemItunesTitle, + ItemDescription, + ItemContent, + ItemSummary, + ItemGuid, + ItemPubDate, + ItemDcDate, + ItemUpdated, + ItemDuration, + ItemLink, +} + +#[derive(Debug)] +struct Capture { + /// Stack depth of the captured element. + depth: usize, + field: Field, + text: String, +} + +#[derive(Debug, Default)] +struct FeedAcc { + title: Option, + description: Option, + itunes_summary: Option, + link: Option, + itunes_author: Option, + atom_author: Option, + dc_creator: Option, + managing_editor: Option, + itunes_image: Option, + image_url: Option, + logo: Option, + icon: Option, +} + +#[derive(Debug, Clone)] +struct Media { + url: String, + mime: Option, + len: Option, +} + +#[derive(Debug, Default)] +struct ItemAcc { + title: Option, + itunes_title: Option, + description: Option, + content: Option, + summary: Option, + guid: Option, + pub_date: Option, + dc_date: Option, + updated: Option, + duration: Option, + link: Option, + enclosure: Option, + media_content: Option, + itunes_image: Option, + thumbnail: Option, +} + +#[derive(Debug, Default)] +struct Parser { + kind: Option, + stack: Vec, + /// Namespace declarations: (depth of declaring element, prefix, uri). + ns_decls: Vec<(usize, String, String)>, + /// Start tags ignored because they exceeded `MAX_DEPTH`. + skipped_depth: usize, + capture: Option, + feed: FeedAcc, + item: Option, + item_depth: usize, + episodes: Vec, + seen_guids: HashSet, + full: bool, + /// URL the document was fetched from, for relative media URLs. + base: Option, +} + +/// Sets `slot` unless it already holds a value (first occurrence wins). +fn set_once(slot: &mut Option, value: String) { + if slot.is_none() && !value.trim().is_empty() { + *slot = Some(value); + } +} + +impl Parser { + fn run(mut self, text: &str) -> Result { + let mut reader = Reader::from_str(text); + { + let config = reader.config_mut(); + config.check_end_names = false; + config.allow_unmatched_ends = true; + config.allow_dangling_amp = true; + config.expand_empty_elements = false; + config.trim_text(false); + } + let mut malformed = None; + loop { + match reader.read_event() { + Ok(Event::Eof) => break, + Ok(event) => { + self.handle(event)?; + if self.full { + break; + } + } + Err(err) => { + if self.kind.is_none() { + bail!("not an RSS or Atom feed (invalid XML: {err})"); + } + malformed = Some(err.to_string()); + break; + } + } + } + if self.kind.is_none() { + bail!("not an RSS or Atom feed"); + } + if let Some(err) = malformed { + if self.episodes.is_empty() { + bail!("malformed feed: {err}"); + } + tracing::warn!("podcast feed is malformed, keeping what parsed: {err}"); + } + Ok(self.finish()) + } + + fn handle(&mut self, event: Event<'_>) -> Result<()> { + match event { + Event::Start(start) => self.on_start(&start, false)?, + Event::Empty(start) => self.on_start(&start, true)?, + Event::End(end) => { + let name = end.name(); + let local = local_name(name.as_ref()); + self.on_end(&local); + } + Event::Text(text) => { + if let Some(capture) = self.capture.as_mut() { + match text.xml10_content() { + Ok(value) => push_capped(&mut capture.text, &value), + Err(_) => push_capped(&mut capture.text, &String::from_utf8_lossy(&text)), + } + } + } + Event::CData(data) => { + if let Some(capture) = self.capture.as_mut() { + match data.decode() { + Ok(value) => push_capped(&mut capture.text, &value), + Err(_) => push_capped(&mut capture.text, &String::from_utf8_lossy(&data)), + } + } + } + Event::GeneralRef(reference) => { + if let Some(capture) = self.capture.as_mut() { + let raw = String::from_utf8_lossy(&reference); + match resolve_entity(&raw) { + Some(ch) => push_capped(&mut capture.text, ch.encode_utf8(&mut [0; 4])), + None => { + // Keep unknown entities verbatim instead of failing. + push_capped(&mut capture.text, "&"); + push_capped(&mut capture.text, &raw); + push_capped(&mut capture.text, ";"); + } + } + } + } + Event::Comment(_) | Event::Decl(_) | Event::PI(_) | Event::DocType(_) | Event::Eof => {} + } + Ok(()) + } + + fn resolve_ns(&self, prefix: &str) -> Ns { + for (_, declared, uri) in self.ns_decls.iter().rev() { + if declared == prefix { + return classify_uri(uri); + } + } + classify_prefix(prefix) + } + + fn on_start(&mut self, start: &BytesStart<'_>, empty: bool) -> Result<()> { + if self.stack.len() >= MAX_DEPTH { + if !empty { + self.skipped_depth += 1; + } + return Ok(()); + } + let depth = self.stack.len() + 1; + let attrs = Attrs::collect(start); + for (key, value) in &attrs.raw { + if key == "xmlns" { + self.ns_decls.push((depth, String::new(), value.clone())); + } else if let Some(prefix) = key.strip_prefix("xmlns:") { + self.ns_decls + .push((depth, prefix.to_string(), value.clone())); + } + } + let qname = start.name(); + let (prefix, local) = split_qname(qname.as_ref()); + let mut ns = self.resolve_ns(&prefix); + if self.kind == Some(Kind::Rss) && prefix.is_empty() && matches!(ns, Ns::Atom | Ns::Other) { + // RSS has no namespace of its own; an unprefixed element is a core + // RSS element whatever default namespace the publisher declared. + ns = Ns::Plain; + } + self.stack.push(Elem { ns, local }); + + if self.kind.is_none() { + let local = self.stack[0].local.as_str(); + self.kind = match local { + "rss" | "rdf" => Some(Kind::Rss), + "feed" => Some(Kind::Atom), + _ => bail!("not an RSS or Atom feed (root element <{local}>)"), + }; + } else if let Some(capture) = self.capture.as_mut() { + // Markup nested in a captured field (e.g. Atom xhtml content): + // keep words apart. + push_capped(&mut capture.text, " "); + } else { + self.dispatch_start(&attrs); + } + + if empty { + self.close_top(); + } + Ok(()) + } + + fn dispatch_start(&mut self, attrs: &Attrs) { + let Some(kind) = self.kind else { return }; + let depth = self.stack.len(); + let local_at = |back: usize| { + depth + .checked_sub(back) + .and_then(|index| self.stack.get(index)) + .map(|elem| elem.local.clone()) + .unwrap_or_default() + }; + let ns = self.stack[depth - 1].ns; + let local = local_at(1); + let parent = local_at(2); + let grandparent = local_at(3); + let core = match kind { + Kind::Rss => ns == Ns::Plain, + Kind::Atom => matches!(ns, Ns::Plain | Ns::Atom), + }; + + if self.item.is_some() { + let direct = depth == self.item_depth + 1; + if let Some(field) = self.item_field(kind, ns, core, &local, direct, attrs) { + self.begin_capture(field); + } + return; + } + + let is_item = match kind { + Kind::Rss => core && local == "item", + Kind::Atom => core && local == "entry", + }; + if is_item { + self.item = Some(ItemAcc::default()); + self.item_depth = depth; + return; + } + + let feed_level = match kind { + Kind::Rss => parent == "channel", + Kind::Atom => depth == 2, + }; + let field = if feed_level { + self.feed_field(kind, ns, core, &local, attrs) + } else if kind == Kind::Rss + && core + && local == "url" + && parent == "image" + && matches!(grandparent.as_str(), "channel" | "rdf") + { + Some(Field::FeedImageUrl) + } else if kind == Kind::Atom && core && local == "name" && parent == "author" && depth == 3 + { + Some(Field::FeedAtomAuthor) + } else { + None + }; + if let Some(field) = field { + self.begin_capture(field); + } + } + + fn feed_field( + &mut self, + kind: Kind, + ns: Ns, + core: bool, + local: &str, + attrs: &Attrs, + ) -> Option { + if core { + return match (kind, local) { + (_, "title") => Some(Field::FeedTitle), + (Kind::Rss, "description") | (Kind::Atom, "subtitle") => { + Some(Field::FeedDescription) + } + (Kind::Rss, "link") => Some(Field::FeedLink), + (Kind::Rss, "managingeditor") => Some(Field::FeedManagingEditor), + (Kind::Atom, "link") => { + let rel = attrs.get("rel").unwrap_or_default().to_ascii_lowercase(); + if rel.is_empty() || rel == "alternate" { + let href = attrs.get("href").unwrap_or_default(); + set_once(&mut self.feed.link, clean_short(&href)); + } + None + } + (Kind::Atom, "logo") => Some(Field::FeedLogo), + (Kind::Atom, "icon") => Some(Field::FeedIcon), + _ => None, + }; + } + match (ns, local) { + (Ns::Itunes, "author") => Some(Field::FeedItunesAuthor), + (Ns::Itunes, "summary") => Some(Field::FeedItunesSummary), + (Ns::Itunes, "image") => { + if let Some(href) = attrs.get("href") { + set_once(&mut self.feed.itunes_image, clean_short(&href)); + } + None + } + (Ns::Dc, "creator") => Some(Field::FeedDcCreator), + _ => None, + } + } + + fn item_field( + &mut self, + kind: Kind, + ns: Ns, + core: bool, + local: &str, + direct: bool, + attrs: &Attrs, + ) -> Option { + let item = self.item.as_mut()?; + // Media RSS may wrap content in , so accept any depth. + if ns == Ns::Media { + match local { + "content" => { + let url = attrs.get("url").unwrap_or_default(); + let mime = attrs.get("type"); + let medium = attrs.get("medium"); + if item.media_content.is_none() + && is_playable(&url, mime.as_deref(), medium.as_deref(), false) + { + item.media_content = Some(Media { + url: url.trim().to_string(), + mime: clean_mime(mime.as_deref()), + len: parse_len(attrs.get("filesize")), + }); + } + } + "thumbnail" => { + if let Some(url) = attrs.get("url") { + set_once(&mut item.thumbnail, clean_short(&url)); + } + } + _ => {} + } + return None; + } + if !direct { + return None; + } + if core { + return match (kind, local) { + (_, "title") => Some(Field::ItemTitle), + (Kind::Rss, "description") => Some(Field::ItemDescription), + (Kind::Rss, "guid") | (Kind::Atom, "id") => Some(Field::ItemGuid), + (Kind::Rss, "pubdate") | (Kind::Atom, "published") => Some(Field::ItemPubDate), + (Kind::Atom, "updated") => Some(Field::ItemUpdated), + (Kind::Rss, "link") => Some(Field::ItemLink), + (Kind::Atom, "summary") => Some(Field::ItemDescription), + (Kind::Atom, "content") => Some(Field::ItemContent), + (Kind::Rss, "enclosure") => { + let url = attrs.get("url").unwrap_or_default(); + let mime = attrs.get("type"); + if item.enclosure.is_none() && is_playable(&url, mime.as_deref(), None, true) { + item.enclosure = Some(Media { + url: url.trim().to_string(), + mime: clean_mime(mime.as_deref()), + len: parse_len(attrs.get("length")), + }); + } + None + } + (Kind::Atom, "link") => { + let rel = attrs.get("rel").unwrap_or_default().to_ascii_lowercase(); + let href = attrs.get("href").unwrap_or_default(); + let mime = attrs.get("type"); + if rel == "enclosure" { + if item.enclosure.is_none() + && is_playable(&href, mime.as_deref(), None, true) + { + item.enclosure = Some(Media { + url: href.trim().to_string(), + mime: clean_mime(mime.as_deref()), + len: parse_len(attrs.get("length")), + }); + } + } else if rel.is_empty() || rel == "alternate" { + set_once(&mut item.link, clean_short(&href)); + } + None + } + _ => None, + }; + } + match (ns, local) { + (Ns::Itunes, "title") => Some(Field::ItemItunesTitle), + (Ns::Itunes, "summary") => Some(Field::ItemSummary), + (Ns::Itunes, "duration") => Some(Field::ItemDuration), + (Ns::Itunes, "image") => { + if let Some(href) = attrs.get("href") { + set_once(&mut item.itunes_image, clean_short(&href)); + } + None + } + (Ns::Content, "encoded") => Some(Field::ItemContent), + (Ns::Dc, "date") => Some(Field::ItemDcDate), + _ => None, + } + } + + fn begin_capture(&mut self, field: Field) { + self.capture = Some(Capture { + depth: self.stack.len(), + field, + text: String::new(), + }); + } + + fn on_end(&mut self, local: &str) { + if self.skipped_depth > 0 { + self.skipped_depth -= 1; + return; + } + // Tolerate mismatched end tags: close up to the nearest open element + // with the same local name, ignore the tag if none is open. + let Some(index) = self.stack.iter().rposition(|elem| elem.local == local) else { + return; + }; + while self.stack.len() > index { + self.close_top(); + } + } + + fn close_top(&mut self) { + let depth = self.stack.len(); + if depth == 0 { + return; + } + if self + .capture + .as_ref() + .is_some_and(|capture| capture.depth == depth) + && let Some(capture) = self.capture.take() + { + self.store_capture(capture); + } + if depth == self.item_depth + && let Some(item) = self.item.take() + { + self.finish_item(item); + } + while self + .ns_decls + .last() + .is_some_and(|(decl_depth, _, _)| *decl_depth >= depth) + { + self.ns_decls.pop(); + } + self.stack.pop(); + } + + fn store_capture(&mut self, capture: Capture) { + let text = capture.text; + if let Some(item) = self.item.as_mut() { + let slot = match capture.field { + Field::ItemTitle => &mut item.title, + Field::ItemItunesTitle => &mut item.itunes_title, + Field::ItemDescription => &mut item.description, + Field::ItemContent => &mut item.content, + Field::ItemSummary => &mut item.summary, + Field::ItemGuid => &mut item.guid, + Field::ItemPubDate => &mut item.pub_date, + Field::ItemDcDate => &mut item.dc_date, + Field::ItemUpdated => &mut item.updated, + Field::ItemDuration => &mut item.duration, + Field::ItemLink => &mut item.link, + _ => return, + }; + set_once(slot, text); + return; + } + let feed = &mut self.feed; + let slot = match capture.field { + Field::FeedTitle => &mut feed.title, + Field::FeedDescription => &mut feed.description, + Field::FeedItunesSummary => &mut feed.itunes_summary, + Field::FeedLink => &mut feed.link, + Field::FeedItunesAuthor => &mut feed.itunes_author, + Field::FeedAtomAuthor => &mut feed.atom_author, + Field::FeedDcCreator => &mut feed.dc_creator, + Field::FeedManagingEditor => &mut feed.managing_editor, + Field::FeedImageUrl => &mut feed.image_url, + Field::FeedLogo => &mut feed.logo, + Field::FeedIcon => &mut feed.icon, + _ => return, + }; + set_once(slot, text); + } + + fn finish_item(&mut self, item: ItemAcc) { + if self.full { + return; + } + let base = self.base.as_ref(); + let Some(media) = [item.enclosure, item.media_content] + .into_iter() + .flatten() + .find_map(|media| { + let url = resolve_http_url(&media.url, base)?; + Some(Media { url, ..media }) + }) + else { + return; + }; + let guid = item + .guid + .as_deref() + .map(|guid| guid.trim().to_string()) + .filter(|guid| !guid.is_empty()) + .unwrap_or_else(|| media.url.clone()); + if !self.seen_guids.insert(guid.clone()) { + return; + } + let title = [item.title.as_deref(), item.itunes_title.as_deref()] + .into_iter() + .flatten() + .map(clean_short) + .find(|title| !title.is_empty()) + .unwrap_or_else(|| UNTITLED_EPISODE.to_string()); + let description = [ + item.description.as_deref(), + item.content.as_deref(), + item.summary.as_deref(), + ] + .into_iter() + .flatten() + .map(clean_long) + .find(|text| !text.is_empty()); + let published_at = [ + item.pub_date.as_deref(), + item.dc_date.as_deref(), + item.updated.as_deref(), + ] + .into_iter() + .flatten() + .find_map(parse_date); + self.episodes.push(ParsedEpisode { + guid, + title, + description, + published_at, + duration_seconds: item.duration.as_deref().and_then(parse_duration), + audio_url: media.url, + mime_type: media.mime, + byte_len: media.len, + link: item + .link + .as_deref() + .map(clean_short) + .filter(|s| !s.is_empty()), + image_url: [item.itunes_image, item.thumbnail] + .into_iter() + .flatten() + .find_map(|url| resolve_http_url(&url, base)), + }); + if self.episodes.len() >= MAX_EPISODES { + self.full = true; + } + } + + fn finish(self) -> ParsedFeed { + let feed = self.feed; + let title = feed + .title + .as_deref() + .map(clean_short) + .filter(|title| !title.is_empty()) + .unwrap_or_else(|| UNTITLED_PODCAST.to_string()); + let author = [ + feed.itunes_author.as_deref(), + feed.atom_author.as_deref(), + feed.dc_creator.as_deref(), + feed.managing_editor.as_deref(), + ] + .into_iter() + .flatten() + .map(clean_short) + .find(|author| !author.is_empty()); + let description = [feed.description.as_deref(), feed.itunes_summary.as_deref()] + .into_iter() + .flatten() + .map(clean_long) + .find(|text| !text.is_empty()); + let image_url = [feed.itunes_image, feed.image_url, feed.logo, feed.icon] + .into_iter() + .flatten() + .find_map(|url| resolve_http_url(&url, self.base.as_ref())); + ParsedFeed { + title, + author, + description, + link: feed + .link + .as_deref() + .map(clean_short) + .filter(|s| !s.is_empty()), + image_url, + episodes: self.episodes, + } + } +} + +// --------------------------------------------------------------------------- +// Element and attribute helpers + +fn split_qname(name: &[u8]) -> (String, String) { + let name = String::from_utf8_lossy(name); + match name.split_once(':') { + Some((prefix, local)) => (prefix.to_string(), local.to_ascii_lowercase()), + None => (String::new(), name.to_ascii_lowercase()), + } +} + +fn local_name(name: &[u8]) -> String { + split_qname(name).1 +} + +/// Attributes of one element: raw keys with entity-decoded values. +struct Attrs { + raw: Vec<(String, String)>, +} + +impl Attrs { + fn collect(start: &BytesStart<'_>) -> Attrs { + let mut attributes = start.attributes(); + attributes.with_checks(false); + let raw = attributes + .flatten() + .map(|attr| { + let key = String::from_utf8_lossy(attr.key.as_ref()).into_owned(); + let value = decode_entities(&String::from_utf8_lossy(&attr.value)); + (key, value) + }) + .collect(); + Attrs { raw } + } + + /// Value of the attribute whose local name matches `name` (any prefix). + fn get(&self, name: &str) -> Option { + self.raw + .iter() + .find(|(key, _)| { + let local = key.rsplit_once(':').map_or(key.as_str(), |(_, l)| l); + local.eq_ignore_ascii_case(name) && !key.starts_with("xmlns") + }) + .map(|(_, value)| value.clone()) + } +} + +fn push_capped(text: &mut String, value: &str) { + if text.len() >= MAX_CAPTURE_BYTES { + return; + } + let room = MAX_CAPTURE_BYTES - text.len(); + if value.len() <= room { + text.push_str(value); + } else { + let mut end = room; + while !value.is_char_boundary(end) { + end -= 1; + } + text.push_str(&value[..end]); + } +} + +fn parse_len(value: Option) -> Option { + value?.trim().parse::().ok().filter(|len| *len > 0) +} + +fn clean_mime(mime: Option<&str>) -> Option { + let mime = mime?.split(';').next()?.trim().to_ascii_lowercase(); + (!mime.is_empty()).then_some(mime) +} + +const MEDIA_EXTENSIONS: &[&str] = &[ + "mp3", "m4a", "m4b", "aac", "ogg", "oga", "opus", "flac", "wav", "mp4", "m4v", "mov", "webm", + "mka", +]; + +fn has_media_extension(url: &str) -> bool { + let path = url.split(['?', '#']).next().unwrap_or_default(); + let file = path.rsplit('/').next().unwrap_or_default(); + file.rsplit_once('.').is_some_and(|(_, ext)| { + MEDIA_EXTENSIONS + .iter() + .any(|known| known.eq_ignore_ascii_case(ext)) + }) +} + +/// Whether an enclosure/media element points at something playable. +/// `lenient_untyped`: accept a URL without type information (RSS +/// enclosures); media:content without type must at least look like audio. +fn is_playable(url: &str, mime: Option<&str>, medium: Option<&str>, lenient_untyped: bool) -> bool { + let url = url.trim(); + if url.is_empty() { + return false; + } + if let Some(mime) = clean_mime(mime) { + return mime.starts_with("audio/") + || mime.starts_with("video/") + || matches!( + mime.as_str(), + "application/octet-stream" + | "binary/octet-stream" + | "application/ogg" + | "application/mp4" + | "application/x-mpegurl" + | "application/vnd.apple.mpegurl" + ) + || (mime == "application/x-unknown" && has_media_extension(url)); + } + if let Some(medium) = medium.map(|m| m.trim().to_ascii_lowercase()) + && !medium.is_empty() + { + return medium == "audio" || medium == "video"; + } + lenient_untyped || has_media_extension(url) +} + +/// An absolute `http`/`https` URL for a media or image reference: absolute +/// http(s) URLs are kept as written, relative ones (including +/// protocol-relative `//host/...`) are resolved against `base`, and anything +/// else (`file:`, `ftp:`, unresolvable relative paths) yields `None`. +fn resolve_http_url(raw: &str, base: Option<&Url>) -> Option { + let raw = raw.trim(); + if raw.is_empty() { + return None; + } + let has_host = |url: &Url| url.host_str().is_some_and(|host| !host.is_empty()); + if super::is_remote_url(raw) { + return Url::parse(raw) + .ok() + .filter(has_host) + .map(|_| raw.to_string()); + } + let resolved = match base { + Some(base) => base.join(raw).ok()?, + None if raw.starts_with("//") => Url::parse(&format!("https:{raw}")).ok()?, + None => return None, + }; + (matches!(resolved.scheme(), "http" | "https") && has_host(&resolved)) + .then(|| resolved.to_string()) +} + +// --------------------------------------------------------------------------- +// Text cleanup + +fn clean_short(text: &str) -> String { + html_to_text(text, MAX_SHORT_CHARS) +} + +fn clean_long(text: &str) -> String { + html_to_text(text, MAX_DESCRIPTION_CHARS) +} + +const BLOCK_TAGS: &[&str] = &[ + "br", + "p", + "div", + "li", + "ul", + "ol", + "tr", + "td", + "th", + "table", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "blockquote", + "hr", + "pre", + "section", + "article", + "header", + "footer", + "dd", + "dt", +]; + +/// Converts (possibly HTML) text to plain text: strips tags (dropping +/// `]]> + Jane Host + + https://example.test/small.pngignored"#, + r#" + Episode one + One + <p>First &amp; best</p> + ep-1 + Tue, 02 Jan 2024 10:00:00 GMT + 1:02:03 + + https://example.test/ep1 + + + + + Only itunes title + Long show notes]]> + ep-2 + 754 + + + + Summary only + ep-3 + +"#, + ); + let feed = parse_feed(xml.as_bytes()).unwrap(); + assert_eq!(feed.title, "Test Cast"); + assert_eq!(feed.author.as_deref(), Some("Jane Host")); + assert_eq!(feed.description.as_deref(), Some("Weekly talk show.")); + assert_eq!(feed.link.as_deref(), Some("https://example.test/cast")); + assert_eq!( + feed.image_url.as_deref(), + Some("https://example.test/cover.jpg") + ); + assert_eq!(feed.episodes.len(), 3); + + let first = &feed.episodes[0]; + assert_eq!(first.guid, "ep-1"); + assert_eq!(first.title, "Episode one"); + assert_eq!(first.description.as_deref(), Some("First & best")); + assert_eq!(first.published_at, Some(1_704_189_600)); + assert_eq!(first.duration_seconds, Some(3723.0)); + assert_eq!(first.audio_url, "https://cdn.example.test/1.mp3"); + assert_eq!(first.mime_type.as_deref(), Some("audio/mpeg")); + assert_eq!(first.byte_len, Some(5000)); + assert_eq!(first.link.as_deref(), Some("https://example.test/ep1")); + assert_eq!( + first.image_url.as_deref(), + Some("https://example.test/ep1.jpg") + ); + + let second = &feed.episodes[1]; + assert_eq!(second.title, "Only itunes title"); + assert_eq!(second.description.as_deref(), Some("Long show notes")); + assert_eq!(second.duration_seconds, Some(754.0)); + assert_eq!(second.byte_len, None); + assert_eq!(second.published_at, None); + + let third = &feed.episodes[2]; + assert_eq!(third.title, "Untitled episode"); + assert_eq!(third.description.as_deref(), Some("Summary only")); + assert_eq!(third.mime_type, None); + } + + #[test] + fn entities_numeric_refs_and_unknown_html_entities() { + let xml = rss( + "", + r#" + A & B — AП — &bogus; R&D © + x < y && z + e + +"#, + ); + let feed = parse_feed(xml.as_bytes()).unwrap(); + let episode = &feed.episodes[0]; + assert_eq!(episode.title, "A & B — AП — &bogus; R&D ©"); + assert_eq!(episode.description.as_deref(), Some("x < y && z")); + assert_eq!(episode.audio_url, "https://cdn.example.test/a.mp3?x=1&y=2"); + } + + #[test] + fn atom_feed() { + let xml = r#" + + Atom Cast + About <b>things</b> + + + https://example.test/logo.png + Atom Author + + Entry one + urn:uuid:1 + 2024-03-01T12:30:00+02:00 + 2024-03-05T00:00:00Z + <p>Entry summary</p> + + + + + Entry two + urn:uuid:2 + 2024-03-06T00:00:00Z +

Inline

xhtml

+ +
+ + No audio + urn:uuid:3 + + +
"#; + let feed = parse_feed(xml.as_bytes()).unwrap(); + assert_eq!(feed.title, "Atom Cast"); + assert_eq!(feed.description.as_deref(), Some("About things")); + assert_eq!(feed.link.as_deref(), Some("https://example.test/")); + assert_eq!( + feed.image_url.as_deref(), + Some("https://example.test/logo.png") + ); + assert_eq!(feed.author.as_deref(), Some("Atom Author")); + assert_eq!(feed.episodes.len(), 2); + let first = &feed.episodes[0]; + assert_eq!(first.guid, "urn:uuid:1"); + assert_eq!(first.published_at, Some(1_709_289_000)); + assert_eq!(first.description.as_deref(), Some("Entry summary")); + assert_eq!(first.link.as_deref(), Some("https://example.test/e1")); + assert_eq!(first.audio_url, "https://cdn.example.test/e1.ogg"); + assert_eq!(first.byte_len, Some(42)); + let second = &feed.episodes[1]; + assert_eq!(second.published_at, Some(1_709_683_200)); + assert_eq!(second.description.as_deref(), Some("Inline xhtml")); + } + + #[test] + fn items_without_audio_are_skipped_and_media_content_is_a_fallback() { + let xml = r#"T +No enclosurea +Image enclosureb +Empty urlc +Mediad + + + + +Videoe +"#; + let feed = parse_feed(xml.as_bytes()).unwrap(); + let titles: Vec<_> = feed.episodes.iter().map(|e| e.title.as_str()).collect(); + assert_eq!(titles, ["Media", "Video"]); + assert_eq!(feed.episodes[0].audio_url, "https://x.test/d.mp3"); + assert_eq!(feed.episodes[0].byte_len, Some(77)); + assert_eq!( + feed.episodes[0].image_url.as_deref(), + Some("https://x.test/d-thumb.jpg") + ); + } + + #[test] + fn duplicate_guids_keep_the_first_and_guid_falls_back_to_the_url() { + let items = [ + item("dup", "First", "Mon, 01 Jan 2024 00:00:00 +0000"), + item("dup", "Second", "Tue, 02 Jan 2024 00:00:00 +0000"), + r#"No guid"#.to_string(), + r#"Blank guid "#.to_string(), + ] + .concat(); + let feed = parse_feed(rss("", &items).as_bytes()).unwrap(); + let pairs: Vec<_> = feed + .episodes + .iter() + .map(|e| (e.guid.as_str(), e.title.as_str())) + .collect(); + assert_eq!( + pairs, + [ + ("dup", "First"), + ("https://cdn.example.test/noguid.mp3", "No guid"), + ("https://cdn.example.test/blank.mp3", "Blank guid"), + ] + ); + } + + #[test] + fn durations() { + let cases = [ + ("01:02:03", Some(3723.0)), + ("1:02:03", Some(3723.0)), + ("62:03", Some(3723.0)), + ("3723", Some(3723.0)), + ("3723.5", Some(3723.5)), + ("00:00:01.25", Some(1.25)), + (" 45:00 ", Some(2700.0)), + ("0", None), + ("00:00:00", None), + ("", None), + ("abc", None), + ("1:2:3:4", None), + ("-5", None), + ("1e3", None), + ("NaN", None), + ("12:", None), + ]; + for (input, expected) in cases { + assert_eq!(parse_duration(input), expected, "{input:?}"); + } + } + + #[test] + fn dates() { + let reference = Some(1_704_189_600); // 2024-01-02 10:00:00 UTC + let cases = [ + ("Tue, 02 Jan 2024 10:00:00 GMT", reference), + ("Tue, 02 Jan 2024 10:00:00 +0000", reference), + ("02 Jan 2024 10:00:00 UT", reference), + ("Tue, 2 Jan 2024 13:00:00 +0300", reference), + ("Tue, 02 Jan 2024 05:00:00 EST", reference), + ("Tue, 02 Jan 2024 02:00:00 PST", reference), + ("Tuesday, 02 January 2024 10:00 GMT", reference), + ("Tue, 02 Jan 24 10:00:00 GMT", reference), + ("Tue, 02 Jan 2024 13:00:00 +03:00", reference), + ("Tue, 02 Jan 2024 10:00:00", reference), + ("Вт, 02 янв 2024 13:00:00 +0300", reference), + ("2024-01-02T10:00:00Z", reference), + ("2024-01-02T13:00:00+03:00", reference), + ("2024-01-02T10:00:00.123Z", reference), + ("2024-01-02 10:00:00", reference), + ("2024-01-02", Some(1_704_153_600)), + ("not a date", None), + ("Tue, 31 Feb 2024 10:00:00 GMT", None), + ("Tue, 02 Foo 2024 10:00:00 GMT", None), + ("2024-13-02T10:00:00Z", None), + ("", None), + ]; + for (input, expected) in cases { + assert_eq!(parse_date(input), expected, "{input:?}"); + } + } + + #[test] + fn non_ascii_zones_do_not_panic() { + for input in [ + "Mon, 07 Nov 2022 10:00:00 +й0", + "Mon, 07 Nov 2022 10:00:00 -йй", + "Mon, 07 Nov 2022 10:00+й0", + "Mon, 07 Nov 2022 10:00:00 +0й00", + "2022-11-07T10:00:00+0й0", + "2022-11-07T10:00:00+й", + "2022-11-07T10:00:00-€:00", + "2022-11-07T10:00:00+日本", + ] { + assert_eq!(parse_date(input), None, "{input:?}"); + } + // Exhaustive-ish: every short suffix of mixed ASCII / multi-byte + // characters after a sign. + let alphabet = ['0', '9', ':', 'й', '€', '日', '+', '-']; + for a in alphabet { + for b in alphabet { + for c in alphabet { + for prefix in ["Mon, 07 Nov 2022 10:00:00 ", "2022-11-07T10:00:00"] { + for sign in ['+', '-'] { + let _ = parse_date(&format!("{prefix}{sign}{a}{b}{c}")); + } + } + } + } + } + // In a feed, the bad date only loses the date. + let xml = rss("", &item("z", "Zone", "Mon, 07 Nov 2022 10:00:00 +й0")); + let feed = parse_feed(xml.as_bytes()).unwrap(); + assert_eq!(feed.episodes.len(), 1); + assert_eq!(feed.episodes[0].published_at, None); + } + + #[test] + fn media_urls_are_resolved_and_must_be_http() { + let xml = rss( + r#""#, + r#"relRelative + + +protoProtocol relative + +fileLocal file + +ftpFTP + +fallbackMedia fallback + + +absAbsolute + "#, + ); + let feed = + parse_feed_with_base(xml.as_bytes(), Some("https://host.test/feeds/rss.xml")).unwrap(); + let urls: Vec<(&str, &str)> = feed + .episodes + .iter() + .map(|e| (e.guid.as_str(), e.audio_url.as_str())) + .collect(); + assert_eq!( + urls, + [ + ("rel", "https://host.test/audio/1.mp3"), + ("proto", "https://cdn.example.test/2.mp3"), + ("fallback", "https://cdn.example.test/4.mp3"), + ("abs", "HTTPS://cdn.example.test/5.mp3"), + ] + ); + assert_eq!( + feed.image_url.as_deref(), + Some("https://host.test/img/cover.jpg") + ); + assert_eq!( + feed.episodes[0].image_url.as_deref(), + Some("https://host.test/feeds/ep.png") + ); + for episode in &feed.episodes { + assert!(is_remote_url(&episode.audio_url), "{}", episode.audio_url); + } + + // Without a base, relative media cannot be resolved and is dropped; + // protocol-relative URLs default to https. + let feed = parse_feed(xml.as_bytes()).unwrap(); + let guids: Vec<&str> = feed.episodes.iter().map(|e| e.guid.as_str()).collect(); + assert_eq!(guids, ["proto", "fallback", "abs"]); + assert_eq!(feed.image_url, None); + } + + #[test] + fn rss_with_an_unrelated_default_namespace() { + for ns in ["http://example.test/x", "http://www.w3.org/2005/Atom"] { + let xml = format!( + r#"T + +1One +"# + ); + let feed = parse_feed(xml.as_bytes()).unwrap(); + assert_eq!(feed.title, "T", "{ns}"); + assert_eq!(feed.episodes.len(), 1, "{ns}"); + assert_eq!(feed.episodes[0].title, "One"); + } + } + + #[test] + fn html_pages_and_garbage_are_rejected() { + let html = br#"Vivat

Hi   there

"#; + let err = parse_feed(html).unwrap_err().to_string(); + assert!(err.contains("not an RSS or Atom feed"), "{err}"); + for garbage in [ + &b""[..], + b"hello world", + b"\x00\xff\xfe garbage", + b"{\"json\": true}", + b"<", + b"<<<>>>", + ] { + let err = parse_feed(garbage).unwrap_err().to_string(); + assert!( + err.contains("not an RSS or Atom feed"), + "{garbage:?}: {err}" + ); + } + } + + #[test] + fn truncated_and_malformed_xml_never_panics() { + let items: String = (0..5) + .map(|i| item(&format!("g{i}"), &format!("T {i} &  "), "bad date")) + .collect(); + let xml = rss( + "", + &items, + ); + let bytes = xml.as_bytes(); + for len in 0..=bytes.len() { + let _ = parse_feed(&bytes[..len]); + } + // Mismatched end tags are tolerated. + let sloppy = r#"SA</b>1"#; + let feed = parse_feed(sloppy.as_bytes()).unwrap(); + assert_eq!(feed.episodes.len(), 1); + assert_eq!(feed.episodes[0].title, "A"); + // Truncation after complete items keeps them. + let third = xml.find("T 3").unwrap(); + let cut = &bytes[..xml[..third].rfind("<item>").unwrap()]; + let feed = parse_feed(cut).unwrap(); + assert_eq!(feed.episodes.len(), 3); + } + + #[test] + fn deep_nesting_does_not_overflow() { + let depth = 100_000; + let mut xml = String::from("<rss><channel><title>Deep"); + xml.push_str(&"".repeat(depth)); + xml.push_str(&"".repeat(depth)); + xml.push_str(&item("after", "After", "")); + xml.push_str(""); + let feed = parse_feed(xml.as_bytes()).unwrap(); + assert_eq!(feed.episodes.len(), 1); + } + + #[test] + fn cyrillic_titles_in_utf8_and_windows_1251() { + let xml = rss( + "Иван Петров", + &item( + "1", + "Выпуск №1: «Привет»", + "Mon, 01 Jan 2024 00:00:00 +0300", + ), + ) + .replace("Test Cast", "Подкаст"); + let feed = parse_feed(xml.as_bytes()).unwrap(); + assert_eq!(feed.title, "Подкаст"); + assert_eq!(feed.author.as_deref(), Some("Иван Петров")); + assert_eq!(feed.episodes[0].title, "Выпуск №1: «Привет»"); + + let cp1251 = xml.replace("encoding=\"UTF-8\"", "encoding=\"windows-1251\""); + let (encoded, _, unmappable) = encoding_rs::WINDOWS_1251.encode(&cp1251); + assert!(!unmappable); + let feed = parse_feed(&encoded).unwrap(); + assert_eq!(feed.title, "Подкаст"); + assert_eq!(feed.episodes[0].title, "Выпуск №1: «Привет»"); + + // Invalid UTF-8 without a declaration is decoded lossily. + let mut broken = xml.into_bytes(); + let at = broken + .windows(7) + .position(|w| w == b"Test Ca") + .unwrap_or(10); + broken.insert(at, 0xff); + assert!(parse_feed(&broken).is_ok()); + } + + #[test] + fn namespace_prefixes_are_matched_tolerantly() { + // Undeclared `itunes:` prefix and a custom prefix bound to the + // iTunes namespace. + let xml = format!( + r#"PUndeclared +1Custom prefix90 +"# + ); + let feed = parse_feed(xml.as_bytes()).unwrap(); + assert_eq!(feed.author.as_deref(), Some("Undeclared")); + assert_eq!(feed.episodes[0].title, "Custom prefix"); + assert_eq!(feed.episodes[0].duration_seconds, Some(90.0)); + } + + #[test] + fn long_descriptions_are_truncated() { + let long = "word ".repeat(2000); + let text = html_to_text(&long, 4000); + assert!(text.chars().count() <= 4000); + assert!(text.ends_with('…')); + let xml = rss(&format!("{long}"), ""); + let feed = parse_feed(xml.as_bytes()).unwrap(); + assert!(feed.description.unwrap().chars().count() <= 4000); + } +} + +mod store_tests { + use super::*; + + fn parsed(guid: &str, title: &str, published_at: Option) -> ParsedEpisode { + ParsedEpisode { + guid: guid.to_string(), + title: title.to_string(), + description: None, + published_at, + duration_seconds: Some(60.0), + audio_url: format!("https://cdn.example.test/{guid}.mp3"), + mime_type: Some("audio/mpeg".to_string()), + byte_len: Some(1000), + link: None, + image_url: None, + } + } + + fn feed(title: &str, episodes: Vec) -> ParsedFeed { + ParsedFeed { + title: title.to_string(), + author: Some("Author".to_string()), + description: Some("About".to_string()), + link: None, + image_url: Some("https://example.test/cover.png".to_string()), + episodes, + } + } + + #[test] + fn add_list_and_episode_order() { + let store = Store::open_in_memory().unwrap(); + let b = store + .add_podcast( + "https://b.test/feed", + &feed( + "beta", + vec![ + parsed("old", "Old", Some(100)), + parsed("undated", "Undated", None), + parsed("new", "New", Some(300)), + parsed("mid", "Mid", Some(200)), + ], + ), + 10, + ) + .unwrap(); + let a = store + .add_podcast("https://a.test/feed", &feed("Alpha", vec![]), 11) + .unwrap(); + let list = store.list_podcasts().unwrap(); + let titles: Vec<_> = list.iter().map(|p| p.title.as_str()).collect(); + assert_eq!(titles, ["Alpha", "beta"]); + assert_eq!(list[0].id, a); + assert_eq!(list[0].episode_count, 0); + assert_eq!(list[0].latest_published_at, None); + let beta = &list[1]; + assert_eq!(beta.id, b); + assert_eq!(beta.episode_count, 4); + assert_eq!(beta.latest_published_at, Some(300)); + assert_eq!(beta.last_checked_at, Some(10)); + assert_eq!(beta.last_error, None); + assert_eq!(beta.author.as_deref(), Some("Author")); + assert_eq!(store.podcast(b).unwrap().as_ref(), Some(beta)); + assert_eq!( + store.podcast_by_feed_url("https://b.test/feed").unwrap(), + Some(beta.clone()) + ); + assert_eq!(store.podcast(9999).unwrap(), None); + + let episodes = store.episodes(b).unwrap(); + let guids: Vec<_> = episodes.iter().map(|e| e.guid.as_str()).collect(); + assert_eq!(guids, ["new", "mid", "old", "undated"]); + let first = &episodes[0]; + assert_eq!(store.episode(first.id).unwrap().as_ref(), Some(first)); + assert_eq!(first.byte_len, Some(1000)); + assert_eq!(first.podcast_id, b); + } + + #[test] + fn apply_feed_counts_changes_and_keeps_missing_episodes() { + let store = Store::open_in_memory().unwrap(); + let id = store + .add_podcast( + "https://a.test/feed", + &feed( + "Cast", + vec![ + parsed("1", "One", Some(1)), + parsed("2", "Two", Some(2)), + parsed("3", "Three", Some(3)), + ], + ), + 10, + ) + .unwrap(); + let before = store.episodes(id).unwrap(); + store.record_check(id, 15, Some("boom")).unwrap(); + assert_eq!( + store.podcast(id).unwrap().unwrap().last_error.as_deref(), + Some("boom") + ); + + let mut changed = parsed("2", "Two (remastered)", Some(2)); + changed.duration_seconds = Some(61.5); + let next = feed( + "Cast renamed", + vec![ + parsed("4", "Four", Some(4)), + changed, + parsed("3", "Three", Some(3)), + ], + ); + let summary = store.apply_feed(id, &next, 20).unwrap(); + assert_eq!( + summary, + RefreshSummary { + new_episodes: 1, + updated_episodes: 1, + not_modified: false + } + ); + // Re-applying the same feed changes nothing. + let again = store.apply_feed(id, &next, 21).unwrap(); + assert_eq!(again, RefreshSummary::default()); + + let podcast = store.podcast(id).unwrap().unwrap(); + assert_eq!(podcast.title, "Cast renamed"); + assert_eq!(podcast.episode_count, 4); + assert_eq!(podcast.last_checked_at, Some(21)); + assert_eq!(podcast.last_error, None); + + let after = store.episodes(id).unwrap(); + let guids: Vec<_> = after.iter().map(|e| e.guid.as_str()).collect(); + assert_eq!(guids, ["4", "3", "2", "1"], "missing episode 1 is kept"); + for old in &before { + let new = after.iter().find(|e| e.guid == old.guid).unwrap(); + assert_eq!(new.id, old.id, "row ids are stable"); + } + let two = after.iter().find(|e| e.guid == "2").unwrap(); + assert_eq!(two.title, "Two (remastered)"); + assert_eq!(two.duration_seconds, Some(61.5)); + + assert!(store.apply_feed(9999, &next, 22).is_err()); + } + + #[test] + fn duplicate_feed_url_is_rejected() { + let store = Store::open_in_memory().unwrap(); + store + .add_podcast("https://a.test/feed", &feed("Cast", vec![]), 1) + .unwrap(); + let err = store + .add_podcast("https://a.test/feed", &feed("Cast", vec![]), 2) + .unwrap_err(); + assert!(err.to_string().contains("already subscribed"), "{err}"); + assert_eq!(store.list_podcasts().unwrap().len(), 1); + } + + #[test] + fn validators_covers_and_removal_cascade() { + let store = Store::open_in_memory().unwrap(); + let id = store + .add_podcast( + "https://a.test/feed", + &feed("Cast", vec![parsed("1", "One", Some(1))]), + 1, + ) + .unwrap(); + let other = store + .add_podcast( + "https://b.test/feed", + &feed("Other", vec![parsed("1", "One", Some(1))]), + 1, + ) + .unwrap(); + assert_eq!(store.http_validators(id).unwrap(), (None, None)); + store + .set_http_validators(id, Some("\"v1\""), Some("Mon, 01 Jan 2024 00:00:00 GMT")) + .unwrap(); + assert_eq!( + store.http_validators(id).unwrap(), + ( + Some("\"v1\"".to_string()), + Some("Mon, 01 Jan 2024 00:00:00 GMT".to_string()) + ) + ); + store + .set_cover(id, Some("https://example.test/c.png"), Some("/tmp/c.png")) + .unwrap(); + assert_eq!( + store.cover_source(id).unwrap(), + ( + Some("https://example.test/c.png".to_string()), + Some("/tmp/c.png".to_string()) + ) + ); + assert_eq!( + store.podcast(id).unwrap().unwrap().cover_path.as_deref(), + Some("/tmp/c.png") + ); + let episode_id = store.episodes(id).unwrap()[0].id; + + assert_eq!( + store.remove_podcast(id).unwrap().as_deref(), + Some("/tmp/c.png") + ); + assert_eq!(store.podcast(id).unwrap(), None); + assert_eq!(store.episode(episode_id).unwrap(), None); + assert!(store.episodes(id).unwrap().is_empty()); + assert_eq!(store.episodes(other).unwrap().len(), 1); + assert_eq!(store.remove_podcast(id).unwrap(), None); + } + + #[test] + fn ids_are_never_reused_after_removal() { + let store = Store::open_in_memory().unwrap(); + let first = store + .add_podcast( + "https://a.test/feed", + &feed("A", vec![parsed("1", "One", Some(1))]), + 1, + ) + .unwrap(); + let second = store + .add_podcast( + "https://b.test/feed", + &feed( + "B", + vec![parsed("1", "One", Some(1)), parsed("2", "Two", Some(2))], + ), + 1, + ) + .unwrap(); + let removed_episodes: Vec = store + .episodes(second) + .unwrap() + .iter() + .map(|e| e.id) + .collect(); + // Remove the newest subscription, then subscribe to something else. + store.remove_podcast(second).unwrap(); + let third = store + .add_podcast( + "https://c.test/feed", + &feed("C", vec![parsed("1", "One", Some(1))]), + 2, + ) + .unwrap(); + assert!(third > second && second > first); + let new_episode = store.episodes(third).unwrap()[0].id; + assert!( + removed_episodes.iter().all(|old| new_episode > *old), + "{new_episode} reuses one of {removed_episodes:?}" + ); + // A refresh of the removed podcast that finishes late cannot touch + // the new subscription. + assert!(store.apply_feed(second, &feed("B", vec![]), 3).is_err()); + assert_eq!(store.podcast(third).unwrap().unwrap().title, "C"); + } + + #[test] + fn migrations_are_idempotent_on_disk() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("nested").join("podcasts.sqlite3"); + let id = { + let store = Store::open(&path).unwrap(); + assert_eq!(store.schema_version().unwrap(), 1); + store + .add_podcast( + "https://a.test/feed", + &feed("Cast", vec![parsed("1", "One", Some(1))]), + 1, + ) + .unwrap() + }; + let store = Store::open(&path).unwrap(); + assert_eq!(store.schema_version().unwrap(), 1); + assert_eq!(store.podcast(id).unwrap().unwrap().episode_count, 1); + drop(store); + let store = Store::open(&path).unwrap(); + assert_eq!(store.list_podcasts().unwrap().len(), 1); + } +} + +mod mapping { + use super::*; + + fn podcast() -> Podcast { + Podcast { + id: 3, + feed_url: "https://a.test/feed".to_string(), + title: "Cast".to_string(), + author: None, + description: None, + link: None, + image_url: None, + cover_path: Some("/covers/3.png".to_string()), + episode_count: 1, + latest_published_at: None, + last_checked_at: None, + last_error: None, + } + } + + fn episode() -> Episode { + Episode { + id: 42, + podcast_id: 3, + guid: "g".to_string(), + title: "Episode".to_string(), + description: None, + published_at: Some(1_704_189_600), + duration_seconds: Some(125.5), + audio_url: "https://cdn.example.test/e.mp3".to_string(), + mime_type: Some("audio/mpeg".to_string()), + byte_len: Some(9_999), + link: None, + image_url: None, + } + } + + #[test] + fn episode_track_maps_fields() { + let track = episode_track(&podcast(), &episode()); + assert_eq!(track.id, -(EPISODE_TRACK_ID_BASE + 42)); + assert_eq!(track.title, "Episode"); + assert_eq!(track.artists.len(), 1); + assert_eq!(track.artists[0].id, -1); + assert_eq!(track.artists[0].name, "Cast"); + assert!(track.featured_artists.is_empty()); + assert_eq!(track.release_id, -1); + assert_eq!(track.release_title, "Cast"); + assert_eq!(track.release_year, Some(2024)); + assert_eq!(track.track_number, None); + assert_eq!(track.disc_number, None); + assert_eq!(track.file_path, "https://cdn.example.test/e.mp3"); + assert_eq!(track.content_id, None); + assert_eq!(track.cover_path.as_deref(), Some("/covers/3.png")); + assert_eq!(track.audio_format.as_deref(), Some("MP3")); + assert_eq!(track.file_size_bytes, Some(9_999)); + assert_eq!(track.duration_seconds, 125.5); + assert_eq!(track.play_count, 0); + assert!(track.fed.is_none()); + + let mut bare = episode(); + bare.duration_seconds = None; + bare.published_at = None; + bare.mime_type = Some("audio/x-m4a".to_string()); + bare.byte_len = None; + let track = episode_track(&podcast(), &bare); + assert_eq!(track.duration_seconds, 0.0); + assert_eq!(track.release_year, None); + assert_eq!(track.audio_format.as_deref(), Some("M4A")); + assert_eq!(track.file_size_bytes, None); + } + + #[test] + fn track_id_inverse() { + let track = episode_track(&podcast(), &episode()); + assert_eq!(episode_id_from_track_id(track.id), Some(42)); + assert_eq!(episode_id_from_track_id(1), None); + assert_eq!(episode_id_from_track_id(0), None); + assert_eq!(episode_id_from_track_id(-1), None); + assert_eq!(episode_id_from_track_id(-EPISODE_TRACK_ID_BASE), None); + assert_eq!(episode_id_from_track_id(i64::MIN), None); + assert_eq!(episode_id_from_track_id(i64::MAX), None); + // Only the band reserved for episodes maps back. + let max = EPISODE_TRACK_ID_BASE - 1; + assert_eq!( + episode_id_from_track_id(-(EPISODE_TRACK_ID_BASE + max)), + Some(max) + ); + assert_eq!( + episode_id_from_track_id(-(EPISODE_TRACK_ID_BASE + 1)), + Some(1) + ); + assert_eq!(episode_id_from_track_id(-(2 * EPISODE_TRACK_ID_BASE)), None); + // Hash-derived placeholder ids (as used by device sync) spread over + // the whole negative range and must not look like episodes. + let mut hits = 0; + for seed in 0..10_000u64 { + let hash = blake3::hash(&seed.to_le_bytes()); + let bytes: [u8; 8] = hash.as_bytes()[..8].try_into().unwrap(); + let placeholder = -(i64::from_le_bytes(bytes) & i64::MAX); + hits += usize::from(episode_id_from_track_id(placeholder).is_some()); + } + assert_eq!(hits, 0); + } + + #[test] + fn remote_urls() { + assert!(is_remote_url("http://a.test/x.mp3")); + assert!(is_remote_url("HTTPS://a.test/x.mp3")); + assert!(!is_remote_url("/music/x.mp3")); + assert!(!is_remote_url("ftp://a.test/x")); + assert!(!is_remote_url("http:/")); + assert!(!is_remote_url("")); + } + + #[test] + fn normalizes_feed_urls() { + let ok = [ + ( + "https://podster.test/rss.xml?pid=778", + "https://podster.test/rss.xml?pid=778", + ), + (" http://a.test/feed ", "http://a.test/feed"), + ("a.test/feed.xml", "https://a.test/feed.xml"), + ("feed://a.test/rss", "https://a.test/rss"), + ("feed:https://a.test/rss", "https://a.test/rss"), + ("podcast://a.test/rss", "https://a.test/rss"), + ("HTTPS://A.TEST/Feed", "https://a.test/Feed"), + ("a.test:8080/rss", "https://a.test:8080/rss"), + // A URL embedded in the query is not a scheme. + ( + "example.test/rss?src=https://other.test", + "https://example.test/rss?src=https://other.test", + ), + ( + "localhost:8080/feed?u=http://x.test/", + "https://localhost:8080/feed?u=http://x.test/", + ), + ]; + for (input, expected) in ok { + assert_eq!(normalize_feed_url(input).unwrap(), expected, "{input:?}"); + } + for bad in [ + "", + " ", + "ftp://a.test/feed", + "https://a.test/my feed", + "https://", + "file:///etc/passwd", + "javascript:alert(1)", + ] { + assert!(normalize_feed_url(bad).is_err(), "{bad:?}"); + } + } +} + +mod network { + use super::*; + use crate::podcasts::test_server::{Route, TestServer}; + use std::sync::Arc; + + fn png() -> Vec { + let image = image::RgbImage::from_pixel(2, 2, image::Rgb([200, 10, 10])); + let mut out = std::io::Cursor::new(Vec::new()); + image.write_to(&mut out, image::ImageFormat::Png).unwrap(); + out.into_inner() + } + + fn feed_xml(server: &TestServer, guids: &[&str]) -> String { + let items: String = guids + .iter() + .enumerate() + .map(|(i, guid)| { + item( + guid, + &format!("Episode {guid}"), + &format!("Mon, 0{} Jan 2024 00:00:00 GMT", i + 1), + ) + }) + .collect(); + rss( + &format!(r#""#, server.url("/cover.png")), + &items, + ) + } + + struct Env { + server: TestServer, + store: Arc, + fetcher: Fetcher, + covers: tempfile::TempDir, + } + + fn env() -> Env { + let covers = tempfile::tempdir().unwrap(); + Env { + server: TestServer::start(), + store: Arc::new(Store::open_in_memory().unwrap()), + fetcher: Fetcher::new(covers.path().join("covers")).unwrap(), + covers, + } + } + + #[tokio::test] + async fn subscribe_stores_metadata_and_cover() { + let env = env(); + let xml = feed_xml(&env.server, &["a", "b"]); + env.server.set( + "/feed.xml", + Route::new(xml, "application/rss+xml").etag("\"v1\""), + ); + env.server.set("/cover.png", Route::new(png(), "image/png")); + + let id = subscribe( + Arc::clone(&env.store), + &env.fetcher, + &env.server.url("/feed.xml"), + 100, + ) + .await + .unwrap(); + let podcast = env.store.podcast(id).unwrap().unwrap(); + assert_eq!(podcast.title, "Test Cast"); + assert_eq!(podcast.episode_count, 2); + assert_eq!(podcast.last_checked_at, Some(100)); + let cover = podcast.cover_path.clone().unwrap(); + assert!(cover.ends_with(".png"), "{cover}"); + assert!(std::path::Path::new(&cover).is_file()); + assert!(cover.starts_with(&*env.covers.path().to_string_lossy())); + assert_eq!( + env.store.http_validators(id).unwrap().0.as_deref(), + Some("\"v1\"") + ); + // Only the feed and the cover were requested — never the audio. + assert!(env.server.requests("/a.mp3").is_empty()); + + let err = subscribe( + Arc::clone(&env.store), + &env.fetcher, + &env.server.url("/feed.xml"), + 101, + ) + .await + .unwrap_err(); + assert!( + err.to_string().contains("already subscribed to Test Cast"), + "{err}" + ); + } + + #[tokio::test] + async fn subscribe_rejects_non_feeds_without_storing() { + let env = env(); + env.server.set( + "/page", + Route::new("Hi", "text/html"), + ); + env.server + .set("/missing", Route::new("nope", "text/plain").status(404)); + let err = subscribe( + Arc::clone(&env.store), + &env.fetcher, + &env.server.url("/page"), + 1, + ) + .await + .unwrap_err(); + assert!( + format!("{err:#}").contains("not an RSS or Atom feed"), + "{err:#}" + ); + let err = subscribe( + Arc::clone(&env.store), + &env.fetcher, + &env.server.url("/missing"), + 1, + ) + .await + .unwrap_err(); + assert!(format!("{err:#}").contains("404"), "{err:#}"); + assert!(env.store.list_podcasts().unwrap().is_empty()); + } + + #[tokio::test] + async fn refresh_uses_etag_and_picks_up_new_episodes() { + let env = env(); + let feed_url = env.server.url("/feed.xml"); + env.server.set( + "/feed.xml", + Route::new(feed_xml(&env.server, &["a"]), "application/rss+xml").etag("\"v1\""), + ); + env.server.set("/cover.png", Route::new(png(), "image/png")); + let id = subscribe(Arc::clone(&env.store), &env.fetcher, &feed_url, 1) + .await + .unwrap(); + + let summary = refresh(Arc::clone(&env.store), &env.fetcher, id, 2) + .await + .unwrap(); + assert_eq!( + summary, + RefreshSummary { + not_modified: true, + ..Default::default() + } + ); + assert_eq!( + env.store.podcast(id).unwrap().unwrap().last_checked_at, + Some(2) + ); + let cover_requests = env.server.requests("/cover.png").len(); + assert_eq!(cover_requests, 1, "cover is not downloaded again"); + + env.server.set( + "/feed.xml", + Route::new(feed_xml(&env.server, &["a", "b"]), "application/rss+xml").etag("\"v2\""), + ); + let summary = refresh(Arc::clone(&env.store), &env.fetcher, id, 3) + .await + .unwrap(); + assert_eq!(summary.new_episodes, 1); + assert!(!summary.not_modified); + assert_eq!(env.store.episodes(id).unwrap().len(), 2); + assert_eq!( + env.store.http_validators(id).unwrap().0.as_deref(), + Some("\"v2\"") + ); + let sent: Vec<_> = env.server.requests("/feed.xml"); + assert_eq!(sent.len(), 3); + + // A deleted cover file is downloaded again on the next refresh. + let cover = env.store.podcast(id).unwrap().unwrap().cover_path.unwrap(); + std::fs::remove_file(&cover).unwrap(); + refresh(Arc::clone(&env.store), &env.fetcher, id, 4) + .await + .unwrap(); + assert!(std::path::Path::new(&cover).is_file()); + assert_eq!(env.server.requests("/cover.png").len(), 2); + } + + #[tokio::test] + async fn relative_enclosures_resolve_against_the_feed_url() { + let env = env(); + let xml = rss( + "", + r#"rRelative + +fLocal file + "#, + ); + env.server + .set("/feeds/main.xml", Route::new(xml, "application/rss+xml")); + let id = subscribe( + Arc::clone(&env.store), + &env.fetcher, + &env.server.url("/feeds/main.xml"), + 1, + ) + .await + .unwrap(); + let episodes = env.store.episodes(id).unwrap(); + assert_eq!(episodes.len(), 1); + assert_eq!(episodes[0].audio_url, env.server.url("/audio/r.mp3")); + } + + #[tokio::test] + async fn refresh_failure_is_recorded() { + let env = env(); + let feed_url = env.server.url("/feed.xml"); + env.server.set( + "/feed.xml", + Route::new(feed_xml(&env.server, &["a"]), "application/rss+xml"), + ); + let id = subscribe(Arc::clone(&env.store), &env.fetcher, &feed_url, 1) + .await + .unwrap(); + env.server + .set("/feed.xml", Route::new("oops", "text/plain").status(500)); + let err = refresh(Arc::clone(&env.store), &env.fetcher, id, 5) + .await + .unwrap_err(); + assert!(format!("{err:#}").contains("500")); + let podcast = env.store.podcast(id).unwrap().unwrap(); + assert_eq!(podcast.last_checked_at, Some(5)); + assert!(podcast.last_error.unwrap().contains("500")); + assert_eq!( + podcast.episode_count, 1, + "episodes survive a failed refresh" + ); + } + + #[tokio::test] + async fn feed_body_is_capped() { + let env = env(); + let huge = vec![b' '; fetch::MAX_FEED_BYTES + 1]; + env.server + .set("/declared", Route::new(huge.clone(), "application/rss+xml")); + env.server.set( + "/streamed", + Route::new(huge, "application/rss+xml").no_length(), + ); + for path in ["/declared", "/streamed"] { + let result = env + .fetcher + .fetch_feed(&env.server.url(path), None, None) + .await; + let err = result.err().expect("oversized feed must fail"); + assert!(format!("{err:#}").contains("too large"), "{path}: {err:#}"); + } + } + + #[tokio::test] + async fn cover_must_be_an_image() { + let env = env(); + env.server + .set("/not-image", Route::new("hello", "image/png")); + assert!( + env.fetcher + .fetch_cover(1, &env.server.url("/not-image")) + .await + .is_err() + ); + } +} + +mod streaming { + use crate::podcasts::stream::{self, MAX_BUFFERED}; + use crate::podcasts::test_server::{Route, TestServer, noise}; + use std::io::{ErrorKind, Read, Seek, SeekFrom}; + use std::time::{Duration, Instant}; + + const MIB: usize = 1024 * 1024; + + fn read_to_end(reader: &mut impl Read) -> Vec { + let mut out = Vec::new(); + reader.read_to_end(&mut out).unwrap(); + out + } + + fn read_n(reader: &mut impl Read, len: usize) -> Vec { + let mut out = vec![0; len]; + reader.read_exact(&mut out).unwrap(); + out + } + + fn serve(route: Route) -> (TestServer, String) { + let server = TestServer::start(); + server.set("/audio.mp3", route); + let url = server.url("/audio.mp3"); + (server, url) + } + + #[test] + fn sequential_read_matches_source() { + let body = noise(3 * MIB + 123, 1); + let (server, url) = serve(Route::new(body.clone(), "audio/mpeg; charset=binary")); + let mut opened = stream::open(&url).unwrap(); + assert_eq!(opened.byte_len, Some(body.len() as u64)); + assert_eq!(opened.mime_type.as_deref(), Some("audio/mpeg")); + assert!(opened.seekable); + assert_eq!(read_to_end(&mut opened.reader), body); + let mut buf = [0u8; 16]; + assert_eq!(opened.reader.read(&mut buf).unwrap(), 0, "EOF stays EOF"); + assert_eq!( + server.requests("/audio.mp3"), + [Some("bytes=0-".to_string())] + ); + } + + #[test] + fn seeks_forward_backward_and_from_end() { + let body = noise(12 * MIB, 2); + let (server, url) = serve(Route::new(body.clone(), "audio/mpeg")); + let mut reader = stream::open(&url).unwrap().reader; + assert_eq!(read_n(&mut reader, 1000), body[..1000]); + + // Far forward: outside the read-ahead window -> new range request. + let far = 11 * MIB + 7; + assert_eq!( + reader.seek(SeekFrom::Start(far as u64)).unwrap(), + far as u64 + ); + assert_eq!(read_n(&mut reader, 70_000), body[far..far + 70_000]); + assert!( + server + .requests("/audio.mp3") + .contains(&Some(format!("bytes={far}-"))) + ); + + // Small backward seek within the kept window: no new request. + let requests = server.requests("/audio.mp3").len(); + reader.seek(SeekFrom::Current(-50_000)).unwrap(); + let pos = far + 20_000; + assert_eq!(read_n(&mut reader, 1000), body[pos..pos + 1000]); + assert_eq!(server.requests("/audio.mp3").len(), requests); + + // Back into the permanently kept head: no new request. + reader.seek(SeekFrom::Start(10)).unwrap(); + assert_eq!(read_n(&mut reader, 100), body[10..110]); + assert_eq!(server.requests("/audio.mp3").len(), requests); + + // Backward outside the window and the head. + let back = 2 * MIB + 3; + reader.seek(SeekFrom::Start(back as u64)).unwrap(); + assert_eq!(read_n(&mut reader, 300_000), body[back..back + 300_000]); + + // From the end. + let end = reader.seek(SeekFrom::End(-100)).unwrap(); + assert_eq!(end, body.len() as u64 - 100); + assert_eq!(read_to_end(&mut reader), body[body.len() - 100..]); + + // Past the end. + let beyond = reader.seek(SeekFrom::End(50)).unwrap(); + assert_eq!(beyond, body.len() as u64 + 50); + let mut buf = [0u8; 8]; + assert_eq!(reader.read(&mut buf).unwrap(), 0); + assert_eq!( + reader + .seek(SeekFrom::Current(-(beyond as i64) - 1)) + .unwrap_err() + .kind(), + ErrorKind::InvalidInput + ); + } + + #[test] + fn server_without_range_support() { + let body = noise(3 * MIB, 3); + let (server, url) = serve(Route::new(body.clone(), "audio/mpeg").no_ranges()); + let opened = stream::open(&url).unwrap(); + assert!(opened.seekable, "length is known"); + let mut reader = opened.reader; + assert_eq!(read_n(&mut reader, 400_000), body[..400_000]); + // Forward seek: read and discard on the same response. + reader.seek(SeekFrom::Start(2 * MIB as u64)).unwrap(); + assert_eq!(read_n(&mut reader, 1000), body[2 * MIB..2 * MIB + 1000]); + // Backward seek outside window and head: restart from 0. + reader.seek(SeekFrom::Start(300_000)).unwrap(); + let _ = read_n(&mut reader, 1); + reader.seek(SeekFrom::Start(300_000)).unwrap(); + assert_eq!(read_to_end(&mut reader), body[300_000..]); + let requests = server.requests("/audio.mp3"); + assert!(requests.len() >= 2, "{requests:?}"); + assert!(requests[1..].iter().all(Option::is_none), "{requests:?}"); + reader.seek(SeekFrom::End(-10)).unwrap(); + assert_eq!(read_to_end(&mut reader), body[body.len() - 10..]); + } + + #[test] + fn unknown_length_is_not_seekable_from_end() { + let body = noise(MIB + 5, 4); + let (_server, url) = serve( + Route::new(body.clone(), "audio/mpeg") + .no_ranges() + .no_length(), + ); + let opened = stream::open(&url).unwrap(); + assert!(!opened.seekable); + assert_eq!(opened.byte_len, None); + let mut reader = opened.reader; + assert_eq!( + reader.seek(SeekFrom::End(0)).unwrap_err().kind(), + ErrorKind::Unsupported + ); + assert_eq!(read_to_end(&mut reader), body); + } + + #[test] + fn transient_disconnects_are_retried() { + let body = noise(2 * MIB, 5); + let (server, url) = serve(Route::new(body.clone(), "audio/mpeg").cut(700_000, 2)); + let mut reader = stream::open(&url).unwrap().reader; + assert_eq!(read_to_end(&mut reader), body); + let requests = server.requests("/audio.mp3"); + assert_eq!(requests.len(), 3, "{requests:?}"); + assert_eq!(requests[1], Some("bytes=700000-".to_string())); + } + + #[test] + fn persistent_failure_surfaces_an_error() { + let body = noise(2 * MIB, 6); + let (_server, url) = serve(Route::new(body, "audio/mpeg").cut(100_000, 100)); + let mut reader = stream::open(&url).unwrap().reader; + let mut out = Vec::new(); + let started = Instant::now(); + let err = reader.read_to_end(&mut out).unwrap_err(); + assert_eq!(out.len(), 100_000); + assert_eq!(err.kind(), ErrorKind::TimedOut, "{err}"); + assert!(err.to_string().contains("stalled"), "{err}"); + // Bounded by the starvation deadline, not by a retry count. + assert!(started.elapsed() >= stream::STARVE_TIMEOUT); + assert!(started.elapsed() < stream::STARVE_TIMEOUT * 3); + } + + /// An outage that ends while buffered audio is still playing must not + /// end playback: the downloader keeps retrying instead of giving up + /// after a fixed number of attempts. + #[test] + fn outage_shorter_than_the_buffer_is_bridged() { + let body = noise(3 * MIB, 10); + let (server, url) = serve(Route::new(body.clone(), "audio/mpeg").cut(MIB, 4)); + let mut reader = stream::open(&url).unwrap().reader; + assert_eq!(read_n(&mut reader, 1000), body[..1000]); + // "Play" buffered audio while the server fails four times and then + // recovers. + std::thread::sleep(Duration::from_millis(4500)); + assert_eq!(read_to_end(&mut reader), body[1000..]); + let requests = server.requests("/audio.mp3"); + assert_eq!(requests.len(), 5, "{requests:?}"); + assert!( + requests[1..] + .iter() + .all(|range| range.as_deref() == Some("bytes=1048576-")), + "{requests:?}" + ); + } + + #[test] + fn client_errors_are_reported_without_waiting() { + let body = noise(2 * MIB, 11); + let (server, url) = serve(Route::new(body, "audio/mpeg").cut(100_000, 1)); + let mut reader = stream::open(&url).unwrap().reader; + // The signed URL "expires" after the first response. + server.set("/audio.mp3", Route::new("gone", "text/plain").status(404)); + let started = Instant::now(); + let mut out = Vec::new(); + let err = reader.read_to_end(&mut out).unwrap_err(); + assert_eq!(out.len(), 100_000); + assert!(err.to_string().contains("404"), "{err}"); + assert!( + started.elapsed() < stream::STARVE_TIMEOUT, + "{:?}", + started.elapsed() + ); + } + + #[test] + fn large_body_keeps_memory_bounded() { + let body = noise(20 * MIB, 7); + let (_server, url) = serve(Route::new(body.clone(), "audio/mpeg")); + let mut reader = stream::open(&url).unwrap().reader; + let mut buf = vec![0u8; 32 * 1024]; + let mut pos = 0usize; + let mut hasher_ok = true; + loop { + let read = reader.read(&mut buf).unwrap(); + if read == 0 { + break; + } + hasher_ok &= buf[..read] == body[pos..pos + read]; + pos += read; + if pos % (2 * MIB) < 32 * 1024 && pos + stream::READ_AHEAD as usize <= body.len() { + // Let the downloader run ahead until it pauses at its cap. + let deadline = Instant::now() + Duration::from_secs(5); + while reader.buffered_bytes() < stream::READ_AHEAD as usize + && Instant::now() < deadline + { + std::thread::sleep(Duration::from_millis(5)); + } + } + assert!(reader.buffered_bytes() <= MAX_BUFFERED); + } + assert_eq!(pos, body.len()); + assert!(hasher_ok, "data mismatch"); + let peak = reader.peak_buffered_bytes(); + assert!(peak <= MAX_BUFFERED, "peak {peak} > {MAX_BUFFERED}"); + assert!( + peak > 4 * MIB, + "read-ahead should have buffered, peak {peak}" + ); + // Far seeks restart the window without growing its allocation. + for target in [MIB + 5, 15 * MIB, 3 * MIB] { + reader.seek(SeekFrom::Start(target as u64)).unwrap(); + assert_eq!(read_n(&mut reader, 1000), body[target..target + 1000]); + let deadline = Instant::now() + Duration::from_secs(5); + while reader.buffered_bytes() < stream::READ_AHEAD as usize && Instant::now() < deadline + { + std::thread::sleep(Duration::from_millis(5)); + } + } + // The allocation, not just the length, is bounded. + let allocated = reader.peak_allocated_bytes(); + assert!( + allocated <= MAX_BUFFERED, + "allocated {allocated} > {MAX_BUFFERED}" + ); + } + + #[test] + fn dropping_the_reader_stops_the_thread() { + let body = noise(20 * MIB, 8); + let (_server, url) = serve(Route::new(body.clone(), "audio/mpeg")); + let mut reader = stream::open(&url).unwrap().reader; + assert_eq!(read_n(&mut reader, 100_000), body[..100_000]); + let exited = reader.exit_probe(); + let deadline = Instant::now() + Duration::from_secs(5); + // Let it fill the read-ahead window (it then pauses). + while reader.buffered_bytes() < stream::READ_AHEAD as usize && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + assert!(!exited()); + drop(reader); + let deadline = Instant::now() + Duration::from_secs(5); + while !exited() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + assert!(exited(), "downloader thread did not stop"); + + // Also while actively downloading (not paused). + let mut reader = stream::open(&url).unwrap().reader; + let exited = reader.exit_probe(); + let _ = read_n(&mut reader, 10); + drop(reader); + let deadline = Instant::now() + Duration::from_secs(5); + while !exited() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + assert!(exited(), "downloader thread did not stop"); + } + + /// The documented calling convention: `open` on Tokio's blocking pool, + /// reads on another plain thread (like the audio thread). + #[test] + fn open_from_spawn_blocking() { + let body = noise(MIB, 9); + let (server, url) = serve(Route::new(body.clone(), "audio/mpeg")); + server.set("/missing.mp3", Route::new("x", "text/plain").status(404)); + let missing = server.url("/missing.mp3"); + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .unwrap(); + let (opened, failed) = runtime.block_on(async move { + let opened = tokio::task::spawn_blocking(move || stream::open(&url)) + .await + .unwrap(); + let failed = tokio::task::spawn_blocking(move || stream::open(&missing).is_err()) + .await + .unwrap(); + (opened, failed) + }); + assert!(failed); + let mut reader = opened.unwrap().reader; + let read = std::thread::spawn(move || read_to_end(&mut reader)) + .join() + .unwrap(); + assert_eq!(read, body); + drop(runtime); + } + + #[test] + fn open_fails_for_http_errors() { + let (_server, url) = serve(Route::new("gone", "text/plain").status(404)); + let err = stream::open(&url).err().expect("404 must fail"); + assert!(format!("{err:#}").contains("404"), "{err:#}"); + } +} + +/// Manual check against a real feed (not run by default): +/// `FURUMI_PODCAST_FEED=/path/to/rss.xml cargo test podcasts::tests::manual_feed -- --ignored --nocapture` +#[test] +#[ignore] +fn manual_feed() { + let Ok(path) = std::env::var("FURUMI_PODCAST_FEED") else { + return; + }; + let bytes = std::fs::read(&path).unwrap(); + let feed = parse_feed(&bytes).unwrap(); + let dated = feed + .episodes + .iter() + .filter(|e| e.published_at.is_some()) + .count(); + let timed = feed + .episodes + .iter() + .filter(|e| e.duration_seconds.is_some()) + .count(); + println!( + "title={:?} author={:?} image={:?} episodes={} dated={} with_duration={}", + feed.title, + feed.author, + feed.image_url, + feed.episodes.len(), + dated, + timed + ); + for episode in feed.episodes.iter().take(3).chain(feed.episodes.last()) { + println!( + " {:?} | {:?} | {:?} | {}", + episode.title, episode.published_at, episode.duration_seconds, episode.audio_url + ); + } +} + +/// Manual streaming check against a real episode URL (not run by default): +/// `FURUMI_PODCAST_AUDIO=https://... cargo test podcasts::tests::manual_stream -- --ignored --nocapture` +#[test] +#[ignore] +fn manual_stream() { + use std::io::{Read, Seek, SeekFrom}; + let Ok(url) = std::env::var("FURUMI_PODCAST_AUDIO") else { + return; + }; + let started = std::time::Instant::now(); + let mut opened = stream::open(&url).unwrap(); + println!( + "len={:?} mime={:?} seekable={} opened in {:?}", + opened.byte_len, + opened.mime_type, + opened.seekable, + started.elapsed() + ); + let mut buf = vec![0u8; 256 * 1024]; + opened.reader.read_exact(&mut buf).unwrap(); + println!("first bytes {:02x?}", &buf[..4]); + if let Some(len) = opened.byte_len { + let started = std::time::Instant::now(); + opened.reader.seek(SeekFrom::Start(len / 2)).unwrap(); + opened.reader.read_exact(&mut buf).unwrap(); + println!("seek to middle + 256 KiB in {:?}", started.elapsed()); + } +} + +#[test] +fn http_stream_is_send_and_sync() { + fn check() {} + check::(); +} diff --git a/src/ui/mod.rs b/src/ui/mod.rs index 5d5cac3..bd33e73 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -4,6 +4,7 @@ mod federation; pub(crate) mod global; mod logs; mod playlists; +mod podcasts; mod popup; #[cfg(test)] mod status_tests; @@ -75,6 +76,7 @@ pub fn draw(frame: &mut Frame, state: &AppState, keymap: &Keymap) { Tab::Queue => draw_queue(frame, main_area, state), Tab::Federation => federation::draw(frame, main_area, state), Tab::Logs => logs::draw(frame, main_area, state), + Tab::Podcasts => podcasts::draw(frame, main_area, state), } draw_status(frame, status_area, state); @@ -140,13 +142,22 @@ fn is_waiting_message(message: &str) -> bool { } fn draw_tabs(frame: &mut Frame, area: Rect, state: &AppState) { - let titles = Tab::ALL - .iter() - .map(|tab| format!(" {} {} ", tab.index() + 1, tab.title())); + // Titles carry their own spacing. When all of them do not fit, inactive + // tabs collapse to their number so the active one is never cut off. + let full: usize = Tab::ALL.iter().map(|tab| tab.title().len() + 4).sum(); + let compact = full > usize::from(area.width); + let titles = Tab::ALL.iter().map(|tab| { + if compact && *tab != state.active_tab { + format!(" {} ", tab.index() + 1) + } else { + format!(" {} {} ", tab.index() + 1, tab.title()) + } + }); let tabs = Tabs::new(titles) .select(state.active_tab.index()) .style(theme::dim()) .highlight_style(theme::tab_active_for(state)) + .padding("", "") .divider(""); frame.render_widget(tabs, area); } diff --git a/src/ui/podcasts.rs b/src/ui/podcasts.rs new file mode 100644 index 0000000..746bb45 --- /dev/null +++ b/src/ui/podcasts.rs @@ -0,0 +1,493 @@ +//! Podcasts tab: subscriptions with their cover, and the episode catalog of +//! one podcast with title search, date sort and the selected episode's notes. + +use ratatui::Frame; +use ratatui::layout::{Alignment, Constraint, Layout, Rect}; +use ratatui::style::{Color, Modifier, Style}; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{Block, Borders, Paragraph, Wrap}; +use unicode_width::UnicodeWidthStr; + +use super::{loading_line, theme}; +use crate::app::state::{ + ART_HEADER_HEIGHT, ART_HEADER_WIDTH, AppState, ArtState, Loadable, PodcastListRow, +}; +use crate::podcasts::{Episode, Podcast}; + +/// Width below which the side panel with the cover is dropped. +const SIDE_PANEL_MIN_TOTAL_WIDTH: u16 = 72; +const SIDE_PANEL_WIDTH: u16 = ART_HEADER_WIDTH + 2; + +pub fn draw(frame: &mut Frame, area: Rect, state: &AppState) { + match state.podcasts.opened { + Some(opened) => draw_episodes(frame, area, state, opened.id, opened.cursor), + None => draw_list(frame, area, state), + } +} + +fn bordered(frame: &mut Frame, area: Rect, state: &AppState, title: String) -> Rect { + let block = Block::bordered() + .title(title) + .title_style(theme::header_for(state)) + .border_style(theme::border_for(state)); + let inner = block.inner(area); + frame.render_widget(block, area); + inner +} + +fn centered_line(frame: &mut Frame, area: Rect, line: Line) { + if area.height == 0 { + return; + } + let middle = Rect { + y: area.y + area.height / 2, + height: 1, + ..area + }; + frame.render_widget(Paragraph::new(line).alignment(Alignment::Center), middle); +} + +fn error_style() -> Style { + Style::new().fg(Color::Red) +} + +fn draw_list(frame: &mut Frame, area: Rect, state: &AppState) { + let tab = &state.podcasts; + let inner = bordered(frame, area, state, " Podcasts ".to_string()); + match &tab.list { + Some(Loadable::Failed(error)) => { + return centered_line(frame, inner, Line::styled(error.clone(), error_style())); + } + None | Some(Loadable::Loading) => { + return centered_line(frame, inner, loading_line(state, "loading podcasts…")); + } + Some(Loadable::Ready(_)) => {} + } + + let (list_area, side_area) = split_side_panel(inner); + if let Some(side) = side_area { + draw_side_panel(frame, side, state, tab.current_podcast()); + } + + let rows = tab.list_rows(); + let visible = usize::from(list_area.height.max(1)); + let first = tab + .selected + .saturating_sub(visible / 2) + .min(rows.len().saturating_sub(visible)); + for (index, row) in rows.iter().enumerate().skip(first).take(visible) { + let area = Rect { + x: list_area.x, + y: list_area.y + (index - first) as u16, + width: list_area.width, + height: 1, + }; + let (left, right) = list_row_lines(state, *row, list_area.width); + frame.render_widget(Paragraph::new(left), area); + if let Some(right) = right { + frame.render_widget(Paragraph::new(right).alignment(Alignment::Right), area); + } + if index == tab.selected { + frame + .buffer_mut() + .set_style(area, theme::tab_active_for(state)); + } + } + if tab.podcasts().is_empty() { + let hint_y = list_area.y + rows.len() as u16 + 1; + if hint_y < list_area.y + list_area.height { + frame.render_widget( + Paragraph::new(Line::styled( + "No subscriptions yet. Choose \"Add podcast\" and paste an RSS feed URL.", + theme::dim(), + )) + .wrap(Wrap { trim: true }), + Rect { + y: hint_y, + height: list_area.y + list_area.height - hint_y, + ..list_area + }, + ); + } + } +} + +fn list_row_lines( + state: &AppState, + row: PodcastListRow, + width: u16, +) -> (Line<'static>, Option>) { + let tab = &state.podcasts; + match row { + PodcastListRow::Add => { + let label = if tab.subscribing { + format!("{} Adding podcast…", state.spinner()) + } else { + "+ Add podcast (RSS feed URL)…".to_string() + }; + (Line::styled(label, theme::accent_for(state)), None) + } + PodcastListRow::RefreshAll => { + let busy = !tab.refreshing.is_empty(); + let label = if busy { + format!( + "{} Checking {} feed(s) for new episodes…", + state.spinner(), + tab.refreshing.len() + ) + } else { + "↻ Check all podcasts for new episodes".to_string() + }; + (Line::styled(label, theme::accent_for(state)), None) + } + PodcastListRow::Podcast(index) => { + let Some(podcast) = tab.podcasts().get(index) else { + return (Line::raw(""), None); + }; + let marker = if tab.refreshing.contains(&podcast.id) { + Span::styled(format!("{} ", state.spinner()), theme::accent_for(state)) + } else if podcast.last_error.is_some() { + Span::styled("! ", error_style()) + } else { + Span::raw(" ") + }; + let mut meta = format!("{} ep", podcast.episode_count); + if let Some(latest) = podcast.latest_published_at { + meta.push_str(&format!(" · {}", format_date(latest))); + } + meta.push(' '); + // Marker (2), the title, one gap column, then the meta. + let title_width = + usize::from(width).saturating_sub(2 + UnicodeWidthStr::width(meta.as_str()) + 1); + let left = Line::from(vec![ + marker, + Span::raw(fit_width(&podcast.title, title_width)), + ]); + (left, Some(Line::styled(meta, theme::dim()))) + } + } +} + +/// Main area plus an optional right-hand panel for the cover and details. +fn split_side_panel(area: Rect) -> (Rect, Option) { + if area.width < SIDE_PANEL_MIN_TOTAL_WIDTH { + return (area, None); + } + let [main, side] = + Layout::horizontal([Constraint::Min(0), Constraint::Length(SIDE_PANEL_WIDTH)]).areas(area); + (main, Some(side)) +} + +fn draw_side_panel(frame: &mut Frame, area: Rect, state: &AppState, podcast: Option<&Podcast>) { + let block = Block::default() + .borders(Borders::LEFT) + .border_style(theme::border_for(state)); + let inner = block.inner(area); + frame.render_widget(block, area); + let Some(podcast) = podcast else { + return; + }; + let inner = Rect { + x: inner.x + 1, + width: inner.width.saturating_sub(1), + ..inner + }; + let art_height = ART_HEADER_HEIGHT.min(inner.height); + draw_cover( + frame, + Rect { + height: art_height, + width: ART_HEADER_WIDTH.min(inner.width), + ..inner + }, + state, + podcast, + ); + let text_area = Rect { + y: inner.y + art_height + 1, + height: inner.height.saturating_sub(art_height + 1), + ..inner + }; + if text_area.height == 0 { + return; + } + let mut lines = vec![Line::styled( + podcast.title.clone(), + Style::new().add_modifier(Modifier::BOLD), + )]; + if let Some(author) = &podcast.author { + lines.push(Line::styled(author.clone(), theme::dim())); + } + lines.push(Line::styled( + format!("{} episodes", podcast.episode_count), + theme::dim(), + )); + lines.extend(check_status_line(state, podcast)); + if let Some(description) = &podcast.description { + lines.push(Line::raw("")); + lines.push(Line::raw(description.clone())); + } + frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: true }), text_area); +} + +fn check_status_line(state: &AppState, podcast: &Podcast) -> Option> { + if state.podcasts.refreshing.contains(&podcast.id) { + return Some(loading_line(state, "checking for new episodes…")); + } + if let Some(error) = &podcast.last_error { + return Some(Line::styled( + format!("last check failed: {error}"), + error_style(), + )); + } + podcast + .last_checked_at + .map(|at| Line::styled(format!("checked {}", format_date(at)), theme::dim())) +} + +fn draw_cover(frame: &mut Frame, area: Rect, state: &AppState, podcast: &Podcast) { + let art = podcast.cover_path.as_ref().and_then(|path| { + state.art.get(&crate::art::cache_key( + path, + ART_HEADER_WIDTH, + ART_HEADER_HEIGHT, + )) + }); + match art { + Some(ArtState::Ready(image)) => { + frame.render_widget(Paragraph::new(super::art::to_text(image)), area); + } + Some(ArtState::Loading) => centered_line(frame, area, Line::styled("…", theme::dim())), + _ => centered_line(frame, area, Line::styled("🎙", theme::dim())), + } +} + +fn draw_episodes(frame: &mut Frame, area: Rect, state: &AppState, id: i64, cursor: usize) { + let tab = &state.podcasts; + let podcast = tab.podcast(id); + let title = podcast.map_or("…".to_string(), |podcast| podcast.title.clone()); + let mut header = format!(" Podcasts ▸ {title} · {} ", tab.sort.label()); + if !tab.filter.is_empty() { + header.push_str(&format!("· search: \"{}\" ", tab.filter)); + } + let inner = bordered(frame, area, state, header); + + let episodes = match &tab.episodes { + Some((loaded, Loadable::Ready(episodes))) if *loaded == id => episodes, + Some((loaded, Loadable::Failed(error))) if *loaded == id => { + return centered_line(frame, inner, Line::styled(error.clone(), error_style())); + } + _ => return centered_line(frame, inner, loading_line(state, "loading episodes…")), + }; + let visible_indices = tab.visible_episode_indices(); + + let (main, side) = split_side_panel(inner); + if let Some(side) = side { + draw_side_panel(frame, side, state, podcast); + } + // Episode notes below the list when there is room for them. + let notes_height = if main.height >= 16 { 6 } else { 0 }; + let [list_area, notes_area] = + Layout::vertical([Constraint::Min(1), Constraint::Length(notes_height)]).areas(main); + let [summary_area, list_area] = + Layout::vertical([Constraint::Length(1), Constraint::Min(0)]).areas(list_area); + + let summary = if tab.filter.is_empty() { + format!("{} episodes", episodes.len()) + } else { + format!( + "{} of {} episodes match \"{}\"", + visible_indices.len(), + episodes.len(), + tab.filter + ) + }; + let mut summary_spans = vec![Span::styled(summary, theme::dim())]; + if tab.refreshing.contains(&id) { + summary_spans.push(Span::raw(" ")); + summary_spans.extend(loading_line(state, "checking for new episodes…").spans); + } + frame.render_widget(Paragraph::new(Line::from(summary_spans)), summary_area); + + if visible_indices.is_empty() { + let message = if episodes.is_empty() { + "this feed has no playable episodes" + } else { + "no episode title matches the search" + }; + return centered_line(frame, list_area, Line::styled(message, theme::dim())); + } + + let cursor = cursor.min(visible_indices.len() - 1); + let playing_id = state + .player + .current + .as_ref() + .and_then(|track| crate::podcasts::episode_id_from_track_id(track.id)); + let visible = usize::from(list_area.height.max(1)); + let first = cursor + .saturating_sub(visible / 2) + .min(visible_indices.len().saturating_sub(visible)); + for (row_index, &episode_index) in visible_indices.iter().enumerate().skip(first).take(visible) + { + let episode = &episodes[episode_index]; + let area = Rect { + x: list_area.x, + y: list_area.y + (row_index - first) as u16, + width: list_area.width, + height: 1, + }; + draw_episode_row( + frame, + area, + state, + episode, + playing_id == Some(episode.id), + row_index == cursor, + ); + } + + if notes_height > 0 + && let Some(episode) = visible_indices + .get(cursor) + .and_then(|&index| episodes.get(index)) + { + draw_notes(frame, notes_area, state, episode); + } +} + +fn draw_episode_row( + frame: &mut Frame, + area: Rect, + state: &AppState, + episode: &Episode, + playing: bool, + selected: bool, +) { + let date = episode + .published_at + .map(format_date) + .unwrap_or_else(|| " ".to_string()); + let marker = if playing { + Span::styled("▶ ", theme::accent_for(state)) + } else { + Span::raw(" ") + }; + let duration = episode + .duration_seconds + .map(format_duration) + .unwrap_or_default(); + let title_width = usize::from(area.width) + .saturating_sub(2 + 10 + 2 + UnicodeWidthStr::width(duration.as_str()) + 2); + let line = Line::from(vec![ + marker, + Span::styled(date, theme::dim()), + Span::raw(" "), + Span::raw(fit_width(&episode.title, title_width)), + ]); + frame.render_widget(Paragraph::new(line), area); + if !duration.is_empty() { + frame.render_widget( + Paragraph::new(Line::styled(format!("{duration} "), theme::dim())) + .alignment(Alignment::Right), + area, + ); + } + if selected { + frame + .buffer_mut() + .set_style(area, theme::tab_active_for(state)); + } +} + +fn draw_notes(frame: &mut Frame, area: Rect, state: &AppState, episode: &Episode) { + let block = Block::default() + .borders(Borders::TOP) + .border_style(theme::border_for(state)) + .title(Span::styled(" Episode notes ", theme::dim())); + let inner = block.inner(area); + frame.render_widget(block, area); + let text = episode + .description + .clone() + .unwrap_or_else(|| "No description in the feed.".to_string()); + frame.render_widget( + Paragraph::new(Line::raw(text)).wrap(Wrap { trim: true }), + inner, + ); +} + +/// Truncate to a display width, adding an ellipsis when cut. +fn fit_width(text: &str, width: usize) -> String { + if UnicodeWidthStr::width(text) <= width { + return text.to_string(); + } + if width == 0 { + return String::new(); + } + let mut out = String::new(); + let mut used = 0; + for ch in text.chars() { + let w = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0); + if used + w + 1 > width { + break; + } + out.push(ch); + used += w; + } + out.push('…'); + out +} + +fn format_duration(seconds: f64) -> String { + let total = seconds.max(0.0).round() as u64; + let (hours, minutes, secs) = (total / 3600, total / 60 % 60, total % 60); + if hours > 0 { + format!("{hours}:{minutes:02}:{secs:02}") + } else { + format!("{minutes}:{secs:02}") + } +} + +/// `YYYY-MM-DD` (UTC) for unix seconds, without a date library: Howard +/// Hinnant's days-to-civil algorithm. +fn format_date(unix_seconds: i64) -> String { + let days = unix_seconds.div_euclid(86_400); + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + format!("{year:04}-{month:02}-{day:02}") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn formats_dates_in_utc() { + assert_eq!(format_date(0), "1970-01-01"); + assert_eq!(format_date(951_782_400), "2000-02-29"); + assert_eq!(format_date(1_718_409_600), "2024-06-15"); + assert_eq!(format_date(-86_400), "1969-12-31"); + } + + #[test] + fn formats_durations() { + assert_eq!(format_duration(59.6), "1:00"); + assert_eq!(format_duration(754.0), "12:34"); + assert_eq!(format_duration(3_723.0), "1:02:03"); + } + + #[test] + fn fits_display_width_with_ellipsis() { + assert_eq!(fit_width("Выпуск 650", 20), "Выпуск 650"); + assert_eq!(fit_width("Выпуск 650", 5), "Выпу…"); + assert_eq!(fit_width("abc", 0), ""); + } +} diff --git a/src/ui/popup.rs b/src/ui/popup.rs index d6ba588..660a0b9 100644 --- a/src/ui/popup.rs +++ b/src/ui/popup.rs @@ -24,7 +24,9 @@ pub fn draw(frame: &mut Frame, state: &AppState) { error, .. }) => draw_edit(frame, state, title, fields, *focus, error.as_deref()), - Some(Popup::ConfirmDelete { label, .. }) => draw_confirm_delete(frame, state, label), + Some(Popup::ConfirmDelete { target, label }) => { + draw_confirm_delete(frame, state, *target, label) + } Some(Popup::SimilarityPrivacyConsent { .. }) => { draw_similarity_privacy_consent(frame, state) } @@ -43,7 +45,12 @@ pub fn draw(frame: &mut Frame, state: &AppState) { }) => draw_track_artists(frame, state, tracks, *cursor, *selected), Some(Popup::LogDetail(entry)) => draw_log_detail(frame, state, entry), Some(Popup::FedInput { field, input }) => { - draw_fed_input(frame, state, field.title(), field.help(), input) + let keys = if *field == crate::app::state::FedInputField::PodcastFilter { + "enter: keep · esc: clear" + } else { + "enter: apply · esc: cancel" + }; + draw_fed_input(frame, state, field.title(), field.help(), keys, input) } Some(Popup::FedText { title, text }) => draw_fed_text(frame, state, title, text), Some(Popup::FedCopyText { @@ -891,6 +898,7 @@ fn draw_fed_input( state: &AppState, title: &str, help: &str, + keys: &str, input: &crate::app::input::LineEdit, ) { let area = centered(frame.area(), 72, 8); @@ -916,8 +924,7 @@ fn draw_fed_input( let spans = super::line_edit_spans(input, usize::from(entry_area.width.saturating_sub(1))); frame.render_widget(Paragraph::new(Line::from(spans)), entry_area); frame.render_widget( - Paragraph::new(Line::styled("enter: apply · esc: cancel", theme::dim())) - .alignment(Alignment::Center), + Paragraph::new(Line::styled(keys.to_string(), theme::dim())).alignment(Alignment::Center), hint_area, ); } @@ -1241,11 +1248,23 @@ fn draw_edit( frame.render_widget(Paragraph::new(hint).alignment(Alignment::Center), footer); } -fn draw_confirm_delete(frame: &mut Frame, state: &AppState, label: &str) { +fn draw_confirm_delete( + frame: &mut Frame, + state: &AppState, + target: crate::app::state::DeleteTarget, + label: &str, +) { + // Unsubscribing only drops the feed's stored metadata, not music. + let (title, verb, key) = match target { + crate::app::state::DeleteTarget::Podcast(_) => { + (" Unsubscribe? ", "Unsubscribe from", "unsubscribe") + } + _ => (" Delete? ", "Delete", "delete"), + }; let width = 64.min(frame.area().width.saturating_sub(4)).max(30); let area = centered(frame.area(), width, 7); let block = Block::bordered() - .title(" Delete? ") + .title(title) .title_style(theme::header_for(state)) .border_style(theme::strong_border_for(state)); let inner = block.inner(area); @@ -1254,14 +1273,17 @@ fn draw_confirm_delete(frame: &mut Frame, state: &AppState, label: &str) { let [body, footer] = Layout::vertical([Constraint::Min(1), Constraint::Length(1)]).areas(inner); frame.render_widget( - Paragraph::new(format!("Delete {label}?")) + Paragraph::new(format!("{verb} {label}?")) .wrap(Wrap { trim: false }) .alignment(Alignment::Center), body, ); frame.render_widget( - Paragraph::new(Line::styled("enter/y delete · esc/n cancel", theme::dim())) - .alignment(Alignment::Center), + Paragraph::new(Line::styled( + format!("enter/y {key} · esc/n cancel"), + theme::dim(), + )) + .alignment(Alignment::Center), footer, ); } -- 2.54.0