Add offline podcast downloads and release 0.5.3
This commit is contained in:
1 parent
3cd6d94895
commit
5aef2cb1e7
22 files changed
+519
-17
No files matched your search
@@ -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.
|
||||
Generated
+1
-1
@@ -1715,7 +1715,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "furumi_tui"
|
||||
version = "0.5.1"
|
||||
version = "0.5.3"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64",
|
||||
|
||||
+1
-1
@@ -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"
|
||||
|
||||
@@ -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
|
||||
|
||||
+2
-2
@@ -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(),
|
||||
|
||||
@@ -273,6 +273,11 @@ pub enum AppEvent {
|
||||
},
|
||||
/// Scheduler timer: ask the store which feeds are due.
|
||||
PodcastRefreshTick,
|
||||
PodcastDownloads(Result<std::collections::HashSet<String>, String>),
|
||||
PodcastDownloaded {
|
||||
id: String,
|
||||
result: Result<(), String>,
|
||||
},
|
||||
/// Feeds due for a background refresh.
|
||||
PodcastsDue(Result<Vec<(music_dht::podcast::PodcastId, music_dht::podcast::FeedUrl)>, String>),
|
||||
/// What sharing a podcast would publish (`Effect::PodcastPrepareShare`).
|
||||
|
||||
+14
-4
@@ -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 { .. }
|
||||
|
||||
@@ -41,6 +41,8 @@ const PUBLICATION_FLUSH_TIMEOUT: Duration = Duration::from_secs(4);
|
||||
pub struct PodcastRuntime {
|
||||
pub services: Services,
|
||||
refresh_slots: Arc<tokio::sync::Semaphore>,
|
||||
download_slots: Arc<tokio::sync::Semaphore>,
|
||||
downloads_cancelled: Arc<std::sync::atomic::AtomicBool>,
|
||||
/// Writes progress in order on its own thread; `None` if it could not
|
||||
/// start (episodes then play without saving progress).
|
||||
progress: Option<ProgressWriter>,
|
||||
@@ -187,6 +189,18 @@ fn services(runtime: &Runtime) -> Option<Services> {
|
||||
|
||||
/// Executes a podcast [`Effect`]; any other effect is handed back.
|
||||
pub fn perform(state: &mut AppState, runtime: &mut Runtime, effect: Effect) -> Option<Effect> {
|
||||
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;
|
||||
|
||||
@@ -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::<u32>() {
|
||||
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());
|
||||
|
||||
@@ -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<usize> {
|
||||
pub fn additional_settings_rows(state: &AppState) -> Vec<SettingsRow> {
|
||||
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<String>,
|
||||
pub podcast_downloading: std::collections::HashSet<String>,
|
||||
pub player: PlayerBar,
|
||||
pub device_playback: DevicePlaybackState,
|
||||
pub jam: crate::jam::JamStatus,
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -54,6 +54,31 @@ pub(super) fn handle(state: &mut AppState, action: &Action) -> Option<Option<Eff
|
||||
open_add(state);
|
||||
None
|
||||
}
|
||||
Action::DownloadSelected => {
|
||||
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),
|
||||
|
||||
@@ -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,
|
||||
..
|
||||
})
|
||||
));
|
||||
}
|
||||
@@ -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());
|
||||
|
||||
+3
-1
@@ -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<dyn OpLog>) -
|
||||
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,
|
||||
|
||||
@@ -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<std::collections::HashSet<String>> {
|
||||
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<std::collections::HashSet<String>> {
|
||||
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<Option<File>> {
|
||||
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(())
|
||||
}
|
||||
@@ -163,6 +163,9 @@ pub fn open_at(
|
||||
start_ms: i64,
|
||||
cancel: &CancelToken,
|
||||
) -> Result<PreparedEpisode> {
|
||||
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<PreparedEpisode> {
|
||||
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,
|
||||
};
|
||||
|
||||
@@ -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
|
||||
);
|
||||
}
|
||||
@@ -28,6 +28,7 @@ pub const FAILURE_BACKOFF_MAX: Duration = Duration::from_secs(24 * 60 * 60);
|
||||
#[derive(Clone)]
|
||||
pub struct Services {
|
||||
pub store: Arc<PodcastStore>,
|
||||
pub downloads_dir: std::path::PathBuf,
|
||||
pub fetcher: Arc<Fetcher>,
|
||||
pub log: Arc<dyn OpLog>,
|
||||
/// Device-local privacy confirmations for sharing (never synced).
|
||||
|
||||
@@ -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<Shared>);
|
||||
pub struct StreamProbe(Option<Arc<Shared>>);
|
||||
|
||||
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<OpenedStream> {
|
||||
.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,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)");
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user