diff --git a/src/app/action.rs b/src/app/action.rs index 1fa972a..4f7b70f 100644 --- a/src/app/action.rs +++ b/src/app/action.rs @@ -249,7 +249,7 @@ impl Action { Action::CycleSourceMode => "Cycle source mode: Local / My / Global".into(), Action::OpenLibraryFilters => "Library filters…".into(), Action::OpenCommandLine => "Command line (:help for commands)".into(), - Action::OpenSearch => "Search artists, releases, tracks".into(), + Action::OpenSearch => "Search artists, releases, tracks, public podcasts".into(), Action::EditSelected => "Edit the selected item".into(), Action::DeleteSelected => "Delete the selected item".into(), Action::AddPodcast => "Add podcast (RSS URL)".into(), diff --git a/src/app/cmdline.rs b/src/app/cmdline.rs index c14c1c7..7bbb660 100644 --- a/src/app/cmdline.rs +++ b/src/app/cmdline.rs @@ -109,6 +109,7 @@ pub(super) fn schedule_search(state: &mut AppState, runtime: &Runtime) { state.search.results = None; state.search.fed_tracks.clear(); state.search.fed_artists.clear(); + state.search.fed_podcasts.clear(); state.search.fed_loading = false; return; } @@ -132,6 +133,7 @@ pub(super) fn schedule_search(state: &mut AppState, runtime: &Runtime) { // node is up); its results render as a separate, marked section. state.search.fed_tracks.clear(); state.search.fed_artists.clear(); + state.search.fed_podcasts.clear(); state.search.fed_loading = false; if runtime.federation.settings().enabled { state.search.fed_loading = true; @@ -139,12 +141,34 @@ pub(super) fn schedule_search(state: &mut AppState, runtime: &Runtime) { let query = state.search.query.clone(); let tx = runtime.event_tx.clone(); let latest = Arc::clone(&runtime.search_seq); + let podcast_store = runtime + .podcasts + .as_ref() + .map(|podcasts| Arc::clone(&podcasts.services.store)); tokio::spawn(async move { tokio::time::sleep(SEARCH_DEBOUNCE).await; if latest.load(Ordering::SeqCst) != seq { return; } - let result = fed.search(&query).await.map_err(|err| format!("{err:#}")); + let mut result = fed.search(&query).await.map_err(|err| format!("{err:#}")); + // Which public podcasts this device already knows (feed + // aliases included), for the "subscribed" mark. + if let Ok(results) = &mut result + && let Some(store) = podcast_store + && !results.podcasts.is_empty() + { + let mut hits = std::mem::take(&mut results.podcasts); + results.podcasts = tokio::task::spawn_blocking(move || { + if let Err(err) = + crate::podcasts::discovery::resolve_local_ids(&store, &mut hits) + { + tracing::warn!("podcast search: feed aliases not resolved: {err:#}"); + } + hits + }) + .await + .unwrap_or_default(); + } let _ = tx.send(AppEvent::FedSearchLoaded { seq, result }); }); } @@ -171,6 +195,7 @@ pub(super) fn schedule_similarity_search( state.search.results = None; state.search.fed_tracks.clear(); state.search.fed_artists.clear(); + state.search.fed_podcasts.clear(); state.search.fed_loading = false; state.active_tab = crate::app::state::Tab::Global; if let Some(crate::app::state::GlobalView::Search { cursor }) = state.global.stack.last_mut() { diff --git a/src/app/event.rs b/src/app/event.rs index 013bbd7..b06a68d 100644 --- a/src/app/event.rs +++ b/src/app/event.rs @@ -283,4 +283,9 @@ pub enum AppEvent { }, /// The publication reconciler finished a pass. PodcastPublication(crate::podcasts::publication::PublicationReport), + /// A public card's feed was read for a preview (`Effect::PodcastPreview`). + PodcastPreviewLoaded { + podcast_id: music_dht::podcast::PodcastId, + result: Result, String>, + }, } diff --git a/src/app/mod.rs b/src/app/mod.rs index 1483dd1..389d3e9 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -1737,7 +1737,9 @@ fn perform_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) { | Effect::PodcastSetPlayed { .. } | Effect::PodcastPrepareShare { .. } | Effect::PodcastSetShared { .. } - | Effect::PodcastPublicationSync => {} + | Effect::PodcastPublicationSync + | Effect::PodcastSubscribeFromCard(_) + | Effect::PodcastPreview { .. } => {} Effect::LoadListenHistory => { let library = Arc::clone(&runtime.library); let devices = Arc::clone(&runtime.devices); @@ -3537,7 +3539,8 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent | AppEvent::PodcastsDue(_) | AppEvent::PodcastSharePrepared { .. } | AppEvent::PodcastShareSet { .. } - | AppEvent::PodcastPublication(_) => {} + | AppEvent::PodcastPublication(_) + | AppEvent::PodcastPreviewLoaded { .. } => {} AppEvent::StatusVisualizationReady(ready) => { runtime.status_visualizer.busy = false; state.status_visualizer.apply(ready); @@ -3798,6 +3801,7 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent Ok(results) => { state.search.fed_artists = results.artists; state.search.fed_tracks = results.tracks; + state.search.fed_podcasts = results.podcasts; } Err(message) => tracing::warn!(%message, "federated search failed"), } diff --git a/src/app/podcast_runtime.rs b/src/app/podcast_runtime.rs index 064f0dc..e2f0b9c 100644 --- a/src/app/podcast_runtime.rs +++ b/src/app/podcast_runtime.rs @@ -12,9 +12,10 @@ use music_dht::podcast::{PodcastEpisodeRef, reaches_completion}; use super::event::AppEvent; use super::state::{AppState, PodcastRow}; -use super::update::{Effect, podcasts}; +use super::update::{Effect, podcast_discovery, podcasts}; use super::{Runtime, err_string, perform_effect}; use crate::library::models::TrackItem; +use crate::podcasts::discovery; use crate::podcasts::playback::{self, StartAt}; use crate::podcasts::progress::{ CHECKPOINT_INTERVAL, ProgressCommand, ProgressEvent, ProgressWriter, @@ -169,9 +170,19 @@ pub fn perform(state: &mut AppState, runtime: &mut Runtime, effect: Effect) -> O state.podcasts.refreshing.remove(id); } } - if matches!(effect, Effect::PodcastSubscribe(_)) { + if matches!( + effect, + Effect::PodcastSubscribe(_) | Effect::PodcastSubscribeFromCard(_) + ) { state.podcasts.subscribing = false; } + if let Effect::PodcastPreview { podcast_id, .. } = &effect { + podcast_discovery::preview_loaded( + state, + podcast_id.clone(), + Err("podcasts are unavailable".into()), + ); + } if let Effect::PodcastPrepareShare { podcast_id, .. } | Effect::PodcastSetShared { podcast_id, .. } = &effect { @@ -215,6 +226,26 @@ pub fn perform(state: &mut AppState, runtime: &mut Runtime, effect: Effect) -> O let _ = tx.send(AppEvent::PodcastSubscribed(result)); }); } + Effect::PodcastSubscribeFromCard(hit) => { + tokio::spawn(async move { + let result = discovery::subscribe_from_hit(&services, &hit, now_ms()) + .await + .map_err(err_string); + let _ = tx.send(AppEvent::PodcastSubscribed(result)); + }); + } + Effect::PodcastPreview { + podcast_id, + feed_url, + } => { + tokio::spawn(async move { + let result = discovery::preview(&services.fetcher, &feed_url) + .await + .map(Box::new) + .map_err(err_string); + let _ = tx.send(AppEvent::PodcastPreviewLoaded { podcast_id, result }); + }); + } Effect::PodcastRefresh { targets, manual } => { let slots = runtime .podcasts @@ -346,6 +377,8 @@ fn is_podcast_effect(effect: &Effect) -> bool { | Effect::PodcastPrepareShare { .. } | Effect::PodcastSetShared { .. } | Effect::PodcastPublicationSync + | Effect::PodcastSubscribeFromCard(_) + | Effect::PodcastPreview { .. } ) } @@ -466,6 +499,10 @@ pub fn handle_event( .into_iter() .collect() } + AppEvent::PodcastPreviewLoaded { podcast_id, result } => { + podcast_discovery::preview_loaded(state, podcast_id, result); + Vec::new() + } AppEvent::PodcastPublication(report) => { podcasts::publication_reported(state, report); Vec::new() diff --git a/src/app/popup.rs b/src/app/popup.rs index c015a8b..97fe21a 100644 --- a/src/app/popup.rs +++ b/src/app/popup.rs @@ -124,6 +124,13 @@ pub fn handle_key(state: &mut AppState, runtime: &mut Runtime, key: KeyEvent) { KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('q') => {} _ => state.popup = Some(Popup::ConfirmPodcastUnsubscribe { podcast_id, title }), }, + popup @ Popup::PodcastCard { .. } => { + if let Some(effect) = + crate::app::update::podcast_discovery::card_key(state, popup, key.code) + { + super::perform_effect(state, runtime, effect); + } + } popup @ Popup::ConfirmPodcastShare { .. } => { if let Some(effect) = crate::app::update::podcasts::share_confirmation_key(state, popup, key.code) diff --git a/src/app/state.rs b/src/app/state.rs index 7eceb6a..fbc7acc 100644 --- a/src/app/state.rs +++ b/src/app/state.rs @@ -780,6 +780,16 @@ pub enum Popup { warnings: Vec, already_shared: bool, }, + /// A public podcast card from the search results: its claims, an + /// optional episode preview read from the feed, and "Подписаться" (or + /// "Уже подписан" when this device is subscribed under any of its ids). + PodcastCard { + hit: Box, + /// `None` until the user asks for the episodes (`e`). + preview: Option>, + /// First body line shown. + scroll: u16, + }, /// Enabling network similarity reveals an embedding query to peers. SimilarityPrivacyConsent { enable_federation: bool }, /// Derived data is safe to recreate but potentially expensive. @@ -1432,6 +1442,9 @@ pub struct SearchState { /// Artists a federated card can be opened for — from artist records and /// from the artist names of matching tracks. pub fed_artists: Vec, + /// Public podcast cards (type `podcast`), listed after the federated + /// tracks; Enter opens the card. + pub fed_podcasts: Vec, pub fed_loading: bool, /// Present only for a track-seeded search; text-search refreshes must not /// replace this page with a title query. @@ -1445,6 +1458,23 @@ pub struct SearchState { } impl SearchState { + /// Rows the cursor can reach in a text search: local artists, releases + /// and tracks, then federated artists, tracks and podcasts. + pub fn total_len(&self) -> usize { + self.results.as_ref().map_or(0, SearchResults::len) + + self.fed_artists.len() + + self.fed_tracks.len() + + self.fed_podcasts.len() + } + + /// Something federated is shown (or still loading). + pub fn has_federated(&self) -> bool { + !self.fed_tracks.is_empty() + || !self.fed_artists.is_empty() + || !self.fed_podcasts.is_empty() + || self.fed_loading + } + pub fn similarity_len(&self) -> usize { usize::from(self.similarity_source_track.is_some()) + self.similarity_tracks.len() } @@ -1826,6 +1856,13 @@ impl PodcastsTab { self.podcasts().iter().find(|row| row.id() == id) } + /// This device is subscribed to the podcast of a public card: under the + /// card's id or under the id its origin URL resolves to here (a feed + /// alias of a podcast subscribed earlier). + pub fn subscribed_to(&self, hit: &crate::podcasts::discovery::PodcastHit) -> bool { + hit.ids().into_iter().any(|id| self.podcast(id).is_some()) + } + pub fn list_rows(&self) -> Vec { let mut rows = vec![PodcastListRow::Add, PodcastListRow::RefreshAll]; rows.extend((0..self.podcasts().len()).map(PodcastListRow::Podcast)); diff --git a/src/app/update.rs b/src/app/update.rs index f337303..32599c3 100644 --- a/src/app/update.rs +++ b/src/app/update.rs @@ -153,6 +153,15 @@ pub enum Effect { }, /// Reconcile this device's public podcast cards now. PodcastPublicationSync, + /// Subscribe to the podcast of a public card with its origin feed URL + /// (`podcasts::discovery::subscribe_from_hit`); reported as + /// `AppEvent::PodcastSubscribed`. + PodcastSubscribeFromCard(Box), + /// Read a public card's feed for an episode preview (nothing stored). + PodcastPreview { + podcast_id: music_dht::podcast::PodcastId, + feed_url: music_dht::podcast::FeedUrl, + }, } pub fn update(state: &mut AppState, action: Action) -> Option { @@ -2068,9 +2077,7 @@ fn move_selection(state: &mut AppState, dx: isize, dy: isize) { let total = if state.search.similarity_source.is_some() { state.search.similarity_len() } else { - state.search.results.as_ref().map_or(0, |r| r.len()) - + state.search.fed_artists.len() - + state.search.fed_tracks.len() + state.search.total_len() } as isize; if total == 0 { return; @@ -2194,9 +2201,7 @@ fn current_view_len(state: &AppState) -> usize { if state.search.similarity_source.is_some() { state.search.similarity_len() } else { - state.search.results.as_ref().map_or(0, |r| r.len()) - + state.search.fed_artists.len() - + state.search.fed_tracks.len() + state.search.total_len() } } Some(GlobalView::FedArtist { .. }) => fed_card_len(state), @@ -2632,6 +2637,10 @@ fn select_current(state: &mut AppState) -> Option { state.active_tab = Tab::Global; Some(Effect::FedOpenArtist(name)) } + Outcome::OpenPodcastCard(index) => { + podcast_discovery::open_card(state, index); + None + } Outcome::OpenFedRelease { name, card, index } => { let start = if card.releases.get(index).is_some_and(|release| { @@ -2873,6 +2882,7 @@ enum Outcome { start: usize, }, OpenFedArtist(String), + OpenPodcastCard(usize), OpenFedRelease { name: String, card: crate::federation::FedArtistCard, @@ -2883,7 +2893,8 @@ enum Outcome { } /// Enter inside the federated section of the search results: artists open -/// their card, tracks queue up like a local track list. +/// their card, tracks queue up like a local track list, podcasts open their +/// public card. fn fed_outcome(state: &AppState, fed_index: usize) -> Outcome { let artists = &state.search.fed_artists; if fed_index < artists.len() { @@ -2891,7 +2902,12 @@ fn fed_outcome(state: &AppState, fed_index: usize) -> Outcome { } let start = fed_index - artists.len(); if start >= state.search.fed_tracks.len() { - return Outcome::Nothing; + let podcast = start - state.search.fed_tracks.len(); + return if podcast < state.search.fed_podcasts.len() { + Outcome::OpenPodcastCard(podcast) + } else { + Outcome::Nothing + }; } Outcome::Play { tracks: state @@ -3396,6 +3412,7 @@ fn not_yet(state: &mut AppState, what: &str) { state.status_message = Some(format!("{what}: coming in a later milestone")); } +pub(crate) mod podcast_discovery; pub(crate) mod podcasts; #[cfg(test)] diff --git a/src/app/update/podcast_discovery.rs b/src/app/update/podcast_discovery.rs new file mode 100644 index 0000000..0dd38ef --- /dev/null +++ b/src/app/update/podcast_discovery.rs @@ -0,0 +1,117 @@ +//! Public podcast cards opened from the search results. +//! +//! The card shows what its publishers claim. "Подписаться" subscribes with +//! the card's origin feed URL only (`Effect::PodcastSubscribeFromCard`); the +//! subscription is private and its metadata comes from the feed. When this +//! device is already subscribed (under the card's id or a feed alias), the +//! action reads «Уже подписан» and Enter opens the podcast instead. + +use crossterm::event::KeyCode; +use music_dht::podcast::PodcastId; + +use super::Effect; +use super::podcasts::{display_title, reveal_podcast, store_ready}; +use crate::app::state::{AppState, Loadable, Popup}; +use crate::podcasts::discovery::{FeedPreview, PodcastHit}; + +/// Lines a page key scrolls the card by. +const PAGE: u16 = 10; + +/// Enter on a podcast hit of the search results. +pub fn open_card(state: &mut AppState, index: usize) { + let Some(hit) = state.search.fed_podcasts.get(index) else { + return; + }; + state.popup = Some(Popup::PodcastCard { + hit: Box::new(hit.clone()), + preview: None, + scroll: 0, + }); +} + +/// A key in [`Popup::PodcastCard`] (the popup was taken out of the state): +/// Enter/s subscribes (or opens the subscribed podcast), `e` reads the +/// episodes from the feed, arrows and page keys scroll, Esc/q closes. +pub fn card_key(state: &mut AppState, popup: Popup, key: KeyCode) -> Option { + let Popup::PodcastCard { + hit, + mut preview, + mut scroll, + } = popup + else { + state.popup = Some(popup); + return None; + }; + let mut effect = None; + match key { + KeyCode::Esc | KeyCode::Char('q') => return None, + KeyCode::Enter | KeyCode::Char('s') => { + if let Some(id) = subscribed_id(state, &hit) { + // «Уже подписан»: show the subscription instead. + return reveal_podcast(state, id, hit.title()); + } + effect = subscribe(state, &hit); + } + KeyCode::Char('e') => { + if !matches!(preview, Some(Loadable::Loading | Loadable::Ready(_))) { + preview = Some(Loadable::Loading); + effect = Some(Effect::PodcastPreview { + podcast_id: hit.hit.podcast_id.clone(), + feed_url: hit.hit.feed_url.clone(), + }); + } + } + KeyCode::Up | KeyCode::Char('k') => scroll = scroll.saturating_sub(1), + KeyCode::Down | KeyCode::Char('j') => scroll = scroll.saturating_add(1), + KeyCode::PageUp => scroll = scroll.saturating_sub(PAGE), + KeyCode::PageDown => scroll = scroll.saturating_add(PAGE), + KeyCode::Home | KeyCode::Char('g') => scroll = 0, + _ => {} + } + state.popup = Some(Popup::PodcastCard { + hit, + preview, + scroll, + }); + effect +} + +/// The id under which this device is subscribed to the card's podcast. +fn subscribed_id(state: &AppState, hit: &PodcastHit) -> Option { + hit.ids() + .into_iter() + .find(|id| state.podcasts.podcast(id).is_some()) + .cloned() +} + +fn subscribe(state: &mut AppState, hit: &PodcastHit) -> Option { + if !store_ready(state) { + return None; + } + if state.podcasts.subscribing { + state.status_message = Some("podcasts: a subscription is already being added".into()); + return None; + } + state.podcasts.subscribing = true; + state.status_message = Some(format!( + "podcasts: reading the feed of {}…", + display_title(hit.title()) + )); + Some(Effect::PodcastSubscribeFromCard(Box::new(hit.hit.clone()))) +} + +/// The preview of an open card arrived (ignored when another card is open). +pub fn preview_loaded( + state: &mut AppState, + podcast_id: PodcastId, + result: Result, String>, +) { + if let Some(Popup::PodcastCard { hit, preview, .. }) = &mut state.popup + && hit.hit.podcast_id == podcast_id + { + *preview = Some(match result { + Ok(feed) => Loadable::Ready(*feed), + Err(err) => Loadable::Failed(err), + }); + } +} diff --git a/src/app/update/podcasts.rs b/src/app/update/podcasts.rs index fe9ca17..d280f18 100644 --- a/src/app/update/podcasts.rs +++ b/src/app/update/podcasts.rs @@ -67,7 +67,7 @@ pub(super) fn handle(state: &mut AppState, action: &Action) -> Option bool { +pub(super) fn store_ready(state: &mut AppState) -> bool { match &state.podcasts.store { PodcastStoreStatus::Ready => true, PodcastStoreStatus::Opening => { @@ -371,6 +371,15 @@ pub fn reveal_episode_podcast(state: &mut AppState, track: &TrackItem) -> Option let episode = track.podcast_episode_ref()?; let podcast_id = episode.podcast_id.clone(); let title = episode.podcast_title.clone(); + reveal_podcast(state, podcast_id, &title) +} + +/// Switches to the Podcasts tab and opens a subscribed podcast. +pub(super) fn reveal_podcast( + state: &mut AppState, + podcast_id: PodcastId, + title: &str, +) -> Option { state.active_tab = Tab::Podcasts; state.help_visible = false; state.track_selection.clear(); @@ -400,7 +409,7 @@ pub fn reveal_episode_podcast(state: &mut AppState, track: &TrackItem) -> Option None => { state.status_message = Some(format!( "podcasts: {} is not subscribed on this device", - display_title(&title) + display_title(title) )); None } @@ -1077,7 +1086,7 @@ pub fn subscribed(state: &mut AppState, result: Result) } } -fn display_title(title: &str) -> String { +pub(super) fn display_title(title: &str) -> String { if title.trim().is_empty() { "the podcast".to_string() } else { diff --git a/src/app/update_tests.rs b/src/app/update_tests.rs index 98c6f4c..56beb9d 100644 --- a/src/app/update_tests.rs +++ b/src/app/update_tests.rs @@ -2525,3 +2525,234 @@ mod podcast_queue { assert!(crate::app::update::podcasts::synced(&mut opening, Vec::new(), true).is_empty()); } } + +mod podcast_discovery { + use crossterm::event::KeyCode; + use music_dht::podcast::{FeedUrl, PodcastId}; + use music_dht::podcast_dht::ClaimedFeedUrl; + + use super::*; + use crate::app::podcast_fixtures::{self as fx, podcast_id}; + use crate::app::state::{Loadable, PODCAST_ACTION_ROWS, Popup}; + use crate::app::update::podcast_discovery::{card_key, preview_loaded}; + use crate::podcasts::discovery::{FeedPreview, PodcastHit, test_hit}; + + const ORIGIN: &str = "https://feeds.example.test/origin.xml"; + const CLAIMED: &str = "https://elsewhere.example.test/claimed.xml"; + + /// A card whose publisher also claims the feed moved elsewhere. + fn claimed_hit() -> PodcastHit { + let mut hit = test_hit(ORIGIN, "Rust Radio"); + let claimed = FeedUrl::parse(CLAIMED).unwrap(); + hit.claimed_feed_urls = vec![ClaimedFeedUrl { + feed_url: claimed.clone(), + publishers: hit.publishers.clone(), + }]; + hit.card.feed_url = claimed; + hit.card.id_feed_url = Some(FeedUrl::parse(ORIGIN).unwrap()); + PodcastHit::new(hit) + } + + /// The search view with one local track, a federated artist and the + /// given podcast hits; the podcast store is ready with `rows`. + fn search_state(rows: Vec, hits: Vec) -> AppState { + let mut state = fx::ready_state(rows); + state.active_tab = Tab::Global; + state.search.query = "rust radio".into(); + state.search.results = Some(crate::library::models::SearchResults { + tracks: vec![test_track(1)], + ..Default::default() + }); + state.search.fed_artists = vec![crate::federation::FedArtistHit { + name: "Rust Radio Band".into(), + peers: 2, + }]; + state.search.fed_podcasts = hits; + state.global.stack.push(GlobalView::Search { cursor: 0 }); + state + } + + fn open_card_at(state: &mut AppState, cursor: usize) -> Popup { + if let Some(GlobalView::Search { cursor: at }) = state.global.stack.last_mut() { + *at = cursor; + } + assert_eq!(update(state, Action::Select), None); + state.popup.take().expect("the card opens") + } + + #[test] + fn the_cursor_reaches_podcast_hits_after_the_music_results() { + let mut state = search_state(Vec::new(), vec![claimed_hit()]); + assert_eq!(state.search.total_len(), 3); + update(&mut state, Action::SelectLast); + assert!(matches!( + state.global.stack.last(), + Some(GlobalView::Search { cursor: 2 }) + )); + // Enter on a podcast opens its card; nothing is played or queued. + assert_eq!(update(&mut state, Action::Select), None); + assert!(state.player.queue.is_empty()); + assert!(matches!( + &state.popup, + Some(Popup::PodcastCard { hit, preview: None, scroll: 0 }) if hit.title() == "Rust Radio" + )); + // The music rows keep their behavior. + let mut state = search_state(Vec::new(), vec![claimed_hit()]); + assert_eq!( + update(&mut state, Action::Select), + Some(Effect::PlayCurrent) + ); + } + + #[test] + fn subscribing_from_a_card_uses_the_origin_url_only() { + let mut state = search_state(Vec::new(), vec![claimed_hit()]); + let popup = open_card_at(&mut state, 2); + let effect = card_key(&mut state, popup, KeyCode::Enter); + let Some(Effect::PodcastSubscribeFromCard(hit)) = effect else { + panic!("expected a subscription, got {effect:?}"); + }; + assert_eq!(hit.feed_url.as_str(), ORIGIN); + assert_eq!( + hit.podcast_id, + PodcastId::from_feed_url(&FeedUrl::parse(ORIGIN).unwrap()) + ); + assert!(state.podcasts.subscribing); + assert!(matches!(state.popup, Some(Popup::PodcastCard { .. }))); + + // One subscription at a time. + let popup = state.popup.take().unwrap(); + assert_eq!(card_key(&mut state, popup, KeyCode::Char('s')), None); + assert!( + state + .status_message + .as_deref() + .is_some_and(|message| message.contains("already being added")) + ); + + // Esc closes without anything else. + state.podcasts.subscribing = false; + let popup = state.popup.take().unwrap(); + assert_eq!(card_key(&mut state, popup, KeyCode::Esc), None); + assert!(state.popup.is_none()); + + // Without a podcast store nothing is requested. + let mut state = search_state(Vec::new(), vec![claimed_hit()]); + state.podcasts.store = crate::app::state::PodcastStoreStatus::Opening; + let popup = open_card_at(&mut state, 2); + assert_eq!(card_key(&mut state, popup, KeyCode::Enter), None); + assert!(!state.podcasts.subscribing); + } + + #[test] + fn already_subscribed_cards_open_the_podcast_instead() { + // Subscribed under the card's own id. + let mut hit = test_hit("https://example.test/feed.xml", "Test Show"); + hit.card.episode_count = None; + let mut state = search_state( + vec![fx::row("Test Show", 0, 3, 0)], + vec![PodcastHit::new(hit)], + ); + assert!(state.podcasts.subscribed_to(&state.search.fed_podcasts[0])); + let popup = open_card_at(&mut state, 2); + let effect = card_key(&mut state, popup, KeyCode::Enter); + assert!( + matches!(&effect, Some(Effect::PodcastLoadEpisodes { query, .. }) if query.podcast_id == podcast_id()), + "{effect:?}" + ); + assert_eq!(state.active_tab, Tab::Podcasts); + assert_eq!(state.podcasts.selected, PODCAST_ACTION_ROWS); + assert!(state.popup.is_none()); + assert!(!state.podcasts.subscribing); + + // Subscribed under another id: the card's origin URL is a feed + // alias of that podcast here (resolved by the search task). + let mut aliased = claimed_hit(); + assert_ne!(aliased.hit.podcast_id, podcast_id()); + aliased.local_id = podcast_id(); + let mut state = search_state(vec![fx::row("Test Show", 0, 3, 0)], vec![aliased]); + assert!(state.podcasts.subscribed_to(&state.search.fed_podcasts[0])); + let popup = open_card_at(&mut state, 2); + let effect = card_key(&mut state, popup, KeyCode::Enter); + assert!( + !matches!(effect, Some(Effect::PodcastSubscribeFromCard(_))), + "{effect:?}" + ); + assert_eq!(state.active_tab, Tab::Podcasts); + + // Not subscribed: an unsubscribed podcast is not in the rows. + let state = search_state(Vec::new(), vec![claimed_hit()]); + assert!(!state.podcasts.subscribed_to(&state.search.fed_podcasts[0])); + } + + #[test] + fn the_episode_preview_is_requested_once_and_folded_in() { + let mut state = search_state(Vec::new(), vec![claimed_hit()]); + let popup = open_card_at(&mut state, 2); + let effect = card_key(&mut state, popup, KeyCode::Char('e')); + let Some(Effect::PodcastPreview { + podcast_id: card_id, + feed_url, + }) = effect + else { + panic!("expected a preview request, got {effect:?}"); + }; + assert_eq!(feed_url.as_str(), ORIGIN, "never the claimed URL"); + let popup = state.popup.take().unwrap(); + assert_eq!(card_key(&mut state, popup, KeyCode::Char('e')), None); + assert!(matches!( + state.popup, + Some(Popup::PodcastCard { + preview: Some(Loadable::Loading), + .. + }) + )); + // Scrolling keeps the card. + let popup = state.popup.take().unwrap(); + assert_eq!(card_key(&mut state, popup, KeyCode::Down), None); + assert!(matches!( + state.popup, + Some(Popup::PodcastCard { scroll: 1, .. }) + )); + + let feed = FeedPreview { + title: "Rust Radio".into(), + episode_count: 0, + seasons: Vec::new(), + episodes: Vec::new(), + moved_to: None, + }; + // A preview of another card is ignored. + preview_loaded(&mut state, podcast_id(), Ok(Box::new(feed.clone()))); + assert!(matches!( + state.popup, + Some(Popup::PodcastCard { + preview: Some(Loadable::Loading), + .. + }) + )); + preview_loaded( + &mut state, + card_id.clone(), + Err("HTTP 404 Not Found".into()), + ); + assert!(matches!( + state.popup, + Some(Popup::PodcastCard { + preview: Some(Loadable::Failed(_)), + .. + }) + )); + // A failed preview may be asked again. + let popup = state.popup.take().unwrap(); + assert!(matches!( + card_key(&mut state, popup, KeyCode::Char('e')), + Some(Effect::PodcastPreview { .. }) + )); + preview_loaded(&mut state, card_id, Ok(Box::new(feed.clone()))); + assert!(matches!( + &state.popup, + Some(Popup::PodcastCard { preview: Some(Loadable::Ready(ready)), .. }) if *ready == feed + )); + } +} diff --git a/src/federation/mod.rs b/src/federation/mod.rs index f9c6dff..8d87903 100644 --- a/src/federation/mod.rs +++ b/src/federation/mod.rs @@ -346,6 +346,10 @@ pub struct FedArtistHit { pub struct FedSearchResults { pub artists: Vec, pub tracks: Vec, + /// Public podcast cards from the discovery overlay (explicit type + /// `podcast`), in `merge_search_results` order. Empty while the overlay + /// is not running. + pub podcasts: Vec, } #[derive(Debug, Clone)] @@ -1262,13 +1266,31 @@ impl Federation { /// Searches the federated network: matching tracks plus the artists a /// card can be assembled for (from artist records and from the artist /// names of matching tracks/releases). + /// + /// Public podcast cards are looked up in the discovery overlay at the + /// same time; a failure there only leaves the podcast hits empty. pub async fn search(&self, query: &str) -> Result { let service = self.service().await?; let normalized = music_dht::normalize_name(query); - let outcome = service - .search_network(query) - .await - .map_err(|err| anyhow::anyhow!("federated search failed: {err}"))?; + let podcast_dht = self.podcast_dht.borrow().clone(); + let (outcome, podcast_hits) = tokio::join!(service.search_network(query), async { + match podcast_dht { + Some(dht) => dht + .search(query, crate::podcasts::discovery::PODCAST_SEARCH_LIMIT) + .await + .unwrap_or_else(|err| { + tracing::warn!("podcast discovery search failed: {err}"); + Vec::new() + }), + None => Vec::new(), + } + }); + let outcome = outcome.map_err(|err| anyhow::anyhow!("federated search failed: {err}"))?; + let podcasts = crate::podcasts::discovery::podcast_hits( + query, + outcome.network_results.clone(), + podcast_hits, + ); let own = service.endpoint_id(); let mut tracks: Vec = outcome .network_results @@ -1354,7 +1376,11 @@ impl Federation { artists.sort_by(|a, b| b.peers.cmp(&a.peers).then_with(|| a.name.cmp(&b.name))); rank_fed_search_results(&mut artists, &mut tracks, &normalized); - Ok(FedSearchResults { artists, tracks }) + Ok(FedSearchResults { + artists, + tracks, + podcasts, + }) } /// Bounded fan-out to known peers using the exact model/profile diff --git a/src/podcasts/discovery.rs b/src/podcasts/discovery.rs new file mode 100644 index 0000000..59f76ed --- /dev/null +++ b/src/podcasts/discovery.rs @@ -0,0 +1,203 @@ +//! Public podcast cards found by federated search: their order next to the +//! music results, whether this device is already subscribed, an episode +//! preview read from the feed itself, and subscribing from a card. +//! +//! A card is a publisher's claim. Only its origin feed URL +//! ([`PodcastSearchHit::feed_url`]) is bound to the podcast id, so it is the +//! only URL this module ever fetches or subscribes with; the claimed moved +//! URLs are shown, never used. Nothing from the card is stored: subscribing +//! reads the feed from the podcast's own host like any other subscription, +//! and the new subscription is private. + +use anyhow::{Result, bail}; +use furumi_library::podcasts::PodcastStore; +use music_dht::LibraryItem; +use music_dht::podcast::{FeedUrl, PodcastId}; +use music_dht::podcast_dht::{FederatedSearchHit, PodcastSearchHit, merge_search_results}; + +use super::fetch::{FeedBody, Fetcher, Validators}; +use super::refresh::{self, Services, SubscribeReport}; + +/// Podcast hits asked from the discovery overlay per search. +pub const PODCAST_SEARCH_LIMIT: usize = 20; +/// Episodes kept in a preview (newest first). +pub const PREVIEW_EPISODES: usize = 200; + +/// One public podcast in the search results. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PodcastHit { + pub hit: PodcastSearchHit, + /// The id this device gives the hit's origin URL + /// (`PodcastStore::resolve_podcast_id`): the card's id, unless the URL + /// is a known alias of a podcast this device already has. + pub local_id: PodcastId, +} + +impl PodcastHit { + /// A hit not yet resolved against the local store. + pub fn new(hit: PodcastSearchHit) -> Self { + let local_id = hit.podcast_id.clone(); + Self { hit, local_id } + } + + /// Ids under which this device may know the podcast. + pub fn ids(&self) -> [&PodcastId; 2] { + [&self.local_id, &self.hit.podcast_id] + } + + pub fn title(&self) -> &str { + &self.hit.card.title + } +} + +/// The podcast hits of a federated search, in the order of +/// [`merge_search_results`] (exact title matches first). The TUI keeps its +/// own sections for the music results; only the podcast entries of the +/// merged list are taken. +pub fn podcast_hits( + query: &str, + music: Vec, + podcasts: Vec, +) -> Vec { + merge_search_results(query, music, podcasts) + .into_iter() + .filter_map(|hit| match hit { + FederatedSearchHit::Podcast(hit) => Some(PodcastHit::new(hit)), + FederatedSearchHit::Music(_) => None, + }) + .collect() +} + +/// Resolves each hit's origin URL against the local store (feed aliases +/// included). Blocking. +pub fn resolve_local_ids(store: &PodcastStore, hits: &mut [PodcastHit]) -> Result<()> { + for hit in hits { + hit.local_id = store.resolve_podcast_id(&hit.hit.feed_url)?; + } + Ok(()) +} + +/// Subscribes to the podcast of a public card with its origin URL, never a +/// claimed one. The feed is read from its own host (following its own +/// redirects and `itunes:new-feed-url`), the subscription is private and +/// none of the card's metadata is stored. +pub async fn subscribe_from_hit( + services: &Services, + hit: &PodcastSearchHit, + now_ms: i64, +) -> Result { + if PodcastId::from_feed_url(&hit.feed_url) != hit.podcast_id { + bail!("the card's feed URL does not match its podcast id"); + } + refresh::subscribe_url(services, hit.feed_url.clone(), now_ms).await +} + +/// One episode of a preview. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PreviewEpisode { + pub title: String, + pub season: Option, + pub episode_number: Option, + pub published_at_ms: Option, + pub duration_ms: Option, +} + +/// What a podcast's own feed says, read without subscribing. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FeedPreview { + /// Channel title in the feed (may differ from the card's claim). + pub title: String, + pub episode_count: usize, + /// Season number (`None`: episodes without one) and episode count, + /// seasons in ascending order, unnumbered last. + pub seasons: Vec<(Option, usize)>, + /// Newest first, at most [`PREVIEW_EPISODES`]. + pub episodes: Vec, + /// The feed answered from, or announced, another address. + pub moved_to: Option, +} + +/// Reads the feed at `url` (a card's origin URL) for a preview. Nothing is +/// stored and no fetch state is recorded. +pub async fn preview(fetcher: &Fetcher, url: &FeedUrl) -> Result { + let response = fetcher.fetch_feed(url, Validators::default()).await?; + let FeedBody::Modified { body, .. } = response.body else { + bail!("the server answered 304 Not Modified to an unconditional request"); + }; + let feed = refresh::parse(body, &response.final_url).await?; + let announced = feed + .new_feed_url + .as_deref() + .and_then(|url| FeedUrl::parse(url).ok()); + let moved_to = response + .moved_permanently_to + .or(announced) + .filter(|moved| moved != url); + + let mut seasons: std::collections::BTreeMap<(bool, u32), usize> = Default::default(); + for episode in &feed.episodes { + let key = match episode.season { + Some(season) => (false, season), + None => (true, 0), + }; + *seasons.entry(key).or_default() += 1; + } + let mut episodes: Vec = feed + .episodes + .iter() + .map(|episode| PreviewEpisode { + title: episode.title.clone(), + season: episode.season, + episode_number: episode.episode_number, + published_at_ms: episode.published_at_ms, + duration_ms: episode.duration_ms, + }) + .collect(); + episodes.sort_by_key(|episode| std::cmp::Reverse(episode.published_at_ms)); + episodes.truncate(PREVIEW_EPISODES); + Ok(FeedPreview { + title: feed.title.clone(), + episode_count: feed.episodes.len(), + seasons: seasons + .into_iter() + .map(|((unnumbered, season), count)| ((!unnumbered).then_some(season), count)) + .collect(), + episodes, + moved_to, + }) +} + +/// A search hit for `feed_url` as one publisher would announce it (tests of +/// the search UI and of subscribing from a card). +#[cfg(test)] +pub(crate) fn test_hit(feed_url: &str, title: &str) -> PodcastSearchHit { + let feed_url = FeedUrl::parse(feed_url).unwrap(); + let podcast_id = PodcastId::from_feed_url(&feed_url); + let publisher = music_dht::SecretKey::from_bytes(&[7; 32]).public(); + PodcastSearchHit { + podcast_id: podcast_id.clone(), + feed_url: feed_url.clone(), + card: music_dht::podcast_dht::PodcastCard { + version: 1, + network_id: music_dht::NetworkId::from_name("furumi-tui-discovery-test"), + publisher, + podcast_id, + feed_url, + id_feed_url: None, + title: title.to_string(), + author: Some("Ferris Crab".to_string()), + description: Some("Weekly news about Rust.".to_string()), + image_url: None, + link: None, + language: Some("en".to_string()), + categories: vec!["Technology".to_string()], + episode_count: Some(12), + latest_episode_at_ms: Some(1_718_445_600_000), + revision: 1, + issued_at_ms: 1, + expires_at_ms: 2, + }, + publishers: vec![publisher], + claimed_feed_urls: Vec::new(), + } +} diff --git a/src/podcasts/mod.rs b/src/podcasts/mod.rs index c880526..21e9e0c 100644 --- a/src/podcasts/mod.rs +++ b/src/podcasts/mod.rs @@ -20,10 +20,14 @@ //! * [`progress`] writes resume positions, completions and listening //! sessions in order on its own thread; //! * [`publication`] publishes the podcasts the user chose to share to the -//! public discovery overlay (`music_dht::podcast_dht`) and revokes them. +//! public discovery overlay (`music_dht::podcast_dht`) and revokes them; +//! * [`discovery`] handles public cards found by search: their order, the +//! "already subscribed" mark, an episode preview read from the feed and +//! subscribing from a card. //! //! Only RSS metadata is stored. Audio stays on the publisher's server. +pub mod discovery; pub mod fetch; pub mod playback; pub mod progress; diff --git a/src/ui/global.rs b/src/ui/global.rs index 3f9ead9..f71f5b7 100644 --- a/src/ui/global.rs +++ b/src/ui/global.rs @@ -947,12 +947,7 @@ fn draw_search(frame: &mut Frame, area: Rect, state: &AppState, cursor: usize) { let empty_results = SearchResults::default(); let results = match &search.results { Some(results) => results, - None if !state.search.fed_tracks.is_empty() - || !state.search.fed_artists.is_empty() - || state.search.fed_loading => - { - &empty_results - } + None if state.search.has_federated() => &empty_results, None => { let hint = if search.query.is_empty() { "type to search artists, releases and tracks" @@ -967,11 +962,7 @@ fn draw_search(frame: &mut Frame, area: Rect, state: &AppState, cursor: usize) { return centered_line(frame, inner, line); } }; - if results.is_empty() - && state.search.fed_tracks.is_empty() - && state.search.fed_artists.is_empty() - && !state.search.fed_loading - { + if results.is_empty() && !state.search.has_federated() { return centered_line(frame, inner, Line::styled("nothing found", theme::dim())); } @@ -1037,11 +1028,8 @@ fn draw_search(frame: &mut Frame, area: Rect, state: &AppState, cursor: usize) { } } // Federated section: artists whose card can be assembled, then tracks - // (both marked with the owning peers). - if !state.search.fed_tracks.is_empty() - || !state.search.fed_artists.is_empty() - || state.search.fed_loading - { + // (both marked with the owning peers), then public podcast cards. + if state.search.has_federated() { if !rows.is_empty() { rows.push((Line::default(), None, None)); } @@ -1100,6 +1088,23 @@ fn draw_search(frame: &mut Frame, area: Rect, state: &AppState, cursor: usize) { )); index += 1; } + // Podcasts carry an explicit type marker: they are not music and + // Enter opens their public card, never plays anything. + if !state.search.fed_podcasts.is_empty() { + rows.push(( + Line::styled("Podcasts · public cards", theme::header_for(state)), + None, + None, + )); + } + for hit in &state.search.fed_podcasts { + rows.push(( + podcast_hit_line(state, hit), + Some(podcast_hit_meta(state, hit)), + Some(index), + )); + index += 1; + } } // Absolute cursor indices covered by an active Shift-V range in the @@ -1145,6 +1150,47 @@ fn draw_search(frame: &mut Frame, area: Rect, state: &AppState, cursor: usize) { } } +/// One public podcast in the search results: the `podcast` type marker, +/// the title and the claimed author. +fn podcast_hit_line( + state: &AppState, + hit: &crate::podcasts::discovery::PodcastHit, +) -> Line<'static> { + let card = &hit.hit.card; + let mut detail = String::from(" "); + if let Some(author) = &card.author { + detail.push_str(author); + detail.push_str(" · "); + } + detail.push_str("open the card"); + Line::from(vec![ + Span::styled( + format!("[{}] ", hit.hit.kind().as_str()), + theme::accent_for(state), + ), + Span::raw(card.title.clone()), + Span::styled(detail, theme::dim()), + ]) +} + +/// Right column of a podcast hit: subscribed here, or how many devices +/// publish the card (not a subscriber count). +fn podcast_hit_meta(state: &AppState, hit: &crate::podcasts::discovery::PodcastHit) -> String { + if state.podcasts.subscribed_to(hit) { + return "✓ subscribed".to_string(); + } + let mut meta = match hit.hit.card.episode_count { + Some(count) => format!("{count} ep · "), + None => String::new(), + }; + let publishers = hit.hit.publishers.len(); + meta.push_str(&format!( + "{publishers} publisher{}", + if publishers == 1 { "" } else { "s" } + )); + meta +} + fn draw_similarity_search(frame: &mut Frame, area: Rect, state: &AppState, cursor: usize) { let search = &state.search; let status = if search.fed_loading { diff --git a/src/ui/mod.rs b/src/ui/mod.rs index 5e2a278..fe3d7fa 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -4,6 +4,7 @@ mod federation; pub(crate) mod global; mod logs; mod playlists; +mod podcast_card; mod podcasts; mod popup; #[cfg(test)] @@ -217,6 +218,142 @@ mod tests { assert!(screen.contains("not published:"), "{screen}"); } + /// Search view with a federated artist and two public podcast cards; + /// the first podcast is subscribed on this device. + fn search_with_podcasts() -> AppState { + use crate::podcasts::discovery::{PodcastHit, test_hit}; + let mut state = + podcast_fixtures::ready_state(vec![podcast_fixtures::row("Test Show", 0, 3, 0)]); + state.active_tab = Tab::Global; + state.search.query = "show".into(); + state.search.results = Some(Default::default()); + state.search.fed_artists = vec![crate::federation::FedArtistHit { + name: "Show Band".into(), + peers: 2, + }]; + let mut other = test_hit("https://feeds.example.test/other.xml", "Other Show"); + other.card.author = None; + state.search.fed_podcasts = vec![ + PodcastHit::new(test_hit("https://example.test/feed.xml", "Test Show")), + PodcastHit::new(other), + ]; + state.global.stack.push(GlobalView::Search { cursor: 1 }); + state + } + + #[test] + fn search_marks_podcast_hits_apart_from_music() { + let screen = render(&search_with_podcasts(), 120, 20); + assert!(screen.contains("Federation"), "{screen}"); + assert!( + screen.contains("Show Band artist · open the card"), + "{screen}" + ); + assert!(screen.contains("Podcasts · public cards"), "{screen}"); + assert!( + screen.contains("[podcast] Test Show Ferris Crab · open the card"), + "{screen}" + ); + assert!( + screen.contains("[podcast] Other Show open the card"), + "{screen}" + ); + assert!(screen.contains("✓ subscribed"), "{screen}"); + assert!(screen.contains("12 ep · 1 publisher"), "{screen}"); + // The podcasts come after the music rows. + let artist = screen.find("Show Band").unwrap(); + let podcast = screen.find("[podcast]").unwrap(); + assert!(artist < podcast, "{screen}"); + } + + #[test] + fn podcast_card_offers_subscribe_or_shows_already_subscribed() { + use crate::app::state::{Loadable, Popup}; + use crate::podcasts::discovery::{FeedPreview, PreviewEpisode}; + let mut state = search_with_podcasts(); + let mut hit = state.search.fed_podcasts[1].clone(); + hit.hit.claimed_feed_urls = vec![music_dht::podcast_dht::ClaimedFeedUrl { + feed_url: music_dht::podcast::FeedUrl::parse("https://elsewhere.test/claimed.xml") + .unwrap(), + publishers: hit.hit.publishers.clone(), + }]; + state.popup = Some(Popup::PodcastCard { + hit: Box::new(hit.clone()), + preview: None, + scroll: 0, + }); + let screen = render(&state, 110, 40); + assert!(screen.contains("[podcast] Other Show"), "{screen}"); + assert!(screen.contains("они не проверены"), "{screen}"); + assert!(screen.contains("Категории: Technology"), "{screen}"); + assert!( + screen.contains("Выпусков: 12 · последний 2024-06-15"), + "{screen}" + ); + assert!( + screen.contains("Опубликовали: 1 устройство (не число подписчиков"), + "{screen}" + ); + assert!( + screen.contains("Лента: https://feeds.example.test/other.xml"), + "{screen}" + ); + assert!( + screen.contains("(не проверен, не используется): https://elsewhere.test/claimed.xml"), + "{screen}" + ); + assert!(screen.contains("[ Подписаться ]"), "{screen}"); + assert!( + screen.contains("e — прочитать ленту без подписки"), + "{screen}" + ); + assert!(screen.contains("enter подписаться"), "{screen}"); + assert!(!screen.contains("Уже подписан"), "{screen}"); + + state.popup = Some(Popup::PodcastCard { + hit: Box::new(hit), + preview: Some(Loadable::Ready(FeedPreview { + title: "Other Show (feed)".into(), + episode_count: 3, + seasons: vec![(Some(1), 2), (None, 1)], + episodes: vec![PreviewEpisode { + title: "Pilot".into(), + season: Some(1), + episode_number: Some(1), + published_at_ms: Some(1_718_445_600_000), + duration_ms: Some(2_700_000), + }], + moved_to: None, + })), + scroll: 0, + }); + let screen = render(&state, 110, 40); + assert!( + screen.contains("Название в ленте: Other Show (feed)"), + "{screen}" + ); + assert!( + screen.contains("В ленте: 3 выпуска · сезон 1: 2, без сезона: 1"), + "{screen}" + ); + assert!( + screen.contains("• Pilot S1E1 · 2024-06-15 · 45:00"), + "{screen}" + ); + assert!(screen.contains("… и ещё 2"), "{screen}"); + + // The subscribed podcast: «Уже подписан», Enter opens it. + state.popup = Some(Popup::PodcastCard { + hit: Box::new(state.search.fed_podcasts[0].clone()), + preview: None, + scroll: 0, + }); + let screen = render(&state, 110, 40); + assert!(screen.contains("✓ Уже подписан"), "{screen}"); + assert!(screen.contains("enter открыть"), "{screen}"); + assert!(!screen.contains("[ Подписаться ]"), "{screen}"); + } + #[test] fn podcast_share_confirmation_lists_the_warnings_in_russian() { let mut state = diff --git a/src/ui/podcast_card.rs b/src/ui/podcast_card.rs new file mode 100644 index 0000000..c64745e --- /dev/null +++ b/src/ui/podcast_card.rs @@ -0,0 +1,285 @@ +//! The public podcast card opened from the search results. In Russian, like +//! the share confirmation: «Подписаться» / «Уже подписан» are the actions +//! the requirements name. +//! +//! Everything but the origin feed URL is a publisher's claim and is shown as +//! such; the episode preview comes from the feed itself. + +use ratatui::Frame; +use ratatui::layout::{Alignment, Constraint, Layout}; +use ratatui::style::{Color, Modifier, Style}; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{Block, Clear, Paragraph, Wrap}; + +use super::podcasts::{format_date, format_duration_ms}; +use super::popup::centered; +use super::theme; +use crate::app::state::{AppState, Loadable}; +use crate::podcasts::discovery::{FeedPreview, PodcastHit}; + +pub(super) fn draw( + frame: &mut Frame, + state: &AppState, + hit: &PodcastHit, + preview: Option<&Loadable>, + scroll: u16, +) { + let subscribed = state.podcasts.subscribed_to(hit); + let subscribing = state.podcasts.subscribing; + let lines = card_lines(state, hit, preview, subscribed, subscribing); + + let width = 92.min(frame.area().width.saturating_sub(4)).max(30); + let inner_width = width.saturating_sub(2).max(1); + let body_height = lines + .iter() + .map(|line| (line.width().max(1) as u16).div_ceil(inner_width)) + .sum::(); + let height = (body_height + 4).min(frame.area().height.saturating_sub(2)); + let area = centered(frame.area(), width, height); + let block = Block::bordered() + .title(" Подкаст · публичная карточка ") + .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 [body, footer_area] = + Layout::vertical([Constraint::Min(1), Constraint::Length(1)]).areas(inner); + let max_scroll = body_height.saturating_sub(body.height); + frame.render_widget( + Paragraph::new(lines) + .wrap(Wrap { trim: false }) + .scroll((scroll.min(max_scroll), 0)), + body, + ); + let footer = if subscribed { + "enter открыть · e выпуски · ↑↓ прокрутка · esc закрыть" + } else { + "enter подписаться · e выпуски · ↑↓ прокрутка · esc закрыть" + }; + frame.render_widget( + Paragraph::new(Line::styled(footer, theme::dim())).alignment(Alignment::Center), + footer_area, + ); +} + +fn card_lines( + state: &AppState, + hit: &PodcastHit, + preview: Option<&Loadable>, + subscribed: bool, + subscribing: bool, +) -> Vec> { + let card = &hit.hit.card; + let bold = Style::new().add_modifier(Modifier::BOLD); + let mut lines = vec![ + Line::from(vec![ + Span::styled("[podcast] ", theme::accent_for(state)), + Span::styled(card.title.clone(), bold), + ]), + Line::styled( + "Сведения ниже указали издатели карточки; они не проверены.", + theme::dim(), + ), + Line::raw(""), + ]; + if let Some(author) = &card.author { + lines.push(field("Автор", author.clone())); + } + if !card.categories.is_empty() { + lines.push(field("Категории", card.categories.join(", "))); + } + if let Some(language) = &card.language { + lines.push(field("Язык", language.clone())); + } + let mut episodes = match card.episode_count { + Some(count) => format!("{count}"), + None => "не указано".to_string(), + }; + if let Some(latest) = card.latest_episode_at_ms { + episodes.push_str(&format!( + " · последний {}", + format_date(latest.div_euclid(1000)) + )); + } + lines.push(field("Выпусков", episodes)); + let publishers = hit.hit.publishers.len(); + lines.push(field( + "Опубликовали", + format!( + "{publishers} {} (не число подписчиков и не знак доверия)", + plural_ru(publishers, "устройство", "устройства", "устройств") + ), + )); + lines.push(field("Лента", hit.hit.feed_url.as_str().to_string())); + for claim in &hit.hit.claimed_feed_urls { + lines.push(Line::styled( + format!( + "Заявленный новый адрес (не проверен, не используется): {}", + claim.feed_url.as_str() + ), + theme::dim(), + )); + } + if let Some(link) = &card.link { + lines.push(field("Сайт", link.clone())); + } + if let Some(description) = &card.description { + lines.push(Line::raw("")); + lines.extend( + description + .lines() + .map(|line| Line::raw(line.replace('\t', " "))), + ); + } + + lines.push(Line::raw("")); + if subscribed { + lines.push(Line::from(vec![ + Span::styled( + "✓ Уже подписан", + Style::new().fg(Color::Green).add_modifier(Modifier::BOLD), + ), + Span::styled( + " · enter откроет подкаст во вкладке Podcasts", + theme::dim(), + ), + ])); + } else if subscribing { + lines.push(Line::styled( + "Подписка… читаем ленту", + theme::accent_for(state), + )); + } else { + lines.push(Line::from(vec![ + Span::styled( + "[ Подписаться ]", + theme::accent_for(state).add_modifier(Modifier::BOLD), + ), + Span::styled( + " лента будет прочитана с её сервера; подписка личная и не публикуется", + theme::dim(), + ), + ])); + } + + lines.push(Line::raw("")); + lines.push(Line::styled( + "Сезоны и выпуски (из RSS-ленты)", + theme::header_for(state), + )); + match preview { + None => lines.push(Line::styled( + "e — прочитать ленту без подписки (запрос к серверу ленты)", + theme::dim(), + )), + Some(Loadable::Loading) => { + lines.push(Line::styled("читаем ленту…", theme::accent_for(state))) + } + Some(Loadable::Failed(err)) => lines.push(Line::styled( + format!("не удалось прочитать ленту: {err}"), + Style::new().fg(Color::Red), + )), + Some(Loadable::Ready(feed)) => preview_lines(&mut lines, card.title.as_str(), feed), + } + lines +} + +fn preview_lines(lines: &mut Vec>, card_title: &str, feed: &FeedPreview) { + if feed.title != card_title { + lines.push(field("Название в ленте", feed.title.clone())); + } + if let Some(moved) = &feed.moved_to { + lines.push(field("Лента переехала", moved.as_str().to_string())); + } + let seasons: Vec = feed + .seasons + .iter() + .map(|(season, count)| match season { + Some(season) => format!("сезон {season}: {count}"), + None => format!("без сезона: {count}"), + }) + .collect(); + lines.push(field( + "В ленте", + format!( + "{} {}{}", + feed.episode_count, + plural_ru(feed.episode_count, "выпуск", "выпуска", "выпусков"), + if seasons.is_empty() { + String::new() + } else { + format!(" · {}", seasons.join(", ")) + } + ), + )); + for episode in &feed.episodes { + let mut meta = Vec::new(); + match (episode.season, episode.episode_number) { + (Some(season), Some(number)) => meta.push(format!("S{season}E{number}")), + (Some(season), None) => meta.push(format!("S{season}")), + (None, Some(number)) => meta.push(format!("#{number}")), + (None, None) => {} + } + if let Some(published) = episode.published_at_ms { + meta.push(format_date(published.div_euclid(1000))); + } + if let Some(duration) = episode.duration_ms { + meta.push(format_duration_ms(duration)); + } + lines.push(Line::from(vec![ + Span::raw(format!("• {}", episode.title)), + Span::styled( + if meta.is_empty() { + String::new() + } else { + format!(" {}", meta.join(" · ")) + }, + theme::dim(), + ), + ])); + } + if feed.episodes.len() < feed.episode_count { + lines.push(Line::styled( + format!("… и ещё {}", feed.episode_count - feed.episodes.len()), + theme::dim(), + )); + } +} + +fn field(label: &str, value: String) -> Line<'static> { + Line::from(vec![ + Span::styled(format!("{label}: "), theme::dim()), + Span::raw(value), + ]) +} + +/// Russian plural form for `n`. +fn plural_ru(n: usize, one: &'static str, few: &'static str, many: &'static str) -> &'static str { + let (tens, units) = (n % 100, n % 10); + if (11..=14).contains(&tens) { + many + } else if units == 1 { + one + } else if (2..=4).contains(&units) { + few + } else { + many + } +} + +#[cfg(test)] +mod tests { + use super::plural_ru; + + #[test] + fn russian_plurals() { + let forms = |n| plural_ru(n, "устройство", "устройства", "устройств"); + assert_eq!(forms(1), "устройство"); + assert_eq!(forms(3), "устройства"); + assert_eq!(forms(5), "устройств"); + assert_eq!(forms(11), "устройств"); + assert_eq!(forms(21), "устройство"); + assert_eq!(forms(0), "устройств"); + } +} diff --git a/src/ui/popup.rs b/src/ui/popup.rs index 2465af6..68334ea 100644 --- a/src/ui/popup.rs +++ b/src/ui/popup.rs @@ -28,6 +28,11 @@ pub fn draw(frame: &mut Frame, state: &AppState) { Some(Popup::ConfirmPodcastUnsubscribe { title, .. }) => { draw_confirm_podcast_unsubscribe(frame, state, title) } + Some(Popup::PodcastCard { + hit, + preview, + scroll, + }) => super::podcast_card::draw(frame, state, hit, preview.as_ref(), *scroll), Some(Popup::ConfirmPodcastShare { title, urls, @@ -1824,7 +1829,7 @@ fn draw_name_entry( frame.render_widget(Paragraph::new(hint).alignment(Alignment::Center), footer); } -fn centered(area: Rect, width: u16, height: u16) -> Rect { +pub(super) fn centered(area: Rect, width: u16, height: u16) -> Rect { let [rect] = Layout::horizontal([Constraint::Length(width.min(area.width))]) .flex(Flex::Center) .areas(area);