From 588ea4e99e3235e1ad730d4ea85ed60efea578a0 Mon Sep 17 00:00:00 2001 From: Sanapach Date: Thu, 19 Nov 2026 23:12:21 +0200 Subject: [PATCH] Add the podcast share endpoint with privacy confirmation Co-Authored-By: Claude Opus 5.5 --- src/podcasts/api.rs | 209 ++++++++++++++++++++++++++++++++- src/podcasts/http.rs | 81 ++++++++++++- src/podcasts/postgres_tests.rs | 19 +-- 3 files changed, 298 insertions(+), 11 deletions(-) diff --git a/src/podcasts/api.rs b/src/podcasts/api.rs index 1251599..7b90b10 100644 --- a/src/podcasts/api.rs +++ b/src/podcasts/api.rs @@ -24,6 +24,7 @@ use music_dht::podcast::{ EpisodeId, EpisodeType, FeedUrl, ListenSession, PodcastEpisodeRef, PodcastId, PodcastMeta, ProgressRecord, ProgressStatus, reaches_completion, }; +use music_dht::podcast_dht::{FeedUrlPrivacyWarning, PodcastDht}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -162,7 +163,8 @@ pub(crate) struct PodcastView { pub(crate) link: Option, pub(crate) image_url: Option, pub(crate) subscribed: bool, - /// `effective_share` (publication is MR-W3; shown read-only). + /// The account's synced share decision applies (`effective_share`). + /// Whether the card is actually published is [`ShareView`]. pub(crate) shared: bool, pub(crate) episode_count: u64, pub(crate) unplayed_count: u64, @@ -376,18 +378,23 @@ pub(crate) struct HistoryView { #[derive(Debug, Serialize)] pub(crate) struct PodcastDetail { pub(crate) podcast: PodcastView, + /// Public discovery state of the podcast for this account. + pub(crate) share: ShareView, pub(crate) seasons: Vec, /// Newest listening sessions of this podcast, from every device. pub(crate) history: Vec, } -/// One podcast with its season groups. +/// One podcast with its season groups and its public discovery state +/// (`discovery`: the server's overlay, when it runs). pub(crate) async fn podcast_detail( store: &PodcastStore, user_id: i64, podcast_id: &PodcastId, + discovery: Option<&PodcastDht>, ) -> ApiResult { let podcast = podcast_view(store, user_id, podcast_id).await?; + let share = share_view(store, user_id, podcast_id, discovery).await?; let seasons = store .seasons(user_id, podcast_id) .await? @@ -409,6 +416,7 @@ pub(crate) async fn podcast_detail( .collect(); Ok(PodcastDetail { podcast, + share, seasons, history, }) @@ -476,6 +484,203 @@ pub(crate) async fn unsubscribe( podcast_view(store, user_id, podcast_id).await } +// --------------------------------------------------------------------------- +// Sharing (public discovery) +// --------------------------------------------------------------------------- + +/// Public discovery state of one podcast for the signed-in account. +/// +/// Sharing is the account's synced decision; the card is published by the +/// server's federation node (see [`super::discovery`]) and contains only +/// the podcast's public metadata. +#[derive(Debug, Clone, Serialize)] +pub(crate) struct ShareView { + /// The account's share decision applies (`effective_share`). + pub(crate) shared: bool, + /// Shared, but the card's privacy warnings are not confirmed by this + /// account for the current decision and URLs: not published for it. + pub(crate) pending_confirmation: bool, + /// Whether the account can share the podcast now (subscribed and the + /// card can be built). + pub(crate) can_share: bool, + /// Why the card cannot be built, if it cannot. + pub(crate) card_error: Option, + /// Why the card's feed URLs may be private (`PodcastCardSpec:: + /// privacy_warnings`); enabling sharing must be confirmed when present. + pub(crate) warnings: Vec, + /// Feed URL the card would publish. + pub(crate) feed_url: Option, + /// Origin URL the podcast id comes from, when the feed moved. + pub(crate) id_feed_url: Option, + /// `running` when the server's node runs public discovery, `off` + /// otherwise (federation disabled or the overlay failed to start). + pub(crate) discovery: &'static str, + /// The server currently publishes a card of this podcast and this + /// account shares it. + pub(crate) published: bool, +} + +/// The account's [`ShareView`] of a podcast. +pub(crate) async fn share_view( + store: &PodcastStore, + user_id: i64, + podcast_id: &PodcastId, + discovery: Option<&PodcastDht>, +) -> ApiResult { + let account = store.account_share(user_id, podcast_id).await?; + let mut view = ShareView { + shared: false, + pending_confirmation: false, + can_share: false, + card_error: None, + warnings: Vec::new(), + feed_url: None, + id_feed_url: None, + discovery: if discovery.is_some() { + "running" + } else { + "off" + }, + published: false, + }; + let Some(account) = account else { + return Ok(view); + }; + view.shared = account.is_shared(); + view.pending_confirmation = account.pending_confirmation(); + view.warnings = account.warnings(); + match &account.card { + Ok(card) => { + view.can_share = account.subscription.subscribed; + view.feed_url = Some(card.feed_url.to_string()); + view.id_feed_url = card.id_feed_url.as_ref().map(ToString::to_string); + } + Err(error) => view.card_error = Some(error.clone()), + } + if let Some(dht) = discovery + && account.publishable() + { + view.published = dht + .published() + .await + .map_err(|error| anyhow::anyhow!("podcast publications unavailable: {error}"))? + .iter() + .any(|publication| publication.active && publication.podcast_id == *podcast_id); + } + Ok(view) +} + +/// URLs the user confirmed in the privacy dialog. +#[derive(Debug, Clone, Deserialize)] +pub(crate) struct ShareConfirmRequest { + pub(crate) feed_url: String, + #[serde(default)] + pub(crate) id_feed_url: Option, +} + +#[derive(Debug, Clone, Deserialize)] +struct ShareRequest { + shared: bool, + /// Confirmation of the card's URLs despite its privacy warnings. + #[serde(default)] + confirm: Option, +} + +#[derive(Debug, Serialize)] +pub(crate) struct ShareResponse { + pub(crate) podcast: PodcastView, + pub(crate) share: ShareView, +} + +/// Result of [`set_share`]. +#[derive(Debug)] +pub(crate) enum ShareOutcome { + /// The decision is stored (or was already in place). + Done(Box), + /// The card's feed URLs look private: nothing was written; ask the user + /// and send the shown URLs back as `confirm` (HTTP 409). + NeedsConfirmation(ShareView), +} + +/// "Share in the federation": `{ "shared": bool, "confirm"?: {feed_url, +/// id_feed_url} }`. +/// +/// * Off: writes `shared = false` (no-op when not shared) and forgets the +/// confirmation; the reconciler revokes the card unless another account +/// still shares the podcast. +/// * On: needs an active subscription (409). When the card has privacy +/// warnings, `confirm` must name exactly the card's current URLs; +/// otherwise nothing is written and [`ShareOutcome::NeedsConfirmation`] +/// carries the warnings. A podcast already shared from another device +/// but pending this account's confirmation is confirmed the same way. +pub(crate) async fn set_share( + store: &PodcastStore, + user_id: i64, + podcast_id: &PodcastId, + body: Value, + discovery: Option<&PodcastDht>, + now_ms: i64, +) -> ApiResult { + let request: ShareRequest = decode(body)?; + if store.podcast(user_id, podcast_id).await?.is_none() { + return Err(ApiError::not_found("unknown podcast")); + } + if request.shared { + let Some(account) = store.account_share(user_id, podcast_id).await? else { + return Err( + anyhow::Error::from(PodcastStoreError::NotSubscribed(podcast_id.clone())).into(), + ); + }; + if !account.subscription.subscribed { + return Err( + anyhow::Error::from(PodcastStoreError::NotSubscribed(podcast_id.clone())).into(), + ); + } + if let Err(error) = &account.card { + return Err(ApiError::new( + 422, + format!("this podcast cannot be published: {error}"), + )); + } + if account.warnings().is_empty() { + store.set_shared(user_id, podcast_id, true).await?; + } else { + let confirmed = match &request.confirm { + Some(confirm) => { + let parse = |url: &str| { + FeedUrl::parse(url) + .map_err(|_| ApiError::bad_request("invalid confirmed feed URL")) + }; + let feed_url = parse(&confirm.feed_url)?; + let id_feed_url = confirm.id_feed_url.as_deref().map(parse).transpose()?; + store + .share_confirmed( + user_id, + podcast_id, + &feed_url, + id_feed_url.as_ref(), + now_ms, + ) + .await? + .is_some() + } + None => false, + }; + if !confirmed { + let view = share_view(store, user_id, podcast_id, discovery).await?; + return Ok(ShareOutcome::NeedsConfirmation(view)); + } + } + } else { + store.set_shared(user_id, podcast_id, false).await?; + store.clear_share_confirmation(user_id, podcast_id).await?; + } + Ok(ShareOutcome::Done(Box::new(ShareResponse { + podcast: podcast_view(store, user_id, podcast_id).await?, + share: share_view(store, user_id, podcast_id, discovery).await?, + }))) +} + // --------------------------------------------------------------------------- // Episodes // --------------------------------------------------------------------------- diff --git a/src/podcasts/http.rs b/src/podcasts/http.rs index b57ac46..a464837 100644 --- a/src/podcasts/http.rs +++ b/src/podcasts/http.rs @@ -12,7 +12,10 @@ //! * `GET /feeds/{podcast_id}` — one podcast and its season groups. //! * `GET /feeds/{podcast_id}/episodes?season=&played=&q=&sort=&limit=&offset=` //! * `POST /feeds/{podcast_id}/subscribe`, `POST /feeds/{podcast_id}/unsubscribe` -//! (unsubscribing keeps progress and history). +//! (unsubscribing keeps progress and history and revokes sharing). +//! * `POST /feeds/{podcast_id}/share` `{shared, confirm?}` — "share in the +//! federation" on or off; 409 with `needs_confirmation` when the feed URLs +//! look private and the request does not confirm exactly them. //! * `POST /episodes/{episode_id}/restart|played|unplayed` — explicit //! progress actions. //! * `POST /{podcast_id}/refresh` — manual feed refresh of a subscribed @@ -534,7 +537,10 @@ async fn podcast_handler( let store = state.store().await?; match route { PodcastRoute::Detail => { - api_response(api::podcast_detail(&store, user_id, &podcast_id).await) + let discovery = crate::federation::handle().podcast_discovery(); + api_response( + api::podcast_detail(&store, user_id, &podcast_id, discovery.as_deref()).await, + ) } PodcastRoute::Subscribe => { api_response(api::resubscribe(&store, user_id, &podcast_id).await) @@ -545,6 +551,63 @@ async fn podcast_handler( } } +async fn share_handler( + state: State, + auth_ctx: auth::AuthContext, + session: Session, + db: Database, + path: Path, + request: cot::request::Request, +) -> cot::Result { + let Some(user_id) = signed_in(&auth_ctx, &session, &db).await else { + return Ok(unauthorized()); + }; + let podcast_id = match api::parse_podcast_id(&path.0.podcast_id) { + Ok(id) => id, + Err(error) => return Ok(api_error(error)), + }; + // A JSON body is required (415 otherwise): the toggle cannot be sent by + // a cross-origin form or `text/plain` request without a CORS preflight. + let body = match json_body(request).await { + Ok(serde_json::Value::Object(body)) if !body.is_empty() => serde_json::Value::Object(body), + Ok(_) => { + return Ok(json_error( + StatusCode::BAD_REQUEST, + "expected {\"shared\": bool}", + )); + } + Err(error) => return Ok(api_error(error)), + }; + let store = state.store().await?; + let discovery = crate::federation::handle().podcast_discovery(); + match api::set_share( + &store, + user_id, + &podcast_id, + body, + discovery.as_deref(), + now_ms(), + ) + .await + { + Ok(api::ShareOutcome::Done(response)) => api_response(Ok(*response)), + Ok(api::ShareOutcome::NeedsConfirmation(share)) => { + let body = serde_json::json!({ + "error": "the feed URL may contain private data; confirm publishing it", + "needs_confirmation": true, + "share": share, + }); + Ok(cot::http::Response::builder() + .status(StatusCode::CONFLICT) + .header(CONTENT_TYPE, "application/json") + .header(CACHE_CONTROL, "private, no-store") + .body(Body::fixed(body.to_string())) + .map_err(internal)?) + } + Err(error) => Ok(api_error(error)), + } +} + async fn episodes_handler( state: State, auth_ctx: auth::AuthContext, @@ -632,6 +695,7 @@ impl App for PodcastsApp { let list_state = self.state.clone(); let subscribe_state = self.state.clone(); let episodes_state = self.state.clone(); + let share_state = self.state.clone(); let podcast_route = |route: PodcastRoute| { let state = self.state.clone(); move |auth_ctx: auth::AuthContext, @@ -703,6 +767,19 @@ impl App for PodcastsApp { post(podcast_route(PodcastRoute::Unsubscribe)), "podcasts_unsubscribe", ), + Route::with_handler_and_name( + "/feeds/{podcast_id}/share", + post( + move |auth_ctx: auth::AuthContext, + session: Session, + db: Database, + path: Path, + request: cot::request::Request| { + share_handler(share_state.clone(), auth_ctx, session, db, path, request) + }, + ), + "podcasts_share", + ), Route::with_handler_and_name( "/feeds/{podcast_id}", get(podcast_route(PodcastRoute::Detail)), diff --git a/src/podcasts/postgres_tests.rs b/src/podcasts/postgres_tests.rs index f3f91c9..8c32023 100644 --- a/src/podcasts/postgres_tests.rs +++ b/src/podcasts/postgres_tests.rs @@ -60,13 +60,14 @@ pub(crate) async fn test_pool() -> sqlx::PgPool { sqlx::PgPool::connect(&url).await.unwrap() } -fn random_user() -> i64 { +pub(crate) fn random_user() -> i64 { let bytes = blake3::hash(random_hex(8).as_bytes()); 9_000_000_000 + i64::from(u32::from_le_bytes(bytes.as_bytes()[..4].try_into().unwrap()) % 1_000_000_000) } -const ACCOUNT_TABLES: &[&str] = &[ +pub(crate) const ACCOUNT_TABLES: &[&str] = &[ + "furumusic__podcast_share_confirmation", "furumusic__podcast_fetch_state", "furumusic__podcast_listen_session", "furumusic__podcast_progress", @@ -85,7 +86,7 @@ const ACCOUNT_TABLES: &[&str] = &[ "furumusic__fed_state_playlist_item", ]; -async fn cleanup(pool: &sqlx::PgPool, users: impl IntoIterator) { +pub(crate) async fn cleanup(pool: &sqlx::PgPool, users: impl IntoIterator) { let users: Vec = users.into_iter().collect(); for table in ACCOUNT_TABLES { sqlx::query(&format!("DELETE FROM {table} WHERE user_id = ANY($1)")) @@ -1254,7 +1255,11 @@ async fn postgres_podcast_migrations_import_the_relay_state() { let url = format!("{base}/{name}"); // A 0.13.0 database: every migration up to the relay table. - let new_migrations = ["m_0056_create_podcast_store", "m_0057_import_podcast_relay"]; + let new_migrations = [ + "m_0056_create_podcast_store", + "m_0057_import_podcast_relay", + "m_0058_create_podcast_share_confirmation", + ]; let old: Vec<_> = all_migrations() .into_iter() .filter(|migration| { @@ -2056,13 +2061,13 @@ async fn postgres_podcast_api_subscribes_plays_and_keeps_progress() { .is_empty() ); assert_eq!( - api::podcast_detail(&store, other, &podcast_id) + api::podcast_detail(&store, other, &podcast_id, None) .await .unwrap_err() .status, 404 ); - let detail = api::podcast_detail(&store, user, &podcast_id) + let detail = api::podcast_detail(&store, user, &podcast_id, None) .await .unwrap(); let seasons: Vec> = detail.seasons.iter().map(|season| season.season).collect(); @@ -2247,7 +2252,7 @@ async fn postgres_podcast_api_subscribes_plays_and_keeps_progress() { .await .unwrap(); assert_eq!((replay.position_ms, replay.status), (0, "completed")); - let history = api::podcast_detail(&store, user, &podcast_id) + let history = api::podcast_detail(&store, user, &podcast_id, None) .await .unwrap() .history;