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
+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,
|
||||
..
|
||||
})
|
||||
));
|
||||
}
|
||||
Reference in new issue
Block a user