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 { .. })
));
}
}
+42
View File
@@ -271,3 +271,45 @@ command = "OpenCommandLine"
[[keymaps]]
key_sequence = "/"
command = "OpenSearch"
# Podcasts tab. Enter opens a podcast, its seasons and episodes; Esc goes
# back. Shift-D also unsubscribes here.
[[keymaps]]
key_sequence = "o"
command = "AddPodcast"
context = "podcasts"
[[keymaps]]
key_sequence = "/"
command = "SearchEpisodes"
context = "podcasts"
[[keymaps]]
key_sequence = "shift-r"
command = "RefreshPodcast"
context = "podcasts"
[[keymaps]]
key_sequence = "ctrl-r"
command = "RefreshAllPodcasts"
context = "podcasts"
[[keymaps]]
key_sequence = "shift-s"
command = "CycleEpisodeSort"
context = "podcasts"
[[keymaps]]
key_sequence = "f"
command = "CycleEpisodeFilter"
context = "podcasts"
[[keymaps]]
key_sequence = "m"
command = "ToggleEpisodePlayed"
context = "podcasts"
[[keymaps]]
key_sequence = "shift-u"
command = "UnsubscribePodcast"
context = "podcasts"
+37
View File
@@ -890,6 +890,43 @@ mod tests {
assert_eq!(KeyContext::Podcasts.label(), "podcasts");
}
#[test]
fn default_podcast_keys_resolve_only_in_the_podcasts_context() {
let mut km = keymap_from(DEFAULT_KEYMAP);
let shift = |c| KeyCombination::new(KeyCode::Char(c), KeyModifiers::SHIFT);
let cases = [
(key!(o), Action::AddPodcast),
(key!('/'), Action::SearchEpisodes),
(shift('R'), Action::RefreshPodcast),
(key!(ctrl - r), Action::RefreshAllPodcasts),
(shift('S'), Action::CycleEpisodeSort),
(key!(f), Action::CycleEpisodeFilter),
(key!(m), Action::ToggleEpisodePlayed),
(shift('U'), Action::UnsubscribePodcast),
];
for (key, action) in cases {
assert_eq!(
km.resolve(key, KeyContext::Podcasts),
KeyResolution::Action(action.clone()),
"{action:?}"
);
assert_ne!(
km.resolve(key, KeyContext::Library),
KeyResolution::Action(action.clone()),
"{action:?} leaks into the library"
);
}
// Playback keys keep working on the Podcasts tab.
assert_eq!(
km.resolve(key!(space), KeyContext::Podcasts),
KeyResolution::Action(Action::PlayPause)
);
assert_eq!(
km.resolve(key!(n), KeyContext::Podcasts),
KeyResolution::Action(Action::NextTrack)
);
}
#[test]
fn default_listening_history_key_resolves() {
let mut km = keymap_from(DEFAULT_KEYMAP);
+1 -1
View File
@@ -101,7 +101,7 @@ pub async fn subscribe(services: &Services, input: &str, now_ms: i64) -> Result<
.subscription(&id)?
.is_some_and(|record| record.subscribed);
let title = store.podcast(&id)?.map(|summary| summary.meta.title);
Ok(subscribed.then(|| (id, title)))
Ok(subscribed.then_some((id, title)))
})
.await?;
if let Some((podcast_id, title)) = existing {
+94 -14
View File
@@ -134,33 +134,113 @@ mod tests {
assert_eq!((cell.fg, cell.bg), (highlight.fg, highlight.bg));
}
use crate::app::podcast_fixtures;
#[test]
fn podcasts_tab_shows_placeholder() {
fn podcasts_tab_reports_opening_and_failed_store() {
let mut state = AppState::default();
state.active_tab = Tab::Podcasts;
let screen = render(&state, 100, 12);
assert!(screen.contains(podcasts::UNAVAILABLE), "{screen}");
}
assert!(screen.contains("opening the podcast database"), "{screen}");
#[test]
fn podcasts_placeholder_wraps_without_losing_text_on_narrow_terminals() {
let mut state = AppState::default();
state.active_tab = Tab::Podcasts;
for width in [60, 40] {
let screen = render(&state, width, 14);
state.podcasts.store = crate::app::state::PodcastStoreStatus::Failed(
"podcast database schema v9 is newer than this Furumi supports".into(),
);
for width in [100, 50] {
let screen = render(&state, width, 16);
let words: Vec<&str> = screen
.split(|c: char| c.is_whitespace() || c == '│')
.filter(|word| !word.is_empty())
.collect();
for word in ["available", "progress", "appear", "here."] {
assert!(
words.contains(&word),
"{word} missing at {width}:\n{screen}"
);
for word in ["unavailable", "v9", "newer", "unchanged."] {
assert!(words.contains(&word), "{word} at {width}:\n{screen}");
}
}
}
#[test]
fn podcasts_list_shows_actions_counts_and_errors() {
let state = podcast_fixtures::ready_state(Vec::new());
let screen = render(&state, 100, 14);
assert!(screen.contains("+ Add podcast (RSS feed URL)"), "{screen}");
assert!(screen.contains("Check all podcasts"), "{screen}");
assert!(screen.contains("No subscriptions yet"), "{screen}");
let mut row = podcast_fixtures::row("Test Show", 2, 3, 0);
row.fetch.last_error = Some("HTTP 503 Service Unavailable".into());
row.fetch.consecutive_failures = 2;
let mut state = podcast_fixtures::ready_state(vec![row]);
state.podcasts.selected = crate::app::state::PODCAST_ACTION_ROWS;
// Wide: side panel with details; narrow: status below the list.
for width in [110, 60] {
let screen = render(&state, width, 30);
assert!(screen.contains("! Test Show"), "{screen}");
assert!(screen.contains("2 unplayed · 3 ep"), "{screen}");
assert!(screen.contains("last check failed"), "{screen}");
assert!(screen.contains("503"), "{screen}");
}
}
#[test]
fn podcast_seasons_and_episodes_render_progress() {
use music_dht::podcast::ProgressStatus;
let mut state =
podcast_fixtures::ready_state(vec![podcast_fixtures::row("Test Show", 1, 5, 1)]);
state.podcasts.opened = Some(crate::app::state::OpenedPodcast {
podcast_id: podcast_fixtures::podcast_id(),
season_cursor: Some(0),
season: None,
episode_cursor: 0,
});
state.podcasts.seasons = Some((
podcast_fixtures::podcast_id(),
Loadable::Ready(podcast_fixtures::seasons()),
));
let screen = render(&state, 100, 14);
assert!(screen.contains("All episodes"), "{screen}");
assert!(screen.contains("1 unplayed · 5 ep"), "{screen}");
assert!(screen.contains("Season 1"), "{screen}");
assert!(screen.contains("2021–2022"), "{screen}");
assert!(screen.contains("Without a season"), "{screen}");
let state = podcast_fixtures::with_episodes(
podcast_fixtures::ready_state(vec![podcast_fixtures::row("Test Show", 1, 3, 0)]),
vec![
podcast_fixtures::episode(1, "Pilot", Some((ProgressStatus::Completed, 0))),
podcast_fixtures::episode(2, "Second", Some((ProgressStatus::InProgress, 754_000))),
podcast_fixtures::episode(3, "Third", None),
],
);
let screen = render(&state, 110, 30);
assert!(
screen.contains("3 episodes · all episodes · newest first"),
"{screen}"
);
assert!(screen.contains("✓ 2024-06-15 S1E1 Pilot"), "{screen}");
assert!(screen.contains("played · 45:00"), "{screen}");
assert!(screen.contains("◐ 2024-06-15 S1E2 Second"), "{screen}");
assert!(screen.contains("12:34 / 45:00"), "{screen}");
assert!(screen.contains("● 2024-06-15 S1E3 Third"), "{screen}");
assert!(screen.contains("Notes for Pilot."), "{screen}");
}
#[test]
fn podcast_unsubscribe_confirmation_says_progress_is_kept() {
let mut state =
podcast_fixtures::ready_state(vec![podcast_fixtures::row("Test Show", 0, 1, 0)]);
state.popup = Some(crate::app::state::Popup::ConfirmPodcastUnsubscribe {
podcast_id: podcast_fixtures::podcast_id(),
title: "Test Show".into(),
});
let screen = render(&state, 100, 24);
assert!(
screen.contains("Unsubscribe from \"Test Show\"?"),
"{screen}"
);
assert!(screen.contains("progress and history are kept"), "{screen}");
}
#[test]
fn help_lists_tab_names_for_digit_shortcuts() {
let mut state = AppState::default();
+728 -39
View File
@@ -1,58 +1,747 @@
//! Podcasts tab: subscriptions with their check status, a podcast's
//! seasons, and its episodes with saved position, played state, duration
//! and date. Rendering only reads `AppState`.
use furumi_library::podcasts::{EpisodeListItem, SeasonSummary};
use music_dht::podcast::ProgressStatus;
use ratatui::Frame;
use ratatui::layout::{Alignment, Rect};
use ratatui::text::Line;
use ratatui::widgets::{Block, Paragraph, Wrap};
use ratatui::layout::{Alignment, Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph, Wrap};
use unicode_width::UnicodeWidthStr;
use super::theme;
use crate::app::state::AppState;
use super::{loading_line, theme};
use crate::app::state::{
ART_HEADER_HEIGHT, ART_HEADER_WIDTH, AppState, ArtState, Loadable, PodcastListRow, PodcastRow,
PodcastStoreStatus, SeasonRow,
};
use crate::app::update::podcasts::{played_label, sort_label};
/// Placeholder notice shown until podcast support lands: the tab already
/// holds its final position so the numeric shortcuts stay stable.
pub(crate) const UNAVAILABLE: &str = "Podcasts are not available in this build yet.";
/// Width below which the side panel with the cover is dropped.
const SIDE_PANEL_MIN_TOTAL_WIDTH: u16 = 80;
const SIDE_PANEL_WIDTH: u16 = ART_HEADER_WIDTH + 2;
pub(crate) const EMPTY_HINT: &str =
"No subscriptions yet. Choose \"Add podcast\" and paste an RSS feed URL.";
pub(crate) const STORE_FAILED_NOTE: &str = "The podcast database was left unchanged. \
Music, playlists and sync keep working.";
pub fn draw(frame: &mut Frame, area: Rect, state: &AppState) {
let tab = &state.podcasts;
match &tab.store {
PodcastStoreStatus::Opening => {
let inner = bordered(frame, area, state, " Podcasts ".into());
return centered_line(
frame,
inner,
loading_line(state, "opening the podcast database…"),
);
}
PodcastStoreStatus::Failed(err) => {
let inner = bordered(frame, area, state, " Podcasts ".into());
let lines = vec![
Line::styled("Podcasts are unavailable", theme::header_for(state)),
Line::default(),
Line::styled(err.clone(), error_style()),
Line::default(),
Line::styled(STORE_FAILED_NOTE, theme::dim()),
];
frame.render_widget(
Paragraph::new(lines)
.alignment(Alignment::Center)
.wrap(Wrap { trim: true }),
inner,
);
return;
}
PodcastStoreStatus::Ready => {}
}
match &tab.opened {
None => draw_list(frame, area, state),
Some(opened) if opened.season.is_none() => draw_seasons(frame, area, state),
Some(_) => draw_episodes(frame, area, state),
}
}
fn bordered(frame: &mut Frame, area: Rect, state: &AppState, title: String) -> Rect {
let block = Block::bordered()
.title(" Podcasts ")
.title(title)
.title_style(theme::header_for(state))
.border_style(theme::border_for(state));
let inner = block.inner(area);
frame.render_widget(block, area);
if inner.height == 0 {
inner
}
fn centered_line(frame: &mut Frame, area: Rect, line: Line) {
if area.height == 0 {
return;
}
let middle = Rect {
y: area.y + area.height / 2,
height: 1,
..area
};
frame.render_widget(Paragraph::new(line).alignment(Alignment::Center), middle);
}
let lines = vec![
Line::styled(UNAVAILABLE, theme::header_for(state)),
Line::default(),
Line::styled(
"Subscriptions, episodes and listening progress will appear here.",
theme::dim(),
),
];
// Center on the estimated wrapped height, but let the paragraph use every
// row down to the bottom so narrow terminals never cut off the text.
let wrapped = estimated_rows(&lines, inner.width).min(inner.height);
let top = inner.height.saturating_sub(wrapped) / 2;
let body = Rect {
y: inner.y + top,
height: inner.height - top,
fn error_style() -> Style {
Style::new().fg(Color::Red)
}
/// First row so that `cursor` stays visible, roughly centered.
fn first_visible(cursor: usize, len: usize, visible: usize) -> usize {
cursor
.saturating_sub(visible / 2)
.min(len.saturating_sub(visible))
}
fn row_area(area: Rect, offset: usize) -> Rect {
Rect {
y: area.y + offset as u16,
height: 1,
..area
}
}
/// A row with a left part and a right-aligned dim part.
fn draw_row(
frame: &mut Frame,
area: Rect,
state: &AppState,
left: Line<'static>,
right: Option<String>,
selected: bool,
) {
frame.render_widget(Paragraph::new(left), area);
if let Some(right) = right {
frame.render_widget(
Paragraph::new(Line::styled(format!("{right} "), theme::dim()))
.alignment(Alignment::Right),
area,
);
}
if selected {
frame
.buffer_mut()
.set_style(area, theme::tab_active_for(state));
}
}
// ---------------------------------------------------------------------------
// Subscriptions
fn draw_list(frame: &mut Frame, area: Rect, state: &AppState) {
let tab = &state.podcasts;
let inner = bordered(frame, area, state, " Podcasts ".to_string());
match &tab.list {
Some(Loadable::Failed(error)) => {
return centered_line(frame, inner, Line::styled(error.clone(), error_style()));
}
None | Some(Loadable::Loading) => {
return centered_line(frame, inner, loading_line(state, "loading podcasts…"));
}
Some(Loadable::Ready(_)) => {}
}
let (list_area, side_area) = split_side_panel(inner);
if let Some(side) = side_area {
draw_side_panel(frame, side, state, tab.current_podcast());
}
let rows = tab.list_rows();
let visible = usize::from(list_area.height.max(1));
let first = first_visible(tab.selected, rows.len(), visible);
for (index, row) in rows.iter().enumerate().skip(first).take(visible) {
let (left, right) = list_row(state, *row, list_area.width);
draw_row(
frame,
row_area(list_area, index - first),
state,
left,
right,
index == tab.selected,
);
}
let used = rows.len().saturating_sub(first).min(visible) as u16;
let below = Rect {
y: list_area.y + used + 1,
height: list_area.height.saturating_sub(used + 1),
..list_area
};
if below.height == 0 {
return;
}
let hint = if tab.podcasts().is_empty() {
Line::styled(EMPTY_HINT, theme::dim())
} else if side_area.is_none()
&& let Some(row) = tab.current_podcast()
{
// Narrow terminal: the selected podcast's status below the list.
fetch_status_line(state, row)
} else {
Line::default()
};
frame.render_widget(Paragraph::new(hint).wrap(Wrap { trim: true }), below);
}
fn list_row(state: &AppState, row: PodcastListRow, width: u16) -> (Line<'static>, Option<String>) {
let tab = &state.podcasts;
match row {
PodcastListRow::Add => {
let label = if tab.subscribing {
format!("{} Adding podcast…", state.spinner())
} else {
"+ Add podcast (RSS feed URL)…".to_string()
};
(Line::styled(label, theme::accent_for(state)), None)
}
PodcastListRow::RefreshAll => {
let label = if tab.refreshing.is_empty() {
"↻ Check all podcasts for new episodes".to_string()
} else {
format!(
"{} Checking {} feed(s) for new episodes…",
state.spinner(),
tab.refreshing.len()
)
};
(Line::styled(label, theme::accent_for(state)), None)
}
PodcastListRow::Podcast(index) => {
let Some(podcast) = tab.podcasts().get(index) else {
return (Line::raw(""), None);
};
let marker = if tab.refreshing.contains(podcast.id()) {
Span::styled(format!("{} ", state.spinner()), theme::accent_for(state))
} else if podcast.fetch.last_error.is_some() {
Span::styled("! ", error_style())
} else {
Span::raw(" ")
};
let summary = &podcast.summary;
let meta = if summary.unplayed_count > 0 {
format!(
"{} unplayed · {} ep",
summary.unplayed_count, summary.episode_count
)
} else {
format!("{} ep", summary.episode_count)
};
let title_width = usize::from(width).saturating_sub(2 + meta.width() + 2);
let left = Line::from(vec![
marker,
Span::raw(fit_width(podcast.title(), title_width)),
]);
(left, Some(meta))
}
}
}
/// Main area plus an optional right-hand panel for the cover and details.
fn split_side_panel(area: Rect) -> (Rect, Option<Rect>) {
if area.width < SIDE_PANEL_MIN_TOTAL_WIDTH {
return (area, None);
}
let [main, side] =
Layout::horizontal([Constraint::Min(0), Constraint::Length(SIDE_PANEL_WIDTH)]).areas(area);
(main, Some(side))
}
fn draw_side_panel(frame: &mut Frame, area: Rect, state: &AppState, podcast: Option<&PodcastRow>) {
let block = Block::default()
.borders(Borders::LEFT)
.border_style(theme::border_for(state));
let inner = block.inner(area);
frame.render_widget(block, area);
let Some(podcast) = podcast else {
return;
};
let inner = Rect {
x: inner.x + 1,
width: inner.width.saturating_sub(1),
..inner
};
frame.render_widget(
Paragraph::new(lines)
.alignment(Alignment::Center)
.wrap(Wrap { trim: true }),
body,
let art_height = ART_HEADER_HEIGHT.min(inner.height);
draw_cover(
frame,
Rect {
height: art_height,
width: ART_HEADER_WIDTH.min(inner.width),
..inner
},
state,
podcast,
);
let text_area = Rect {
y: inner.y + art_height + 1,
height: inner.height.saturating_sub(art_height + 1),
..inner
};
if text_area.height == 0 {
return;
}
let summary = &podcast.summary;
let mut lines = vec![Line::styled(
podcast.title().to_string(),
Style::new().add_modifier(Modifier::BOLD),
)];
if let Some(author) = &summary.meta.author {
lines.push(Line::styled(author.clone(), theme::dim()));
}
let mut counts = format!("{} episodes", summary.episode_count);
if summary.season_count > 0 {
counts.push_str(&format!(" · {} seasons", summary.season_count));
}
lines.push(Line::styled(counts, theme::dim()));
lines.push(Line::styled("private", theme::dim()));
lines.push(fetch_status_line(state, podcast));
if let Some(description) = &summary.meta.description {
lines.push(Line::raw(""));
lines.push(Line::raw(description.clone()));
}
frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: true }), text_area);
}
/// Refresh status of one podcast: checking, the last error, or when it was
/// last checked.
fn fetch_status_line(state: &AppState, podcast: &PodcastRow) -> Line<'static> {
if state.podcasts.refreshing.contains(podcast.id()) {
return loading_line(state, "checking for new episodes…");
}
let fetch = &podcast.fetch;
if let Some(error) = &fetch.last_error {
let mut text = format!("last check failed: {error}");
if fetch.consecutive_failures > 1 {
text.push_str(&format!(" ({} times)", fetch.consecutive_failures));
}
if let Some(next) = fetch.next_check_at_ms {
text.push_str(&format!("; next try {}", relative_time(next)));
}
return Line::styled(text, error_style());
}
match fetch.last_success_at_ms {
Some(at) => Line::styled(format!("checked {}", relative_time(at)), theme::dim()),
None => Line::styled("not checked yet", theme::dim()),
}
}
fn draw_cover(frame: &mut Frame, area: Rect, state: &AppState, podcast: &PodcastRow) {
let art = podcast.fetch.cover_path.as_ref().and_then(|path| {
state.art.get(&crate::art::cache_key(
path,
ART_HEADER_WIDTH,
ART_HEADER_HEIGHT,
))
});
match art {
Some(ArtState::Ready(image)) => {
frame.render_widget(Paragraph::new(super::art::to_text(image)), area);
}
Some(ArtState::Loading) => centered_line(frame, area, Line::styled("…", theme::dim())),
_ => centered_line(frame, area, Line::styled("🎙", theme::dim())),
}
}
// ---------------------------------------------------------------------------
// Seasons
fn draw_seasons(frame: &mut Frame, area: Rect, state: &AppState) {
let tab = &state.podcasts;
let podcast = tab.current_podcast();
let title = podcast.map_or("…".to_string(), |row| row.title().to_string());
let inner = bordered(frame, area, state, format!(" Podcasts ▸ {title} "));
let seasons = match &tab.seasons {
Some((_, Loadable::Failed(error))) => {
return centered_line(frame, inner, Line::styled(error.clone(), error_style()));
}
_ => match tab.opened_seasons() {
Some(seasons) => seasons,
None => return centered_line(frame, inner, loading_line(state, "loading seasons…")),
},
};
let (main, side) = split_side_panel(inner);
if let Some(side) = side {
draw_side_panel(frame, side, state, podcast);
}
let cursor = tab
.opened
.as_ref()
.and_then(|opened| opened.season_cursor)
.unwrap_or(0);
let rows = tab.season_rows();
let visible = usize::from(main.height.max(1));
let first = first_visible(cursor, rows.len(), visible);
for (index, row) in rows.iter().enumerate().skip(first).take(visible) {
let (label, meta) = match row {
SeasonRow::All => {
let (episodes, unplayed) = seasons.iter().fold((0, 0), |(e, u), season| {
(e + season.episode_count, u + season.unplayed_count)
});
("All episodes".to_string(), counts(episodes, unplayed))
}
SeasonRow::Group(index) => {
let Some(season) = seasons.get(*index) else {
continue;
};
(season_title(season), season_meta(season))
}
};
let width = usize::from(main.width).saturating_sub(meta.width() + 4);
draw_row(
frame,
row_area(main, index - first),
state,
Line::raw(format!(" {}", fit_width(&label, width))),
Some(meta),
index == cursor,
);
}
}
fn season_title(season: &SeasonSummary) -> String {
match season.season {
Some(number) => format!("Season {number}"),
None => "Without a season".to_string(),
}
}
fn counts(episodes: u64, unplayed: u64) -> String {
if unplayed > 0 {
format!("{unplayed} unplayed · {episodes} ep")
} else {
format!("{episodes} ep")
}
}
fn season_meta(season: &SeasonSummary) -> String {
let mut meta = counts(season.episode_count, season.unplayed_count);
let years = (
season.first_published_at_ms.map(year_of),
season.last_published_at_ms.map(year_of),
);
match years {
(Some(first), Some(last)) if first != last => meta.push_str(&format!(" · {first}–{last}")),
(Some(year), _) | (None, Some(year)) => meta.push_str(&format!(" · {year}")),
(None, None) => {}
}
meta
}
// ---------------------------------------------------------------------------
// Episodes
fn draw_episodes(frame: &mut Frame, area: Rect, state: &AppState) {
let tab = &state.podcasts;
let Some(opened) = &tab.opened else {
return;
};
let podcast = tab.current_podcast();
let mut title = podcast.map_or("…".to_string(), |row| row.title().to_string());
if opened.season_cursor.is_some() {
let season = match opened.season {
Some(furumi_library::podcasts::SeasonFilter::Season(number)) => {
format!("Season {number}")
}
Some(furumi_library::podcasts::SeasonFilter::NoSeason) => {
"Without a season".to_string()
}
_ => "All episodes".to_string(),
};
title = format!("{title} ▸ {season}");
}
let inner = bordered(frame, area, state, format!(" Podcasts ▸ {title} "));
let Some(list) = tab.opened_episodes() else {
return centered_line(frame, inner, loading_line(state, "loading episodes…"));
};
let (main, side) = split_side_panel(inner);
if let Some(side) = side {
draw_side_panel(frame, side, state, podcast);
}
let notes_height = if main.height >= 18 { 6 } else { 0 };
let [summary_area, list_area, notes_area] = Layout::vertical([
Constraint::Length(1),
Constraint::Min(1),
Constraint::Length(notes_height),
])
.areas(main);
let mut summary = vec![Span::styled(
episode_summary(state, list.items.len(), list.complete),
theme::dim(),
)];
if list.loading || list.loading_more {
summary.push(Span::raw(" "));
summary.extend(loading_line(state, "loading…").spans);
} else if podcast.is_some_and(|row| tab.refreshing.contains(row.id())) {
summary.push(Span::raw(" "));
summary.extend(loading_line(state, "checking for new episodes…").spans);
}
frame.render_widget(Paragraph::new(Line::from(summary)), summary_area);
if let Some(error) = &list.error {
return centered_line(frame, list_area, Line::styled(error.clone(), error_style()));
}
if list.items.is_empty() {
if list.loading {
return;
}
let message = if tab.search.trim().is_empty()
&& tab.played == furumi_library::podcasts::PlayedFilter::Any
{
"this feed has no playable episodes yet"
} else {
"no episode matches the search or filter"
};
return centered_line(frame, list_area, Line::styled(message, theme::dim()));
}
let cursor = opened.episode_cursor.min(list.items.len() - 1);
let visible = usize::from(list_area.height.max(1));
let first = first_visible(cursor, list.items.len(), visible);
for (index, item) in list.items.iter().enumerate().skip(first).take(visible) {
draw_episode_row(
frame,
row_area(list_area, index - first),
state,
item,
index == cursor,
);
}
if notes_height > 0
&& let Some(item) = list.items.get(cursor)
{
draw_notes(frame, notes_area, state, item);
}
}
fn episode_summary(state: &AppState, loaded: usize, complete: bool) -> String {
let tab = &state.podcasts;
let count = if complete {
format!("{loaded} episodes")
} else {
format!("{loaded}+ episodes")
};
let mut parts = vec![
count,
played_label(tab.played).to_string(),
sort_label(tab.sort).to_string(),
];
let search = tab.search.trim();
if !search.is_empty() {
parts.push(format!("search: \"{search}\""));
}
parts.join(" · ")
}
/// Marker and right-hand text for an episode's listening state.
pub(crate) fn episode_state(item: &EpisodeListItem) -> (&'static str, String) {
let duration = item.episode.duration_ms.filter(|ms| *ms > 0);
match item.status() {
ProgressStatus::Completed => (
"✓",
match duration {
Some(ms) => format!("played · {}", format_duration_ms(ms)),
None => "played".to_string(),
},
),
ProgressStatus::InProgress => {
let position = format_duration_ms(item.resume_position_ms());
(
"◐",
match duration {
Some(ms) => format!("{position} / {}", format_duration_ms(ms)),
None => format!("at {position}"),
},
)
}
ProgressStatus::NotStarted => ("●", duration.map(format_duration_ms).unwrap_or_default()),
}
}
fn draw_episode_row(
frame: &mut Frame,
area: Rect,
state: &AppState,
item: &EpisodeListItem,
selected: bool,
) {
let episode = &item.episode;
let date = episode
.published_at_ms
.map(|ms| format_date(ms.div_euclid(1000)))
.unwrap_or_else(|| " ".repeat(10));
let (marker, right) = episode_state(item);
let marker_style = match item.status() {
ProgressStatus::NotStarted => theme::accent_for(state),
_ => theme::dim(),
};
let number = match (episode.season, episode.episode_number) {
(Some(season), Some(number)) => format!("S{season}E{number} "),
(None, Some(number)) => format!("#{number} "),
_ => String::new(),
};
let mut title = episode.title.clone();
if !item.in_feed {
title.push_str(" (no longer in the feed)");
}
let title_width =
usize::from(area.width).saturating_sub(2 + 10 + 2 + number.width() + right.width() + 2);
let title_style = match item.status() {
ProgressStatus::Completed => theme::dim(),
_ => Style::default(),
};
let line = Line::from(vec![
Span::styled(format!("{marker} "), marker_style),
Span::styled(date, theme::dim()),
Span::raw(" "),
Span::styled(number, theme::dim()),
Span::styled(fit_width(&title, title_width), title_style),
]);
draw_row(
frame,
area,
state,
line,
(!right.is_empty()).then_some(right),
selected,
);
}
/// Rows the lines need when wrapped to `width` (a lower bound: word wrapping
/// may need one more row per line, which the paragraph area leaves room for).
fn estimated_rows(lines: &[Line], width: u16) -> u16 {
let width = usize::from(width.max(1));
let rows: usize = lines
.iter()
.map(|line| line.width().div_ceil(width).max(1))
.sum();
u16::try_from(rows).unwrap_or(u16::MAX)
fn draw_notes(frame: &mut Frame, area: Rect, state: &AppState, item: &EpisodeListItem) {
let block = Block::default()
.borders(Borders::TOP)
.border_style(theme::border_for(state))
.title(Span::styled(" Episode notes ", theme::dim()));
let inner = block.inner(area);
frame.render_widget(block, area);
let mut text = item
.episode
.description
.clone()
.unwrap_or_else(|| "No description in the feed.".to_string());
if item.completed_count > 1 {
text = format!("Listened {} times. {text}", item.completed_count);
}
frame.render_widget(
Paragraph::new(Line::raw(text)).wrap(Wrap { trim: true }),
inner,
);
}
// ---------------------------------------------------------------------------
// Formatting
/// Truncate to a display width, adding an ellipsis when cut.
pub(crate) fn fit_width(text: &str, width: usize) -> String {
if UnicodeWidthStr::width(text) <= width {
return text.to_string();
}
if width == 0 {
return String::new();
}
let mut out = String::new();
let mut used = 0;
for ch in text.chars() {
let w = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
if used + w + 1 > width {
break;
}
out.push(ch);
used += w;
}
out.push('…');
out
}
pub(crate) fn format_duration_ms(ms: i64) -> String {
let total = (ms.max(0) + 500) / 1000;
let (hours, minutes, secs) = (total / 3600, total / 60 % 60, total % 60);
if hours > 0 {
format!("{hours}:{minutes:02}:{secs:02}")
} else {
format!("{minutes}:{secs:02}")
}
}
/// `YYYY-MM-DD` (UTC) for unix seconds: Howard Hinnant's days-to-civil.
pub(crate) fn format_date(unix_seconds: i64) -> String {
let (year, month, day) = civil(unix_seconds);
format!("{year:04}-{month:02}-{day:02}")
}
fn year_of(unix_ms: i64) -> i64 {
civil(unix_ms.div_euclid(1000)).0
}
fn civil(unix_seconds: i64) -> (i64, i64, i64) {
let days = unix_seconds.div_euclid(86_400);
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + i64::from(month <= 2);
(year, month, day)
}
/// "5 min ago", "in 2 h", or a date for anything further away.
fn relative_time(at_ms: i64) -> String {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as i64)
.unwrap_or(0);
relative_to(at_ms, now)
}
pub(crate) fn relative_to(at_ms: i64, now_ms: i64) -> String {
let delta = (now_ms - at_ms) / 1000;
let (amount, future) = (delta.unsigned_abs(), delta < 0);
let text = match amount {
0..60 => {
return if future {
"soon".into()
} else {
"just now".into()
};
}
60..3_600 => format!("{} min", amount / 60),
3_600..86_400 => format!("{} h", amount / 3_600),
_ => return format_date(at_ms.div_euclid(1000)),
};
if future {
format!("in {text}")
} else {
format!("{text} ago")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_dates_durations_and_relative_times() {
assert_eq!(format_date(0), "1970-01-01");
assert_eq!(format_date(951_782_400), "2000-02-29");
assert_eq!(format_date(-86_400), "1969-12-31");
assert_eq!(format_duration_ms(59_600), "1:00");
assert_eq!(format_duration_ms(754_000), "12:34");
assert_eq!(format_duration_ms(3_723_000), "1:02:03");
let now = 1_700_000_000_000;
assert_eq!(relative_to(now - 30_000, now), "just now");
assert_eq!(relative_to(now - 5 * 60_000, now), "5 min ago");
assert_eq!(relative_to(now + 2 * 3_600_000, now), "in 2 h");
assert_eq!(relative_to(now - 3 * 86_400_000, now), "2023-11-11");
}
#[test]
fn fits_display_width_with_ellipsis() {
assert_eq!(fit_width("Выпуск 650", 20), "Выпуск 650");
assert_eq!(fit_width("Выпуск 650", 5), "Выпу…");
assert_eq!(fit_width("abc", 0), "");
}
}
+55 -3
View File
@@ -25,6 +25,9 @@ pub fn draw(frame: &mut Frame, state: &AppState) {
..
}) => draw_edit(frame, state, title, fields, *focus, error.as_deref()),
Some(Popup::ConfirmDelete { label, .. }) => draw_confirm_delete(frame, state, label),
Some(Popup::ConfirmPodcastUnsubscribe { title, .. }) => {
draw_confirm_podcast_unsubscribe(frame, state, title)
}
Some(Popup::SimilarityPrivacyConsent { .. }) => {
draw_similarity_privacy_consent(frame, state)
}
@@ -43,7 +46,12 @@ pub fn draw(frame: &mut Frame, state: &AppState) {
}) => draw_track_artists(frame, state, tracks, *cursor, *selected),
Some(Popup::LogDetail(entry)) => draw_log_detail(frame, state, entry),
Some(Popup::FedInput { field, input }) => {
draw_fed_input(frame, state, field.title(), field.help(), input)
let keys = if *field == crate::app::state::FedInputField::PodcastSearch {
"enter: keep · esc: clear"
} else {
"enter: apply · esc: cancel"
};
draw_fed_input(frame, state, field.title(), field.help(), keys, input)
}
Some(Popup::FedText { title, text }) => draw_fed_text(frame, state, title, text),
Some(Popup::FedCopyText {
@@ -891,6 +899,7 @@ fn draw_fed_input(
state: &AppState,
title: &str,
help: &str,
keys: &str,
input: &crate::app::input::LineEdit,
) {
let area = centered(frame.area(), 72, 8);
@@ -916,8 +925,7 @@ fn draw_fed_input(
let spans = super::line_edit_spans(input, usize::from(entry_area.width.saturating_sub(1)));
frame.render_widget(Paragraph::new(Line::from(spans)), entry_area);
frame.render_widget(
Paragraph::new(Line::styled("enter: apply · esc: cancel", theme::dim()))
.alignment(Alignment::Center),
Paragraph::new(Line::styled(keys.to_string(), theme::dim())).alignment(Alignment::Center),
hint_area,
);
}
@@ -1266,6 +1274,50 @@ fn draw_confirm_delete(frame: &mut Frame, state: &AppState, label: &str) {
);
}
/// Text of the unsubscribe confirmation: unsubscribing keeps progress and
/// listening history, so subscribing again continues where the user left off.
pub(crate) const PODCAST_UNSUBSCRIBE_NOTE: &str = "Listening progress and history are kept: \
subscribe again later to continue where you left off.";
fn draw_confirm_podcast_unsubscribe(frame: &mut Frame, state: &AppState, title: &str) {
let width = 66.min(frame.area().width.saturating_sub(4)).max(30);
let area = centered(frame.area(), width, 9);
let block = Block::bordered()
.title(" Unsubscribe? ")
.title_style(theme::header_for(state))
.border_style(theme::strong_border_for(state));
let inner = block.inner(area);
frame.render_widget(Clear, area);
frame.render_widget(block, area);
let [question, note, footer] = Layout::vertical([
Constraint::Length(2),
Constraint::Min(1),
Constraint::Length(1),
])
.areas(inner);
frame.render_widget(
Paragraph::new(format!("Unsubscribe from \"{title}\"?"))
.wrap(Wrap { trim: false })
.alignment(Alignment::Center),
question,
);
frame.render_widget(
Paragraph::new(Line::styled(PODCAST_UNSUBSCRIBE_NOTE, theme::dim()))
.wrap(Wrap { trim: true })
.alignment(Alignment::Center),
note,
);
frame.render_widget(
Paragraph::new(Line::styled(
"enter/y unsubscribe · esc/n cancel",
theme::dim(),
))
.alignment(Alignment::Center),
footer,
);
}
fn draw_log_detail(frame: &mut Frame, state: &AppState, entry: &crate::config::logging::LogEntry) {
let width = 90.min(frame.area().width.saturating_sub(4)).max(40);
let height = 18.min(frame.area().height.saturating_sub(2)).max(7);