Replace the Podcasts placeholder with subscriptions, seasons and episodes

The tab opens the FRID podcast store (podcasts.sqlite3, migrating a
prototype database in place; newer or foreign files are reported and left
unchanged) off the UI thread and shows subscriptions with unplayed counts
and check status, podcast -> seasons -> episodes navigation, and episodes
with saved position, played state, duration and date. Episode search,
played filter and order run as paged store queries with request sequence
numbers. Adding a feed, checking one or all feeds, marking played and
unsubscribing (with a confirmation that progress is kept) go through
Effect/AppEvent; a scheduler refreshes due feeds in the background.

New actions are bound in the podcasts keymap context and listed in a
Podcasts help section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
sanapachandClaude Opus 5.5 committed 2026-11-19 19:58:37 +02:00
1 parent 07dcd0587c
commit 99c4d05dec
16 files changed
+2957 -63

No files matched your search

+36 -1
View File
@@ -57,6 +57,22 @@ pub enum Action {
OpenSearch,
EditSelected,
DeleteSelected,
/// Podcasts: subscribe to an RSS feed URL.
AddPodcast,
/// Podcasts: search the episodes of the opened podcast.
SearchEpisodes,
/// Podcasts: check the selected or opened podcast for new episodes.
RefreshPodcast,
/// Podcasts: check every subscription for new episodes.
RefreshAllPodcasts,
/// Podcasts: cycle the episode order.
CycleEpisodeSort,
/// Podcasts: cycle the played-state filter.
CycleEpisodeFilter,
/// Podcasts: mark the selected episode played / unplayed.
ToggleEpisodePlayed,
/// Podcasts: unsubscribe (progress and history are kept).
UnsubscribePodcast,
}
/// Help-window sections, in display order.
@@ -66,16 +82,18 @@ pub enum Category {
Queue,
Library,
Navigation,
Podcasts,
Search,
System,
}
impl Category {
pub const ALL: [Category; 6] = [
pub const ALL: [Category; 7] = [
Category::Playback,
Category::Queue,
Category::Library,
Category::Navigation,
Category::Podcasts,
Category::Search,
Category::System,
];
@@ -86,6 +104,7 @@ impl Category {
Category::Queue => "Queue & playlists",
Category::Library => "Library",
Category::Navigation => "Navigation",
Category::Podcasts => "Podcasts",
Category::Search => "Search & commands",
Category::System => "System",
}
@@ -139,6 +158,14 @@ impl Action {
| Action::DeleteSelected
| Action::CycleSourceMode
| Action::OpenLibraryFilters => Category::Library,
Action::AddPodcast
| Action::SearchEpisodes
| Action::RefreshPodcast
| Action::RefreshAllPodcasts
| Action::CycleEpisodeSort
| Action::CycleEpisodeFilter
| Action::ToggleEpisodePlayed
| Action::UnsubscribePodcast => Category::Podcasts,
Action::OpenSearch | Action::OpenCommandLine => Category::Search,
Action::ToggleHelp | Action::Quit => Category::System,
}
@@ -218,6 +245,14 @@ impl Action {
Action::OpenSearch => "Search artists, releases, tracks".into(),
Action::EditSelected => "Edit the selected item".into(),
Action::DeleteSelected => "Delete the selected item".into(),
Action::AddPodcast => "Add podcast (RSS URL)".into(),
Action::SearchEpisodes => "Search episodes".into(),
Action::RefreshPodcast => "Check podcast for new episodes".into(),
Action::RefreshAllPodcasts => "Check all podcasts".into(),
Action::CycleEpisodeSort => "Episode order".into(),
Action::CycleEpisodeFilter => "Filter: all/unplayed/played".into(),
Action::ToggleEpisodePlayed => "Mark played / unplayed".into(),
Action::UnsubscribePodcast => "Unsubscribe (keeps progress)".into(),
}
}
}
+35
View File
@@ -206,4 +206,39 @@ pub enum AppEvent {
JamInvite(Result<String, String>),
/// Result of joining a Jam capability.
JamJoined(Result<String, String>),
/// The podcast store opened (with the feed client), or why it did not.
PodcastStoreOpened(Result<crate::podcasts::refresh::Services, String>),
/// Subscribed podcasts reloaded from the podcast store.
PodcastsLoaded(Result<Vec<crate::app::state::PodcastRow>, String>),
PodcastSeasonsLoaded {
podcast_id: music_dht::podcast::PodcastId,
result: Result<Vec<furumi_library::podcasts::SeasonSummary>, String>,
},
/// One page of episodes; `seq` drops results of older requests.
PodcastEpisodesLoaded {
seq: u64,
offset: usize,
result: Result<Vec<furumi_library::podcasts::EpisodeListItem>, String>,
},
PodcastSubscribed(Result<crate::podcasts::refresh::SubscribeReport, String>),
/// One feed check finished.
PodcastRefreshed {
podcast_id: music_dht::podcast::PodcastId,
result: Result<crate::podcasts::refresh::RefreshReport, String>,
/// Asked by the user (status bar), not the background scheduler.
manual: bool,
},
PodcastUnsubscribed {
podcast_id: music_dht::podcast::PodcastId,
title: String,
result: Result<(), String>,
},
PodcastPlayedSet {
played: bool,
result: Result<(), String>,
},
/// Scheduler timer: ask the store which feeds are due.
PodcastRefreshTick,
/// Feeds due for a background refresh.
PodcastsDue(Result<Vec<(music_dht::podcast::PodcastId, music_dht::podcast::FeedUrl)>, String>),
}
+37 -1
View File
@@ -4,6 +4,9 @@ pub mod command;
mod enrichment;
pub mod event;
pub mod input;
#[cfg(test)]
pub(crate) mod podcast_fixtures;
pub(crate) mod podcast_runtime;
pub(crate) mod popup;
pub mod state;
pub mod update;
@@ -77,6 +80,9 @@ pub struct Runtime {
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` until opened (or if opening
/// failed, which only disables the Podcasts tab).
pub podcasts: Option<podcast_runtime::PodcastRuntime>,
}
#[derive(Debug, Clone, Copy)]
@@ -482,8 +488,10 @@ pub async fn run(
last_media_push: None,
status_publisher: crate::status::Publisher::spawn(),
status_visualizer: crate::visualizer::status::Renderer::default(),
podcasts: None,
};
spawn_content_id_backfill(&runtime);
podcast_runtime::spawn_open(&runtime);
if state.similarity.settings.enabled {
runtime.similarity.start();
}
@@ -1314,6 +1322,9 @@ fn maintenance(state: &mut AppState, runtime: &mut Runtime) {
}
}
}
if let Some(path) = podcast_runtime::wanted_cover(state) {
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) {
@@ -1563,6 +1574,9 @@ fn perform_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) {
perform_control_playback_effect(state, runtime, effect);
return;
}
let Some(effect) = podcast_runtime::perform(state, runtime, effect) else {
return;
};
match effect {
Effect::CheckUpdate => {
let tx = runtime.event_tx.clone();
@@ -1686,6 +1700,14 @@ fn perform_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) {
}
});
}
// Executed by podcast_runtime::perform above.
Effect::PodcastsReload
| Effect::PodcastLoadSeasons(_)
| Effect::PodcastLoadEpisodes { .. }
| Effect::PodcastSubscribe(_)
| Effect::PodcastRefresh { .. }
| Effect::PodcastUnsubscribe { .. }
| Effect::PodcastSetPlayed { .. } => {}
Effect::LoadListenHistory => {
let library = Arc::clone(&runtime.library);
let devices = Arc::clone(&runtime.devices);
@@ -2832,7 +2854,7 @@ fn handle_terminal_event(
}
TermEvent::Paste(pasted) => {
if state.popup.is_some() {
popup::handle_paste(state, &pasted);
popup::handle_paste(state, runtime, &pasted);
} else if state.cmdline.active {
cmdline::handle_paste(state, runtime, &pasted);
}
@@ -3305,7 +3327,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 {
// Folded in by podcast_runtime::handle_event above.
AppEvent::PodcastStoreOpened(_)
| AppEvent::PodcastsLoaded(_)
| AppEvent::PodcastSeasonsLoaded { .. }
| AppEvent::PodcastEpisodesLoaded { .. }
| AppEvent::PodcastSubscribed(_)
| AppEvent::PodcastRefreshed { .. }
| AppEvent::PodcastUnsubscribed { .. }
| AppEvent::PodcastPlayedSet { .. }
| AppEvent::PodcastRefreshTick
| AppEvent::PodcastsDue(_) => {}
AppEvent::StatusVisualizationReady(ready) => {
runtime.status_visualizer.busy = false;
state.status_visualizer.apply(ready);
+128
View File
@@ -0,0 +1,128 @@
//! Podcast state fixtures shared by update and rendering tests.
use furumi_library::podcasts::{
EpisodeListItem, EpisodeQuery, FetchState, PodcastSummary, SeasonSummary,
};
use music_dht::podcast::{
EpisodeId, EpisodeMeta, EpisodeType, FeedUrl, PodcastId, PodcastMeta, ProgressRecord,
ProgressStatus,
};
use crate::app::state::{
AppState, EpisodeList, Loadable, OpenedPodcast, PodcastRow, PodcastStoreStatus, Tab,
};
pub fn podcast_id() -> PodcastId {
PodcastId::from_feed_url(&FeedUrl::parse("https://example.test/feed.xml").unwrap())
}
pub fn row(title: &str, unplayed: u64, episodes: u64, seasons: u64) -> PodcastRow {
PodcastRow {
summary: PodcastSummary {
podcast_id: podcast_id(),
meta: PodcastMeta {
feed_url: FeedUrl::parse("https://example.test/feed.xml").unwrap(),
title: title.into(),
author: Some("Host".into()),
description: Some("A show about tests.".into()),
link: None,
image_url: None,
},
subscribed: true,
shared: false,
episode_count: episodes,
unplayed_count: unplayed,
in_progress_count: 0,
latest_published_at_ms: None,
season_count: seasons,
},
fetch: FetchState::default(),
}
}
pub fn episode(n: u32, title: &str, status: Option<(ProgressStatus, i64)>) -> EpisodeListItem {
let podcast = podcast_id();
let episode_id = EpisodeId::from_guid(&podcast, &format!("ep-{n}")).unwrap();
EpisodeListItem {
episode: EpisodeMeta {
episode_id: episode_id.clone(),
podcast_id: podcast.clone(),
guid: Some(format!("ep-{n}")),
title: title.into(),
description: Some(format!("Notes for {title}.")),
season: Some(1),
episode_number: Some(n),
episode_type: EpisodeType::Full,
published_at_ms: Some(1_718_409_600_000),
duration_ms: Some(2_700_000),
audio_url: format!("https://example.test/{n}.mp3"),
mime: Some("audio/mpeg".into()),
byte_len: None,
image_url: None,
link: None,
},
progress: status.map(|(status, position_ms)| ProgressRecord {
episode_id,
podcast_id: podcast,
position_ms,
status,
generation: 1,
session_id: "s".into(),
hlc_ms: 1,
device_id: "dev".into(),
op_id: "dev:1".into(),
}),
completed_count: 0,
in_feed: true,
}
}
pub fn ready_state(rows: Vec<PodcastRow>) -> AppState {
let mut state = AppState {
active_tab: Tab::Podcasts,
..AppState::default()
};
state.podcasts.store = PodcastStoreStatus::Ready;
state.podcasts.list = Some(Loadable::Ready(rows));
state
}
pub fn with_episodes(mut state: AppState, items: Vec<EpisodeListItem>) -> AppState {
let season = furumi_library::podcasts::SeasonFilter::Any;
state.podcasts.opened = Some(OpenedPodcast {
podcast_id: podcast_id(),
season_cursor: None,
season: Some(season),
episode_cursor: 0,
});
state.podcasts.episodes = Some(EpisodeList {
seq: 1,
query: EpisodeQuery::new(podcast_id()),
items,
loading: false,
loading_more: false,
complete: true,
error: None,
focus: None,
});
state
}
pub fn seasons() -> Vec<SeasonSummary> {
vec![
SeasonSummary {
season: Some(1),
episode_count: 3,
unplayed_count: 1,
first_published_at_ms: Some(1_609_459_200_000),
last_published_at_ms: Some(1_640_995_200_000),
},
SeasonSummary {
season: None,
episode_count: 2,
unplayed_count: 0,
first_published_at_ms: None,
last_published_at_ms: None,
},
]
}
+315
View File
@@ -0,0 +1,315 @@
//! Runtime side of the Podcasts tab: opens the podcast store, runs store
//! queries, feed fetches and sync-log writes off the UI thread, schedules
//! background refreshes, and hands results back as `AppEvent`s. Decisions
//! about state live in `update::podcasts`.
use std::sync::Arc;
use std::time::Duration;
use furumi_library::podcasts::{PodcastListFilter, PodcastStore};
use super::event::AppEvent;
use super::state::{AppState, PodcastRow};
use super::update::{Effect, podcasts};
use super::{Runtime, err_string, perform_effect};
use crate::podcasts::refresh::{self, Services};
/// How often the scheduler asks the store which feeds are due. Each feed's
/// own due time (success interval or failure back-off) lives in the store.
const SCHEDULER_INTERVAL: Duration = Duration::from_secs(60);
/// Delay before the first scheduler pass, so startup work goes first.
const SCHEDULER_FIRST_DELAY: Duration = Duration::from_secs(10);
/// Feeds fetched at the same time.
const MAX_CONCURRENT_REFRESHES: usize = 4;
/// Feeds started per scheduler pass.
const MAX_DUE_PER_PASS: usize = 16;
/// Podcast services available once the store opened.
pub struct PodcastRuntime {
pub services: Services,
refresh_slots: Arc<tokio::sync::Semaphore>,
}
fn now_ms() -> i64 {
super::unix_time_ms()
}
/// Opens `podcasts.sqlite3` (migrating a prototype database in place) and
/// builds the HTTP client on the blocking pool. A failure only disables the
/// Podcasts tab; the store never modifies a file it refuses.
pub fn spawn_open(runtime: &Runtime) {
let tx = runtime.event_tx.clone();
let log: Arc<dyn crate::podcasts::OpLog> = runtime.devices.clone();
tokio::task::spawn_blocking(move || {
let result = open(log).map_err(|err| {
let message = crate::podcasts::describe_open_error(&err);
tracing::warn!("podcast storage unavailable: {message}");
message
});
let _ = tx.send(AppEvent::PodcastStoreOpened(result));
});
}
fn open(log: Arc<dyn crate::podcasts::OpLog>) -> anyhow::Result<Services> {
crate::podcasts::open_services(
&crate::podcasts::db_path()?,
crate::podcasts::covers_dir()?,
log,
)
}
fn spawn_scheduler(tx: tokio::sync::mpsc::UnboundedSender<AppEvent>) {
tokio::spawn(async move {
let start = tokio::time::Instant::now() + SCHEDULER_FIRST_DELAY;
let mut interval = tokio::time::interval_at(start, SCHEDULER_INTERVAL);
interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
loop {
interval.tick().await;
if tx.send(AppEvent::PodcastRefreshTick).is_err() {
return;
}
}
});
}
fn services(runtime: &Runtime) -> Option<Services> {
runtime
.podcasts
.as_ref()
.map(|podcasts| podcasts.services.clone())
}
/// Executes a podcast [`Effect`]; any other effect is handed back.
pub fn perform(state: &mut AppState, runtime: &mut Runtime, effect: Effect) -> Option<Effect> {
let Some(services) = services(runtime) else {
if is_podcast_effect(&effect) {
if let Effect::PodcastRefresh { targets, .. } = &effect {
for (id, _) in targets {
state.podcasts.refreshing.remove(id);
}
}
if matches!(effect, Effect::PodcastSubscribe(_)) {
state.podcasts.subscribing = false;
}
state.status_message = Some("podcasts are unavailable (see the Podcasts tab)".into());
return None;
}
return Some(effect);
};
let tx = runtime.event_tx.clone();
match effect {
Effect::PodcastsReload => {
tokio::task::spawn_blocking(move || {
let result = load_rows(&services.store).map_err(err_string);
let _ = tx.send(AppEvent::PodcastsLoaded(result));
});
}
Effect::PodcastLoadSeasons(podcast_id) => {
tokio::task::spawn_blocking(move || {
let result = services.store.seasons(&podcast_id).map_err(err_string);
let _ = tx.send(AppEvent::PodcastSeasonsLoaded { podcast_id, result });
});
}
Effect::PodcastLoadEpisodes { seq, query } => {
tokio::task::spawn_blocking(move || {
let offset = query.offset;
let result = services.store.episodes(&query).map_err(err_string);
let _ = tx.send(AppEvent::PodcastEpisodesLoaded {
seq,
offset,
result,
});
});
}
Effect::PodcastSubscribe(input) => {
tokio::spawn(async move {
let result = refresh::subscribe(&services, &input, now_ms())
.await
.map_err(err_string);
let _ = tx.send(AppEvent::PodcastSubscribed(result));
});
}
Effect::PodcastRefresh { targets, manual } => {
let slots = runtime
.podcasts
.as_ref()
.map(|podcasts| Arc::clone(&podcasts.refresh_slots))?;
for (podcast_id, url) in targets {
let services = services.clone();
let slots = Arc::clone(&slots);
let tx = tx.clone();
tokio::spawn(async move {
let Ok(_permit) = slots.acquire_owned().await else {
return;
};
let result = refresh::refresh(&services, &podcast_id, &url, now_ms())
.await
.map_err(err_string);
let _ = tx.send(AppEvent::PodcastRefreshed {
podcast_id,
result,
manual,
});
});
}
}
Effect::PodcastUnsubscribe { podcast_id, title } => {
tokio::task::spawn_blocking(move || {
let store = Arc::clone(&services.store);
let id = podcast_id.clone();
let result = services
.log
.record(&mut |stamps| store.unsubscribe(stamps, &id))
.map_err(err_string);
let _ = tx.send(AppEvent::PodcastUnsubscribed {
podcast_id,
title,
result,
});
});
}
Effect::PodcastSetPlayed { episode_id, played } => {
tokio::task::spawn_blocking(move || {
let result = set_played(&services, &episode_id, played).map_err(err_string);
let _ = tx.send(AppEvent::PodcastPlayedSet { played, result });
});
}
other => return Some(other),
}
None
}
fn is_podcast_effect(effect: &Effect) -> bool {
matches!(
effect,
Effect::PodcastsReload
| Effect::PodcastLoadSeasons(_)
| Effect::PodcastLoadEpisodes { .. }
| Effect::PodcastSubscribe(_)
| Effect::PodcastRefresh { .. }
| Effect::PodcastUnsubscribe { .. }
| Effect::PodcastSetPlayed { .. }
)
}
/// Subscribed podcasts with their local fetch state.
pub(crate) fn load_rows(store: &PodcastStore) -> anyhow::Result<Vec<PodcastRow>> {
store
.list_podcasts(PodcastListFilter::Subscribed)?
.into_iter()
.map(|summary| {
let fetch = store.fetch_state(&summary.podcast_id)?;
Ok(PodcastRow { summary, fetch })
})
.collect()
}
/// "Mark played" / "Mark unplayed": explicit progress actions that bump the
/// generation and are appended to the sync log.
fn set_played(
services: &Services,
episode_id: &music_dht::podcast::EpisodeId,
played: bool,
) -> anyhow::Result<()> {
let episode = services
.store
.episode_ref(episode_id)?
.ok_or_else(|| anyhow::anyhow!("the episode is no longer in the catalog"))?;
let store = &services.store;
services.log.record(&mut |stamps| {
let write = if played {
store.mark_played(stamps, &episode)?
} else {
store.mark_unplayed(stamps, &episode)?
};
Ok(vec![write.op])
})
}
/// Folds a podcast `AppEvent` into the state; any other event is handed
/// back.
pub fn handle_event(
state: &mut AppState,
runtime: &mut Runtime,
event: AppEvent,
) -> Option<AppEvent> {
let effects: Vec<Effect> = match event {
AppEvent::PodcastStoreOpened(result) => {
let result = result.map(|services| {
runtime.podcasts = Some(PodcastRuntime {
services,
refresh_slots: Arc::new(tokio::sync::Semaphore::new(MAX_CONCURRENT_REFRESHES)),
});
spawn_scheduler(runtime.event_tx.clone());
});
podcasts::store_opened(state, result).into_iter().collect()
}
AppEvent::PodcastsLoaded(result) => {
podcasts::list_loaded(state, result);
Vec::new()
}
AppEvent::PodcastSeasonsLoaded { podcast_id, result } => {
podcasts::seasons_loaded(state, podcast_id, result);
Vec::new()
}
AppEvent::PodcastEpisodesLoaded {
seq,
offset,
result,
} => {
podcasts::episodes_loaded(state, seq, offset, result);
Vec::new()
}
AppEvent::PodcastSubscribed(result) => {
podcasts::subscribed(state, result).into_iter().collect()
}
AppEvent::PodcastRefreshed {
podcast_id,
result,
manual,
} => podcasts::refreshed(state, podcast_id, result, manual),
AppEvent::PodcastUnsubscribed {
podcast_id,
title,
result,
} => podcasts::unsubscribed(state, podcast_id, title, result)
.into_iter()
.collect(),
AppEvent::PodcastPlayedSet { played, result } => {
podcasts::played_set(state, played, result)
}
AppEvent::PodcastRefreshTick => {
if let Some(services) = services(runtime) {
let tx = runtime.event_tx.clone();
tokio::task::spawn_blocking(move || {
let result = services
.store
.podcasts_due_for_refresh(now_ms(), MAX_DUE_PER_PASS)
.map_err(err_string);
let _ = tx.send(AppEvent::PodcastsDue(result));
});
}
Vec::new()
}
AppEvent::PodcastsDue(result) => match result {
Ok(due) => podcasts::refresh_due(state, due).into_iter().collect(),
Err(err) => {
tracing::warn!(%err, "podcast scheduler query failed");
Vec::new()
}
},
other => return Some(other),
};
for effect in effects {
perform_effect(state, runtime, effect);
}
None
}
/// Cover of the podcast under the cursor (or opened), for the art cache.
pub fn wanted_cover(state: &AppState) -> Option<String> {
if state.active_tab != super::state::Tab::Podcasts {
return None;
}
state.podcasts.current_podcast()?.fetch.cover_path.clone()
}
+50 -3
View File
@@ -115,6 +115,15 @@ pub fn handle_key(state: &mut AppState, runtime: &mut Runtime, key: KeyEvent) {
Popup::ConfirmDelete { target, label } => {
handle_confirm_delete(state, runtime, target, label, key);
}
Popup::ConfirmPodcastUnsubscribe { podcast_id, title } => match key.code {
KeyCode::Enter | KeyCode::Char('y') => super::perform_effect(
state,
runtime,
crate::app::update::Effect::PodcastUnsubscribe { podcast_id, title },
),
KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('q') => {}
_ => state.popup = Some(Popup::ConfirmPodcastUnsubscribe { podcast_id, title }),
},
Popup::SimilarityPrivacyConsent { enable_federation } => match key.code {
KeyCode::Enter | KeyCode::Char('y') => {
state.similarity.settings.federation_consent = true;
@@ -557,10 +566,31 @@ fn handle_fed_input(
key: KeyEvent,
) {
match key.code {
KeyCode::Esc => {}
KeyCode::Esc => {
// Esc in the episode search clears it.
if field == FedInputField::PodcastSearch
&& let Some(effect) = crate::app::update::podcasts::set_search(state, String::new())
{
super::perform_effect(state, runtime, effect);
}
}
KeyCode::Enter => {
let value = input.trim().to_string();
match field {
FedInputField::PodcastFeedUrl => {
if let Some(effect) =
crate::app::update::podcasts::submit_feed_url(state, &value)
{
super::perform_effect(state, runtime, effect);
}
}
// The search is applied while typing; Enter keeps it.
FedInputField::PodcastSearch => {
let search = input.to_string();
if let Some(effect) = crate::app::update::podcasts::set_search(state, search) {
super::perform_effect(state, runtime, effect);
}
}
FedInputField::NetworkId => {
state.federation.settings.network_id = value;
// An empty id turns federation off rather than leaving a
@@ -666,7 +696,13 @@ fn handle_fed_input(
}
_ => {
input.handle_key(key);
let search = (field == FedInputField::PodcastSearch).then(|| input.to_string());
state.popup = Some(Popup::FedInput { field, input });
if let Some(search) = search
&& let Some(effect) = crate::app::update::podcasts::set_search(state, search)
{
super::perform_effect(state, runtime, effect);
}
}
}
}
@@ -785,11 +821,17 @@ 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) {
pub fn handle_paste(state: &mut AppState, runtime: &mut Runtime, pasted: &str) {
let cleaned: String = pasted.chars().filter(|c| !c.is_control()).collect();
let mut search = 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::PodcastSearch {
search = Some(input.to_string());
}
}
Some(Popup::Edit { fields, focus, .. }) => {
if let Some(field) = fields.get_mut(*focus) {
field.value.insert_str(&cleaned);
@@ -797,6 +839,11 @@ pub fn handle_paste(state: &mut AppState, pasted: &str) {
}
_ => {}
}
if let Some(search) = search
&& let Some(effect) = crate::app::update::podcasts::set_search(state, search)
{
super::perform_effect(state, runtime, effect);
}
}
// ---------------------------------------------------------------------------
+200
View File
@@ -763,6 +763,11 @@ pub enum Popup {
},
/// Delete confirmation; Enter/y deletes, Esc/n cancels.
ConfirmDelete { target: DeleteTarget, label: String },
/// Unsubscribe confirmation; progress and history are kept.
ConfirmPodcastUnsubscribe {
podcast_id: music_dht::podcast::PodcastId,
title: String,
},
/// Enabling network similarity reveals an embedding query to peers.
SimilarityPrivacyConsent { enable_federation: bool },
/// Derived data is safe to recreate but potentially expensive.
@@ -900,6 +905,10 @@ pub enum FedInputField {
DeviceName,
ConnectInvite,
JamInvite,
/// Podcasts: RSS/Atom feed URL of a new subscription.
PodcastFeedUrl,
/// Podcasts: live search in the opened episode list.
PodcastSearch,
}
impl FedInputField {
@@ -914,6 +923,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::PodcastSearch => "Search episodes",
}
}
@@ -946,6 +957,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 or Atom feed URL. Only episode information is stored; audio streams from the publisher when you play. New subscriptions are private."
}
FedInputField::PodcastSearch => {
"Words from episode titles or descriptions; the list updates as you type. Enter keeps the search, Esc clears it."
}
}
}
}
@@ -1666,6 +1683,188 @@ impl DevicePlaybackState {
}
}
// ---------------------------------------------------------------------------
// Podcasts tab
// ---------------------------------------------------------------------------
/// Episodes loaded per page; the next page loads when the cursor nears the end.
pub const PODCAST_EPISODE_PAGE: usize = 500;
/// "Add podcast" and "Check all" rows above the subscriptions.
pub const PODCAST_ACTION_ROWS: usize = 2;
/// State of the podcast store (`podcasts.sqlite3`).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum PodcastStoreStatus {
#[default]
Opening,
Ready,
/// The store could not be opened (newer schema, foreign file, I/O). The
/// file was left unchanged; only the Podcasts tab is unavailable.
Failed(String),
}
/// A subscribed podcast with its local fetch state.
#[derive(Debug, Clone, PartialEq)]
pub struct PodcastRow {
pub summary: furumi_library::podcasts::PodcastSummary,
pub fetch: furumi_library::podcasts::FetchState,
}
impl PodcastRow {
pub fn id(&self) -> &music_dht::podcast::PodcastId {
&self.summary.podcast_id
}
pub fn title(&self) -> &str {
&self.summary.meta.title
}
}
/// One row of the subscriptions list.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PodcastListRow {
Add,
RefreshAll,
/// Index into the loaded podcasts.
Podcast(usize),
}
/// One row of a podcast's season list.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SeasonRow {
All,
/// Index into the loaded seasons.
Group(usize),
}
/// The podcast opened from the list: its season list (when the feed has
/// seasons) and the episode list of the chosen group.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OpenedPodcast {
pub podcast_id: music_dht::podcast::PodcastId,
/// Season list cursor; `None` when the podcast has no seasons and its
/// episodes open directly.
pub season_cursor: Option<usize>,
/// The episode group shown; `None` while the season list is shown.
pub season: Option<furumi_library::podcasts::SeasonFilter>,
pub episode_cursor: usize,
}
/// The episode list of the opened group, loaded page by page.
#[derive(Debug, Clone)]
pub struct EpisodeList {
/// Request sequence: results of older requests are dropped.
pub seq: u64,
/// Query of the first page (`offset` 0, `limit` one page).
pub query: furumi_library::podcasts::EpisodeQuery,
pub items: Vec<furumi_library::podcasts::EpisodeListItem>,
/// The first page of `query` is in flight (`items` may still hold the
/// previous result, so the list does not flash empty).
pub loading: bool,
pub loading_more: bool,
/// Every matching episode is loaded.
pub complete: bool,
pub error: Option<String>,
/// Episode to keep the cursor on when the first page arrives.
pub focus: Option<music_dht::podcast::EpisodeId>,
}
/// Podcasts tab: subscriptions, seasons and episodes from the podcast store.
/// Nothing here touches SQLite or the network; see `app::podcast_runtime`.
#[derive(Debug, Default)]
pub struct PodcastsTab {
pub store: PodcastStoreStatus,
/// Subscribed podcasts; `None` until the first load.
pub list: Option<Loadable<Vec<PodcastRow>>>,
/// Cursor over [`PodcastsTab::list_rows`] (action rows first).
pub selected: usize,
pub opened: Option<OpenedPodcast>,
/// Season groups of the opened podcast.
pub seasons: Option<(
music_dht::podcast::PodcastId,
Loadable<Vec<furumi_library::podcasts::SeasonSummary>>,
)>,
pub episodes: Option<EpisodeList>,
/// Episode search text (titles and descriptions).
pub search: String,
pub played: furumi_library::podcasts::PlayedFilter,
pub sort: furumi_library::podcasts::EpisodeSort,
/// Feeds with a refresh in flight (spinner and request de-duplication).
pub refreshing: HashSet<music_dht::podcast::PodcastId>,
pub subscribing: bool,
/// Podcast to select once the reloaded list arrives.
pub pending_select: Option<music_dht::podcast::PodcastId>,
/// Last episode request sequence handed out.
pub episode_seq: u64,
}
impl PodcastsTab {
pub fn podcasts(&self) -> &[PodcastRow] {
match &self.list {
Some(Loadable::Ready(list)) => list,
_ => &[],
}
}
pub fn podcast(&self, id: &music_dht::podcast::PodcastId) -> Option<&PodcastRow> {
self.podcasts().iter().find(|row| row.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 opened podcast, or the one under the list cursor.
pub fn current_podcast(&self) -> Option<&PodcastRow> {
if let Some(opened) = &self.opened {
return self.podcast(&opened.podcast_id);
}
match self.list_rows().get(self.selected)? {
PodcastListRow::Podcast(index) => self.podcasts().get(*index),
_ => None,
}
}
/// Season groups of the opened podcast, when loaded.
pub fn opened_seasons(&self) -> Option<&[furumi_library::podcasts::SeasonSummary]> {
let opened = self.opened.as_ref()?;
match &self.seasons {
Some((id, Loadable::Ready(seasons))) if *id == opened.podcast_id => Some(seasons),
_ => None,
}
}
pub fn season_rows(&self) -> Vec<SeasonRow> {
let mut rows = vec![SeasonRow::All];
rows.extend((0..self.opened_seasons().map_or(0, <[_]>::len)).map(SeasonRow::Group));
rows
}
/// Whether the episode list (rather than the season list) is shown.
pub fn showing_episodes(&self) -> bool {
self.opened
.as_ref()
.is_some_and(|opened| opened.season.is_some())
}
/// Episodes of the opened group, when they belong to it.
pub fn opened_episodes(&self) -> Option<&EpisodeList> {
let opened = self.opened.as_ref()?;
let season = opened.season?;
self.episodes.as_ref().filter(|list| {
list.query.podcast_id == opened.podcast_id && list.query.season == season
})
}
pub fn selected_episode(&self) -> Option<&furumi_library::podcasts::EpisodeListItem> {
let opened = self.opened.as_ref()?;
let list = self.opened_episodes()?;
list.items.get(opened.episode_cursor)
}
}
/// 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)]
@@ -1718,6 +1917,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>)>,
+52 -1
View File
@@ -106,6 +106,32 @@ pub enum Effect {
},
/// Load qualified listening history without blocking the UI thread.
LoadListenHistory,
/// Reload the subscribed podcasts with their fetch state.
PodcastsReload,
/// Load the season groups of a podcast.
PodcastLoadSeasons(music_dht::podcast::PodcastId),
/// Load one page of episodes; `seq` drops stale results.
PodcastLoadEpisodes {
seq: u64,
query: furumi_library::podcasts::EpisodeQuery,
},
/// Fetch a feed the user typed and subscribe to it.
PodcastSubscribe(String),
/// Check feeds for new episodes (`manual`: asked by the user).
PodcastRefresh {
targets: Vec<(music_dht::podcast::PodcastId, music_dht::podcast::FeedUrl)>,
manual: bool,
},
/// Unsubscribe; progress and history are kept.
PodcastUnsubscribe {
podcast_id: music_dht::podcast::PodcastId,
title: String,
},
/// Mark an episode played or unplayed (an explicit progress action).
PodcastSetPlayed {
episode_id: music_dht::podcast::EpisodeId,
played: bool,
},
}
pub fn update(state: &mut AppState, action: Action) -> Option<Effect> {
@@ -115,6 +141,14 @@ pub fn update(state: &mut AppState, action: Action) -> Option<Effect> {
.take()
.is_some_and(|deadline| Instant::now() <= deadline);
state.status_message = None;
if state.active_tab == Tab::Podcasts
&& !state.help_visible
&& !state.visualizer.active
&& !state.additional_settings_open
&& let Some(effect) = podcasts::handle(state, &action)
{
return effect;
}
if state.additional_settings_open
&& !matches!(
action,
@@ -475,6 +509,20 @@ pub fn update(state: &mut AppState, action: Action) -> Option<Effect> {
None
}
Action::DeleteSelected => delete_selected(state),
Action::AddPodcast
| Action::SearchEpisodes
| Action::RefreshPodcast
| Action::RefreshAllPodcasts
| Action::CycleEpisodeSort
| Action::CycleEpisodeFilter
| Action::ToggleEpisodePlayed
| Action::UnsubscribePodcast => {
state.status_message = Some(format!(
"open the Podcasts tab ({}) for this command",
Tab::Podcasts.index() + 1
));
None
}
}
}
@@ -3250,7 +3298,8 @@ fn reset_tab(state: &mut AppState, tab: Tab) {
state.logs.follow = true;
state.logs.selected_seq = None;
}
Tab::Queue | Tab::Podcasts => {}
Tab::Queue => {}
Tab::Podcasts => podcasts::close(state),
}
}
@@ -3258,6 +3307,8 @@ fn not_yet(state: &mut AppState, what: &str) {
state.status_message = Some(format!("{what}: coming in a later milestone"));
}
pub(crate) mod podcasts;
#[cfg(test)]
#[path = "update_tests.rs"]
mod tests;
+754
View File
@@ -0,0 +1,754 @@
//! Podcasts tab state transitions.
//!
//! Pure functions over `AppState`: they request store, HTTP and sync work
//! through [`Effect`]s (executed by `app::podcast_runtime`) and fold the
//! results back in when the runtime reports them.
use furumi_library::podcasts::{
EpisodeListItem, EpisodeQuery, EpisodeSort, PlayedFilter, SeasonFilter, SeasonSummary,
};
use music_dht::podcast::{EpisodeId, FeedUrl, PodcastId, ProgressStatus};
use super::Effect;
use crate::app::action::Action;
use crate::app::input::LineEdit;
use crate::app::state::{
AppState, EpisodeList, FedInputField, Loadable, OpenedPodcast, PODCAST_ACTION_ROWS,
PODCAST_EPISODE_PAGE, PodcastListRow, PodcastRow, PodcastStoreStatus, Popup, SeasonRow,
};
use crate::podcasts::refresh::{RefreshReport, SubscribeReport};
/// The next page starts loading when the cursor is this close to the end.
const LOAD_MORE_MARGIN: usize = 20;
/// Podcasts-tab handling of `action`; `None` lets the global handler run.
pub(super) fn handle(state: &mut AppState, action: &Action) -> Option<Option<Effect>> {
let effect = match action {
Action::MoveUp => move_by(state, -1),
Action::MoveDown => move_by(state, 1),
Action::PageUp => move_by(state, -super::page_step(state)),
Action::PageDown => move_by(state, super::page_step(state)),
Action::SelectFirst => move_by(state, isize::MIN),
Action::SelectLast => move_by(state, isize::MAX),
Action::Select => select(state),
Action::Back if state.podcasts.opened.is_some() => {
back(state);
None
}
Action::OpenSearch | Action::SearchEpisodes => {
open_search(state);
None
}
Action::DeleteSelected | Action::UnsubscribePodcast => {
confirm_unsubscribe(state);
None
}
Action::EditSelected => {
state.status_message = Some("podcast details come from the RSS feed".into());
None
}
Action::AddPodcast => {
open_add(state);
None
}
Action::RefreshPodcast => refresh_current(state),
Action::RefreshAllPodcasts => refresh_all(state),
Action::CycleEpisodeSort => cycle_sort(state),
Action::CycleEpisodeFilter => cycle_played_filter(state),
Action::ToggleEpisodePlayed => toggle_played(state),
_ => return None,
};
Some(effect)
}
/// Whether podcast actions may run; explains why not in the status bar.
fn store_ready(state: &mut AppState) -> bool {
match &state.podcasts.store {
PodcastStoreStatus::Ready => true,
PodcastStoreStatus::Opening => {
state.status_message = Some("podcasts: the podcast database is still opening".into());
false
}
PodcastStoreStatus::Failed(err) => {
state.status_message = Some(format!("podcasts are unavailable: {err}"));
false
}
}
}
// ---------------------------------------------------------------------------
// Navigation
fn move_by(state: &mut AppState, delta: isize) -> Option<Effect> {
let tab = &mut state.podcasts;
let len = match &tab.opened {
None => tab.list_rows().len(),
Some(opened) if opened.season.is_none() => tab.season_rows().len(),
Some(_) => tab.opened_episodes().map_or(0, |list| list.items.len()),
};
if len == 0 {
return None;
}
let target = |cursor: usize| {
(cursor as isize)
.saturating_add(delta)
.clamp(0, len as isize - 1) as usize
};
match &mut tab.opened {
None => tab.selected = target(tab.selected),
Some(opened) => match (opened.season, &mut opened.season_cursor) {
(None, Some(cursor)) => *cursor = target(*cursor),
(None, None) => {}
(Some(_), _) => opened.episode_cursor = target(opened.episode_cursor),
},
}
load_more_if_needed(state)
}
/// Requests the next episode page when the cursor nears the loaded end.
fn load_more_if_needed(state: &mut AppState) -> Option<Effect> {
let cursor = state.podcasts.opened.as_ref()?.episode_cursor;
state.podcasts.opened_episodes()?;
let list = state.podcasts.episodes.as_mut()?;
if list.complete
|| list.loading
|| list.loading_more
|| cursor + LOAD_MORE_MARGIN < list.items.len()
{
return None;
}
list.loading_more = true;
let mut query = list.query.clone();
query.offset = list.items.len();
Some(Effect::PodcastLoadEpisodes {
seq: list.seq,
query,
})
}
fn select(state: &mut AppState) -> Option<Effect> {
let Some(opened) = state.podcasts.opened.clone() else {
return match state
.podcasts
.list_rows()
.get(state.podcasts.selected)
.copied()?
{
PodcastListRow::Add => {
open_add(state);
None
}
PodcastListRow::RefreshAll => refresh_all(state),
PodcastListRow::Podcast(index) => open_podcast(state, index),
};
};
if opened.season.is_none() {
let cursor = opened.season_cursor.unwrap_or(0);
let season = match state.podcasts.season_rows().get(cursor).copied()? {
SeasonRow::All => SeasonFilter::Any,
SeasonRow::Group(index) => match state.podcasts.opened_seasons()?.get(index)?.season {
Some(number) => SeasonFilter::Season(number),
None => SeasonFilter::NoSeason,
},
};
if let Some(opened) = &mut state.podcasts.opened {
opened.season = Some(season);
opened.episode_cursor = 0;
}
state.podcasts.search.clear();
return Some(load_episodes(state, None));
}
if state.podcasts.selected_episode().is_some() {
state.status_message =
Some("podcasts: episode playback is not available in this build yet".into());
}
None
}
fn open_podcast(state: &mut AppState, index: usize) -> Option<Effect> {
let row = state.podcasts.podcasts().get(index)?;
let podcast_id = row.id().clone();
let has_seasons = row.summary.season_count > 0;
state.podcasts.opened = Some(OpenedPodcast {
podcast_id: podcast_id.clone(),
season_cursor: has_seasons.then_some(0),
season: (!has_seasons).then_some(SeasonFilter::Any),
episode_cursor: 0,
});
state.podcasts.search.clear();
if has_seasons {
state.podcasts.seasons = Some((podcast_id.clone(), Loadable::Loading));
Some(Effect::PodcastLoadSeasons(podcast_id))
} else {
Some(load_episodes(state, None))
}
}
/// Esc: episodes -> seasons (when the podcast has them) -> podcast list.
fn back(state: &mut AppState) {
let tab = &mut state.podcasts;
match &mut tab.opened {
Some(opened) if opened.season.is_some() && opened.season_cursor.is_some() => {
opened.season = None;
tab.search.clear();
}
Some(_) => close(state),
None => {}
}
}
/// Closes the opened podcast and puts the list cursor on it.
pub(super) fn close(state: &mut AppState) {
let tab = &mut state.podcasts;
if let Some(opened) = tab.opened.take()
&& let Some(index) = tab
.podcasts()
.iter()
.position(|row| *row.id() == opened.podcast_id)
{
tab.selected = index + PODCAST_ACTION_ROWS;
}
tab.search.clear();
}
// ---------------------------------------------------------------------------
// Episode queries
/// Starts loading the first page of the opened group with the current
/// search, filter and sort. `focus` keeps the cursor on that episode when
/// it is still listed (reloads after a refresh); otherwise the cursor goes
/// to the top.
fn load_episodes(state: &mut AppState, focus: Option<EpisodeId>) -> Effect {
let tab = &mut state.podcasts;
let opened = tab
.opened
.as_mut()
.expect("load_episodes needs an opened podcast");
let season = opened.season.unwrap_or_default();
let search = tab.search.trim();
let query = EpisodeQuery {
podcast_id: opened.podcast_id.clone(),
season,
played: tab.played,
search: (!search.is_empty()).then(|| search.to_string()),
sort: tab.sort,
limit: Some(PODCAST_EPISODE_PAGE),
offset: 0,
};
if focus.is_none() {
opened.episode_cursor = 0;
}
tab.episode_seq += 1;
let seq = tab.episode_seq;
// Keep showing the previous rows of the same group while the new query
// runs, so typing a search does not flash an empty list.
let items = match tab.episodes.take() {
Some(list) if list.query.podcast_id == query.podcast_id && list.query.season == season => {
list.items
}
_ => Vec::new(),
};
tab.episodes = Some(EpisodeList {
seq,
query: query.clone(),
items,
loading: true,
loading_more: false,
complete: false,
error: None,
focus,
});
Effect::PodcastLoadEpisodes { seq, query }
}
/// Reloads the visible episodes, keeping the cursor on the same episode.
fn reload_episodes(state: &mut AppState) -> Option<Effect> {
if !state.podcasts.showing_episodes() {
return None;
}
let focus = state
.podcasts
.selected_episode()
.map(|item| item.episode.episode_id.clone());
Some(load_episodes(state, focus))
}
/// Live search: called for every edit of the search field.
pub fn set_search(state: &mut AppState, search: String) -> Option<Effect> {
if state.podcasts.search == search {
return None;
}
state.podcasts.search = search;
state
.podcasts
.showing_episodes()
.then(|| load_episodes(state, None))
}
fn open_search(state: &mut AppState) {
if !state.podcasts.showing_episodes() {
state.status_message = Some("podcasts: open a podcast to search its episodes".into());
return;
}
state.popup = Some(Popup::FedInput {
field: FedInputField::PodcastSearch,
input: LineEdit::new(state.podcasts.search.clone()),
});
}
fn cycle_sort(state: &mut AppState) -> Option<Effect> {
let next = match state.podcasts.sort {
EpisodeSort::NewestFirst => EpisodeSort::OldestFirst,
EpisodeSort::OldestFirst => EpisodeSort::EpisodeNumber,
EpisodeSort::EpisodeNumber => EpisodeSort::EpisodeNumberDesc,
EpisodeSort::EpisodeNumberDesc => EpisodeSort::NewestFirst,
};
state.podcasts.sort = next;
state.status_message = Some(format!("episodes: {}", sort_label(next)));
state
.podcasts
.showing_episodes()
.then(|| load_episodes(state, None))
}
fn cycle_played_filter(state: &mut AppState) -> Option<Effect> {
let next = match state.podcasts.played {
PlayedFilter::Any => PlayedFilter::Unplayed,
PlayedFilter::Unplayed => PlayedFilter::InProgress,
PlayedFilter::InProgress => PlayedFilter::Played,
PlayedFilter::Played | PlayedFilter::NotStarted => PlayedFilter::Any,
};
state.podcasts.played = next;
state.status_message = Some(format!("episodes: {}", played_label(next)));
state
.podcasts
.showing_episodes()
.then(|| load_episodes(state, None))
}
pub fn sort_label(sort: EpisodeSort) -> &'static str {
match sort {
EpisodeSort::NewestFirst => "newest first",
EpisodeSort::OldestFirst => "oldest first",
EpisodeSort::EpisodeNumber => "by episode number",
EpisodeSort::EpisodeNumberDesc => "by episode number, descending",
}
}
pub fn played_label(filter: PlayedFilter) -> &'static str {
match filter {
PlayedFilter::Any => "all episodes",
PlayedFilter::Unplayed => "unplayed",
PlayedFilter::NotStarted => "not started",
PlayedFilter::InProgress => "in progress",
PlayedFilter::Played => "played",
}
}
// ---------------------------------------------------------------------------
// Subscriptions
fn open_add(state: &mut AppState) {
if !store_ready(state) {
return;
}
if state.podcasts.subscribing {
state.status_message = Some("podcasts: a subscription is already being added".into());
return;
}
state.popup = Some(Popup::FedInput {
field: FedInputField::PodcastFeedUrl,
input: LineEdit::default(),
});
}
/// Enter in the "Add podcast" field.
pub fn submit_feed_url(state: &mut AppState, input: &str) -> Option<Effect> {
let input = input.trim();
if input.is_empty() {
state.status_message = Some("podcasts: the feed URL is empty".into());
return None;
}
if !store_ready(state) {
return None;
}
if let Err(err) = FeedUrl::from_user_input(input) {
state.status_message = Some(format!("podcasts: {err}"));
return None;
}
state.podcasts.subscribing = true;
state.status_message = Some("podcasts: reading the feed…".into());
Some(Effect::PodcastSubscribe(input.to_string()))
}
fn confirm_unsubscribe(state: &mut AppState) {
if !store_ready(state) {
return;
}
let Some(row) = state.podcasts.current_podcast() else {
state.status_message = Some("podcasts: select a podcast to unsubscribe".into());
return;
};
state.popup = Some(Popup::ConfirmPodcastUnsubscribe {
podcast_id: row.id().clone(),
title: row.title().to_string(),
});
}
fn refresh_targets(state: &mut AppState, rows: Vec<&PodcastRow>) -> Vec<(PodcastId, FeedUrl)> {
rows.into_iter()
.filter(|row| !state.podcasts.refreshing.contains(row.id()))
.map(|row| (row.id().clone(), row.summary.meta.feed_url.clone()))
.collect()
}
fn start_refresh(
state: &mut AppState,
targets: Vec<(PodcastId, FeedUrl)>,
manual: bool,
) -> Option<Effect> {
if targets.is_empty() {
return None;
}
state
.podcasts
.refreshing
.extend(targets.iter().map(|(id, _)| id.clone()));
Some(Effect::PodcastRefresh { targets, manual })
}
/// Shift-R: the opened podcast or the one under the cursor.
fn refresh_current(state: &mut AppState) -> Option<Effect> {
if !store_ready(state) {
return None;
}
let Some(row) = state.podcasts.current_podcast().cloned() else {
return refresh_all(state);
};
if state.podcasts.refreshing.contains(row.id()) {
state.status_message = Some(format!("podcasts: already checking {}", row.title()));
return None;
}
let targets = refresh_targets(state, vec![&row]);
state.status_message = Some(format!("podcasts: checking {}…", row.title()));
start_refresh(state, targets, true)
}
/// Ctrl-R / "Check all": every subscription.
fn refresh_all(state: &mut AppState) -> Option<Effect> {
if !store_ready(state) {
return None;
}
let rows: Vec<PodcastRow> = state.podcasts.podcasts().to_vec();
if rows.is_empty() {
state.status_message = Some("podcasts: no subscriptions yet".into());
return None;
}
let targets = refresh_targets(state, rows.iter().collect());
if targets.is_empty() {
state.status_message = Some("podcasts: already checking every feed".into());
return None;
}
state.status_message = Some(format!(
"podcasts: checking {} feed(s) for new episodes…",
targets.len()
));
start_refresh(state, targets, true)
}
/// Scheduler: feeds the store reports as due (back-off already applied).
pub fn refresh_due(state: &mut AppState, due: Vec<(PodcastId, FeedUrl)>) -> Option<Effect> {
let targets: Vec<_> = due
.into_iter()
.filter(|(id, _)| !state.podcasts.refreshing.contains(id))
.collect();
start_refresh(state, targets, false)
}
fn toggle_played(state: &mut AppState) -> Option<Effect> {
if !store_ready(state) {
return None;
}
let Some(item) = state.podcasts.selected_episode() else {
state.status_message = Some("podcasts: select an episode".into());
return None;
};
let played = item.status() != ProgressStatus::Completed;
Some(Effect::PodcastSetPlayed {
episode_id: item.episode.episode_id.clone(),
played,
})
}
// ---------------------------------------------------------------------------
// Results from the runtime
/// The store opened (or failed to).
pub fn store_opened(state: &mut AppState, result: Result<(), String>) -> Option<Effect> {
match result {
Ok(()) => {
state.podcasts.store = PodcastStoreStatus::Ready;
state.podcasts.list = Some(Loadable::Loading);
Some(Effect::PodcastsReload)
}
Err(err) => {
state.podcasts.store = PodcastStoreStatus::Failed(err);
None
}
}
}
pub fn list_loaded(state: &mut AppState, result: Result<Vec<PodcastRow>, String>) {
let tab = &mut state.podcasts;
let previous = match (&tab.opened, tab.list_rows().get(tab.selected)) {
(None, Some(PodcastListRow::Podcast(index))) => {
tab.podcasts().get(*index).map(|row| row.id().clone())
}
_ => None,
};
match result {
Ok(rows) => tab.list = Some(Loadable::Ready(rows)),
Err(err) => {
tracing::warn!(%err, "podcast list load failed");
if matches!(tab.list, Some(Loadable::Ready(_))) {
state.status_message = Some(format!("podcasts: {err}"));
return;
}
tab.list = Some(Loadable::Failed(err));
return;
}
}
if let Some(id) = tab.pending_select.take().or(previous)
&& let Some(index) = tab.podcasts().iter().position(|row| *row.id() == id)
{
tab.selected = index + PODCAST_ACTION_ROWS;
}
tab.selected = tab.selected.min(tab.list_rows().len().saturating_sub(1));
// A podcast unsubscribed elsewhere closes.
if let Some(opened) = &tab.opened
&& tab.podcast(&opened.podcast_id).is_none()
{
close(state);
}
}
pub fn seasons_loaded(
state: &mut AppState,
podcast_id: PodcastId,
result: Result<Vec<SeasonSummary>, String>,
) {
let tab = &mut state.podcasts;
if tab.opened.as_ref().map(|opened| &opened.podcast_id) != Some(&podcast_id) {
return;
}
let loaded = match result {
Ok(seasons) => Loadable::Ready(seasons),
Err(err) => {
if matches!(&tab.seasons, Some((id, Loadable::Ready(_))) if *id == podcast_id) {
state.status_message = Some(format!("podcasts: {err}"));
return;
}
Loadable::Failed(err)
}
};
tab.seasons = Some((podcast_id, loaded));
let rows = tab.season_rows().len();
if let Some(OpenedPodcast {
season_cursor: Some(cursor),
..
}) = &mut tab.opened
{
*cursor = (*cursor).min(rows.saturating_sub(1));
}
}
/// A page of episodes arrived. Stale sequences and pages that no longer
/// line up with the loaded rows are dropped.
pub fn episodes_loaded(
state: &mut AppState,
seq: u64,
offset: usize,
result: Result<Vec<EpisodeListItem>, String>,
) {
let tab = &mut state.podcasts;
let Some(list) = tab.episodes.as_mut().filter(|list| list.seq == seq) else {
return;
};
match result {
Ok(page) => {
let complete = page.len() < PODCAST_EPISODE_PAGE;
if offset == 0 {
list.items = page;
list.loading = false;
} else if offset == list.items.len() && list.loading_more {
list.items.extend(page);
list.loading_more = false;
} else {
return;
}
list.complete = complete;
list.error = None;
}
Err(err) => {
tracing::warn!(%err, "podcast episodes load failed");
list.loading = false;
list.loading_more = false;
list.error = Some(err);
return;
}
}
let focus = list.focus.take();
let len = list.items.len();
let focused = focus.and_then(|id| {
list.items
.iter()
.position(|item| item.episode.episode_id == id)
});
if let Some(opened) = &mut tab.opened {
if let Some(index) = focused {
opened.episode_cursor = index;
}
opened.episode_cursor = opened.episode_cursor.min(len.saturating_sub(1));
}
}
pub fn subscribed(state: &mut AppState, result: Result<SubscribeReport, String>) -> Option<Effect> {
state.podcasts.subscribing = false;
match result {
Ok(report) => {
let title = display_title(&report.title);
state.status_message = Some(if report.already_subscribed {
format!("podcasts: already subscribed to {title}")
} else {
format!(
"podcasts: subscribed to {title} ({} episode(s); private)",
report.new_episodes
)
});
if state.podcasts.opened.is_some() {
close(state);
}
state.podcasts.pending_select = Some(report.podcast_id);
Some(Effect::PodcastsReload)
}
Err(err) => {
state.status_message = Some(format!("podcasts: cannot subscribe: {err}"));
None
}
}
}
fn display_title(title: &str) -> String {
if title.trim().is_empty() {
"the podcast".to_string()
} else {
format!("\"{title}\"")
}
}
pub fn refreshed(
state: &mut AppState,
podcast_id: PodcastId,
result: Result<RefreshReport, String>,
manual: bool,
) -> Vec<Effect> {
state.podcasts.refreshing.remove(&podcast_id);
let title = state
.podcasts
.podcast(&podcast_id)
.map(|row| display_title(row.title()))
.unwrap_or_else(|| "the podcast".to_string());
let mut effects = vec![Effect::PodcastsReload];
match result {
Ok(report) => {
if report.new_episodes > 0 {
state.status_message = Some(format!(
"podcasts: {} new episode(s) in {title}",
report.new_episodes
));
} else if manual && state.podcasts.refreshing.is_empty() {
state.status_message = Some("podcasts: no new episodes".into());
}
let changed = report.new_episodes > 0 || report.updated_episodes > 0;
let opened_here = state
.podcasts
.opened
.as_ref()
.is_some_and(|opened| opened.podcast_id == podcast_id);
if changed && opened_here {
if state
.podcasts
.opened
.as_ref()
.is_some_and(|opened| opened.season_cursor.is_some())
{
effects.push(Effect::PodcastLoadSeasons(podcast_id.clone()));
}
effects.extend(reload_episodes(state));
}
}
Err(err) => {
tracing::warn!(podcast = %podcast_id, %err, "podcast refresh failed");
if manual {
state.status_message = Some(format!("podcasts: {title}: {err}"));
}
}
}
effects
}
pub fn unsubscribed(
state: &mut AppState,
podcast_id: PodcastId,
title: String,
result: Result<(), String>,
) -> Option<Effect> {
match result {
Ok(()) => {
state.status_message = Some(format!(
"podcasts: unsubscribed from {}; progress and history are kept",
display_title(&title)
));
if state
.podcasts
.opened
.as_ref()
.is_some_and(|opened| opened.podcast_id == podcast_id)
{
close(state);
}
Some(Effect::PodcastsReload)
}
Err(err) => {
state.status_message = Some(format!("podcasts: unsubscribe failed: {err}"));
None
}
}
}
pub fn played_set(state: &mut AppState, played: bool, result: Result<(), String>) -> Vec<Effect> {
match result {
Ok(()) => {
state.status_message = Some(
if played {
"podcasts: marked as played"
} else {
"podcasts: marked as unplayed"
}
.into(),
);
let mut effects = vec![Effect::PodcastsReload];
if let Some(opened) = &state.podcasts.opened
&& opened.season_cursor.is_some()
{
effects.push(Effect::PodcastLoadSeasons(opened.podcast_id.clone()));
}
effects.extend(reload_episodes(state));
effects
}
Err(err) => {
state.status_message = Some(format!("podcasts: {err}"));
Vec::new()
}
}
}
+393
View File
@@ -1442,3 +1442,396 @@ fn card_refresh_animates_while_previous_results_stay_visible() {
assert!(!render_enrichment_card(&state).contains("searching peers"));
}
}
// ---------------------------------------------------------------------------
// Podcasts tab
mod podcast_tab {
use furumi_library::podcasts::{EpisodeSort, PlayedFilter, SeasonFilter};
use music_dht::podcast::{FeedUrl, PodcastId, ProgressStatus};
use super::*;
use crate::app::podcast_fixtures::{self as fx, podcast_id};
use crate::app::state::{
FedInputField, PODCAST_ACTION_ROWS, PODCAST_EPISODE_PAGE, PodcastStoreStatus, Popup,
};
use crate::app::update::podcasts;
use crate::podcasts::refresh::{RefreshReport, SubscribeReport};
fn ready(rows: Vec<crate::app::state::PodcastRow>) -> AppState {
let mut state = fx::ready_state(rows);
state.podcasts.selected = PODCAST_ACTION_ROWS;
state
}
fn other_id() -> PodcastId {
PodcastId::from_feed_url(&FeedUrl::parse("https://other.test/feed.xml").unwrap())
}
fn episode_request(effect: Option<Effect>) -> (u64, furumi_library::podcasts::EpisodeQuery) {
match effect {
Some(Effect::PodcastLoadEpisodes { seq, query }) => (seq, query),
other => panic!("expected an episode load, got {other:?}"),
}
}
fn page(count: u32) -> Vec<furumi_library::podcasts::EpisodeListItem> {
(1..=count)
.map(|n| fx::episode(n, &format!("Episode {n}"), None))
.collect()
}
#[test]
fn podcast_actions_wait_for_the_store() {
let mut state = AppState {
active_tab: Tab::Podcasts,
..AppState::default()
};
assert_eq!(update(&mut state, Action::AddPodcast), None);
assert!(state.popup.is_none());
assert!(
state
.status_message
.as_deref()
.is_some_and(|m| m.contains("still opening"))
);
state.podcasts.store = PodcastStoreStatus::Failed("newer schema".into());
assert_eq!(update(&mut state, Action::RefreshAllPodcasts), None);
assert!(
state
.status_message
.as_deref()
.is_some_and(|m| m.contains("unavailable: newer schema"))
);
// Opening the store loads the list.
assert_eq!(
podcasts::store_opened(&mut state, Ok(())),
Some(Effect::PodcastsReload)
);
assert_eq!(state.podcasts.store, PodcastStoreStatus::Ready);
}
#[test]
fn podcast_actions_outside_the_tab_only_explain() {
let mut state = fx::ready_state(vec![fx::row("Show", 0, 1, 0)]);
state.active_tab = Tab::Global;
assert_eq!(update(&mut state, Action::RefreshAllPodcasts), None);
assert!(state.podcasts.refreshing.is_empty());
assert!(
state
.status_message
.as_deref()
.is_some_and(|m| m.contains("Podcasts tab (4)"))
);
}
#[test]
fn podcast_opens_seasons_then_a_season_then_goes_back() {
let mut state = ready(vec![fx::row("Show", 1, 5, 1)]);
assert_eq!(
update(&mut state, Action::Select),
Some(Effect::PodcastLoadSeasons(podcast_id()))
);
assert!(!state.podcasts.showing_episodes());
podcasts::seasons_loaded(&mut state, podcast_id(), Ok(fx::seasons()));
// Rows: All, Season 1, Without a season.
assert_eq!(state.podcasts.season_rows().len(), 3);
update(&mut state, Action::MoveDown);
let (seq, query) = episode_request(update(&mut state, Action::Select));
assert_eq!(query.season, SeasonFilter::Season(1));
assert_eq!(query.limit, Some(PODCAST_EPISODE_PAGE));
assert_eq!(query.offset, 0);
podcasts::episodes_loaded(&mut state, seq, 0, Ok(page(3)));
update(&mut state, Action::MoveDown);
assert_eq!(
state
.podcasts
.selected_episode()
.map(|item| item.episode.title.as_str()),
Some("Episode 2")
);
// Esc: episodes -> seasons (cursor kept) -> list (on the podcast).
update(&mut state, Action::Back);
let opened = state.podcasts.opened.as_ref().unwrap();
assert_eq!((opened.season, opened.season_cursor), (None, Some(1)));
update(&mut state, Action::Back);
assert!(state.podcasts.opened.is_none());
assert_eq!(state.podcasts.selected, PODCAST_ACTION_ROWS);
// A late seasons result for the closed podcast is ignored.
podcasts::seasons_loaded(&mut state, podcast_id(), Ok(Vec::new()));
assert!(state.podcasts.opened_seasons().is_none());
}
#[test]
fn podcast_without_seasons_opens_its_episodes_and_tab_key_resets() {
let mut state = ready(vec![fx::row("Show", 1, 2, 0)]);
let (_, query) = episode_request(update(&mut state, Action::Select));
assert_eq!(query.season, SeasonFilter::Any);
assert!(state.podcasts.showing_episodes());
// Pressing the tab's number again returns to the list.
update(&mut state, Action::GoToTab(Tab::Podcasts.index()));
assert!(state.podcasts.opened.is_none());
}
#[test]
fn live_search_drops_stale_pages_and_keeps_the_rows_meanwhile() {
let mut state = ready(vec![fx::row("Show", 1, 3, 0)]);
let (first, _) = episode_request(update(&mut state, Action::Select));
podcasts::episodes_loaded(&mut state, first, 0, Ok(page(3)));
update(&mut state, Action::SearchEpisodes);
assert!(matches!(
state.popup,
Some(Popup::FedInput {
field: FedInputField::PodcastSearch,
..
})
));
let (second, query) = episode_request(podcasts::set_search(&mut state, "pilot".into()));
assert_eq!(query.search.as_deref(), Some("pilot"));
assert!(second > first);
// The old rows stay visible while the search runs.
let list = state.podcasts.opened_episodes().unwrap();
assert!(list.loading);
assert_eq!(list.items.len(), 3);
// Typing on: the previous request's result arrives late and is dropped.
let (third, _) = episode_request(podcasts::set_search(&mut state, "pilot 2".into()));
podcasts::episodes_loaded(&mut state, second, 0, Ok(page(2)));
assert_eq!(state.podcasts.opened_episodes().unwrap().items.len(), 3);
podcasts::episodes_loaded(&mut state, third, 0, Ok(page(1)));
let list = state.podcasts.opened_episodes().unwrap();
assert_eq!(list.items.len(), 1);
assert!(!list.loading && list.complete);
// An unchanged search requests nothing.
assert_eq!(podcasts::set_search(&mut state, "pilot 2".into()), None);
// Search, filter and sort are per opened podcast view.
update(&mut state, Action::Back);
assert!(state.podcasts.search.is_empty());
}
#[test]
fn sort_and_played_filter_reload_from_the_top() {
let mut state = ready(vec![fx::row("Show", 1, 3, 0)]);
let (seq, _) = episode_request(update(&mut state, Action::Select));
podcasts::episodes_loaded(&mut state, seq, 0, Ok(page(3)));
update(&mut state, Action::SelectLast);
let (_, query) = episode_request(update(&mut state, Action::CycleEpisodeSort));
assert_eq!(query.sort, EpisodeSort::OldestFirst);
assert_eq!(state.podcasts.opened.as_ref().unwrap().episode_cursor, 0);
let (_, query) = episode_request(update(&mut state, Action::CycleEpisodeFilter));
assert_eq!(query.played, PlayedFilter::Unplayed);
assert_eq!(query.sort, EpisodeSort::OldestFirst);
}
#[test]
fn long_episode_lists_load_page_by_page() {
let mut state = ready(vec![fx::row("Show", 600, 600, 0)]);
let (seq, _) = episode_request(update(&mut state, Action::Select));
podcasts::episodes_loaded(&mut state, seq, 0, Ok(page(PODCAST_EPISODE_PAGE as u32)));
assert!(!state.podcasts.opened_episodes().unwrap().complete);
let (more_seq, query) = episode_request(update(&mut state, Action::SelectLast));
assert_eq!(more_seq, seq);
assert_eq!(query.offset, PODCAST_EPISODE_PAGE);
// No duplicate request while the page is in flight.
assert_eq!(update(&mut state, Action::MoveUp), None);
podcasts::episodes_loaded(&mut state, seq, PODCAST_EPISODE_PAGE, Ok(page(100)));
let list = state.podcasts.opened_episodes().unwrap();
assert_eq!(list.items.len(), PODCAST_EPISODE_PAGE + 100);
assert!(list.complete);
assert_eq!(update(&mut state, Action::SelectLast), None);
}
#[test]
fn manual_and_scheduled_refreshes_are_deduplicated() {
let mut state = ready(vec![fx::row("Show", 0, 1, 0)]);
let url = FeedUrl::parse("https://example.test/feed.xml").unwrap();
assert_eq!(
update(&mut state, Action::RefreshPodcast),
Some(Effect::PodcastRefresh {
targets: vec![(podcast_id(), url.clone())],
manual: true,
})
);
assert!(state.podcasts.refreshing.contains(&podcast_id()));
assert_eq!(update(&mut state, Action::RefreshPodcast), None);
assert_eq!(update(&mut state, Action::RefreshAllPodcasts), None);
// The scheduler skips feeds already in flight.
let due = vec![(podcast_id(), url.clone()), (other_id(), url.clone())];
assert_eq!(
podcasts::refresh_due(&mut state, due),
Some(Effect::PodcastRefresh {
targets: vec![(other_id(), url)],
manual: false,
})
);
let effects = podcasts::refreshed(
&mut state,
podcast_id(),
Ok(RefreshReport {
new_episodes: 2,
..RefreshReport::default()
}),
true,
);
assert_eq!(effects, vec![Effect::PodcastsReload]);
assert!(!state.podcasts.refreshing.contains(&podcast_id()));
assert!(
state
.status_message
.as_deref()
.is_some_and(|m| m.contains("2 new episode(s) in \"Show\""))
);
// A background failure stays out of the status bar.
state.status_message = None;
podcasts::refreshed(&mut state, other_id(), Err("HTTP 500".into()), false);
assert!(state.status_message.is_none());
}
#[test]
fn refreshing_the_opened_podcast_reloads_it_on_the_same_episode() {
let mut state = ready(vec![fx::row("Show", 0, 3, 0)]);
let (seq, _) = episode_request(update(&mut state, Action::Select));
podcasts::episodes_loaded(&mut state, seq, 0, Ok(page(3)));
update(&mut state, Action::MoveDown);
let effects = podcasts::refreshed(
&mut state,
podcast_id(),
Ok(RefreshReport {
new_episodes: 1,
..RefreshReport::default()
}),
false,
);
assert_eq!(effects.len(), 2);
let (seq, _) = episode_request(effects.into_iter().nth(1));
// A new episode arrived on top: the cursor follows "Episode 2".
let mut rows = vec![fx::episode(9, "Newest", None)];
rows.extend(page(3));
podcasts::episodes_loaded(&mut state, seq, 0, Ok(rows));
assert_eq!(
state
.podcasts
.selected_episode()
.map(|item| item.episode.title.as_str()),
Some("Episode 2")
);
}
#[test]
fn adding_a_feed_validates_the_url_then_selects_the_new_podcast() {
let mut state = ready(Vec::new());
state.podcasts.selected = 0;
update(&mut state, Action::Select);
assert!(matches!(
state.popup,
Some(Popup::FedInput {
field: FedInputField::PodcastFeedUrl,
..
})
));
state.popup = None;
assert_eq!(podcasts::submit_feed_url(&mut state, " "), None);
assert_eq!(
podcasts::submit_feed_url(&mut state, "ftp://example.test/feed"),
None
);
assert!(!state.podcasts.subscribing);
assert_eq!(
podcasts::submit_feed_url(&mut state, "example.test/feed.xml"),
Some(Effect::PodcastSubscribe("example.test/feed.xml".into()))
);
assert!(state.podcasts.subscribing);
// A second add while one is running is refused.
update(&mut state, Action::AddPodcast);
assert!(state.popup.is_none());
let effect = podcasts::subscribed(
&mut state,
Ok(SubscribeReport {
podcast_id: podcast_id(),
title: "Show".into(),
already_subscribed: false,
new_episodes: 4,
}),
);
assert_eq!(effect, Some(Effect::PodcastsReload));
assert!(!state.podcasts.subscribing);
assert!(
state
.status_message
.as_deref()
.is_some_and(|m| m.contains("subscribed to \"Show\" (4 episode(s); private)"))
);
let mut other = fx::row("Another", 0, 1, 0);
other.summary.podcast_id = other_id();
podcasts::list_loaded(&mut state, Ok(vec![other, fx::row("Show", 4, 4, 0)]));
assert_eq!(state.podcasts.selected, PODCAST_ACTION_ROWS + 1);
assert_eq!(
state.podcasts.current_podcast().map(|row| row.title()),
Some("Show")
);
}
#[test]
fn unsubscribing_asks_first_and_keeps_progress() {
let mut state = ready(vec![fx::row("Show", 0, 1, 0)]);
let (seq, _) = episode_request(update(&mut state, Action::Select));
podcasts::episodes_loaded(&mut state, seq, 0, Ok(page(1)));
update(&mut state, Action::UnsubscribePodcast);
assert!(matches!(
&state.popup,
Some(Popup::ConfirmPodcastUnsubscribe { podcast_id: id, title })
if *id == podcast_id() && title == "Show"
));
state.popup = None;
let effect = podcasts::unsubscribed(&mut state, podcast_id(), "Show".into(), Ok(()));
assert_eq!(effect, Some(Effect::PodcastsReload));
assert!(state.podcasts.opened.is_none());
assert!(
state
.status_message
.as_deref()
.is_some_and(|m| m.contains("progress and history are kept"))
);
// Unsubscribed elsewhere: the reloaded list closes an open view.
let mut state = ready(vec![fx::row("Show", 0, 1, 0)]);
update(&mut state, Action::Select);
podcasts::list_loaded(&mut state, Ok(Vec::new()));
assert!(state.podcasts.opened.is_none());
}
#[test]
fn marking_played_toggles_by_status() {
let mut state = ready(vec![fx::row("Show", 1, 2, 0)]);
let (seq, _) = episode_request(update(&mut state, Action::Select));
let items = vec![
fx::episode(1, "Done", Some((ProgressStatus::Completed, 0))),
fx::episode(2, "Half", Some((ProgressStatus::InProgress, 60_000))),
];
let done = items[0].episode.episode_id.clone();
let half = items[1].episode.episode_id.clone();
podcasts::episodes_loaded(&mut state, seq, 0, Ok(items));
assert_eq!(
update(&mut state, Action::ToggleEpisodePlayed),
Some(Effect::PodcastSetPlayed {
episode_id: done,
played: false,
})
);
update(&mut state, Action::MoveDown);
assert_eq!(
update(&mut state, Action::ToggleEpisodePlayed),
Some(Effect::PodcastSetPlayed {
episode_id: half,
played: true,
})
);
let effects = podcasts::played_set(&mut state, true, Ok(()));
assert_eq!(effects[0], Effect::PodcastsReload);
assert!(matches!(
effects.last(),
Some(Effect::PodcastLoadEpisodes { .. })
));
}
}