diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 17d5bd9..ef32735 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -699,3 +699,14 @@ Future changes should preserve these rules: 5. Network and storage work must remain outside the interactive UI path. 6. More peers should improve availability; losing peers should only reduce remote capabilities. + +### Device-local podcast audio + +Episode downloads are explicit local actions. Completed files live beside the +podcast database in `podcast-downloads`, keyed by a hash of the shared episode +id. Temporary files become visible only after a complete response is saved. +Playback checks this directory on the blocking pool before opening HTTP and +uses the same progress and queue model for local audio. Downloads and retention +settings never enter the podcast store registers or device-sync protocol. +A background maintenance pass removes downloads after the configured age +(default 30 days from completion); catalog, progress and subscriptions remain. diff --git a/Cargo.lock b/Cargo.lock index b7cb10c..b9453b5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1715,7 +1715,7 @@ dependencies = [ [[package]] name = "furumi_tui" -version = "0.5.1" +version = "0.5.3" dependencies = [ "anyhow", "base64", diff --git a/Cargo.toml b/Cargo.toml index b8099bf..21b41d0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "furumi_tui" -version = "0.5.1" +version = "0.5.3" edition = "2024" rust-version = "1.97" description = "A federated P2P player for personal music libraries" diff --git a/README.md b/README.md index d326d4a..db10019 100644 --- a/README.md +++ b/README.md @@ -186,9 +186,16 @@ take them literally and silence the notice. ### Podcasts -The Podcasts tab (`4`) follows RSS and Atom podcast feeds. Furumi stores only -the feed's episode information; audio stays on the publisher's server and is -never imported into the music library or offered to other peers. +The Podcasts tab (`4`) follows RSS and Atom podcast feeds. Audio streams from +the publisher unless you download an episode. Downloads stay on this device, +are never imported into the music library or offered to other peers. + +- Press `y` on an episode to download it; `[offline]` marks a complete local + copy. Playback uses that copy, including resume and seeking, without HTTP. +- Settings → Additional settings → Podcast downloads: keep days controls + automatic cleanup (default 30 days from download completion). Cleanup runs + while Furumi is open; expired files can be downloaded again. No episodes + are downloaded automatically. - **Add podcast** (`o`, or the first row) takes a feed URL; `feed://`, `podcast://` and URLs without a scheme are accepted. Nothing is stored unless diff --git a/src/app/action.rs b/src/app/action.rs index 85255f3..c3cc76f 100644 --- a/src/app/action.rs +++ b/src/app/action.rs @@ -41,7 +41,7 @@ pub enum Action { QueueAddLast, MoveQueueUp, MoveQueueDown, - /// Download the selected federated track(s) into the local library. + /// Download selected federated tracks, or a podcast episode for offline playback. DownloadSelected, RemoveFromQueue, ClearQueue, @@ -239,7 +239,7 @@ impl Action { Action::QueueAddLast => "Queue: add to end".into(), Action::MoveQueueUp => "Queue: move track/selection up".into(), Action::MoveQueueDown => "Queue: move track/selection down".into(), - Action::DownloadSelected => "Federation: download to library".into(), + Action::DownloadSelected => "Download selected music / podcast episode".into(), Action::RemoveFromQueue => "Queue: remove selected".into(), Action::ClearQueue => "Queue: clear".into(), Action::OpenConnectedDevices => "Connected devices…".into(), diff --git a/src/app/event.rs b/src/app/event.rs index 0cdd107..1618359 100644 --- a/src/app/event.rs +++ b/src/app/event.rs @@ -273,6 +273,11 @@ pub enum AppEvent { }, /// Scheduler timer: ask the store which feeds are due. PodcastRefreshTick, + PodcastDownloads(Result, String>), + PodcastDownloaded { + id: String, + result: Result<(), String>, + }, /// Feeds due for a background refresh. PodcastsDue(Result, String>), /// What sharing a podcast would publish (`Effect::PodcastPrepareShare`). diff --git a/src/app/mod.rs b/src/app/mod.rs index 56c232e..60f7bc3 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -422,6 +422,7 @@ pub async fn run( status_message, ..AppState::default() }; + state.podcast_retention_days = settings.podcast_retention_days; state.player.volume = settings.volume; state.global.filters = settings.library; state.music_dir = settings.music_dir.clone(); @@ -1728,7 +1729,9 @@ fn perform_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) { }); } // Executed by podcast_runtime::perform above. - Effect::PodcastsReload + Effect::SavePodcastSettings + | Effect::PodcastDownload(_) + | Effect::PodcastsReload | Effect::PodcastLoadSeasons(_) | Effect::PodcastLoadEpisodes { .. } | Effect::PodcastSubscribe(_) @@ -3133,14 +3136,19 @@ fn refresh_artists(state: &mut AppState, runtime: &Runtime) { }); } -fn save_app_settings(state: &AppState) { - let settings = crate::config::settings::AppSettings { +fn app_settings(state: &AppState) -> crate::config::settings::AppSettings { + crate::config::settings::AppSettings { + podcast_retention_days: state.podcast_retention_days, playback: state.device_playback.config.clone(), volume: state.player.volume, library: state.global.filters, music_dir: state.music_dir.clone(), similarity: state.similarity.settings.clone(), - }; + } +} + +fn save_app_settings(state: &AppState) { + let settings = app_settings(state); if let Err(err) = crate::config::settings::save(&settings) { tracing::warn!(%err, "saving app settings failed"); } @@ -3535,6 +3543,8 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent | AppEvent::PodcastProgress(_) | AppEvent::PodcastEpisodeStarted { .. } | AppEvent::PodcastEpisodeFailed { .. } + | AppEvent::PodcastDownloads(_) + | AppEvent::PodcastDownloaded { .. } | AppEvent::PodcastRefreshTick | AppEvent::PodcastsDue(_) | AppEvent::PodcastSharePrepared { .. } diff --git a/src/app/podcast_runtime.rs b/src/app/podcast_runtime.rs index 3df4139..e8403ec 100644 --- a/src/app/podcast_runtime.rs +++ b/src/app/podcast_runtime.rs @@ -41,6 +41,8 @@ const PUBLICATION_FLUSH_TIMEOUT: Duration = Duration::from_secs(4); pub struct PodcastRuntime { pub services: Services, refresh_slots: Arc, + download_slots: Arc, + downloads_cancelled: Arc, /// Writes progress in order on its own thread; `None` if it could not /// start (episodes then play without saving progress). progress: Option, @@ -187,6 +189,18 @@ fn services(runtime: &Runtime) -> Option { /// Executes a podcast [`Effect`]; any other effect is handed back. pub fn perform(state: &mut AppState, runtime: &mut Runtime, effect: Effect) -> Option { + if matches!(effect, Effect::SavePodcastSettings) { + let settings = super::app_settings(state); + let tx = runtime.event_tx.clone(); + tokio::task::spawn_blocking(move || { + let message = match crate::config::settings::save(&settings) { + Ok(()) => "podcasts: download retention saved".to_string(), + Err(_) => "podcasts: could not save download retention".to_string(), + }; + let _ = tx.send(AppEvent::StatusMessage(message)); + }); + return None; + } let Some(services) = services(runtime) else { if is_podcast_effect(&effect) { if let Effect::PodcastRefresh { targets, .. } = &effect { @@ -219,6 +233,30 @@ pub fn perform(state: &mut AppState, runtime: &mut Runtime, effect: Effect) -> O }; let tx = runtime.event_tx.clone(); match effect { + Effect::SavePodcastSettings => unreachable!("handled before store lookup"), + Effect::PodcastDownload(episode) => { + let slots = Arc::clone(&runtime.podcasts.as_ref().unwrap().download_slots); + let cancelled = Arc::clone(&runtime.podcasts.as_ref().unwrap().downloads_cancelled); + tokio::spawn(async move { + let Ok(permit) = slots.acquire_owned().await else { + return; + }; + let _ = tokio::task::spawn_blocking(move || { + let _permit = permit; + let id = episode.episode_id.as_str().to_owned(); + let result = crate::podcasts::offline::download_with_cancel( + &services.downloads_dir, + &episode, + CancelToken::new(move || { + cancelled.load(std::sync::atomic::Ordering::Relaxed) + }), + ) + .map_err(|_| "could not download episode audio".to_string()); + let _ = tx.send(AppEvent::PodcastDownloaded { id, result }); + }) + .await; + }); + } Effect::PodcastsReload => { tokio::task::spawn_blocking(move || { let result = load_rows(&services.store).map_err(err_string); @@ -411,7 +449,9 @@ fn set_shared( fn is_podcast_effect(effect: &Effect) -> bool { matches!( effect, - Effect::PodcastsReload + Effect::SavePodcastSettings + | Effect::PodcastDownload(_) + | Effect::PodcastsReload | Effect::PodcastLoadSeasons(_) | Effect::PodcastLoadEpisodes { .. } | Effect::PodcastSubscribe(_) @@ -477,6 +517,8 @@ pub fn handle_event( runtime.podcasts = Some(PodcastRuntime { services, refresh_slots: Arc::new(tokio::sync::Semaphore::new(MAX_CONCURRENT_REFRESHES)), + download_slots: Arc::new(tokio::sync::Semaphore::new(2)), + downloads_cancelled: Arc::new(std::sync::atomic::AtomicBool::new(false)), progress, publication, }); @@ -599,7 +641,34 @@ pub fn handle_event( episode_failed(state, runtime, generation, message); Vec::new() } + AppEvent::PodcastDownloaded { id, result } => { + state.podcast_downloading.remove(&id); + state.status_message = Some(match result { + Ok(()) => "podcasts: episode downloaded".into(), + Err(e) => e, + }); + let _ = runtime.event_tx.send(AppEvent::PodcastRefreshTick); + Vec::new() + } + AppEvent::PodcastDownloads(result) => { + if let Ok(downloads) = result { + state.podcast_downloads = downloads; + } + Vec::new() + } AppEvent::PodcastRefreshTick => { + let offline_services = services(runtime)?; + let days = state.podcast_retention_days.max(1); + let tx = runtime.event_tx.clone(); + tokio::task::spawn_blocking(move || { + let result = crate::podcasts::offline::cleanup( + &offline_services.downloads_dir, + days, + std::time::SystemTime::now(), + ) + .map_err(err_string); + let _ = tx.send(AppEvent::PodcastDownloads(result)); + }); if let Some(services) = services(runtime) { let tx = runtime.event_tx.clone(); tokio::task::spawn_blocking(move || { @@ -1148,6 +1217,12 @@ fn progress_event( /// also one still being written) reach the overlay. Logs a warning when a /// card of a private podcast may still be live. pub(crate) async fn shutdown(runtime: &mut Runtime) { + if let Some(podcasts) = &runtime.podcasts { + podcasts + .downloads_cancelled + .store(true, std::sync::atomic::Ordering::Relaxed); + podcasts.download_slots.close(); + } end_playback(runtime); let Some(podcasts) = runtime.podcasts.as_mut() else { return; diff --git a/src/app/popup.rs b/src/app/popup.rs index 97fe21a..4678b35 100644 --- a/src/app/popup.rs +++ b/src/app/popup.rs @@ -614,6 +614,20 @@ fn handle_fed_input( !state.federation.settings.network_id.is_empty(); super::fed_apply_settings(state, runtime); } + FedInputField::PodcastRetention => match value.parse::() { + Ok(days) if (1..=36500).contains(&days) => { + state.podcast_retention_days = days; + super::perform_effect( + state, + runtime, + crate::app::update::Effect::SavePodcastSettings, + ); + } + _ => { + state.status_message = + Some("enter a retention period from 1 to 36500 days".into()) + } + }, FedInputField::MusicDirectory => { if value.is_empty() { state.status_message = Some("music directory is empty".into()); diff --git a/src/app/state.rs b/src/app/state.rs index 08c3f07..552f1eb 100644 --- a/src/app/state.rs +++ b/src/app/state.rs @@ -923,6 +923,7 @@ impl StatusDetailFocus { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum FedInputField { MusicDirectory, + PodcastRetention, SimilarityWorkers, SimilarityMinimumScore, SimilarityMaxTracksPerArtist, @@ -940,6 +941,7 @@ pub enum FedInputField { impl FedInputField { pub fn title(self) -> &'static str { match self { + FedInputField::PodcastRetention => "Keep podcast downloads (days)", FedInputField::MusicDirectory => "Music save directory", FedInputField::SimilarityWorkers => "Similarity background workers", FedInputField::SimilarityMinimumScore => "Minimum similarity score", @@ -956,6 +958,9 @@ impl FedInputField { pub fn help(self) -> &'static str { match self { + FedInputField::PodcastRetention => { + "Enter 1–36500 days. Downloads expire from the time they finish. Default: 30 days. Only this device is affected." + } FedInputField::MusicDirectory => { "Federated tracks saved to your library use this directory. The directory is checked for write access before anything changes." } @@ -1047,6 +1052,7 @@ pub enum SettingsRow { CheckUpdate, InstallUpdate, MusicDirectory, + PodcastRetention, Similarity(SimilarityRow), Federation(FedRow), StatusDetails, @@ -1188,6 +1194,7 @@ pub fn device_status_order(state: &AppState) -> Vec { pub fn additional_settings_rows(state: &AppState) -> Vec { let mut rows = vec![ SettingsRow::MusicDirectory, + SettingsRow::PodcastRetention, SettingsRow::CheckUpdate, SettingsRow::InstallUpdate, ]; @@ -1958,6 +1965,9 @@ pub struct AppState { /// Root for music permanently downloaded from federation peers. pub music_dir: std::path::PathBuf, pub music_dir_changing: bool, + pub podcast_retention_days: u32, + pub podcast_downloads: std::collections::HashSet, + pub podcast_downloading: std::collections::HashSet, pub player: PlayerBar, pub device_playback: DevicePlaybackState, pub jam: crate::jam::JamStatus, diff --git a/src/app/update.rs b/src/app/update.rs index 11e5dcb..cee2f8d 100644 --- a/src/app/update.rs +++ b/src/app/update.rs @@ -112,6 +112,8 @@ pub enum Effect { LoadListenHistory, /// Reload the subscribed podcasts with their fetch state. PodcastsReload, + PodcastDownload(music_dht::podcast::PodcastEpisodeRef), + SavePodcastSettings, /// Load the season groups of a podcast. PodcastLoadSeasons(music_dht::podcast::PodcastId), /// Load one page of episodes; `seq` drops stale results. @@ -3067,6 +3069,13 @@ fn select_settings_row(state: &mut AppState, row: super::state::SettingsRow) -> state.updater.message = "Downloading update...".into(); Some(Effect::InstallUpdate(update)) } + SettingsRow::PodcastRetention => { + state.popup = Some(Popup::FedInput { + field: FedInputField::PodcastRetention, + input: crate::app::input::LineEdit::new(state.podcast_retention_days.to_string()), + }); + None + } SettingsRow::MusicDirectory => { if state.music_dir_changing { state.status_message = Some("music directory change is already running".into()); diff --git a/src/app/update/podcasts.rs b/src/app/update/podcasts.rs index 188e522..dd20f48 100644 --- a/src/app/update/podcasts.rs +++ b/src/app/update/podcasts.rs @@ -54,6 +54,31 @@ pub(super) fn handle(state: &mut AppState, action: &Action) -> Option { + if !store_ready(state) { + return Some(None); + } + let Some(track) = state.podcasts.selected_episode_track() else { + return Some(None); + }; + let episode = track.podcast_episode_ref().unwrap().clone(); + if state + .podcast_downloads + .contains(&crate::podcasts::offline::key(episode.episode_id.as_str())) + { + state.status_message = + Some("podcasts: episode is already available offline".into()); + return Some(None); + } + if !state + .podcast_downloading + .insert(episode.episode_id.as_str().to_owned()) + { + return Some(None); + } + state.status_message = Some("podcasts: downloading episode…".into()); + Some(Effect::PodcastDownload(episode)) + } Action::RefreshPodcast => refresh_current(state), Action::RefreshAllPodcasts => refresh_all(state), Action::CycleEpisodeSort => cycle_sort(state), diff --git a/src/app/update_tests.rs b/src/app/update_tests.rs index e7b0d84..d43cd5a 100644 --- a/src/app/update_tests.rs +++ b/src/app/update_tests.rs @@ -2827,3 +2827,54 @@ mod podcast_discovery { )); } } + +#[test] +fn episode_download_requires_explicit_action_and_deduplicates_requests() { + use crate::app::podcast_fixtures as fx; + let mut state = fx::with_episodes( + fx::ready_state(vec![fx::row("Show", 1, 1, 0)]), + vec![fx::episode(1, "Episode", None)], + ); + assert!(state.podcast_downloading.is_empty()); + let expected = state + .podcasts + .selected_episode_track() + .unwrap() + .podcast_episode_ref() + .unwrap() + .clone(); + assert_eq!( + update(&mut state, Action::DownloadSelected), + Some(Effect::PodcastDownload(expected.clone())) + ); + assert_eq!(update(&mut state, Action::DownloadSelected), None); + assert_eq!(state.podcast_downloading.len(), 1); + state.podcast_downloading.clear(); + state + .podcast_downloads + .insert(crate::podcasts::offline::key(expected.episode_id.as_str())); + assert_eq!(update(&mut state, Action::DownloadSelected), None); + assert!(state.podcast_downloading.is_empty()); +} + +#[test] +fn podcast_retention_opens_a_numeric_editor_in_additional_settings() { + use crate::app::state::{FedInputField, Popup, SettingsRow, additional_settings_rows}; + let mut state = AppState { + additional_settings_open: true, + podcast_retention_days: 30, + ..Default::default() + }; + state.additional_settings_cursor = additional_settings_rows(&state) + .iter() + .position(|row| *row == SettingsRow::PodcastRetention) + .unwrap(); + assert_eq!(update(&mut state, Action::Select), None); + assert!(matches!( + state.popup, + Some(Popup::FedInput { + field: FedInputField::PodcastRetention, + .. + }) + )); +} diff --git a/src/config/settings.rs b/src/config/settings.rs index 413a85b..2d05ebb 100644 --- a/src/config/settings.rs +++ b/src/config/settings.rs @@ -50,6 +50,8 @@ impl Default for SimilaritySettings { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct AppSettings { + #[serde(default = "default_podcast_retention_days")] + pub podcast_retention_days: u32, #[serde(default)] pub playback: music_dht::playback::Config, #[serde(default = "default_volume")] @@ -66,6 +68,7 @@ pub struct AppSettings { impl Default for AppSettings { fn default() -> Self { Self { + podcast_retention_days: 30, playback: music_dht::playback::Config::default(), volume: default_volume(), library: LibraryFilters::default(), @@ -77,6 +80,7 @@ impl Default for AppSettings { impl AppSettings { pub fn normalized(mut self) -> Self { + self.podcast_retention_days = self.podcast_retention_days.clamp(1, 36500); self.volume = self.volume.min(100); if self.music_dir.as_os_str().is_empty() { self.music_dir = default_music_dir(); @@ -97,6 +101,10 @@ impl AppSettings { } } +fn default_podcast_retention_days() -> u32 { + 30 +} + fn default_volume() -> u8 { 80 } @@ -186,6 +194,7 @@ hide_featured_only = true let settings = settings.normalized(); assert_eq!(settings.volume, 100); + assert_eq!(settings.podcast_retention_days, 30); assert!(settings.library.hide_featured_only); assert_eq!(settings.library.source_mode, LibrarySourceMode::Global); assert_eq!(settings.music_dir, default_music_dir()); diff --git a/src/podcasts/mod.rs b/src/podcasts/mod.rs index 2030bbb..63289d1 100644 --- a/src/podcasts/mod.rs +++ b/src/podcasts/mod.rs @@ -25,10 +25,11 @@ //! "already subscribed" mark, an episode preview read from the feed and //! subscribing from a card. //! -//! Only RSS metadata is stored. Audio stays on the publisher's server. +//! Audio is streamed unless the user explicitly downloads an episode. pub mod discovery; pub mod fetch; +pub mod offline; pub mod playback; pub mod progress; pub mod publication; @@ -125,6 +126,7 @@ pub fn open_services(db_path: &Path, covers_dir: PathBuf, log: Arc) - let confirmations = publication::ShareConfirmations::open(publication::confirmations_path(db_path)); Ok(Services { + downloads_dir: db_path.with_file_name("podcast-downloads"), store: Arc::new(store), fetcher: Arc::new(Fetcher::new(covers_dir)?), log, diff --git a/src/podcasts/offline.rs b/src/podcasts/offline.rs new file mode 100644 index 0000000..f128e86 --- /dev/null +++ b/src/podcasts/offline.rs @@ -0,0 +1,99 @@ +//! Explicit device-local downloads, outside the podcast sync store. +use anyhow::{Result, bail}; +use music_dht::podcast::PodcastEpisodeRef; +use std::{ + fs::{self, File}, + io::{Read, Write}, + path::{Path, PathBuf}, + time::{Duration, SystemTime}, +}; +pub fn key(id: &str) -> String { + blake3::hash(id.as_bytes()).to_hex().to_string() +} +pub fn path(dir: &Path, ep: &PodcastEpisodeRef) -> PathBuf { + dir.join(key(ep.episode_id.as_str())) +} +pub fn available(dir: &Path) -> Result> { + if !dir.exists() { + return Ok(Default::default()); + } + Ok(fs::read_dir(dir)? + .filter_map(Result::ok) + .filter(|e| e.file_type().is_ok_and(|t| t.is_file())) + .filter_map(|e| { + let n = e.file_name().to_str()?.to_owned(); + (n.len() == 64 && n.bytes().all(|b| b.is_ascii_hexdigit())).then_some(n) + }) + .collect()) +} +pub fn cleanup( + dir: &Path, + days: u32, + now: SystemTime, +) -> Result> { + for name in available(dir)? { + let p = dir.join(name); + if now + .duration_since(fs::metadata(&p)?.modified()?) + .unwrap_or_default() + >= Duration::from_secs(u64::from(days.max(1)) * 86400) + { + let _ = fs::remove_file(p); + } + } + available(dir) +} +pub fn open(dir: &Path, ep: &PodcastEpisodeRef) -> Result> { + match File::open(path(dir, ep)) { + Ok(f) => Ok(Some(f)), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e.into()), + } +} +#[cfg(test)] +pub fn download(dir: &Path, ep: &PodcastEpisodeRef) -> Result<()> { + download_with_cancel(dir, ep, super::stream::CancelToken::never()) +} +pub fn download_with_cancel( + dir: &Path, + ep: &PodcastEpisodeRef, + cancel: super::stream::CancelToken, +) -> Result<()> { + let target = path(dir, ep); + let dir = target.parent().unwrap(); + fs::create_dir_all(dir)?; + if target.is_file() { + return Ok(()); + } + let started = std::time::Instant::now(); + let mut stream = super::stream::open_with( + &ep.audio_url, + super::stream::CancelToken::new(move || { + cancel.is_cancelled() || started.elapsed() > Duration::from_secs(7200) + }), + )?; + let mut temp = tempfile::NamedTempFile::new_in(dir)?; + let mut buf = [0; 65536]; + let mut total = 0u64; + loop { + let n = stream.reader.read(&mut buf)?; + if n == 0 { + break; + } + total += n as u64; + if total > 4 * 1024 * 1024 * 1024 { + bail!("episode exceeds 4 GiB"); + } + temp.write_all(&buf[..n])?; + } + if total == 0 + || stream.probe.end() == super::stream::StreamEnd::Failed + || stream.byte_len.is_some_and(|len| len != total) + { + bail!("incomplete episode download"); + } + temp.as_file().sync_all()?; + temp.persist(target) + .map_err(|_| anyhow::anyhow!("cannot save episode"))?; + Ok(()) +} diff --git a/src/podcasts/playback.rs b/src/podcasts/playback.rs index 9c4b61b..837a7ad 100644 --- a/src/podcasts/playback.rs +++ b/src/podcasts/playback.rs @@ -163,6 +163,9 @@ pub fn open_at( start_ms: i64, cancel: &CancelToken, ) -> Result { + if cancel.is_cancelled() { + return Err(Cancelled.into()); + } let opened = stream::open_with(&episode.audio_url, cancel.clone())?; let seekable = opened.seekable; let probe = opened.probe.clone(); @@ -218,6 +221,43 @@ pub fn open_at( }) } +/// Decode a completed local download. Blocking; no HTTP requests. +pub fn open_local( + episode: &PodcastEpisodeRef, + start_ms: i64, + file: std::fs::File, +) -> Result { + let len = file.metadata()?.len(); + let mut source = decode_source_with( + Box::new(file), + Some(len), + episode.mime.as_deref(), + true, + true, + ) + .map_err(|e| anyhow!(e))?; + if start_ms > 0 { + source + .try_seek(Duration::from_millis(start_ms as u64)) + .map_err(|_| CannotResume { + position_ms: start_ms, + })?; + } + let measured = source + .total_duration() + .and_then(|d| i64::try_from(d.as_millis()).ok()) + .filter(|ms| *ms > 0); + Ok(PreparedEpisode { + episode: episode.clone(), + source, + start_ms, + duration_ms: measured.or(episode.duration_ms), + duration_measured: measured.is_some(), + seekable: true, + probe: StreamProbe::local(), + }) +} + /// [`resolve`] + [`open_at`], refreshing the feed once when the audio URL /// answers with a client error (moved or expired file). pub async fn prepare( @@ -233,8 +273,25 @@ pub async fn prepare( let lookup = queued.clone(); let (episode, start_ms) = blocking(move || resolve(store.as_deref(), &lookup, start)).await?; let attempt = episode.clone(); + let downloads_dir = services.as_ref().map(|s| s.downloads_dir.clone()); let attempt_cancel = cancel.clone(); - let error = match blocking(move || open_at(&attempt, start_ms, &attempt_cancel)).await { + let error = match blocking(move || { + if attempt_cancel.is_cancelled() { + return Err(Cancelled.into()); + } + let local = downloads_dir + .as_ref() + .map(|dir| super::offline::open(dir, &attempt)) + .transpose()? + .flatten(); + if let Some(file) = local { + open_local(&attempt, start_ms, file) + } else { + open_at(&attempt, start_ms, &attempt_cancel) + } + }) + .await + { Ok(prepared) => return Ok(prepared), Err(error) => error, }; diff --git a/src/podcasts/playback_tests.rs b/src/podcasts/playback_tests.rs index 36a9a17..5113d06 100644 --- a/src/podcasts/playback_tests.rs +++ b/src/podcasts/playback_tests.rs @@ -834,3 +834,98 @@ fn a_superseded_resume_stops_reading_up_to_its_offset() { started.elapsed() ); } + +#[tokio::test] +async fn downloaded_episode_plays_and_seeks_without_publisher() { + let f = fixture(); + let (_, mut episode) = subscribed(&f).await; + f.server + .set("/offline.wav", Route::new(wav(8), "audio/wav")); + episode.audio_url = f.server.url("/offline.wav"); + let download_dir = f.services.downloads_dir.clone(); + let download_episode = episode.clone(); + tokio::task::spawn_blocking(move || super::offline::download(&download_dir, &download_episode)) + .await + .unwrap() + .unwrap(); + assert!( + super::offline::available(&f.services.downloads_dir) + .unwrap() + .contains(&super::offline::key(episode.episode_id.as_str())) + ); + // No store lookup can replace this reference with the fixture's old URL. + episode.audio_url = "http://127.0.0.1:1/unavailable".into(); + let file = super::offline::open(&f.services.downloads_dir, &episode) + .unwrap() + .unwrap(); + let prepared = playback::open_local(&episode, 2000, file).unwrap(); + assert_eq!(prepared.start_ms, 2000); + assert!(prepared.seekable); + assert_eq!(prepared.probe.end(), StreamEnd::Complete); + assert!(prepared.source.take(100).count() > 0); + // Prepare must prefer the same local file even though resolve finds the old HTTP URL. + let prepared = playback::prepare( + Some(f.services.clone()), + episode, + StartAt::Position { ms: 2000 }, + NOW, + CancelToken::never(), + ) + .await + .unwrap(); + assert_eq!(prepared.start_ms, 2000); +} + +#[test] +fn download_cleanup_expires_only_completed_files_at_the_boundary() { + use std::fs::{File, FileTimes}; + use std::time::SystemTime; + let dir = tempfile::tempdir().unwrap(); + let now = SystemTime::now(); + let expired = dir.path().join(super::offline::key("old")); + let fresh = dir.path().join(super::offline::key("new")); + File::create(&expired) + .unwrap() + .set_times(FileTimes::new().set_modified(now - Duration::from_secs(30 * 86400))) + .unwrap(); + File::create(&fresh) + .unwrap() + .set_times(FileTimes::new().set_modified(now - Duration::from_secs(29 * 86400))) + .unwrap(); + let unrelated = dir.path().join("notes.txt"); + std::fs::write(&unrelated, b"keep").unwrap(); + let remaining = super::offline::cleanup(dir.path(), 30, now).unwrap(); + assert!(!expired.exists()); + assert!(fresh.exists()); + assert!(unrelated.exists()); + assert_eq!(remaining.len(), 1); + assert_eq!( + super::offline::cleanup(dir.path(), 30, now).unwrap(), + remaining + ); +} + +#[tokio::test] +async fn failed_download_never_becomes_available_offline() { + let f = fixture(); + let (_, mut episode) = subscribed(&f).await; + episode.audio_url = f.server.url("/missing-audio"); + let download_dir = f.services.downloads_dir.clone(); + assert!( + tokio::task::spawn_blocking(move || super::offline::download(&download_dir, &episode)) + .await + .unwrap() + .is_err() + ); + assert!( + super::offline::available(&f.services.downloads_dir) + .unwrap() + .is_empty() + ); + assert_eq!( + std::fs::read_dir(&f.services.downloads_dir) + .unwrap() + .count(), + 0 + ); +} diff --git a/src/podcasts/refresh.rs b/src/podcasts/refresh.rs index 20a03af..00870ba 100644 --- a/src/podcasts/refresh.rs +++ b/src/podcasts/refresh.rs @@ -28,6 +28,7 @@ pub const FAILURE_BACKOFF_MAX: Duration = Duration::from_secs(24 * 60 * 60); #[derive(Clone)] pub struct Services { pub store: Arc, + pub downloads_dir: std::path::PathBuf, pub fetcher: Arc, pub log: Arc, /// Device-local privacy confirmations for sharing (never synced). diff --git a/src/podcasts/stream.rs b/src/podcasts/stream.rs index 12d74ce..4bfb6a3 100644 --- a/src/podcasts/stream.rs +++ b/src/podcasts/stream.rs @@ -162,7 +162,7 @@ pub enum StreamEnd { /// Read-only view of a stream's state that outlives handing the reader to /// the decoder. #[derive(Clone)] -pub struct StreamProbe(Arc); +pub struct StreamProbe(Option>); impl std::fmt::Debug for StreamProbe { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { @@ -171,8 +171,14 @@ impl std::fmt::Debug for StreamProbe { } impl StreamProbe { + pub fn local() -> Self { + Self(None) + } pub fn end(&self) -> StreamEnd { - let state = self.0.lock(); + let Some(shared) = &self.0 else { + return StreamEnd::Complete; + }; + let state = shared.lock(); if state.read_failed { StreamEnd::Failed } else if state.declared_total { @@ -385,7 +391,7 @@ pub fn open_with(url: &str, cancel: CancelToken) -> Result { .spawn(move || downloader.run(response)) .context("spawning the podcast stream thread")?; Ok(OpenedStream { - probe: StreamProbe(Arc::clone(&shared)), + probe: StreamProbe(Some(Arc::clone(&shared))), reader: HttpStream { pos: 0, shared }, byte_len: opened.total, mime_type, diff --git a/src/ui/additional_settings.rs b/src/ui/additional_settings.rs index 8497b15..ff739d0 100644 --- a/src/ui/additional_settings.rs +++ b/src/ui/additional_settings.rs @@ -57,6 +57,11 @@ pub fn draw(frame: &mut Frame, state: &AppState) { selected = items.len(); } let (label, value, enabled) = match row { + SettingsRow::PodcastRetention => ( + "Podcast downloads: keep days".into(), + state.podcast_retention_days.to_string(), + true, + ), SettingsRow::MusicDirectory => ( "Music save directory".into(), if state.music_dir_changing { diff --git a/src/ui/podcasts.rs b/src/ui/podcasts.rs index 413e824..161ac36 100644 --- a/src/ui/podcasts.rs +++ b/src/ui/podcasts.rs @@ -652,6 +652,17 @@ fn draw_episode_row( _ => String::new(), }; let mut title = episode.title.clone(); + if state + .podcast_downloading + .contains(episode.episode_id.as_str()) + { + title.push_str(" [downloading]"); + } else if state + .podcast_downloads + .contains(&crate::podcasts::offline::key(episode.episode_id.as_str())) + { + title.push_str(" [offline]"); + } if !item.in_feed { title.push_str(" (no longer in the feed)"); }