Add podcast RSS subscriptions with streaming playback
(cherry picked from commit 20167c5b5e2a55b1965fe7f7a095b909ce2d9267) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
292f17fee1
commit
0da9862cf3
30 files changed
+7479
-75
No files matched your search
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
Generated
+2
@@ -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",
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
@@ -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
|
||||
|
||||
+5
-1
@@ -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(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -206,4 +206,26 @@ pub enum AppEvent {
|
||||
JamInvite(Result<String, String>),
|
||||
/// Result of joining a Jam capability.
|
||||
JamJoined(Result<String, String>),
|
||||
/// Podcast subscriptions (re)loaded from the podcast store.
|
||||
PodcastsLoaded(Result<Vec<crate::podcasts::Podcast>, String>),
|
||||
/// The stored episode catalog of one podcast.
|
||||
PodcastEpisodesLoaded {
|
||||
podcast_id: i64,
|
||||
result: Result<Vec<crate::podcasts::Episode>, String>,
|
||||
},
|
||||
/// A new subscription was stored (its id) or rejected.
|
||||
PodcastSubscribed(Result<i64, String>),
|
||||
/// One feed refresh finished.
|
||||
PodcastRefreshed {
|
||||
podcast_id: i64,
|
||||
result: Result<crate::podcasts::RefreshSummary, String>,
|
||||
/// 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,
|
||||
}
|
||||
+161
-17
@@ -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<std::sync::atomic::AtomicU64>,
|
||||
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<crate::media::MediaUpdate>,
|
||||
pub last_media_push: Option<std::time::Instant>,
|
||||
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<podcast_runtime::PodcastRuntime>,
|
||||
/// 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<std::sync::atomic::AtomicU64>,
|
||||
}
|
||||
|
||||
#[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;
|
||||
|
||||
@@ -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<crate::podcasts::Store>,
|
||||
pub fetcher: Arc<crate::podcasts::Fetcher>,
|
||||
refresh_slots: Arc<tokio::sync::Semaphore>,
|
||||
}
|
||||
|
||||
/// 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<PodcastRuntime, String> {
|
||||
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<AppEvent>) {
|
||||
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<i64>, 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<i64>, 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<i64>) {
|
||||
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<i64> = 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<AppEvent> {
|
||||
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<i64> {
|
||||
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<i64>) {
|
||||
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));
|
||||
}
|
||||
}
|
||||
+44
-3
@@ -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(()) => {
|
||||
|
||||
+184
-1
@@ -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<Loadable<Vec<crate::podcasts::Podcast>>>,
|
||||
/// Cursor over `podcast_list_rows` (action rows first, then podcasts).
|
||||
pub selected: usize,
|
||||
pub opened: Option<OpenedPodcast>,
|
||||
/// 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<Vec<crate::podcasts::Episode>>)>,
|
||||
/// 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<i64>,
|
||||
pub subscribing: bool,
|
||||
/// Wall-clock seconds of the last automatic refresh sweep.
|
||||
pub last_auto_refresh: Option<i64>,
|
||||
/// Newly subscribed podcast to select once the reloaded list arrives.
|
||||
pub pending_select: Option<i64>,
|
||||
}
|
||||
|
||||
/// "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<PodcastListRow> {
|
||||
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<usize> {
|
||||
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<usize> {
|
||||
let terms: Vec<String> = filter.split_whitespace().map(str::to_lowercase).collect();
|
||||
let mut indices: Vec<usize> = 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<crate::federation::FedArtistCard>)>,
|
||||
|
||||
+243
-4
@@ -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<i64>),
|
||||
PodcastUnsubscribe(i64),
|
||||
}
|
||||
|
||||
pub fn update(state: &mut AppState, action: Action) -> Option<Effect> {
|
||||
@@ -283,6 +290,7 @@ pub fn update(state: &mut AppState, action: Action) -> Option<Effect> {
|
||||
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<Effect> {
|
||||
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<Effect> {
|
||||
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<Effect> {
|
||||
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<TrackItem> = 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<Effect> {
|
||||
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<TrackItem> {
|
||||
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<TrackItem> {
|
||||
.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<Effect> {
|
||||
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<Effect> {
|
||||
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<Effect> {
|
||||
if state.active_tab != Tab::Podcasts {
|
||||
return None;
|
||||
}
|
||||
let ids: Vec<i64> = match state.podcasts.opened {
|
||||
Some(opened) => vec![opened.id],
|
||||
None => state.podcasts.podcasts().iter().map(|p| p.id).collect(),
|
||||
};
|
||||
let ids: Vec<i64> = 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<Effect> {
|
||||
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<TrackItem> {
|
||||
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<Effect> {
|
||||
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"));
|
||||
}
|
||||
|
||||
+250
-1
@@ -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<i64>) -> 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<String> {
|
||||
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<i64> {
|
||||
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);
|
||||
}
|
||||
@@ -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"
|
||||
@@ -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",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+19
-3
@@ -131,6 +131,12 @@ pub struct PlaybackTrack {
|
||||
pub fed: Option<SyncedFedTrack>,
|
||||
}
|
||||
|
||||
/// 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<String> {
|
||||
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(),
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
@@ -7,6 +7,7 @@ mod jam;
|
||||
mod library;
|
||||
mod media;
|
||||
mod player;
|
||||
mod podcasts;
|
||||
mod share;
|
||||
mod similarity;
|
||||
mod status;
|
||||
|
||||
+84
-32
@@ -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<u64>) {
|
||||
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<Output>,
|
||||
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<dyn Source + Send>;
|
||||
|
||||
pub(crate) fn decode_source(
|
||||
reader: TrackReader,
|
||||
byte_len: Option<u64>,
|
||||
mime_type: Option<&str>,
|
||||
seekable: bool,
|
||||
) -> Result<DecodedSource, String> {
|
||||
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<u64>,
|
||||
mime_type: Option<&str>,
|
||||
seekable: bool,
|
||||
coarse_seek: bool,
|
||||
) -> Result<DecodedSource, String> {
|
||||
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);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,207 @@
|
||||
//! Async HTTP for podcast feeds and cover images.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use reqwest::header::{ACCEPT, ETAG, IF_MODIFIED_SINCE, IF_NONE_MATCH, LAST_MODIFIED};
|
||||
use reqwest::{StatusCode, Url};
|
||||
|
||||
use super::feed::{ParsedFeed, parse_feed_with_base};
|
||||
|
||||
/// Hard cap on a feed document (large catalogs are a few MiB).
|
||||
pub const MAX_FEED_BYTES: usize = 32 * 1024 * 1024;
|
||||
/// Hard cap on a cover image.
|
||||
pub const MAX_COVER_BYTES: usize = 10 * 1024 * 1024;
|
||||
|
||||
const FEED_ACCEPT: &str =
|
||||
"application/rss+xml, application/atom+xml, application/xml;q=0.9, text/xml;q=0.9, */*;q=0.5";
|
||||
|
||||
pub enum FeedFetch {
|
||||
NotModified,
|
||||
Fetched {
|
||||
feed: ParsedFeed,
|
||||
etag: Option<String>,
|
||||
last_modified: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
pub struct Fetcher {
|
||||
client: reqwest::Client,
|
||||
covers_dir: PathBuf,
|
||||
}
|
||||
|
||||
impl Fetcher {
|
||||
pub fn new(covers_dir: PathBuf) -> Result<Fetcher> {
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
let client = reqwest::Client::builder()
|
||||
.connect_timeout(Duration::from_secs(15))
|
||||
.timeout(Duration::from_secs(60))
|
||||
.redirect(reqwest::redirect::Policy::limited(10))
|
||||
.user_agent(concat!("furumi/", env!("CARGO_PKG_VERSION")))
|
||||
.build()
|
||||
.context("building the podcast HTTP client")?;
|
||||
Ok(Fetcher { client, covers_dir })
|
||||
}
|
||||
|
||||
/// Conditional GET of a feed. Parsing runs on the blocking pool.
|
||||
pub async fn fetch_feed(
|
||||
&self,
|
||||
url: &str,
|
||||
etag: Option<&str>,
|
||||
last_modified: Option<&str>,
|
||||
) -> Result<FeedFetch> {
|
||||
let mut request = self.client.get(url).header(ACCEPT, FEED_ACCEPT);
|
||||
if let Some(etag) = etag {
|
||||
request = request.header(IF_NONE_MATCH, etag);
|
||||
}
|
||||
if let Some(last_modified) = last_modified {
|
||||
request = request.header(IF_MODIFIED_SINCE, last_modified);
|
||||
}
|
||||
let response = request
|
||||
.send()
|
||||
.await
|
||||
.with_context(|| format!("fetching feed {url}"))?;
|
||||
let status = response.status();
|
||||
if status == StatusCode::NOT_MODIFIED {
|
||||
return Ok(FeedFetch::NotModified);
|
||||
}
|
||||
if !status.is_success() {
|
||||
bail!("feed request failed: HTTP {status}");
|
||||
}
|
||||
let header = |name| {
|
||||
response
|
||||
.headers()
|
||||
.get(name)
|
||||
.and_then(|value: &reqwest::header::HeaderValue| value.to_str().ok())
|
||||
.map(str::to_string)
|
||||
};
|
||||
let etag = header(ETAG);
|
||||
let last_modified = header(LAST_MODIFIED);
|
||||
// Relative enclosure URLs resolve against where the feed really is
|
||||
// (after redirects).
|
||||
let base = response.url().to_string();
|
||||
let body = read_capped(response, MAX_FEED_BYTES, "feed").await?;
|
||||
let feed = tokio::task::spawn_blocking(move || parse_feed_with_base(&body, Some(&base)))
|
||||
.await
|
||||
.map_err(|err| anyhow!("feed parser task failed: {err}"))??;
|
||||
Ok(FeedFetch::Fetched {
|
||||
feed,
|
||||
etag,
|
||||
last_modified,
|
||||
})
|
||||
}
|
||||
|
||||
/// Downloads a cover image into the covers directory and returns its path.
|
||||
pub async fn fetch_cover(&self, podcast_id: i64, image_url: &str) -> Result<PathBuf> {
|
||||
let response = self
|
||||
.client
|
||||
.get(image_url)
|
||||
.send()
|
||||
.await
|
||||
.with_context(|| format!("fetching cover {image_url}"))?;
|
||||
let status = response.status();
|
||||
if !status.is_success() {
|
||||
bail!("cover request failed: HTTP {status}");
|
||||
}
|
||||
let body = read_capped(response, MAX_COVER_BYTES, "cover image").await?;
|
||||
let format = image::guess_format(&body).context("cover is not a supported image")?;
|
||||
let extension = format.extensions_str().first().copied().unwrap_or("img");
|
||||
let hash = blake3::hash(image_url.as_bytes()).to_hex();
|
||||
let name = format!("{podcast_id}-{}.{extension}", &hash.as_str()[..16]);
|
||||
let dir = self.covers_dir.clone();
|
||||
tokio::task::spawn_blocking(move || write_atomically(&dir, &name, &body))
|
||||
.await
|
||||
.map_err(|err| anyhow!("cover writer task failed: {err}"))?
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_capped(mut response: reqwest::Response, cap: usize, what: &str) -> Result<Vec<u8>> {
|
||||
if let Some(len) = response.content_length()
|
||||
&& len > cap as u64
|
||||
{
|
||||
bail!("{what} is too large ({len} bytes, limit {cap})");
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
while let Some(chunk) = response
|
||||
.chunk()
|
||||
.await
|
||||
.with_context(|| format!("reading {what}"))?
|
||||
{
|
||||
if body.len() + chunk.len() > cap {
|
||||
bail!("{what} is too large (over {cap} bytes)");
|
||||
}
|
||||
body.extend_from_slice(&chunk);
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
fn write_atomically(dir: &Path, name: &str, bytes: &[u8]) -> Result<PathBuf> {
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
|
||||
let target = dir.join(name);
|
||||
let temp = dir.join(format!(
|
||||
".{name}.{}-{}.tmp",
|
||||
std::process::id(),
|
||||
COUNTER.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
let result = std::fs::write(&temp, bytes)
|
||||
.and_then(|()| std::fs::rename(&temp, &target))
|
||||
.with_context(|| format!("writing {}", target.display()));
|
||||
if result.is_err() {
|
||||
let _ = std::fs::remove_file(&temp);
|
||||
}
|
||||
result?;
|
||||
Ok(target)
|
||||
}
|
||||
|
||||
/// Whether `text` starts with `<scheme>://`. Only a prefix counts: a URL
|
||||
/// embedded in the query (`a.test/rss?src=https://b.test`) is not a scheme.
|
||||
fn has_scheme(text: &str) -> bool {
|
||||
let Some((scheme, rest)) = text.split_once(':') else {
|
||||
return false;
|
||||
};
|
||||
let mut chars = scheme.chars();
|
||||
chars.next().is_some_and(|c| c.is_ascii_alphabetic())
|
||||
&& chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
|
||||
&& rest.starts_with("//")
|
||||
}
|
||||
|
||||
/// Normalizes user input into a feed URL: trims, maps `feed://`,
|
||||
/// `podcast://`, `pcast://` and `itpc://` to `https://`, defaults to
|
||||
/// `https://` without a scheme and accepts only http(s) URLs with a host.
|
||||
pub fn normalize_feed_url(input: &str) -> Result<String> {
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
bail!("feed URL is empty");
|
||||
}
|
||||
if trimmed.chars().any(char::is_whitespace) {
|
||||
bail!("feed URL must not contain whitespace");
|
||||
}
|
||||
let lower = trimmed.to_ascii_lowercase();
|
||||
let mut candidate = trimmed.to_string();
|
||||
for scheme in ["feed:", "podcast:", "pcast:", "itpc:"] {
|
||||
if lower.starts_with(scheme) {
|
||||
let rest = &trimmed[scheme.len()..];
|
||||
let rest_lower = rest.to_ascii_lowercase();
|
||||
candidate = if rest_lower.starts_with("http://") || rest_lower.starts_with("https://") {
|
||||
rest.to_string()
|
||||
} else {
|
||||
format!("https://{}", rest.trim_start_matches('/'))
|
||||
};
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !has_scheme(&candidate) {
|
||||
candidate = format!("https://{candidate}");
|
||||
}
|
||||
let url = Url::parse(&candidate).with_context(|| format!("invalid feed URL {trimmed:?}"))?;
|
||||
if !matches!(url.scheme(), "http" | "https") {
|
||||
bail!("unsupported feed URL scheme {:?}", url.scheme());
|
||||
}
|
||||
if url.host_str().is_none_or(str::is_empty) {
|
||||
bail!("feed URL has no host");
|
||||
}
|
||||
Ok(url.to_string())
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
//! Podcast RSS/Atom subscriptions.
|
||||
//!
|
||||
//! Furumi stores only subscription and episode *metadata* (SQLite, see
|
||||
//! [`store`]); audio stays on the publisher's host and is streamed on demand
|
||||
//! through [`stream`] when an episode is played. Adding a subscription never
|
||||
//! downloads episodes.
|
||||
//!
|
||||
//! * [`feed`] parses RSS 2.0 / RSS 1.0 / Atom documents.
|
||||
//! * [`fetch`] downloads feeds (conditional GET) and cover images.
|
||||
//! * [`store`] persists podcasts and episodes, deduplicated by GUID.
|
||||
//! * [`stream`] plays a remote episode through a bounded read-ahead buffer.
|
||||
//! * [`subscribe`] / [`refresh`] orchestrate the above without blocking
|
||||
//! Tokio workers.
|
||||
|
||||
pub mod feed;
|
||||
pub mod fetch;
|
||||
pub mod store;
|
||||
pub mod stream;
|
||||
|
||||
#[cfg(test)]
|
||||
mod test_server;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Result, anyhow, bail};
|
||||
|
||||
use crate::library::models::{ArtistRef, TrackItem};
|
||||
|
||||
pub use fetch::{FeedFetch, Fetcher, normalize_feed_url};
|
||||
pub use store::Store;
|
||||
// Convenience re-exports used by the module's tests.
|
||||
#[cfg(test)]
|
||||
pub use feed::{ParsedEpisode, ParsedFeed, parse_feed, parse_feed_with_base};
|
||||
#[cfg(test)]
|
||||
pub use stream::HttpStream;
|
||||
|
||||
/// Track ids of podcast episodes are `-(EPISODE_TRACK_ID_BASE + episode.id)`
|
||||
/// for episode ids in `1..EPISODE_TRACK_ID_BASE`, i.e. the narrow band
|
||||
/// `-(2^41 - 1)..=-(2^40 + 1)`, far away from library rows (positive) and
|
||||
/// other synthetic ids.
|
||||
pub const EPISODE_TRACK_ID_BASE: i64 = 1 << 40;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Podcast {
|
||||
pub id: i64,
|
||||
pub feed_url: String,
|
||||
pub title: String,
|
||||
pub author: Option<String>,
|
||||
/// Plain text (HTML stripped, entities decoded, whitespace collapsed),
|
||||
/// at most 4000 characters.
|
||||
pub description: Option<String>,
|
||||
pub link: Option<String>,
|
||||
pub image_url: Option<String>,
|
||||
/// Absolute path of the locally cached cover image, if downloaded.
|
||||
pub cover_path: Option<String>,
|
||||
pub episode_count: usize,
|
||||
/// Unix seconds, max over episodes.
|
||||
pub latest_published_at: Option<i64>,
|
||||
/// Unix seconds of the last refresh attempt.
|
||||
pub last_checked_at: Option<i64>,
|
||||
/// Error of the last refresh attempt; `None` if it succeeded.
|
||||
pub last_error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Episode {
|
||||
/// SQLite rowid, stable across refreshes.
|
||||
pub id: i64,
|
||||
pub podcast_id: i64,
|
||||
pub guid: String,
|
||||
pub title: String,
|
||||
/// Plain text, at most 4000 characters.
|
||||
pub description: Option<String>,
|
||||
/// Unix seconds.
|
||||
pub published_at: Option<i64>,
|
||||
pub duration_seconds: Option<f64>,
|
||||
pub audio_url: String,
|
||||
pub mime_type: Option<String>,
|
||||
pub byte_len: Option<u64>,
|
||||
pub link: Option<String>,
|
||||
pub image_url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct RefreshSummary {
|
||||
pub new_episodes: usize,
|
||||
pub updated_episodes: usize,
|
||||
pub not_modified: bool,
|
||||
}
|
||||
|
||||
/// Runs blocking store/filesystem work off the Tokio workers.
|
||||
async fn blocking<T, F>(work: F) -> Result<T>
|
||||
where
|
||||
T: Send + 'static,
|
||||
F: FnOnce() -> Result<T> + Send + 'static,
|
||||
{
|
||||
tokio::task::spawn_blocking(work)
|
||||
.await
|
||||
.map_err(|err| anyhow!("background task failed: {err}"))?
|
||||
}
|
||||
|
||||
/// Subscribes to a feed: normalizes the URL, rejects duplicates, fetches and
|
||||
/// parses the feed (nothing is stored if it is not a feed), stores the
|
||||
/// podcast with all episode metadata, then downloads the cover (best effort).
|
||||
pub async fn subscribe(
|
||||
store: Arc<Store>,
|
||||
fetcher: &Fetcher,
|
||||
input_url: &str,
|
||||
now: i64,
|
||||
) -> Result<i64> {
|
||||
let feed_url = normalize_feed_url(input_url)?;
|
||||
let existing = {
|
||||
let store = Arc::clone(&store);
|
||||
let feed_url = feed_url.clone();
|
||||
blocking(move || store.podcast_by_feed_url(&feed_url)).await?
|
||||
};
|
||||
if let Some(podcast) = existing {
|
||||
bail!("already subscribed to {}", podcast.title);
|
||||
}
|
||||
let (feed, etag, last_modified) = match fetcher.fetch_feed(&feed_url, None, None).await? {
|
||||
FeedFetch::Fetched {
|
||||
feed,
|
||||
etag,
|
||||
last_modified,
|
||||
} => (feed, etag, last_modified),
|
||||
FeedFetch::NotModified => {
|
||||
bail!("server answered 304 Not Modified to an unconditional request")
|
||||
}
|
||||
};
|
||||
let image_url = feed.image_url.clone();
|
||||
let podcast_id = {
|
||||
let store = Arc::clone(&store);
|
||||
blocking(move || {
|
||||
let id = store.add_podcast(&feed_url, &feed, now)?;
|
||||
store.set_http_validators(id, etag.as_deref(), last_modified.as_deref())?;
|
||||
Ok(id)
|
||||
})
|
||||
.await?
|
||||
};
|
||||
if let Some(image_url) = image_url {
|
||||
update_cover(&store, fetcher, podcast_id, &image_url).await;
|
||||
}
|
||||
Ok(podcast_id)
|
||||
}
|
||||
|
||||
/// Refreshes one subscription with a conditional request. Failures are
|
||||
/// recorded on the podcast (`last_error`) and returned.
|
||||
pub async fn refresh(
|
||||
store: Arc<Store>,
|
||||
fetcher: &Fetcher,
|
||||
podcast_id: i64,
|
||||
now: i64,
|
||||
) -> Result<RefreshSummary> {
|
||||
let (podcast, (etag, last_modified)) = {
|
||||
let store = Arc::clone(&store);
|
||||
blocking(move || {
|
||||
let podcast = store
|
||||
.podcast(podcast_id)?
|
||||
.ok_or_else(|| anyhow!("podcast {podcast_id} not found"))?;
|
||||
Ok((podcast, store.http_validators(podcast_id)?))
|
||||
})
|
||||
.await?
|
||||
};
|
||||
let fetched = fetcher
|
||||
.fetch_feed(&podcast.feed_url, etag.as_deref(), last_modified.as_deref())
|
||||
.await;
|
||||
let (summary, image_url) = match fetched {
|
||||
Err(err) => {
|
||||
let message = format!("{err:#}");
|
||||
let store = Arc::clone(&store);
|
||||
if let Err(record_err) =
|
||||
blocking(move || store.record_check(podcast_id, now, Some(&message))).await
|
||||
{
|
||||
tracing::warn!("recording podcast refresh error failed: {record_err:#}");
|
||||
}
|
||||
return Err(err);
|
||||
}
|
||||
Ok(FeedFetch::NotModified) => {
|
||||
let store = Arc::clone(&store);
|
||||
blocking(move || store.record_check(podcast_id, now, None)).await?;
|
||||
let summary = RefreshSummary {
|
||||
not_modified: true,
|
||||
..RefreshSummary::default()
|
||||
};
|
||||
(summary, podcast.image_url)
|
||||
}
|
||||
Ok(FeedFetch::Fetched {
|
||||
feed,
|
||||
etag,
|
||||
last_modified,
|
||||
}) => {
|
||||
let image_url = feed.image_url.clone();
|
||||
let store = Arc::clone(&store);
|
||||
let applied = blocking(move || {
|
||||
let summary = store.apply_feed(podcast_id, &feed, now);
|
||||
match &summary {
|
||||
Ok(_) => store.set_http_validators(
|
||||
podcast_id,
|
||||
etag.as_deref(),
|
||||
last_modified.as_deref(),
|
||||
)?,
|
||||
Err(err) => {
|
||||
store.record_check(podcast_id, now, Some(&format!("{err:#}")))?;
|
||||
}
|
||||
}
|
||||
summary
|
||||
})
|
||||
.await?;
|
||||
(applied, image_url)
|
||||
}
|
||||
};
|
||||
if let Some(image_url) = image_url {
|
||||
refresh_cover(&store, fetcher, podcast_id, &image_url).await;
|
||||
}
|
||||
Ok(summary)
|
||||
}
|
||||
|
||||
/// Re-downloads the cover when the feed image changed or the cached file is
|
||||
/// gone. Best effort: failures are only logged.
|
||||
async fn refresh_cover(store: &Arc<Store>, fetcher: &Fetcher, podcast_id: i64, image_url: &str) {
|
||||
let source = {
|
||||
let store = Arc::clone(store);
|
||||
blocking(move || {
|
||||
let (url, path) = store.cover_source(podcast_id)?;
|
||||
let missing = path
|
||||
.as_deref()
|
||||
.is_none_or(|path| !Path::new(path).is_file());
|
||||
Ok((url, missing))
|
||||
})
|
||||
.await
|
||||
};
|
||||
match source {
|
||||
Ok((url, missing)) if url.as_deref() == Some(image_url) && !missing => {}
|
||||
Ok(_) => update_cover(store, fetcher, podcast_id, image_url).await,
|
||||
Err(err) => tracing::warn!("reading podcast cover state failed: {err:#}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Downloads `image_url` as the podcast cover, records it and deletes a
|
||||
/// superseded cover file. Best effort.
|
||||
async fn update_cover(store: &Arc<Store>, fetcher: &Fetcher, podcast_id: i64, image_url: &str) {
|
||||
let path = match fetcher.fetch_cover(podcast_id, image_url).await {
|
||||
Ok(path) => path,
|
||||
Err(err) => {
|
||||
tracing::warn!("downloading podcast cover {image_url} failed: {err:#}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let store = Arc::clone(store);
|
||||
let image_url = image_url.to_string();
|
||||
let result = blocking(move || {
|
||||
let new_path = path_string(&path);
|
||||
if store.podcast(podcast_id)?.is_none() {
|
||||
// Unsubscribed while the cover was downloading.
|
||||
let _ = std::fs::remove_file(&path);
|
||||
return Ok(());
|
||||
}
|
||||
let (_, old_path) = store.cover_source(podcast_id)?;
|
||||
store.set_cover(podcast_id, Some(&image_url), Some(&new_path))?;
|
||||
if let Some(old_path) = old_path.filter(|old| *old != new_path) {
|
||||
let _ = std::fs::remove_file(old_path);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.await;
|
||||
if let Err(err) = result {
|
||||
tracing::warn!("recording podcast cover failed: {err:#}");
|
||||
}
|
||||
}
|
||||
|
||||
fn path_string(path: &Path) -> String {
|
||||
let absolute: PathBuf = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
|
||||
absolute.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// Whether a track path is a remote (http/https) URL rather than a file.
|
||||
pub fn is_remote_url(value: &str) -> bool {
|
||||
let value = value.as_bytes();
|
||||
let has_prefix = |prefix: &[u8]| {
|
||||
value.len() >= prefix.len() && value[..prefix.len()].eq_ignore_ascii_case(prefix)
|
||||
};
|
||||
has_prefix(b"http://") || has_prefix(b"https://")
|
||||
}
|
||||
|
||||
/// The player-facing track for an episode. `file_path` is the remote audio
|
||||
/// URL; see [`is_remote_url`] and [`stream::open`].
|
||||
pub fn episode_track(podcast: &Podcast, episode: &Episode) -> TrackItem {
|
||||
TrackItem {
|
||||
id: -(EPISODE_TRACK_ID_BASE + episode.id),
|
||||
title: episode.title.clone(),
|
||||
track_number: None,
|
||||
disc_number: None,
|
||||
duration_seconds: episode.duration_seconds.unwrap_or(0.0),
|
||||
artists: vec![ArtistRef {
|
||||
id: -1,
|
||||
name: podcast.title.clone(),
|
||||
}],
|
||||
featured_artists: Vec::new(),
|
||||
release_id: -1,
|
||||
release_title: podcast.title.clone(),
|
||||
release_year: episode.published_at.map(feed::year_from_unix),
|
||||
file_path: episode.audio_url.clone(),
|
||||
content_id: None,
|
||||
cover_path: podcast.cover_path.clone(),
|
||||
audio_format: episode.mime_type.as_deref().and_then(audio_format),
|
||||
audio_bitrate: None,
|
||||
audio_sample_rate: None,
|
||||
audio_bit_depth: None,
|
||||
file_size_bytes: episode
|
||||
.byte_len
|
||||
.map(|len| i64::try_from(len).unwrap_or(i64::MAX)),
|
||||
play_count: 0,
|
||||
fed: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Inverse of the id mapping in [`episode_track`]. Only the band reserved
|
||||
/// for episodes maps back, so hash-derived negative ids (for example device
|
||||
/// sync placeholders spread over the whole negative range) are almost never
|
||||
/// mistaken for episodes; callers should still confirm with a store lookup.
|
||||
pub fn episode_id_from_track_id(track_id: i64) -> Option<i64> {
|
||||
let episode_id = track_id.checked_neg()?.checked_sub(EPISODE_TRACK_ID_BASE)?;
|
||||
(episode_id > 0 && episode_id < EPISODE_TRACK_ID_BASE).then_some(episode_id)
|
||||
}
|
||||
|
||||
/// Display format from a MIME type: `audio/mpeg` -> `MP3`, otherwise the
|
||||
/// upper-cased subtype without an `x-` prefix.
|
||||
fn audio_format(mime: &str) -> Option<String> {
|
||||
let (kind, subtype) = mime.split(';').next()?.trim().split_once('/')?;
|
||||
let subtype = subtype.strip_prefix("x-").unwrap_or(subtype);
|
||||
if subtype.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let audio = kind.eq_ignore_ascii_case("audio");
|
||||
Some(match subtype.to_ascii_lowercase().as_str() {
|
||||
"mpeg" | "mp3" | "mpeg3" | "mpg" if audio => "MP3".to_string(),
|
||||
"mp4" | "m4a" if audio => "M4A".to_string(),
|
||||
"vorbis" => "OGG".to_string(),
|
||||
_ => subtype.to_ascii_uppercase(),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,504 @@
|
||||
//! SQLite persistence for podcast subscriptions and episode metadata.
|
||||
//!
|
||||
//! Only metadata is stored; audio stays on the publisher's host. Episodes are
|
||||
//! unique per `(podcast_id, guid)` and their row ids stay stable across
|
||||
//! refreshes, so they can be referenced from playback state. Both tables use
|
||||
//! `AUTOINCREMENT`, so ids of removed podcasts and episodes are never handed
|
||||
//! out again (a stale reference or an in-flight refresh of a removed podcast
|
||||
//! can never hit a different subscription).
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::{Mutex, MutexGuard, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use rusqlite::{Connection, OptionalExtension, Row, params};
|
||||
|
||||
use super::feed::{ParsedEpisode, ParsedFeed};
|
||||
use super::{Episode, Podcast, RefreshSummary};
|
||||
|
||||
/// Schema migrations; `PRAGMA user_version` records how many have run.
|
||||
/// Every statement is idempotent so a partially applied step can be re-run.
|
||||
const MIGRATIONS: &[&str] = &[
|
||||
// v1: subscriptions and episode metadata.
|
||||
"
|
||||
CREATE TABLE IF NOT EXISTS podcasts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
feed_url TEXT NOT NULL UNIQUE,
|
||||
title TEXT NOT NULL,
|
||||
author TEXT,
|
||||
description TEXT,
|
||||
link TEXT,
|
||||
image_url TEXT,
|
||||
cover_url TEXT,
|
||||
cover_path TEXT,
|
||||
etag TEXT,
|
||||
last_modified TEXT,
|
||||
added_at INTEGER NOT NULL,
|
||||
last_checked_at INTEGER,
|
||||
last_error TEXT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS podcast_episodes (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
podcast_id INTEGER NOT NULL REFERENCES podcasts(id) ON DELETE CASCADE,
|
||||
guid TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
description TEXT,
|
||||
published_at INTEGER,
|
||||
duration_seconds REAL,
|
||||
audio_url TEXT NOT NULL,
|
||||
mime_type TEXT,
|
||||
byte_len INTEGER,
|
||||
link TEXT,
|
||||
image_url TEXT,
|
||||
first_seen_at INTEGER NOT NULL,
|
||||
UNIQUE (podcast_id, guid)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS podcast_episodes_by_date
|
||||
ON podcast_episodes (podcast_id, published_at DESC, id DESC);
|
||||
",
|
||||
];
|
||||
|
||||
const PODCAST_COLUMNS: &str = "
|
||||
p.id, p.feed_url, p.title, p.author, p.description, p.link, p.image_url,
|
||||
p.cover_path, p.last_checked_at, p.last_error,
|
||||
(SELECT COUNT(*) FROM podcast_episodes e WHERE e.podcast_id = p.id),
|
||||
(SELECT MAX(e.published_at) FROM podcast_episodes e WHERE e.podcast_id = p.id)";
|
||||
|
||||
const EPISODE_COLUMNS: &str = "
|
||||
id, podcast_id, guid, title, description, published_at, duration_seconds,
|
||||
audio_url, mime_type, byte_len, link, image_url";
|
||||
|
||||
pub struct Store {
|
||||
conn: Mutex<Connection>,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
/// Opens (creating if needed) the podcast database at `path`.
|
||||
pub fn open(path: &Path) -> Result<Store> {
|
||||
if let Some(parent) = path.parent()
|
||||
&& !parent.as_os_str().is_empty()
|
||||
{
|
||||
std::fs::create_dir_all(parent)
|
||||
.with_context(|| format!("creating {}", parent.display()))?;
|
||||
}
|
||||
let conn = Connection::open(path)
|
||||
.with_context(|| format!("opening podcast database {}", path.display()))?;
|
||||
Self::init(conn, true)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn open_in_memory() -> Result<Store> {
|
||||
Self::init(Connection::open_in_memory()?, false)
|
||||
}
|
||||
|
||||
fn init(conn: Connection, wal: bool) -> Result<Store> {
|
||||
conn.busy_timeout(Duration::from_secs(5))?;
|
||||
conn.pragma_update(None, "foreign_keys", true)?;
|
||||
if wal {
|
||||
// Returns the resulting mode as a row, hence query instead of execute.
|
||||
let _: String = conn.query_row("PRAGMA journal_mode=WAL", [], |row| row.get(0))?;
|
||||
}
|
||||
migrate(&conn)?;
|
||||
Ok(Store {
|
||||
conn: Mutex::new(conn),
|
||||
})
|
||||
}
|
||||
|
||||
fn conn(&self) -> MutexGuard<'_, Connection> {
|
||||
self.conn.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
pub fn list_podcasts(&self) -> Result<Vec<Podcast>> {
|
||||
let conn = self.conn();
|
||||
let mut stmt = conn.prepare(&format!(
|
||||
"SELECT {PODCAST_COLUMNS} FROM podcasts p ORDER BY p.title COLLATE NOCASE, p.id"
|
||||
))?;
|
||||
let podcasts = stmt
|
||||
.query_map([], podcast_from_row)?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
Ok(podcasts)
|
||||
}
|
||||
|
||||
pub fn podcast(&self, id: i64) -> Result<Option<Podcast>> {
|
||||
let conn = self.conn();
|
||||
Ok(conn
|
||||
.query_row(
|
||||
&format!("SELECT {PODCAST_COLUMNS} FROM podcasts p WHERE p.id = ?1"),
|
||||
[id],
|
||||
podcast_from_row,
|
||||
)
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
pub fn podcast_by_feed_url(&self, feed_url: &str) -> Result<Option<Podcast>> {
|
||||
let conn = self.conn();
|
||||
Ok(conn
|
||||
.query_row(
|
||||
&format!("SELECT {PODCAST_COLUMNS} FROM podcasts p WHERE p.feed_url = ?1"),
|
||||
[feed_url],
|
||||
podcast_from_row,
|
||||
)
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
/// Inserts a subscription and all of its episodes in one transaction.
|
||||
pub fn add_podcast(&self, feed_url: &str, feed: &ParsedFeed, now: i64) -> Result<i64> {
|
||||
let mut conn = self.conn();
|
||||
let tx = conn.transaction()?;
|
||||
let exists: bool = tx.query_row(
|
||||
"SELECT EXISTS (SELECT 1 FROM podcasts WHERE feed_url = ?1)",
|
||||
[feed_url],
|
||||
|row| row.get(0),
|
||||
)?;
|
||||
if exists {
|
||||
bail!("already subscribed");
|
||||
}
|
||||
tx.execute(
|
||||
"INSERT INTO podcasts
|
||||
(feed_url, title, author, description, link, image_url, added_at, last_checked_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7)",
|
||||
params![
|
||||
feed_url,
|
||||
feed.title,
|
||||
feed.author,
|
||||
feed.description,
|
||||
feed.link,
|
||||
feed.image_url,
|
||||
now
|
||||
],
|
||||
)
|
||||
.map_err(|err| match err {
|
||||
rusqlite::Error::SqliteFailure(code, _)
|
||||
if code.extended_code == rusqlite::ffi::SQLITE_CONSTRAINT_UNIQUE =>
|
||||
{
|
||||
anyhow!("already subscribed")
|
||||
}
|
||||
other => other.into(),
|
||||
})?;
|
||||
let podcast_id = tx.last_insert_rowid();
|
||||
upsert_episodes(&tx, podcast_id, &feed.episodes, now)?;
|
||||
tx.commit()?;
|
||||
Ok(podcast_id)
|
||||
}
|
||||
|
||||
/// Applies a freshly fetched feed: updates channel metadata and upserts
|
||||
/// episodes by guid. Episodes no longer in the feed are kept.
|
||||
pub fn apply_feed(
|
||||
&self,
|
||||
podcast_id: i64,
|
||||
feed: &ParsedFeed,
|
||||
now: i64,
|
||||
) -> Result<RefreshSummary> {
|
||||
let mut conn = self.conn();
|
||||
let tx = conn.transaction()?;
|
||||
let updated = tx.execute(
|
||||
"UPDATE podcasts
|
||||
SET title = ?2, author = ?3, description = ?4, link = ?5, image_url = ?6,
|
||||
last_checked_at = ?7, last_error = NULL
|
||||
WHERE id = ?1",
|
||||
params![
|
||||
podcast_id,
|
||||
feed.title,
|
||||
feed.author,
|
||||
feed.description,
|
||||
feed.link,
|
||||
feed.image_url,
|
||||
now
|
||||
],
|
||||
)?;
|
||||
if updated == 0 {
|
||||
bail!("podcast {podcast_id} not found");
|
||||
}
|
||||
let summary = upsert_episodes(&tx, podcast_id, &feed.episodes, now)?;
|
||||
tx.commit()?;
|
||||
Ok(summary)
|
||||
}
|
||||
|
||||
pub fn record_check(&self, podcast_id: i64, now: i64, error: Option<&str>) -> Result<()> {
|
||||
self.conn().execute(
|
||||
"UPDATE podcasts SET last_checked_at = ?2, last_error = ?3 WHERE id = ?1",
|
||||
params![podcast_id, now, error],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn http_validators(&self, podcast_id: i64) -> Result<(Option<String>, Option<String>)> {
|
||||
Ok(self
|
||||
.conn()
|
||||
.query_row(
|
||||
"SELECT etag, last_modified FROM podcasts WHERE id = ?1",
|
||||
[podcast_id],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)
|
||||
.optional()?
|
||||
.unwrap_or((None, None)))
|
||||
}
|
||||
|
||||
pub fn set_http_validators(
|
||||
&self,
|
||||
podcast_id: i64,
|
||||
etag: Option<&str>,
|
||||
last_modified: Option<&str>,
|
||||
) -> Result<()> {
|
||||
self.conn().execute(
|
||||
"UPDATE podcasts SET etag = ?2, last_modified = ?3 WHERE id = ?1",
|
||||
params![podcast_id, etag, last_modified],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Records the cached cover file and the image URL it was downloaded from.
|
||||
pub fn set_cover(
|
||||
&self,
|
||||
podcast_id: i64,
|
||||
cover_url: Option<&str>,
|
||||
cover_path: Option<&str>,
|
||||
) -> Result<()> {
|
||||
self.conn().execute(
|
||||
"UPDATE podcasts SET cover_url = ?2, cover_path = ?3 WHERE id = ?1",
|
||||
params![podcast_id, cover_url, cover_path],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `(cover_url, cover_path)`: the image URL the cached cover came from
|
||||
/// and the cached file.
|
||||
pub fn cover_source(&self, podcast_id: i64) -> Result<(Option<String>, Option<String>)> {
|
||||
Ok(self
|
||||
.conn()
|
||||
.query_row(
|
||||
"SELECT cover_url, cover_path FROM podcasts WHERE id = ?1",
|
||||
[podcast_id],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)
|
||||
.optional()?
|
||||
.unwrap_or((None, None)))
|
||||
}
|
||||
|
||||
/// Episodes of a podcast, newest first (undated episodes last).
|
||||
pub fn episodes(&self, podcast_id: i64) -> Result<Vec<Episode>> {
|
||||
let conn = self.conn();
|
||||
let mut stmt = conn.prepare(&format!(
|
||||
"SELECT {EPISODE_COLUMNS} FROM podcast_episodes
|
||||
WHERE podcast_id = ?1
|
||||
ORDER BY published_at IS NULL, published_at DESC, id DESC"
|
||||
))?;
|
||||
let episodes = stmt
|
||||
.query_map([podcast_id], episode_from_row)?
|
||||
.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||
Ok(episodes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn episode(&self, episode_id: i64) -> Result<Option<Episode>> {
|
||||
Ok(self
|
||||
.conn()
|
||||
.query_row(
|
||||
&format!("SELECT {EPISODE_COLUMNS} FROM podcast_episodes WHERE id = ?1"),
|
||||
[episode_id],
|
||||
episode_from_row,
|
||||
)
|
||||
.optional()?)
|
||||
}
|
||||
|
||||
/// Deletes a subscription and its episodes; returns the cached cover path
|
||||
/// so the caller can delete the file.
|
||||
pub fn remove_podcast(&self, podcast_id: i64) -> Result<Option<String>> {
|
||||
let mut conn = self.conn();
|
||||
let tx = conn.transaction()?;
|
||||
let cover_path: Option<Option<String>> = tx
|
||||
.query_row(
|
||||
"SELECT cover_path FROM podcasts WHERE id = ?1",
|
||||
[podcast_id],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.optional()?;
|
||||
// Explicit delete keeps this correct even on a connection where the
|
||||
// foreign-key cascade is somehow disabled.
|
||||
tx.execute(
|
||||
"DELETE FROM podcast_episodes WHERE podcast_id = ?1",
|
||||
[podcast_id],
|
||||
)?;
|
||||
tx.execute("DELETE FROM podcasts WHERE id = ?1", [podcast_id])?;
|
||||
tx.commit()?;
|
||||
Ok(cover_path.flatten())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn schema_version(&self) -> Result<i64> {
|
||||
Ok(self
|
||||
.conn()
|
||||
.query_row("PRAGMA user_version", [], |row| row.get(0))?)
|
||||
}
|
||||
}
|
||||
|
||||
fn migrate(conn: &Connection) -> Result<()> {
|
||||
let version: i64 = conn.query_row("PRAGMA user_version", [], |row| row.get(0))?;
|
||||
let target = MIGRATIONS.len() as i64;
|
||||
if version > target {
|
||||
bail!("podcast database schema v{version} is newer than this Furumi (v{target})");
|
||||
}
|
||||
for (index, sql) in MIGRATIONS.iter().enumerate().skip(version as usize) {
|
||||
let next = index as i64 + 1;
|
||||
conn.execute_batch(&format!(
|
||||
"BEGIN IMMEDIATE; {sql}; PRAGMA user_version = {next}; COMMIT;"
|
||||
))
|
||||
.inspect_err(|_| {
|
||||
let _ = conn.execute_batch("ROLLBACK");
|
||||
})
|
||||
.with_context(|| format!("migrating podcast database to v{next}"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn podcast_from_row(row: &Row<'_>) -> rusqlite::Result<Podcast> {
|
||||
let episode_count: i64 = row.get(10)?;
|
||||
Ok(Podcast {
|
||||
id: row.get(0)?,
|
||||
feed_url: row.get(1)?,
|
||||
title: row.get(2)?,
|
||||
author: row.get(3)?,
|
||||
description: row.get(4)?,
|
||||
link: row.get(5)?,
|
||||
image_url: row.get(6)?,
|
||||
cover_path: row.get(7)?,
|
||||
last_checked_at: row.get(8)?,
|
||||
last_error: row.get(9)?,
|
||||
episode_count: usize::try_from(episode_count).unwrap_or(0),
|
||||
latest_published_at: row.get(11)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn episode_from_row(row: &Row<'_>) -> rusqlite::Result<Episode> {
|
||||
let byte_len: Option<i64> = row.get(9)?;
|
||||
Ok(Episode {
|
||||
id: row.get(0)?,
|
||||
podcast_id: row.get(1)?,
|
||||
guid: row.get(2)?,
|
||||
title: row.get(3)?,
|
||||
description: row.get(4)?,
|
||||
published_at: row.get(5)?,
|
||||
duration_seconds: row.get(6)?,
|
||||
audio_url: row.get(7)?,
|
||||
mime_type: row.get(8)?,
|
||||
byte_len: byte_len.and_then(|len| u64::try_from(len).ok()),
|
||||
link: row.get(10)?,
|
||||
image_url: row.get(11)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// The mutable columns of an episode row, for change detection.
|
||||
#[derive(PartialEq)]
|
||||
struct EpisodeFields {
|
||||
title: String,
|
||||
description: Option<String>,
|
||||
published_at: Option<i64>,
|
||||
duration_seconds: Option<f64>,
|
||||
audio_url: String,
|
||||
mime_type: Option<String>,
|
||||
byte_len: Option<i64>,
|
||||
link: Option<String>,
|
||||
image_url: Option<String>,
|
||||
}
|
||||
|
||||
impl EpisodeFields {
|
||||
fn from_parsed(episode: &ParsedEpisode) -> EpisodeFields {
|
||||
EpisodeFields {
|
||||
title: episode.title.clone(),
|
||||
description: episode.description.clone(),
|
||||
published_at: episode.published_at,
|
||||
duration_seconds: episode.duration_seconds,
|
||||
audio_url: episode.audio_url.clone(),
|
||||
mime_type: episode.mime_type.clone(),
|
||||
byte_len: episode
|
||||
.byte_len
|
||||
.map(|len| i64::try_from(len).unwrap_or(i64::MAX)),
|
||||
link: episode.link.clone(),
|
||||
image_url: episode.image_url.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn upsert_episodes(
|
||||
tx: &rusqlite::Transaction<'_>,
|
||||
podcast_id: i64,
|
||||
episodes: &[ParsedEpisode],
|
||||
now: i64,
|
||||
) -> Result<RefreshSummary> {
|
||||
let mut summary = RefreshSummary::default();
|
||||
let mut select = tx.prepare_cached(
|
||||
"SELECT id, title, description, published_at, duration_seconds, audio_url,
|
||||
mime_type, byte_len, link, image_url
|
||||
FROM podcast_episodes WHERE podcast_id = ?1 AND guid = ?2",
|
||||
)?;
|
||||
let mut insert = tx.prepare_cached(
|
||||
"INSERT INTO podcast_episodes
|
||||
(podcast_id, guid, title, description, published_at, duration_seconds,
|
||||
audio_url, mime_type, byte_len, link, image_url, first_seen_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
|
||||
)?;
|
||||
let mut update = tx.prepare_cached(
|
||||
"UPDATE podcast_episodes
|
||||
SET title = ?2, description = ?3, published_at = ?4, duration_seconds = ?5,
|
||||
audio_url = ?6, mime_type = ?7, byte_len = ?8, link = ?9, image_url = ?10
|
||||
WHERE id = ?1",
|
||||
)?;
|
||||
for episode in episodes {
|
||||
let fields = EpisodeFields::from_parsed(episode);
|
||||
let existing = select
|
||||
.query_row(params![podcast_id, episode.guid], |row| {
|
||||
Ok((
|
||||
row.get::<_, i64>(0)?,
|
||||
EpisodeFields {
|
||||
title: row.get(1)?,
|
||||
description: row.get(2)?,
|
||||
published_at: row.get(3)?,
|
||||
duration_seconds: row.get(4)?,
|
||||
audio_url: row.get(5)?,
|
||||
mime_type: row.get(6)?,
|
||||
byte_len: row.get(7)?,
|
||||
link: row.get(8)?,
|
||||
image_url: row.get(9)?,
|
||||
},
|
||||
))
|
||||
})
|
||||
.optional()?;
|
||||
match existing {
|
||||
None => {
|
||||
insert.execute(params![
|
||||
podcast_id,
|
||||
episode.guid,
|
||||
fields.title,
|
||||
fields.description,
|
||||
fields.published_at,
|
||||
fields.duration_seconds,
|
||||
fields.audio_url,
|
||||
fields.mime_type,
|
||||
fields.byte_len,
|
||||
fields.link,
|
||||
fields.image_url,
|
||||
now
|
||||
])?;
|
||||
summary.new_episodes += 1;
|
||||
}
|
||||
Some((id, stored)) if stored != fields => {
|
||||
update.execute(params![
|
||||
id,
|
||||
fields.title,
|
||||
fields.description,
|
||||
fields.published_at,
|
||||
fields.duration_seconds,
|
||||
fields.audio_url,
|
||||
fields.mime_type,
|
||||
fields.byte_len,
|
||||
fields.link,
|
||||
fields.image_url
|
||||
])?;
|
||||
summary.updated_episodes += 1;
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
Ok(summary)
|
||||
}
|
||||
@@ -0,0 +1,794 @@
|
||||
//! Seekable playback of a remote episode without downloading it first.
|
||||
//!
|
||||
//! [`open`] issues one `Range: bytes=0-` request and hands the response to a
|
||||
//! dedicated downloader thread. The thread fills a bounded in-memory window
|
||||
//! around the reader position:
|
||||
//!
|
||||
//! * up to [`READ_AHEAD`] bytes ahead of the reader (then it pauses),
|
||||
//! * up to [`KEEP_BEHIND`] bytes behind it (cheap small backward seeks),
|
||||
//! * plus the first [`HEAD_KEEP`] bytes of the file, kept permanently because
|
||||
//! decoders re-read the container header while probing.
|
||||
//!
|
||||
//! The window buffer is allocated once at its maximum size and never grows,
|
||||
//! so memory stays bounded (and no large reallocation happens under the lock
|
||||
//! the audio callback reads through).
|
||||
//!
|
||||
//! A seek inside the window is free. A read outside it restarts the
|
||||
//! downloader at the new position with a fresh `Range` request; a generation
|
||||
//! counter makes sure bytes from the superseded response are dropped. Servers
|
||||
//! that ignore `Range` are still supported: forward seeks read and discard,
|
||||
//! backward seeks restart from the beginning.
|
||||
//!
|
||||
//! Network errors: the downloader never gives up on a transient error by
|
||||
//! itself. It resumes from its current offset with capped exponential backoff
|
||||
//! (shortened while the reader is waiting for data), so a short outage is
|
||||
//! bridged by the buffered window. The decision to fail belongs to the
|
||||
//! reader: a `read` that is blocked on missing data and sees no download
|
||||
//! progress for [`STARVE_TIMEOUT`] returns `io::ErrorKind::TimedOut`; the next
|
||||
//! `read` starts a fresh attempt. Client errors (HTTP 4xx other than 408/429,
|
||||
//! e.g. an expired signed URL) are reported to the reader immediately.
|
||||
//!
|
||||
//! Timeouts: `reqwest::blocking` applies `ClientBuilder::timeout` to waiting
|
||||
//! for the response head and then *separately to every `Response::read`
|
||||
//! call* (verified in reqwest 0.12.28: `blocking::Response::read` wraps each
|
||||
//! read in `wait::timeout(.., self.timeout)`, and the blocking client does not
|
||||
//! forward that value to the async client's total timeout). So
|
||||
//! `timeout(STALL_TIMEOUT)` is a per-read stall timeout, not a cap on the whole
|
||||
//! body, and long episodes are fine. The request-level
|
||||
//! `RequestBuilder::timeout` (which *is* a total timeout) is never used.
|
||||
//!
|
||||
//! Decoder note for the player integration: symphonia's MP3 demuxer in
|
||||
//! accurate seek mode never seeks by byte offset (a backward seek re-parses
|
||||
//! from the first frame), which would re-download the episode. Build rodio
|
||||
//! decoders for these streams with `.with_coarse_seek(true)` (and
|
||||
//! `.with_byte_len(..)`), so a seek maps to a single range request.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::io::{self, Read, Seek, SeekFrom};
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use reqwest::StatusCode;
|
||||
use reqwest::blocking::{Client, Response};
|
||||
use reqwest::header::{CONTENT_RANGE, CONTENT_TYPE, RANGE};
|
||||
|
||||
/// Maximum bytes buffered ahead of the reader position.
|
||||
pub const READ_AHEAD: u64 = 8 * 1024 * 1024;
|
||||
/// Bytes kept behind the reader position for small backward seeks.
|
||||
pub const KEEP_BEHIND: u64 = 1024 * 1024;
|
||||
/// Leading bytes of the file kept for the lifetime of the stream.
|
||||
pub const HEAD_KEEP: usize = 256 * 1024;
|
||||
/// Size of a single network read.
|
||||
const CHUNK: usize = 64 * 1024;
|
||||
/// Largest the window can get: the read-ahead may overshoot by less than one
|
||||
/// chunk before the downloader pauses.
|
||||
const WINDOW_CAP: usize = READ_AHEAD as usize + KEEP_BEHIND as usize + CHUNK;
|
||||
/// A forward gap up to this size is bridged by waiting for the downloader
|
||||
/// instead of issuing a new range request.
|
||||
const NEAR_GAP: u64 = 512 * 1024;
|
||||
/// A restart this close ahead of the current response offset keeps the
|
||||
/// response and discards bytes instead of reconnecting.
|
||||
const DISCARD_LIMIT: u64 = 256 * 1024;
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
/// No progress for this long on one read (or the response head) is an error.
|
||||
const STALL_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
/// First retry delay; doubles per consecutive failure.
|
||||
const RETRY_BASE: Duration = Duration::from_millis(250);
|
||||
/// Longest delay between attempts while the reader still has buffered data.
|
||||
const MAX_BACKOFF: Duration = Duration::from_secs(10);
|
||||
/// Longest delay between attempts while the reader is waiting for data.
|
||||
const STARVED_BACKOFF: Duration = Duration::from_secs(1);
|
||||
/// A `read` blocked on missing data fails after this long without any
|
||||
/// download progress. Shorter in tests to keep failure tests fast.
|
||||
#[cfg(not(test))]
|
||||
pub const STARVE_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
#[cfg(test)]
|
||||
pub const STARVE_TIMEOUT: Duration = Duration::from_secs(4);
|
||||
|
||||
pub struct OpenedStream {
|
||||
pub reader: HttpStream,
|
||||
pub byte_len: Option<u64>,
|
||||
pub mime_type: Option<String>,
|
||||
pub seekable: bool,
|
||||
}
|
||||
|
||||
/// `Read + Seek` view of a remote file; see the module docs.
|
||||
pub struct HttpStream {
|
||||
pos: u64,
|
||||
shared: Arc<Shared>,
|
||||
}
|
||||
|
||||
struct Shared {
|
||||
state: Mutex<State>,
|
||||
/// Signalled when data, EOF, an error or downloader exit is available to
|
||||
/// the reader.
|
||||
data_ready: Condvar,
|
||||
/// Signalled when the reader moved, requested a restart, started waiting
|
||||
/// or went away.
|
||||
space_ready: Condvar,
|
||||
}
|
||||
|
||||
struct State {
|
||||
/// Bumped on every restart; downloader output for older generations is
|
||||
/// discarded.
|
||||
generation: u64,
|
||||
/// Start offset requested for the current generation.
|
||||
target: u64,
|
||||
/// File offset of `window[0]`.
|
||||
window_start: u64,
|
||||
window: VecDeque<u8>,
|
||||
/// Bytes `0..head.len()` of the file.
|
||||
head: Vec<u8>,
|
||||
/// Last position the reader consumed from the window.
|
||||
reader_pos: u64,
|
||||
total: Option<u64>,
|
||||
ranges: bool,
|
||||
/// The current generation reached the end of the body.
|
||||
done: bool,
|
||||
/// The current generation was abandoned (fatal error, or the reader gave
|
||||
/// up waiting); the downloader idles until the reader restarts it.
|
||||
failed: bool,
|
||||
/// Fatal error to report to the reader once.
|
||||
error: Option<(io::ErrorKind, String)>,
|
||||
/// Most recent transient failure, for the reader's timeout message.
|
||||
last_error: Option<String>,
|
||||
/// Bytes received from the network for the current generation
|
||||
/// (including discarded ones); the reader's stall detection watches it.
|
||||
progress: u64,
|
||||
/// The reader is blocked waiting for data.
|
||||
reader_waiting: bool,
|
||||
/// The reader went away.
|
||||
closed: bool,
|
||||
/// The downloader thread exited.
|
||||
exited: bool,
|
||||
peak_buffered: usize,
|
||||
peak_capacity: usize,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn window_end(&self) -> u64 {
|
||||
self.window_start + self.window.len() as u64
|
||||
}
|
||||
|
||||
fn buffered(&self) -> usize {
|
||||
self.window.len() + self.head.len()
|
||||
}
|
||||
|
||||
fn restart_at(&mut self, pos: u64) {
|
||||
self.generation = self.generation.wrapping_add(1);
|
||||
self.target = pos;
|
||||
self.window_start = pos;
|
||||
// Keeps the allocation: the window never needs more than WINDOW_CAP.
|
||||
self.window.clear();
|
||||
self.done = false;
|
||||
self.failed = false;
|
||||
self.error = None;
|
||||
self.last_error = None;
|
||||
self.progress = 0;
|
||||
}
|
||||
|
||||
fn trim_behind(&mut self) {
|
||||
let keep_from = self.reader_pos.saturating_sub(KEEP_BEHIND);
|
||||
if keep_from > self.window_start {
|
||||
let drop = (keep_from - self.window_start).min(self.window.len() as u64) as usize;
|
||||
self.window.drain(..drop);
|
||||
self.window_start += drop as u64;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
fn lock(&self) -> MutexGuard<'_, State> {
|
||||
self.state.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens a remote audio file for streaming playback. Blocking: call it from
|
||||
/// `spawn_blocking` or a plain thread, never directly on a Tokio worker.
|
||||
pub fn open(url: &str) -> Result<OpenedStream> {
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
let client = Client::builder()
|
||||
.connect_timeout(CONNECT_TIMEOUT)
|
||||
// Per-read stall timeout, see the module docs.
|
||||
.timeout(STALL_TIMEOUT)
|
||||
.redirect(reqwest::redirect::Policy::limited(10))
|
||||
.user_agent(concat!("furumi/", env!("CARGO_PKG_VERSION")))
|
||||
.build()
|
||||
.context("building the streaming HTTP client")?;
|
||||
let response = client
|
||||
.get(url)
|
||||
.header(RANGE, "bytes=0-")
|
||||
.send()
|
||||
.with_context(|| format!("requesting {url}"))?;
|
||||
let opened = classify(&response, 0).with_context(|| format!("requesting {url}"))?;
|
||||
let mime_type = response
|
||||
.headers()
|
||||
.get(CONTENT_TYPE)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(|value| value.split(';').next())
|
||||
.map(|value| value.trim().to_ascii_lowercase())
|
||||
.filter(|value| !value.is_empty());
|
||||
|
||||
let window = VecDeque::with_capacity(WINDOW_CAP);
|
||||
let peak_capacity = window.capacity();
|
||||
let shared = Arc::new(Shared {
|
||||
state: Mutex::new(State {
|
||||
generation: 0,
|
||||
target: 0,
|
||||
window_start: 0,
|
||||
window,
|
||||
head: Vec::with_capacity(HEAD_KEEP),
|
||||
reader_pos: 0,
|
||||
total: opened.total,
|
||||
ranges: opened.ranges,
|
||||
done: false,
|
||||
failed: false,
|
||||
error: None,
|
||||
last_error: None,
|
||||
progress: 0,
|
||||
reader_waiting: false,
|
||||
closed: false,
|
||||
exited: false,
|
||||
peak_buffered: 0,
|
||||
peak_capacity,
|
||||
}),
|
||||
data_ready: Condvar::new(),
|
||||
space_ready: Condvar::new(),
|
||||
});
|
||||
let downloader = Downloader {
|
||||
shared: Arc::clone(&shared),
|
||||
client,
|
||||
url: url.to_string(),
|
||||
};
|
||||
std::thread::Builder::new()
|
||||
.name("podcast-stream".to_string())
|
||||
.spawn(move || downloader.run(response))
|
||||
.context("spawning the podcast stream thread")?;
|
||||
Ok(OpenedStream {
|
||||
reader: HttpStream { pos: 0, shared },
|
||||
byte_len: opened.total,
|
||||
mime_type,
|
||||
seekable: opened.total.is_some(),
|
||||
})
|
||||
}
|
||||
|
||||
struct Classified {
|
||||
/// Offset of the first body byte.
|
||||
start: u64,
|
||||
total: Option<u64>,
|
||||
ranges: bool,
|
||||
}
|
||||
|
||||
/// Interprets a response to `Range: bytes=<requested>-` (or a plain GET).
|
||||
fn classify(response: &Response, requested: u64) -> Result<Classified> {
|
||||
let status = response.status();
|
||||
if status == StatusCode::PARTIAL_CONTENT {
|
||||
let range = response
|
||||
.headers()
|
||||
.get(CONTENT_RANGE)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(parse_content_range);
|
||||
let Some((start, total)) = range else {
|
||||
bail!("HTTP 206 without a usable Content-Range");
|
||||
};
|
||||
if start != requested {
|
||||
bail!("server returned range starting at {start}, expected {requested}");
|
||||
}
|
||||
return Ok(Classified {
|
||||
start,
|
||||
total,
|
||||
ranges: true,
|
||||
});
|
||||
}
|
||||
if status.is_success() {
|
||||
return Ok(Classified {
|
||||
start: 0,
|
||||
total: response.content_length(),
|
||||
ranges: false,
|
||||
});
|
||||
}
|
||||
bail!("HTTP {status}");
|
||||
}
|
||||
|
||||
/// Parses `bytes <start>-<end>/<total|*>` into `(start, total)`.
|
||||
fn parse_content_range(value: &str) -> Option<(u64, Option<u64>)> {
|
||||
let value = value.trim();
|
||||
let rest = value
|
||||
.get(..6)
|
||||
.filter(|unit| unit.eq_ignore_ascii_case("bytes "))
|
||||
.map(|_| &value[6..])?;
|
||||
let (range, total) = rest.split_once('/')?;
|
||||
let (start, _end) = range.trim().split_once('-')?;
|
||||
let start = start.trim().parse().ok()?;
|
||||
let total = match total.trim() {
|
||||
"*" => None,
|
||||
total => Some(total.parse().ok()?),
|
||||
};
|
||||
Some((start, total))
|
||||
}
|
||||
|
||||
/// Why a (re)connection attempt failed.
|
||||
enum Failure {
|
||||
/// Worth retrying (network error, 5xx, 408/429, odd range answer).
|
||||
Transient(String),
|
||||
/// Retrying will not help (4xx such as 403/404/410).
|
||||
Fatal(String),
|
||||
}
|
||||
|
||||
struct Downloader {
|
||||
shared: Arc<Shared>,
|
||||
client: Client,
|
||||
url: String,
|
||||
}
|
||||
|
||||
/// Marks the downloader as exited however `run` returns (including a panic).
|
||||
struct ExitFlag(Arc<Shared>);
|
||||
|
||||
impl Drop for ExitFlag {
|
||||
fn drop(&mut self) {
|
||||
// Set under the lock so a reader that checked `exited` and is about
|
||||
// to wait cannot miss the notification.
|
||||
let mut state = self.0.lock();
|
||||
state.exited = true;
|
||||
drop(state);
|
||||
self.0.data_ready.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
impl Downloader {
|
||||
fn run(self, first: Response) {
|
||||
let _exit = ExitFlag(Arc::clone(&self.shared));
|
||||
let mut generation = 0u64;
|
||||
let mut response = Some(first);
|
||||
// File offset of the next byte `response` yields, or where the next
|
||||
// request should start when there is no response.
|
||||
let mut offset = 0u64;
|
||||
// Consecutive failures of the current generation (drives backoff).
|
||||
let mut failures = 0u32;
|
||||
let mut buf = vec![0u8; CHUNK];
|
||||
loop {
|
||||
if !self.wait_for_work(&mut generation, &mut response, &mut offset, &mut failures) {
|
||||
return;
|
||||
}
|
||||
if response.is_none() {
|
||||
match self.reopen(offset) {
|
||||
Ok(Some((next, start))) => {
|
||||
response = Some(next);
|
||||
offset = start;
|
||||
}
|
||||
Ok(None) => {
|
||||
// Nothing left at this offset (HTTP 416).
|
||||
self.mark_done(generation, offset, false);
|
||||
continue;
|
||||
}
|
||||
Err(Failure::Fatal(message)) => {
|
||||
failures = 0;
|
||||
self.fail(generation, message);
|
||||
continue;
|
||||
}
|
||||
Err(Failure::Transient(message)) => {
|
||||
if !self.retry(generation, &mut failures, &message) {
|
||||
return;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
let Some(body) = response.as_mut() else {
|
||||
continue;
|
||||
};
|
||||
match body.read(&mut buf) {
|
||||
Ok(0) => {
|
||||
response = None;
|
||||
let total = self.shared.lock().total;
|
||||
if total.is_some_and(|total| offset < total) {
|
||||
// Connection closed early: resume from `offset`.
|
||||
let message = format!("connection closed at byte {offset}");
|
||||
if !self.retry(generation, &mut failures, &message) {
|
||||
return;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
self.mark_done(generation, offset, true);
|
||||
}
|
||||
Ok(read) => {
|
||||
failures = 0;
|
||||
let start = offset;
|
||||
offset += read as u64;
|
||||
self.publish(generation, start, &buf[..read]);
|
||||
}
|
||||
Err(err) if err.kind() == io::ErrorKind::Interrupted => {}
|
||||
Err(err) => {
|
||||
response = None;
|
||||
if !self.retry(generation, &mut failures, &err.to_string()) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocks until there is something to download, adopting restarts
|
||||
/// requested by the reader. Returns `false` when the reader is gone.
|
||||
fn wait_for_work(
|
||||
&self,
|
||||
generation: &mut u64,
|
||||
response: &mut Option<Response>,
|
||||
offset: &mut u64,
|
||||
failures: &mut u32,
|
||||
) -> bool {
|
||||
let mut state = self.shared.lock();
|
||||
loop {
|
||||
if state.closed {
|
||||
return false;
|
||||
}
|
||||
if state.generation != *generation {
|
||||
*generation = state.generation;
|
||||
// A new generation gets a fresh backoff.
|
||||
*failures = 0;
|
||||
// Keep the open response when the new target is a little
|
||||
// ahead of it (or anywhere ahead if ranges are unsupported):
|
||||
// discarding is cheaper than reconnecting.
|
||||
let keep = response.is_some()
|
||||
&& state.target >= *offset
|
||||
&& (!state.ranges || state.target - *offset <= DISCARD_LIMIT);
|
||||
if !keep {
|
||||
*response = None;
|
||||
*offset = state.target;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let paused = state.done
|
||||
|| state.failed
|
||||
|| state.window_end() >= state.reader_pos.saturating_add(READ_AHEAD);
|
||||
if !paused {
|
||||
return true;
|
||||
}
|
||||
state = self
|
||||
.shared
|
||||
.space_ready
|
||||
.wait(state)
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
}
|
||||
}
|
||||
|
||||
/// Requests the file from `offset` (from 0 when ranges are unsupported).
|
||||
/// `Ok(None)` means the server has nothing at that offset.
|
||||
fn reopen(&self, offset: u64) -> std::result::Result<Option<(Response, u64)>, Failure> {
|
||||
let ranges = self.shared.lock().ranges;
|
||||
let mut request = self.client.get(&self.url);
|
||||
if ranges {
|
||||
request = request.header(RANGE, format!("bytes={offset}-"));
|
||||
}
|
||||
let response = request
|
||||
.send()
|
||||
.map_err(|err| Failure::Transient(format!("{:#}", anyhow!(err))))?;
|
||||
let status = response.status();
|
||||
if ranges && status == StatusCode::RANGE_NOT_SATISFIABLE {
|
||||
return Ok(None);
|
||||
}
|
||||
if status.is_client_error()
|
||||
&& status != StatusCode::REQUEST_TIMEOUT
|
||||
&& status != StatusCode::TOO_MANY_REQUESTS
|
||||
{
|
||||
return Err(Failure::Fatal(format!("HTTP {status}")));
|
||||
}
|
||||
let classified = classify(&response, if ranges { offset } else { 0 })
|
||||
.map_err(|err| Failure::Transient(format!("{err:#}")))?;
|
||||
let mut state = self.shared.lock();
|
||||
if !classified.ranges && state.ranges {
|
||||
// The server stopped honouring Range: read from 0 and discard.
|
||||
state.ranges = false;
|
||||
}
|
||||
if state.total.is_none() {
|
||||
state.total = classified.total;
|
||||
}
|
||||
Ok(Some((response, classified.start)))
|
||||
}
|
||||
|
||||
fn mark_done(&self, generation: u64, offset: u64, learn_total: bool) {
|
||||
let mut state = self.shared.lock();
|
||||
if state.generation != generation {
|
||||
return;
|
||||
}
|
||||
state.done = true;
|
||||
if learn_total && state.total.is_none() {
|
||||
state.total = Some(offset.max(state.window_end()));
|
||||
}
|
||||
self.shared.data_ready.notify_all();
|
||||
}
|
||||
|
||||
/// Abandons the current generation with an error for the reader.
|
||||
fn fail(&self, generation: u64, message: String) {
|
||||
let mut state = self.shared.lock();
|
||||
if state.generation != generation {
|
||||
return;
|
||||
}
|
||||
tracing::warn!("podcast stream failed: {message}");
|
||||
state.failed = true;
|
||||
state.error = Some((io::ErrorKind::Other, message));
|
||||
self.shared.data_ready.notify_all();
|
||||
}
|
||||
|
||||
/// Records a transient failure and backs off before the next attempt.
|
||||
/// Returns `false` when the thread should exit.
|
||||
fn retry(&self, generation: u64, failures: &mut u32, message: &str) -> bool {
|
||||
let mut state = self.shared.lock();
|
||||
if state.closed {
|
||||
return false;
|
||||
}
|
||||
if state.generation != generation {
|
||||
// The reader moved on; `wait_for_work` adopts the new target.
|
||||
return true;
|
||||
}
|
||||
*failures = failures.saturating_add(1);
|
||||
state.last_error = Some(message.to_string());
|
||||
tracing::debug!("podcast stream attempt failed ({failures} in a row): {message}");
|
||||
let delay = RETRY_BASE
|
||||
.saturating_mul(1 << (*failures - 1).min(6))
|
||||
.min(MAX_BACKOFF);
|
||||
let started = Instant::now();
|
||||
// Wakes early when the reader goes away, seeks elsewhere or starts
|
||||
// waiting for data (which shortens the delay).
|
||||
loop {
|
||||
if state.closed {
|
||||
return false;
|
||||
}
|
||||
if state.generation != generation {
|
||||
return true;
|
||||
}
|
||||
let limit = if state.reader_waiting {
|
||||
delay.min(STARVED_BACKOFF)
|
||||
} else {
|
||||
delay
|
||||
};
|
||||
let elapsed = started.elapsed();
|
||||
if elapsed >= limit {
|
||||
return true;
|
||||
}
|
||||
state = self
|
||||
.shared
|
||||
.space_ready
|
||||
.wait_timeout(state, limit - elapsed)
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.0;
|
||||
}
|
||||
}
|
||||
|
||||
fn publish(&self, generation: u64, start: u64, bytes: &[u8]) {
|
||||
let mut state = self.shared.lock();
|
||||
if state.generation != generation {
|
||||
return;
|
||||
}
|
||||
state.progress = state.progress.wrapping_add(bytes.len() as u64);
|
||||
state.last_error = None;
|
||||
let end = start + bytes.len() as u64;
|
||||
// Permanent copy of the file head for format probing.
|
||||
let head_len = state.head.len() as u64;
|
||||
if start <= head_len && end > head_len && head_len < HEAD_KEEP as u64 {
|
||||
let from = (head_len - start) as usize;
|
||||
let to = (HEAD_KEEP as u64).min(end) - start;
|
||||
state.head.extend_from_slice(&bytes[from..to as usize]);
|
||||
}
|
||||
// Only bytes at or after the window end are new; earlier ones are
|
||||
// being skipped (Range-less seek or resume) or are already buffered.
|
||||
let want = state.window_end();
|
||||
if end > want {
|
||||
if start > want {
|
||||
// A gap should not happen; resynchronise rather than corrupt.
|
||||
state.window.clear();
|
||||
state.window_start = start;
|
||||
state.window.extend(bytes);
|
||||
} else {
|
||||
state.window.extend(&bytes[(want - start) as usize..]);
|
||||
}
|
||||
state.trim_behind();
|
||||
}
|
||||
state.peak_buffered = state.peak_buffered.max(state.buffered());
|
||||
state.peak_capacity = state.peak_capacity.max(state.window.capacity());
|
||||
self.shared.data_ready.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
fn downloader_stopped() -> io::Error {
|
||||
io::Error::other("podcast stream downloader stopped")
|
||||
}
|
||||
|
||||
impl Read for HttpStream {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
if buf.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
let shared = &*self.shared;
|
||||
let state = shared.lock();
|
||||
let (mut state, result) = read_locked(shared, &mut self.pos, state, buf);
|
||||
state.reader_waiting = false;
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
/// The body of [`HttpStream::read`]; hands the guard back so the caller can
|
||||
/// clear `reader_waiting` on every exit path.
|
||||
fn read_locked<'a>(
|
||||
shared: &Shared,
|
||||
pos: &mut u64,
|
||||
mut state: MutexGuard<'a, State>,
|
||||
buf: &mut [u8],
|
||||
) -> (MutexGuard<'a, State>, io::Result<usize>) {
|
||||
// When this read started waiting, and the download progress then.
|
||||
let mut starved: Option<(Instant, u64)> = None;
|
||||
loop {
|
||||
if state.total.is_some_and(|total| *pos >= total) {
|
||||
return (state, Ok(0));
|
||||
}
|
||||
if *pos < state.head.len() as u64 {
|
||||
let from = *pos as usize;
|
||||
let len = buf.len().min(state.head.len() - from);
|
||||
buf[..len].copy_from_slice(&state.head[from..from + len]);
|
||||
*pos += len as u64;
|
||||
return (state, Ok(len));
|
||||
}
|
||||
let window_end = state.window_end();
|
||||
if *pos >= state.window_start && *pos < window_end {
|
||||
let from = (*pos - state.window_start) as usize;
|
||||
let len = buf.len().min(state.window.len() - from);
|
||||
let (front, back) = state.window.as_slices();
|
||||
copy_from_ring(front, back, from, &mut buf[..len]);
|
||||
*pos += len as u64;
|
||||
state.reader_pos = *pos;
|
||||
// Free what fell out of the keep-behind range even when the
|
||||
// downloader is idle (paused or done).
|
||||
state.trim_behind();
|
||||
shared.space_ready.notify_all();
|
||||
return (state, Ok(len));
|
||||
}
|
||||
// Not buffered. Wait for the current generation if it is heading
|
||||
// here, otherwise restart the downloader at the reader position.
|
||||
let reachable = *pos >= state.window_start
|
||||
&& (!state.ranges || *pos <= window_end.saturating_add(NEAR_GAP));
|
||||
if reachable && !state.failed {
|
||||
if state.done {
|
||||
return (state, Ok(0));
|
||||
}
|
||||
if state.exited {
|
||||
return (state, Err(downloader_stopped()));
|
||||
}
|
||||
if state.reader_pos != *pos {
|
||||
state.reader_pos = *pos;
|
||||
state.trim_behind();
|
||||
shared.space_ready.notify_all();
|
||||
}
|
||||
let now = Instant::now();
|
||||
let since = match starved {
|
||||
Some((since, seen)) if seen == state.progress => since,
|
||||
_ => {
|
||||
starved = Some((now, state.progress));
|
||||
now
|
||||
}
|
||||
};
|
||||
let waited = now.saturating_duration_since(since);
|
||||
if waited >= STARVE_TIMEOUT {
|
||||
// Give up on this generation; the next read retries.
|
||||
state.failed = true;
|
||||
state.error = None;
|
||||
let cause = state
|
||||
.last_error
|
||||
.take()
|
||||
.unwrap_or_else(|| "no data received".to_string());
|
||||
let error = io::Error::new(
|
||||
io::ErrorKind::TimedOut,
|
||||
format!(
|
||||
"podcast stream stalled for {}s: {cause}",
|
||||
STARVE_TIMEOUT.as_secs()
|
||||
),
|
||||
);
|
||||
return (state, Err(error));
|
||||
}
|
||||
if !state.reader_waiting {
|
||||
// Lets a downloader in backoff retry sooner.
|
||||
state.reader_waiting = true;
|
||||
shared.space_ready.notify_all();
|
||||
}
|
||||
state = shared
|
||||
.data_ready
|
||||
.wait_timeout(state, STARVE_TIMEOUT - waited)
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.0;
|
||||
continue;
|
||||
}
|
||||
if let Some((kind, message)) = state.error.take() {
|
||||
// Report once; the next read retries from scratch.
|
||||
return (state, Err(io::Error::new(kind, message)));
|
||||
}
|
||||
if state.exited {
|
||||
return (state, Err(downloader_stopped()));
|
||||
}
|
||||
state.restart_at(*pos);
|
||||
state.reader_pos = *pos;
|
||||
starved = None;
|
||||
shared.space_ready.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_from_ring(front: &[u8], back: &[u8], from: usize, out: &mut [u8]) {
|
||||
let mut written = 0;
|
||||
if from < front.len() {
|
||||
let len = out.len().min(front.len() - from);
|
||||
out[..len].copy_from_slice(&front[from..from + len]);
|
||||
written = len;
|
||||
}
|
||||
if written < out.len() {
|
||||
let back_from = from + written - front.len();
|
||||
let len = out.len() - written;
|
||||
out[written..].copy_from_slice(&back[back_from..back_from + len]);
|
||||
}
|
||||
}
|
||||
|
||||
impl Seek for HttpStream {
|
||||
fn seek(&mut self, position: SeekFrom) -> io::Result<u64> {
|
||||
let target = match position {
|
||||
SeekFrom::Start(offset) => i128::from(offset),
|
||||
SeekFrom::Current(delta) => i128::from(self.pos) + i128::from(delta),
|
||||
SeekFrom::End(delta) => {
|
||||
let Some(total) = self.shared.lock().total else {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::Unsupported,
|
||||
"stream length is unknown",
|
||||
));
|
||||
};
|
||||
i128::from(total) + i128::from(delta)
|
||||
}
|
||||
};
|
||||
let target = u64::try_from(target).map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"invalid seek to a negative or overflowing position",
|
||||
)
|
||||
})?;
|
||||
// Lazy: the downloader is only redirected when a read needs data.
|
||||
self.pos = target;
|
||||
Ok(target)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for HttpStream {
|
||||
fn drop(&mut self) {
|
||||
let mut state = self.shared.lock();
|
||||
state.closed = true;
|
||||
state.window = VecDeque::new();
|
||||
state.head = Vec::new();
|
||||
drop(state);
|
||||
self.shared.space_ready.notify_all();
|
||||
self.shared.data_ready.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl HttpStream {
|
||||
/// Bytes currently held in memory (window + head).
|
||||
pub(super) fn buffered_bytes(&self) -> usize {
|
||||
self.shared.lock().buffered()
|
||||
}
|
||||
|
||||
/// Highest number of bytes ever held in memory at once.
|
||||
pub(super) fn peak_buffered_bytes(&self) -> usize {
|
||||
self.shared.lock().peak_buffered
|
||||
}
|
||||
|
||||
/// Largest allocation (window + head capacity) ever held.
|
||||
pub(super) fn peak_allocated_bytes(&self) -> usize {
|
||||
let state = self.shared.lock();
|
||||
state.peak_capacity + state.head.capacity()
|
||||
}
|
||||
|
||||
/// Flag the downloader thread sets when it exits.
|
||||
pub(super) fn exit_probe(&self) -> impl Fn() -> bool + Send + 'static {
|
||||
let shared = Arc::clone(&self.shared);
|
||||
move || shared.lock().exited
|
||||
}
|
||||
}
|
||||
|
||||
/// Upper bound of [`HttpStream`] memory use, for tests.
|
||||
#[cfg(test)]
|
||||
pub(super) const MAX_BUFFERED: usize = WINDOW_CAP + HEAD_KEEP;
|
||||
@@ -0,0 +1,260 @@
|
||||
//! Minimal HTTP/1.1 server on 127.0.0.1 for podcast tests (no internet).
|
||||
//! One request per connection (`Connection: close`).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct Route {
|
||||
pub status: u16,
|
||||
pub body: Arc<Vec<u8>>,
|
||||
pub content_type: String,
|
||||
pub etag: Option<String>,
|
||||
/// Honour `Range` requests with 206 responses.
|
||||
pub ranges: bool,
|
||||
/// Send `Content-Length` (otherwise the body is close-delimited).
|
||||
pub send_length: bool,
|
||||
/// Close the connection once the body reaches this absolute file offset,
|
||||
/// on the first `fail_times` responses (simulates a flaky network).
|
||||
pub cut_after: Option<usize>,
|
||||
pub fail_times: usize,
|
||||
}
|
||||
|
||||
impl Route {
|
||||
pub fn new(body: impl Into<Vec<u8>>, content_type: &str) -> Route {
|
||||
Route {
|
||||
status: 200,
|
||||
body: Arc::new(body.into()),
|
||||
content_type: content_type.to_string(),
|
||||
etag: None,
|
||||
ranges: true,
|
||||
send_length: true,
|
||||
cut_after: None,
|
||||
fail_times: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn status(mut self, status: u16) -> Route {
|
||||
self.status = status;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn etag(mut self, etag: &str) -> Route {
|
||||
self.etag = Some(etag.to_string());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn no_ranges(mut self) -> Route {
|
||||
self.ranges = false;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn no_length(mut self) -> Route {
|
||||
self.send_length = false;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn cut(mut self, after: usize, times: usize) -> Route {
|
||||
self.cut_after = Some(after);
|
||||
self.fail_times = times;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ServerState {
|
||||
routes: HashMap<String, Route>,
|
||||
/// Per path: the `Range` header of every request (None if absent).
|
||||
requests: HashMap<String, Vec<Option<String>>>,
|
||||
failures: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
pub(super) struct TestServer {
|
||||
base: String,
|
||||
state: Arc<Mutex<ServerState>>,
|
||||
}
|
||||
|
||||
impl TestServer {
|
||||
pub fn start() -> TestServer {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind test server");
|
||||
let base = format!("http://{}", listener.local_addr().expect("local addr"));
|
||||
let state = Arc::new(Mutex::new(ServerState::default()));
|
||||
let accept_state = Arc::clone(&state);
|
||||
std::thread::spawn(move || {
|
||||
for stream in listener.incoming() {
|
||||
let Ok(stream) = stream else { continue };
|
||||
let state = Arc::clone(&accept_state);
|
||||
std::thread::spawn(move || handle(stream, &state));
|
||||
}
|
||||
});
|
||||
TestServer { base, state }
|
||||
}
|
||||
|
||||
pub fn url(&self, path: &str) -> String {
|
||||
format!("{}{path}", self.base)
|
||||
}
|
||||
|
||||
pub fn set(&self, path: &str, route: Route) {
|
||||
self.lock().routes.insert(path.to_string(), route);
|
||||
}
|
||||
|
||||
pub fn requests(&self, path: &str) -> Vec<Option<String>> {
|
||||
self.lock().requests.get(path).cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, ServerState> {
|
||||
self.state.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
}
|
||||
|
||||
fn handle(stream: TcpStream, state: &Mutex<ServerState>) {
|
||||
let _ = stream.set_read_timeout(Some(Duration::from_secs(10)));
|
||||
let mut reader = BufReader::new(match stream.try_clone() {
|
||||
Ok(stream) => stream,
|
||||
Err(_) => return,
|
||||
});
|
||||
let mut request_line = String::new();
|
||||
if reader.read_line(&mut request_line).is_err() {
|
||||
return;
|
||||
}
|
||||
let path = request_line
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.unwrap_or("/")
|
||||
.to_string();
|
||||
let mut headers = HashMap::new();
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
match reader.read_line(&mut line) {
|
||||
Ok(0) | Err(_) => return,
|
||||
Ok(_) => {}
|
||||
}
|
||||
let line = line.trim_end();
|
||||
if line.is_empty() {
|
||||
break;
|
||||
}
|
||||
if let Some((name, value)) = line.split_once(':') {
|
||||
headers.insert(name.trim().to_ascii_lowercase(), value.trim().to_string());
|
||||
}
|
||||
}
|
||||
let range_header = headers.get("range").cloned();
|
||||
let (route, cut) = {
|
||||
let mut state = state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
state
|
||||
.requests
|
||||
.entry(path.clone())
|
||||
.or_default()
|
||||
.push(range_header.clone());
|
||||
let route = state.routes.get(&path).cloned();
|
||||
let cut = match &route {
|
||||
Some(route) if route.cut_after.is_some() => {
|
||||
let failures = state.failures.entry(path.clone()).or_default();
|
||||
if *failures < route.fail_times {
|
||||
*failures += 1;
|
||||
route.cut_after
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
(route, cut)
|
||||
};
|
||||
let mut out = stream;
|
||||
let Some(route) = route else {
|
||||
let _ = out
|
||||
.write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
|
||||
return;
|
||||
};
|
||||
if let (Some(etag), Some(sent)) = (&route.etag, headers.get("if-none-match"))
|
||||
&& etag == sent
|
||||
{
|
||||
let _ = write!(
|
||||
out,
|
||||
"HTTP/1.1 304 Not Modified\r\nETag: {etag}\r\nConnection: close\r\n\r\n"
|
||||
);
|
||||
return;
|
||||
}
|
||||
let total = route.body.len();
|
||||
let mut status = route.status;
|
||||
let mut start = 0usize;
|
||||
let mut end = total;
|
||||
let mut extra = String::new();
|
||||
if route.status == 200
|
||||
&& route.ranges
|
||||
&& let Some(range) = range_header
|
||||
.as_deref()
|
||||
.and_then(|r| r.strip_prefix("bytes="))
|
||||
&& let Some((from, to)) = range.split_once('-')
|
||||
&& let Ok(from) = from.trim().parse::<usize>()
|
||||
{
|
||||
if from >= total {
|
||||
let _ = write!(
|
||||
out,
|
||||
"HTTP/1.1 416 Range Not Satisfiable\r\nContent-Range: bytes */{total}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
|
||||
);
|
||||
return;
|
||||
}
|
||||
let to = to
|
||||
.trim()
|
||||
.parse::<usize>()
|
||||
.map_or(total, |to| (to + 1).min(total));
|
||||
status = 206;
|
||||
start = from;
|
||||
end = to;
|
||||
extra.push_str(&format!(
|
||||
"Content-Range: bytes {start}-{}/{total}\r\n",
|
||||
end - 1
|
||||
));
|
||||
}
|
||||
if route.ranges {
|
||||
extra.push_str("Accept-Ranges: bytes\r\n");
|
||||
}
|
||||
if let Some(etag) = &route.etag {
|
||||
extra.push_str(&format!("ETag: {etag}\r\n"));
|
||||
}
|
||||
if route.send_length {
|
||||
extra.push_str(&format!("Content-Length: {}\r\n", end - start));
|
||||
}
|
||||
let reason = match status {
|
||||
200 => "OK",
|
||||
206 => "Partial Content",
|
||||
404 => "Not Found",
|
||||
500 => "Internal Server Error",
|
||||
_ => "Status",
|
||||
};
|
||||
if write!(
|
||||
out,
|
||||
"HTTP/1.1 {status} {reason}\r\nContent-Type: {}\r\n{extra}Connection: close\r\n\r\n",
|
||||
route.content_type
|
||||
)
|
||||
.is_err()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let limit = cut.map_or(end, |cut| cut.clamp(start, end));
|
||||
for chunk in route.body[start..limit].chunks(64 * 1024) {
|
||||
if out.write_all(chunk).is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let _ = out.flush();
|
||||
let _ = out.shutdown(std::net::Shutdown::Both);
|
||||
}
|
||||
|
||||
/// Deterministic pseudo-random bytes.
|
||||
pub(super) fn noise(len: usize, seed: u64) -> Vec<u8> {
|
||||
let mut state = seed | 1;
|
||||
let mut out = Vec::with_capacity(len);
|
||||
while out.len() < len {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 7;
|
||||
state ^= state << 17;
|
||||
out.extend_from_slice(&state.to_le_bytes());
|
||||
}
|
||||
out.truncate(len);
|
||||
out
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+14
-3
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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<Line<'static>>) {
|
||||
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<Rect>) {
|
||||
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<Line<'static>> {
|
||||
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), "");
|
||||
}
|
||||
}
|
||||
+31
-9
@@ -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,
|
||||
);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user