diff --git a/src/app/action.rs b/src/app/action.rs index d1d4d2f..1fa972a 100644 --- a/src/app/action.rs +++ b/src/app/action.rs @@ -75,6 +75,9 @@ pub enum Action { UnsubscribePodcast, /// Podcasts: play the selected (or playing) episode from the beginning. RestartEpisode, + /// Podcasts: turn "share in the federation" on or off for the selected + /// or opened podcast (asks first when its feed URL looks private). + TogglePodcastShare, } /// Help-window sections, in display order. @@ -168,7 +171,8 @@ impl Action { | Action::CycleEpisodeFilter | Action::ToggleEpisodePlayed | Action::UnsubscribePodcast - | Action::RestartEpisode => Category::Podcasts, + | Action::RestartEpisode + | Action::TogglePodcastShare => Category::Podcasts, Action::OpenSearch | Action::OpenCommandLine => Category::Search, Action::ToggleHelp | Action::Quit => Category::System, } @@ -257,6 +261,7 @@ impl Action { Action::ToggleEpisodePlayed => "Mark played / unplayed".into(), Action::UnsubscribePodcast => "Unsubscribe (keeps progress)".into(), Action::RestartEpisode => "Play episode from the start".into(), + Action::TogglePodcastShare => "Share podcast in the federation on/off".into(), } } } diff --git a/src/app/event.rs b/src/app/event.rs index 89a9840..013bbd7 100644 --- a/src/app/event.rs +++ b/src/app/event.rs @@ -268,4 +268,19 @@ pub enum AppEvent { PodcastRefreshTick, /// Feeds due for a background refresh. PodcastsDue(Result, String>), + /// What sharing a podcast would publish (`Effect::PodcastPrepareShare`). + PodcastSharePrepared { + podcast_id: music_dht::podcast::PodcastId, + title: String, + result: Result, + }, + /// The share decision was written (`Effect::PodcastSetShared`). + PodcastShareSet { + podcast_id: music_dht::podcast::PodcastId, + title: String, + shared: bool, + result: Result<(), String>, + }, + /// The publication reconciler finished a pass. + PodcastPublication(crate::podcasts::publication::PublicationReport), } diff --git a/src/app/mod.rs b/src/app/mod.rs index 23071bb..1483dd1 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -1734,7 +1734,10 @@ fn perform_effect(state: &mut AppState, runtime: &mut Runtime, effect: Effect) { | Effect::PodcastSubscribe(_) | Effect::PodcastRefresh { .. } | Effect::PodcastUnsubscribe { .. } - | Effect::PodcastSetPlayed { .. } => {} + | Effect::PodcastSetPlayed { .. } + | Effect::PodcastPrepareShare { .. } + | Effect::PodcastSetShared { .. } + | Effect::PodcastPublicationSync => {} Effect::LoadListenHistory => { let library = Arc::clone(&runtime.library); let devices = Arc::clone(&runtime.devices); @@ -3531,7 +3534,10 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent | AppEvent::PodcastEpisodeStarted { .. } | AppEvent::PodcastEpisodeFailed { .. } | AppEvent::PodcastRefreshTick - | AppEvent::PodcastsDue(_) => {} + | AppEvent::PodcastsDue(_) + | AppEvent::PodcastSharePrepared { .. } + | AppEvent::PodcastShareSet { .. } + | AppEvent::PodcastPublication(_) => {} AppEvent::StatusVisualizationReady(ready) => { runtime.status_visualizer.busy = false; state.status_visualizer.apply(ready); diff --git a/src/app/podcast_runtime.rs b/src/app/podcast_runtime.rs index 62af2ce..064f0dc 100644 --- a/src/app/podcast_runtime.rs +++ b/src/app/podcast_runtime.rs @@ -19,6 +19,7 @@ use crate::podcasts::playback::{self, StartAt}; use crate::podcasts::progress::{ CHECKPOINT_INTERVAL, ProgressCommand, ProgressEvent, ProgressWriter, }; +use crate::podcasts::publication::{self, Reconciler, ShareConfirmations}; use crate::podcasts::refresh::{self, Services}; use crate::podcasts::stream::{CancelToken, StreamEnd, StreamProbe}; @@ -39,6 +40,8 @@ pub struct PodcastRuntime { /// Writes progress in order on its own thread; `None` if it could not /// start (episodes then play without saving progress). progress: Option, + /// Publishes shared podcasts to public discovery and revokes the rest. + publication: Reconciler, } /// The episode this device is playing (or starting), as the progress @@ -124,6 +127,32 @@ fn spawn_scheduler(tx: tokio::sync::mpsc::UnboundedSender) { }); } +/// Starts the publication reconciler. Without a store every own public +/// card is revoked (see `publication::reconcile`). +fn spawn_publication( + runtime: &Runtime, + store: Option>, + confirmations: Arc, +) -> Reconciler { + let tx = runtime.event_tx.clone(); + publication::spawn( + runtime.federation.podcast_dht(), + store, + confirmations, + move |report| { + let _ = tx.send(AppEvent::PodcastPublication(report)); + }, + ) +} + +/// Asks the publication reconciler for a pass (share decisions, feed +/// metadata or subscriptions changed). +fn wake_publication(runtime: &Runtime) { + if let Some(podcasts) = &runtime.podcasts { + podcasts.publication.wake(); + } +} + fn services(runtime: &Runtime) -> Option { runtime .podcasts @@ -143,6 +172,11 @@ pub fn perform(state: &mut AppState, runtime: &mut Runtime, effect: Effect) -> O if matches!(effect, Effect::PodcastSubscribe(_)) { state.podcasts.subscribing = false; } + if let Effect::PodcastPrepareShare { podcast_id, .. } + | Effect::PodcastSetShared { podcast_id, .. } = &effect + { + state.podcasts.share_busy.remove(podcast_id); + } state.status_message = Some("podcasts are unavailable (see the Podcasts tab)".into()); return None; } @@ -213,6 +247,13 @@ pub fn perform(state: &mut AppState, runtime: &mut Runtime, effect: Effect) -> O .log .record(&mut |stamps| store.unsubscribe(stamps, &id)) .map_err(err_string); + // Unsubscribing also revoked the share decision: sharing + // after subscribing again asks again. + if result.is_ok() + && let Err(err) = services.confirmations.forget(&podcast_id) + { + tracing::warn!("podcast share confirmation not removed: {err:#}"); + } let _ = tx.send(AppEvent::PodcastUnsubscribed { podcast_id, title, @@ -235,11 +276,63 @@ pub fn perform(state: &mut AppState, runtime: &mut Runtime, effect: Effect) -> O } } } + Effect::PodcastPrepareShare { podcast_id, title } => { + tokio::task::spawn_blocking(move || { + let result = + publication::check_share(&services.store, &services.confirmations, &podcast_id) + .map_err(err_string); + let _ = tx.send(AppEvent::PodcastSharePrepared { + podcast_id, + title, + result, + }); + }); + } + Effect::PodcastSetShared { + podcast_id, + title, + shared, + confirm, + } => { + tokio::task::spawn_blocking(move || { + let result = + set_shared(&services, &podcast_id, shared, confirm).map_err(err_string); + let _ = tx.send(AppEvent::PodcastShareSet { + podcast_id, + title, + shared, + result, + }); + }); + } + Effect::PodcastPublicationSync => wake_publication(runtime), other => return Some(other), } None } +/// Writes a share decision. The local confirmation is recorded before the +/// synced decision, so the reconciler pass the decision triggers already +/// sees it; turning sharing off forgets it. Blocking. +fn set_shared( + services: &Services, + podcast_id: &music_dht::podcast::PodcastId, + shared: bool, + confirm: Option, +) -> anyhow::Result<()> { + if let Some(urls) = confirm { + services.confirmations.confirm(podcast_id, urls)?; + } + let store = Arc::clone(&services.store); + services + .log + .record(&mut |stamps| store.set_shared(stamps, podcast_id, shared))?; + if !shared { + services.confirmations.forget(podcast_id)?; + } + Ok(()) +} + fn is_podcast_effect(effect: &Effect) -> bool { matches!( effect, @@ -250,6 +343,9 @@ fn is_podcast_effect(effect: &Effect) -> bool { | Effect::PodcastRefresh { .. } | Effect::PodcastUnsubscribe { .. } | Effect::PodcastSetPlayed { .. } + | Effect::PodcastPrepareShare { .. } + | Effect::PodcastSetShared { .. } + | Effect::PodcastPublicationSync ) } @@ -274,6 +370,11 @@ pub fn handle_event( ) -> Option { let effects: Vec = match event { AppEvent::PodcastStoreOpened(result) => { + if result.is_err() { + // This device can no longer tell what is shared: revoke its + // own public cards (fail-safe for privacy). + let _ = spawn_publication(runtime, None, Arc::new(ShareConfirmations::in_memory())); + } let result = result.map(|services| { let tx = runtime.event_tx.clone(); let progress = ProgressWriter::spawn(services.clone(), move |event| { @@ -291,10 +392,16 @@ pub fn handle_event( tracing::warn!("podcast sync: {err:#}"); } }); + let publication = spawn_publication( + runtime, + Some(Arc::clone(&services.store)), + Arc::clone(&services.confirmations), + ); runtime.podcasts = Some(PodcastRuntime { services, refresh_slots: Arc::new(tokio::sync::Semaphore::new(MAX_CONCURRENT_REFRESHES)), progress, + publication, }); spawn_scheduler(runtime.event_tx.clone()); }); @@ -323,17 +430,52 @@ pub fn handle_event( podcast_id, result, manual, - } => podcasts::refreshed(state, podcast_id, result, manual), + } => { + // The card of a shared podcast follows its feed metadata. + if result.is_ok() { + wake_publication(runtime); + } + podcasts::refreshed(state, podcast_id, result, manual) + } AppEvent::PodcastUnsubscribed { podcast_id, title, result, - } => podcasts::unsubscribed(state, podcast_id, title, result) + } => { + // Unsubscribing revokes this device's card. + wake_publication(runtime); + podcasts::unsubscribed(state, podcast_id, title, result) + .into_iter() + .collect() + } + AppEvent::PodcastSharePrepared { + podcast_id, + title, + result, + } => podcasts::share_prepared(state, podcast_id, title, result) .into_iter() .collect(), + AppEvent::PodcastShareSet { + podcast_id, + title, + shared, + result, + } => { + wake_publication(runtime); + podcasts::share_set(state, podcast_id, title, shared, result) + .into_iter() + .collect() + } + AppEvent::PodcastPublication(report) => { + podcasts::publication_reported(state, report); + Vec::new() + } AppEvent::PodcastProgress(event) => progress_event(state, runtime, event), AppEvent::PodcastsSynced { progress, changed } => { if changed { + // Share or subscription decisions of another device: publish + // or revoke this device's own cards accordingly. + wake_publication(runtime); // A subscription that came from another device has no // episodes here until its feed is fetched: check now. let _ = runtime.event_tx.send(AppEvent::PodcastRefreshTick); diff --git a/src/app/popup.rs b/src/app/popup.rs index 4bba6e9..c015a8b 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::ConfirmPodcastShare { .. } => { + if let Some(effect) = + crate::app::update::podcasts::share_confirmation_key(state, popup, key.code) + { + super::perform_effect(state, runtime, effect); + } + } Popup::SimilarityPrivacyConsent { enable_federation } => match key.code { KeyCode::Enter | KeyCode::Char('y') => { state.similarity.settings.federation_consent = true; diff --git a/src/app/state.rs b/src/app/state.rs index 37c14dc..7eceb6a 100644 --- a/src/app/state.rs +++ b/src/app/state.rs @@ -768,6 +768,18 @@ pub enum Popup { podcast_id: music_dht::podcast::PodcastId, title: String, }, + /// Sharing a podcast whose feed URL looks private: the user confirms + /// publishing exactly `urls`. Enter/y publishes, Esc/n cancels; when the + /// podcast is already shared (publication held back on this device), + /// `x` turns sharing off. + ConfirmPodcastShare { + podcast_id: music_dht::podcast::PodcastId, + title: String, + urls: crate::podcasts::publication::ConfirmedUrls, + /// Russian descriptions of the privacy warnings. + warnings: Vec, + already_shared: bool, + }, /// Enabling network similarity reveals an embedding query to peers. SimilarityPrivacyConsent { enable_federation: bool }, /// Derived data is safe to recreate but potentially expensive. @@ -1796,6 +1808,10 @@ pub struct PodcastsTab { pub pending_select: Option, /// Last episode request sequence handed out. pub episode_seq: u64, + /// This device's public discovery publications (last reconciler pass). + pub publication: crate::podcasts::publication::PublicationReport, + /// A share check or share decision is being written. + pub share_busy: HashSet, } impl PodcastsTab { diff --git a/src/app/update.rs b/src/app/update.rs index 6fc379e..f337303 100644 --- a/src/app/update.rs +++ b/src/app/update.rs @@ -136,6 +136,23 @@ pub enum Effect { episode_id: music_dht::podcast::EpisodeId, played: bool, }, + /// Check what sharing a podcast would publish (privacy warnings) before + /// turning sharing on or confirming a held-back publication. + PodcastPrepareShare { + podcast_id: music_dht::podcast::PodcastId, + title: String, + }, + /// Turn sharing on or off (synced decision). `confirm` records, on this + /// device only, that the user confirmed publishing these feed URLs + /// despite privacy warnings. + PodcastSetShared { + podcast_id: music_dht::podcast::PodcastId, + title: String, + shared: bool, + confirm: Option, + }, + /// Reconcile this device's public podcast cards now. + PodcastPublicationSync, } pub fn update(state: &mut AppState, action: Action) -> Option { @@ -541,7 +558,8 @@ pub fn update(state: &mut AppState, action: Action) -> Option { | Action::CycleEpisodeSort | Action::CycleEpisodeFilter | Action::ToggleEpisodePlayed - | Action::UnsubscribePodcast => { + | Action::UnsubscribePodcast + | Action::TogglePodcastShare => { state.status_message = Some(format!( "open the Podcasts tab ({}) for this command", Tab::Podcasts.index() + 1 diff --git a/src/app/update/podcasts.rs b/src/app/update/podcasts.rs index 7679718..fe9ca17 100644 --- a/src/app/update/podcasts.rs +++ b/src/app/update/podcasts.rs @@ -18,6 +18,7 @@ use crate::app::state::{ PODCAST_EPISODE_PAGE, PodcastListRow, PodcastRow, PodcastStoreStatus, Popup, SeasonRow, Tab, }; use crate::library::models::TrackItem; +use crate::podcasts::publication::{Publication, PublicationReport, ShareCheck, warning_ru}; use crate::podcasts::refresh::{RefreshReport, SubscribeReport}; /// The next page starts loading when the cursor is this close to the end. @@ -59,6 +60,7 @@ pub(super) fn handle(state: &mut AppState, action: &Action) -> Option cycle_played_filter(state), Action::ToggleEpisodePlayed => toggle_played(state), Action::RestartEpisode => restart_selected(state), + Action::TogglePodcastShare => toggle_share(state), _ => return None, }; Some(effect) @@ -616,6 +618,222 @@ fn confirm_unsubscribe(state: &mut AppState) { }); } +/// Shift-F: share the selected or opened podcast in the federation, or stop +/// sharing it. +/// +/// Turning sharing on first checks the card it would publish +/// ([`Effect::PodcastPrepareShare`]); a feed URL that looks private asks for +/// confirmation in [`Popup::ConfirmPodcastShare`] ([`share_prepared`]). +/// A shared podcast whose publication is held back on this device (the URL +/// changed or was shared from another device) asks again instead of turning +/// sharing off; the dialog can still turn it off. +fn toggle_share(state: &mut AppState) -> Option { + if !store_ready(state) { + return None; + } + let Some(row) = state.podcasts.current_podcast() else { + state.status_message = Some("podcasts: select a podcast to share".into()); + return None; + }; + let podcast_id = row.id().clone(); + let title = row.title().to_string(); + let shared = row.summary.shared; + if state.podcasts.share_busy.contains(&podcast_id) { + state.status_message = Some("podcasts: still saving the share setting".into()); + return None; + } + let held = matches!( + state.podcasts.publication.podcasts.get(&podcast_id), + Some(Publication::HeldBack(_)) + ); + state.podcasts.share_busy.insert(podcast_id.clone()); + if shared && !held { + state.status_message = Some(format!( + "podcasts: stopping sharing {}…", + display_title(&title) + )); + return Some(Effect::PodcastSetShared { + podcast_id, + title, + shared: false, + confirm: None, + }); + } + Some(Effect::PodcastPrepareShare { podcast_id, title }) +} + +/// The card check of [`toggle_share`] arrived: share right away, or ask +/// about the privacy warnings first. +pub fn share_prepared( + state: &mut AppState, + podcast_id: PodcastId, + title: String, + result: Result, +) -> Option { + let check = match result { + Ok(check) => check, + Err(err) => { + state.podcasts.share_busy.remove(&podcast_id); + state.status_message = Some(format!("podcasts: cannot share: {err}")); + return None; + } + }; + let already_shared = state + .podcasts + .podcast(&podcast_id) + .is_some_and(|row| row.summary.shared); + if check.needs_confirmation() || (already_shared && !check.warnings.is_empty()) { + // Wait for the user; nothing is written until they confirm. + state.podcasts.share_busy.remove(&podcast_id); + state.popup = Some(Popup::ConfirmPodcastShare { + podcast_id, + title, + urls: check.urls, + warnings: check.warnings.iter().map(warning_ru).collect(), + already_shared, + }); + return None; + } + if already_shared { + // Held back without warnings any more: the next pass publishes it. + state.podcasts.share_busy.remove(&podcast_id); + state.status_message = Some(format!( + "podcasts: {} is shared; publishing…", + display_title(&title) + )); + return Some(Effect::PodcastPublicationSync); + } + state.status_message = Some(format!("podcasts: sharing {}…", display_title(&title))); + Some(Effect::PodcastSetShared { + podcast_id, + title, + shared: true, + // Already confirmed earlier for exactly these URLs (or no warning). + confirm: None, + }) +} + +/// A key in [`Popup::ConfirmPodcastShare`]: Enter/y publishes exactly the +/// URLs shown (and remembers that confirmation on this device), `x` stops +/// sharing a podcast that is already shared, Esc/n/q cancels (nothing is +/// written). Other keys keep the dialog open. +pub fn share_confirmation_key( + state: &mut AppState, + popup: Popup, + code: crossterm::event::KeyCode, +) -> Option { + use crossterm::event::KeyCode; + let Popup::ConfirmPodcastShare { + podcast_id, + title, + urls, + warnings, + already_shared, + } = popup + else { + state.popup = Some(popup); + return None; + }; + match code { + KeyCode::Enter | KeyCode::Char('y') => { + state.podcasts.share_busy.insert(podcast_id.clone()); + state.status_message = Some(format!("podcasts: sharing {}…", display_title(&title))); + Some(Effect::PodcastSetShared { + podcast_id, + title, + shared: true, + confirm: Some(urls), + }) + } + KeyCode::Char('x') if already_shared => { + state.podcasts.share_busy.insert(podcast_id.clone()); + state.status_message = Some(format!( + "podcasts: stopping sharing {}…", + display_title(&title) + )); + Some(Effect::PodcastSetShared { + podcast_id, + title, + shared: false, + confirm: None, + }) + } + KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('q') => { + state.status_message = Some(if already_shared { + "podcasts: not published from this device until you confirm".into() + } else { + "podcasts: the podcast stays private".into() + }); + None + } + _ => { + state.popup = Some(Popup::ConfirmPodcastShare { + podcast_id, + title, + urls, + warnings, + already_shared, + }); + None + } + } +} + +/// The share decision was written; the reconciler publishes or revokes. +pub fn share_set( + state: &mut AppState, + podcast_id: PodcastId, + title: String, + shared: bool, + result: Result<(), String>, +) -> Option { + state.podcasts.share_busy.remove(&podcast_id); + let title = display_title(&title); + match result { + Ok(()) if shared => { + state.status_message = Some(format!( + "podcasts: {title} is shared in the federation (publishing from this device)" + )); + Some(Effect::PodcastsReload) + } + Ok(()) => { + state.podcasts.publication.podcasts.remove(&podcast_id); + state.status_message = Some(format!( + "podcasts: {title} is private again; the public card is being revoked" + )); + Some(Effect::PodcastsReload) + } + Err(err) => { + state.status_message = Some(format!("podcasts: cannot change sharing: {err}")); + None + } + } +} + +/// A publication reconciler pass finished. Errors go to the status bar +/// when they are new (the log has them too). +pub fn publication_reported(state: &mut AppState, report: PublicationReport) { + let previous = std::mem::replace(&mut state.podcasts.publication, report); + let report = &state.podcasts.publication; + if let Some(error) = &report.error + && previous.error.as_ref() != Some(error) + { + state.status_message = Some(format!("podcasts: public discovery: {error}")); + } + for (podcast_id, publication) in &report.podcasts { + if let Publication::Failed(error) = publication + && previous.podcasts.get(podcast_id) != Some(publication) + { + let title = state + .podcasts + .podcast(podcast_id) + .map(|row| display_title(row.title())) + .unwrap_or_else(|| "a shared podcast".to_string()); + state.status_message = Some(format!("podcasts: cannot publish {title}: {error}")); + } + } +} + fn refresh_targets(state: &mut AppState, rows: Vec<&PodcastRow>) -> Vec<(PodcastId, FeedUrl)> { rows.into_iter() .filter(|row| !state.podcasts.refreshing.contains(row.id())) diff --git a/src/app/update_tests.rs b/src/app/update_tests.rs index 59812d2..98c6f4c 100644 --- a/src/app/update_tests.rs +++ b/src/app/update_tests.rs @@ -1834,6 +1834,311 @@ mod podcast_tab { Some(Effect::PodcastLoadEpisodes { .. }) )); } + + // --- Sharing in the federation (MR-T3) --- + + use crate::podcasts::publication::{ + ConfirmedUrls, Discovery, Publication, PublicationReport, ShareCheck, + }; + use crossterm::event::KeyCode; + + fn urls() -> ConfirmedUrls { + ConfirmedUrls { + feed_url: FeedUrl::parse("https://example.test/feed.xml").unwrap(), + id_feed_url: None, + } + } + + fn check(warnings: bool, confirmed: bool) -> ShareCheck { + ShareCheck { + urls: urls(), + warnings: if warnings { + vec![ + music_dht::podcast_dht::FeedUrlPrivacyWarning::SecretQueryParameter { + name: "token".into(), + }, + ] + } else { + Vec::new() + }, + confirmed, + } + } + + fn set_shared(shared: bool, confirm: Option) -> Option { + Some(Effect::PodcastSetShared { + podcast_id: podcast_id(), + title: "Show".into(), + shared, + confirm, + }) + } + + fn shared_row() -> crate::app::state::PodcastRow { + let mut row = fx::row("Show", 0, 1, 0); + row.summary.shared = true; + row + } + + #[test] + fn sharing_a_podcast_checks_its_card_first_and_shares_without_warnings() { + let mut state = ready(vec![fx::row("Show", 0, 1, 0)]); + assert_eq!( + update(&mut state, Action::TogglePodcastShare), + Some(Effect::PodcastPrepareShare { + podcast_id: podcast_id(), + title: "Show".into(), + }) + ); + // A second press while the check runs does nothing. + assert_eq!(update(&mut state, Action::TogglePodcastShare), None); + let effect = podcasts::share_prepared( + &mut state, + podcast_id(), + "Show".into(), + Ok(check(false, false)), + ); + assert_eq!(effect, set_shared(true, None)); + assert!(state.popup.is_none()); + // Also inside the opened podcast. + 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))); + assert!(matches!( + update(&mut state, Action::TogglePodcastShare), + Some(Effect::PodcastPrepareShare { .. }) + )); + // Already confirmed for exactly these URLs: no dialog. + let effect = podcasts::share_prepared( + &mut state, + podcast_id(), + "Show".into(), + Ok(check(true, true)), + ); + assert_eq!(effect, set_shared(true, None)); + } + + #[test] + fn a_private_looking_feed_url_is_shared_only_after_confirmation() { + let mut state = ready(vec![fx::row("Show", 0, 1, 0)]); + update(&mut state, Action::TogglePodcastShare); + let effect = podcasts::share_prepared( + &mut state, + podcast_id(), + "Show".into(), + Ok(check(true, false)), + ); + assert_eq!(effect, None, "nothing is written before the user confirms"); + let Some(Popup::ConfirmPodcastShare { + warnings, + already_shared, + urls: shown, + .. + }) = &state.popup + else { + panic!("expected the share confirmation, got {:?}", state.popup); + }; + assert_eq!( + warnings, + &vec!["в адресе ленты есть параметр «token», похожий на ключ доступа".to_string()] + ); + assert!(!already_shared); + assert_eq!(shown, &urls()); + assert!(state.podcasts.share_busy.is_empty()); + + // Esc keeps the podcast private; other keys keep the dialog. + let popup = state.popup.take().unwrap(); + assert_eq!( + podcasts::share_confirmation_key(&mut state, popup, KeyCode::Char('j')), + None + ); + assert!(state.popup.is_some()); + let popup = state.popup.take().unwrap(); + assert_eq!( + podcasts::share_confirmation_key(&mut state, popup, KeyCode::Char('x')), + None + ); + assert!(state.popup.is_some(), "x only stops an existing share"); + let popup = state.popup.take().unwrap(); + assert_eq!( + podcasts::share_confirmation_key(&mut state, popup, KeyCode::Esc), + None + ); + assert!(state.popup.is_none()); + assert!( + state + .status_message + .as_deref() + .is_some_and(|m| m.contains("stays private")) + ); + + // Enter confirms exactly the URLs shown. + update(&mut state, Action::TogglePodcastShare); + podcasts::share_prepared( + &mut state, + podcast_id(), + "Show".into(), + Ok(check(true, false)), + ); + let popup = state.popup.take().unwrap(); + assert_eq!( + podcasts::share_confirmation_key(&mut state, popup, KeyCode::Enter), + set_shared(true, Some(urls())) + ); + assert!(state.podcasts.share_busy.contains(&podcast_id())); + assert_eq!( + podcasts::share_set(&mut state, podcast_id(), "Show".into(), true, Ok(())), + Some(Effect::PodcastsReload) + ); + assert!(state.podcasts.share_busy.is_empty()); + } + + #[test] + fn stopping_sharing_needs_no_dialog_and_a_held_publication_asks_again() { + let mut state = ready(vec![shared_row()]); + assert_eq!( + update(&mut state, Action::TogglePodcastShare), + set_shared(false, None) + ); + state + .podcasts + .publication + .podcasts + .insert(podcast_id(), Publication::Published); + let effect = podcasts::share_set(&mut state, podcast_id(), "Show".into(), false, Ok(())); + assert_eq!(effect, Some(Effect::PodcastsReload)); + assert!(state.podcasts.publication.podcasts.is_empty()); + assert!( + state + .status_message + .as_deref() + .is_some_and(|m| m.contains("private again")) + ); + + // Shared (for example from another device) but held back here: the + // key asks for this device's confirmation instead of unsharing. + let mut state = ready(vec![shared_row()]); + state.podcasts.publication.podcasts.insert( + podcast_id(), + Publication::HeldBack(check(true, false).warnings), + ); + assert!(matches!( + update(&mut state, Action::TogglePodcastShare), + Some(Effect::PodcastPrepareShare { .. }) + )); + podcasts::share_prepared( + &mut state, + podcast_id(), + "Show".into(), + Ok(check(true, false)), + ); + assert!(matches!( + &state.popup, + Some(Popup::ConfirmPodcastShare { + already_shared: true, + .. + }) + )); + let popup = state.popup.take().unwrap(); + assert_eq!( + podcasts::share_confirmation_key(&mut state, popup, KeyCode::Char('x')), + set_shared(false, None) + ); + // Or confirms it (sharing is already on; the confirmation is new). + state.podcasts.share_busy.clear(); + podcasts::share_prepared( + &mut state, + podcast_id(), + "Show".into(), + Ok(check(true, false)), + ); + let popup = state.popup.take().unwrap(); + assert_eq!( + podcasts::share_confirmation_key(&mut state, popup, KeyCode::Char('y')), + set_shared(true, Some(urls())) + ); + // Held without warnings any more: just reconcile again. + state.podcasts.share_busy.clear(); + assert_eq!( + podcasts::share_prepared( + &mut state, + podcast_id(), + "Show".into(), + Ok(check(false, false)) + ), + Some(Effect::PodcastPublicationSync) + ); + } + + #[test] + fn share_errors_and_publication_failures_are_shown() { + let mut state = ready(vec![fx::row("Show", 0, 1, 0)]); + update(&mut state, Action::TogglePodcastShare); + assert_eq!( + podcasts::share_prepared(&mut state, podcast_id(), "Show".into(), Err("boom".into())), + None + ); + assert!(state.podcasts.share_busy.is_empty()); + assert!( + state + .status_message + .as_deref() + .is_some_and(|m| m.contains("cannot share: boom")) + ); + assert_eq!( + podcasts::share_set( + &mut state, + podcast_id(), + "Show".into(), + true, + Err("db".into()) + ), + None + ); + assert!( + state + .status_message + .as_deref() + .is_some_and(|m| m.contains("cannot change sharing: db")) + ); + + state.status_message = None; + let mut report = PublicationReport { + discovery: Discovery::Running { peers: 3 }, + ..PublicationReport::default() + }; + report + .podcasts + .insert(podcast_id(), Publication::Failed("signing failed".into())); + podcasts::publication_reported(&mut state, report.clone()); + assert!( + state + .status_message + .as_deref() + .is_some_and(|m| m.contains("cannot publish \"Show\": signing failed")) + ); + // The same failure again is not repeated in the status bar. + state.status_message = None; + podcasts::publication_reported(&mut state, report); + assert_eq!(state.status_message, None); + assert_eq!( + state.podcasts.publication.discovery, + Discovery::Running { peers: 3 } + ); + } + + #[test] + fn share_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::TogglePodcastShare), None); + assert!(state.podcasts.share_busy.is_empty()); + let mut opening = AppState { + active_tab: Tab::Podcasts, + ..AppState::default() + }; + assert_eq!(update(&mut opening, Action::TogglePodcastShare), None); + } } /// Podcast episodes in the shared queue: identity by episode id (never the diff --git a/src/config/default_keymap.toml b/src/config/default_keymap.toml index 3935b3b..d544b68 100644 --- a/src/config/default_keymap.toml +++ b/src/config/default_keymap.toml @@ -319,3 +319,8 @@ context = "podcasts" key_sequence = "b" command = "RestartEpisode" context = "podcasts" + +[[keymaps]] +key_sequence = "shift-f" +command = "TogglePodcastShare" +context = "podcasts" diff --git a/src/config/keymap.rs b/src/config/keymap.rs index c6e6fe4..569bcc9 100644 --- a/src/config/keymap.rs +++ b/src/config/keymap.rs @@ -904,6 +904,7 @@ mod tests { (key!(m), Action::ToggleEpisodePlayed), (shift('U'), Action::UnsubscribePodcast), (key!(b), Action::RestartEpisode), + (shift('F'), Action::TogglePodcastShare), ]; for (key, action) in cases { assert_eq!( diff --git a/src/ui/mod.rs b/src/ui/mod.rs index 96777cb..5e2a278 100644 --- a/src/ui/mod.rs +++ b/src/ui/mod.rs @@ -181,6 +181,74 @@ mod tests { } } + #[test] + fn podcast_share_state_is_shown_in_the_list_and_details() { + use crate::podcasts::publication::{Discovery, Publication}; + let mut state = + podcast_fixtures::ready_state(vec![podcast_fixtures::row("Test Show", 0, 3, 0)]); + state.podcasts.selected = crate::app::state::PODCAST_ACTION_ROWS; + let screen = render(&state, 110, 30); + assert!(screen.contains("private (not shared"), "{screen}"); + assert!(!screen.contains("shared · 3 ep"), "{screen}"); + + let mut row = podcast_fixtures::row("Test Show", 0, 3, 0); + row.summary.shared = true; + let mut state = podcast_fixtures::ready_state(vec![row]); + state.podcasts.selected = crate::app::state::PODCAST_ACTION_ROWS; + state.podcasts.publication.discovery = Discovery::Running { peers: 2 }; + state + .podcasts + .publication + .podcasts + .insert(podcast_fixtures::podcast_id(), Publication::Published); + let screen = render(&state, 110, 30); + assert!(screen.contains("shared · 3 ep"), "{screen}"); + assert!(screen.contains("shared · published from"), "{screen}"); + + state.podcasts.publication.podcasts.insert( + podcast_fixtures::podcast_id(), + Publication::HeldBack(Vec::new()), + ); + let screen = render(&state, 110, 30); + assert!(screen.contains("held back"), "{screen}"); + + state.podcasts.publication.discovery = Discovery::Off("federation is off".into()); + let screen = render(&state, 110, 30); + assert!(screen.contains("not published:"), "{screen}"); + } + + #[test] + fn podcast_share_confirmation_lists_the_warnings_in_russian() { + let mut state = + podcast_fixtures::ready_state(vec![podcast_fixtures::row("Test Show", 0, 1, 0)]); + state.popup = Some(crate::app::state::Popup::ConfirmPodcastShare { + podcast_id: podcast_fixtures::podcast_id(), + title: "Test Show".into(), + urls: crate::podcasts::publication::ConfirmedUrls { + feed_url: music_dht::podcast::FeedUrl::parse( + "https://example.test/feed.xml?token=abc", + ) + .unwrap(), + id_feed_url: None, + }, + warnings: vec!["в адресе ленты есть параметр «token», похожий на ключ доступа".into()], + already_shared: false, + }); + let screen = render(&state, 100, 30); + assert!( + screen.contains("Поделиться подкастом «Test Show»"), + "{screen}" + ); + assert!(screen.contains("Адрес похож на личный"), "{screen}"); + assert!(screen.contains("параметр «token»"), "{screen}"); + assert!(screen.contains("feed.xml?token=abc"), "{screen}"); + assert!( + screen.contains("enter/y опубликовать · esc/n отмена"), + "{screen}" + ); + assert!(!screen.contains("x не делиться"), "{screen}"); + } + #[test] fn podcast_seasons_and_episodes_render_progress() { use music_dht::podcast::ProgressStatus; diff --git a/src/ui/podcasts.rs b/src/ui/podcasts.rs index c7e6cff..11079ca 100644 --- a/src/ui/podcasts.rs +++ b/src/ui/podcasts.rs @@ -17,6 +17,7 @@ use crate::app::state::{ PodcastStoreStatus, SeasonRow, }; use crate::app::update::podcasts::{played_label, sort_label}; +use crate::podcasts::publication::{Discovery, Publication}; /// Width below which the side panel with the cover is dropped. const SIDE_PANEL_MIN_TOTAL_WIDTH: u16 = 80; @@ -219,7 +220,7 @@ fn list_row(state: &AppState, row: PodcastListRow, width: u16) -> (Line<'static> Span::raw(" ") }; let summary = &podcast.summary; - let meta = if summary.unplayed_count > 0 { + let mut meta = if summary.unplayed_count > 0 { format!( "{} unplayed · {} ep", summary.unplayed_count, summary.episode_count @@ -227,6 +228,9 @@ fn list_row(state: &AppState, row: PodcastListRow, width: u16) -> (Line<'static> } else { format!("{} ep", summary.episode_count) }; + if summary.shared { + meta = format!("shared · {meta}"); + } let title_width = usize::from(width).saturating_sub(2 + meta.width() + 2); let left = Line::from(vec![ marker, @@ -293,7 +297,7 @@ fn draw_side_panel(frame: &mut Frame, area: Rect, state: &AppState, podcast: Opt counts.push_str(&format!(" · {} seasons", summary.season_count)); } lines.push(Line::styled(counts, theme::dim())); - lines.push(Line::styled("private", theme::dim())); + lines.push(share_status_line(state, podcast)); lines.push(fetch_status_line(state, podcast)); if let Some(description) = &summary.meta.description { lines.push(Line::raw("")); @@ -302,6 +306,43 @@ fn draw_side_panel(frame: &mut Frame, area: Rect, state: &AppState, podcast: Opt frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: true }), text_area); } +/// Public discovery state of one podcast: private, or shared and whether +/// this device publishes its card. +pub(crate) fn share_status_line(state: &AppState, podcast: &PodcastRow) -> Line<'static> { + let tab = &state.podcasts; + if tab.share_busy.contains(podcast.id()) { + return loading_line(state, "saving the share setting…"); + } + if !podcast.summary.shared { + return Line::styled("private (not shared in the federation)", theme::dim()); + } + let report = &tab.publication; + let (text, style) = match (&report.discovery, report.podcasts.get(podcast.id())) { + (Discovery::Off(reason), _) => (format!("shared · not published: {reason}"), theme::dim()), + (_, Some(Publication::HeldBack(_))) => ( + "shared · held back on this device: the feed URL looks private, \ + press Shift+F to confirm" + .to_string(), + Style::new().fg(Color::Yellow), + ), + (_, Some(Publication::Failed(error))) => { + (format!("shared · not published: {error}"), error_style()) + } + (Discovery::Running { peers: 0 }, Some(Publication::Published)) => ( + "shared · published from this device (no discovery peers yet)".to_string(), + theme::accent_for(state), + ), + (_, Some(Publication::Published)) => ( + "shared · published from this device".to_string(), + theme::accent_for(state), + ), + (Discovery::Starting, _) | (_, Some(Publication::Pending) | None) => { + return loading_line(state, "shared · publishing…"); + } + }; + Line::styled(text, style) +} + /// 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> { diff --git a/src/ui/popup.rs b/src/ui/popup.rs index f4a779a..2465af6 100644 --- a/src/ui/popup.rs +++ b/src/ui/popup.rs @@ -28,6 +28,13 @@ pub fn draw(frame: &mut Frame, state: &AppState) { Some(Popup::ConfirmPodcastUnsubscribe { title, .. }) => { draw_confirm_podcast_unsubscribe(frame, state, title) } + Some(Popup::ConfirmPodcastShare { + title, + urls, + warnings, + already_shared, + .. + }) => draw_confirm_podcast_share(frame, state, title, urls, warnings, *already_shared), Some(Popup::SimilarityPrivacyConsent { .. }) => { draw_similarity_privacy_consent(frame, state) } @@ -1318,6 +1325,87 @@ fn draw_confirm_podcast_unsubscribe(frame: &mut Frame, state: &AppState, title: ); } +/// Sharing a podcast whose feed URL looks private. In Russian: the warning +/// is about the user's own secret, so it must not be missed. +fn draw_confirm_podcast_share( + frame: &mut Frame, + state: &AppState, + title: &str, + urls: &crate::podcasts::publication::ConfirmedUrls, + warnings: &[String], + already_shared: bool, +) { + let width = 78.min(frame.area().width.saturating_sub(4)).max(30); + let mut lines = vec![ + Line::styled( + format!("Поделиться подкастом «{title}» в федерации?"), + ratatui::style::Style::new().add_modifier(ratatui::style::Modifier::BOLD), + ), + Line::raw(""), + Line::raw( + "Карточка с адресом RSS-ленты станет видна всем участникам федерации, \ + и любой из них сможет читать ленту по этому адресу.", + ), + Line::raw(""), + Line::styled( + "Адрес похож на личный:", + ratatui::style::Style::new().fg(ratatui::style::Color::Yellow), + ), + ]; + lines.extend(warnings.iter().map(|warning| { + Line::styled( + format!("• {warning}"), + ratatui::style::Style::new().fg(ratatui::style::Color::Yellow), + ) + })); + lines.push(Line::raw("")); + lines.push(Line::styled( + format!("Лента: {}", urls.feed_url.as_str()), + theme::dim(), + )); + if let Some(origin) = &urls.id_feed_url { + lines.push(Line::styled( + format!("Исходный адрес: {}", origin.as_str()), + theme::dim(), + )); + } + lines.push(Line::raw("")); + lines.push(Line::styled( + "Публикацию можно отозвать, но копии, которые уже получили другие, \ + отозвать нельзя. Подтверждение хранится только на этом устройстве.", + theme::dim(), + )); + let footer = if already_shared { + "enter/y опубликовать · x не делиться · esc/n отмена" + } else { + "enter/y опубликовать · esc/n отмена" + }; + let inner_width = width.saturating_sub(2).max(1); + let body_height = lines + .iter() + .map(|line| { + let text_width = line.width().max(1) as u16; + text_width.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); + frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), body); + frame.render_widget( + Paragraph::new(Line::styled(footer, theme::dim())).alignment(Alignment::Center), + footer_area, + ); +} + 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);