From 659307b7418b2aaabb95923ec4683a41346cfefc Mon Sep 17 00:00:00 2001 From: Sanapach Date: Thu, 19 Nov 2026 23:26:36 +0200 Subject: [PATCH] Preview and subscribe to podcasts found in the federation Co-Authored-By: Claude Opus 5.5 --- src/podcasts/api.rs | 96 +++++++++++++++++++++++++++++++++++++++++++- src/podcasts/http.rs | 64 +++++++++++++++++++++++++++++ 2 files changed, 159 insertions(+), 1 deletion(-) diff --git a/src/podcasts/api.rs b/src/podcasts/api.rs index 7b90b10..07944e0 100644 --- a/src/podcasts/api.rs +++ b/src/podcasts/api.rs @@ -28,8 +28,9 @@ use music_dht::podcast_dht::{FeedUrlPrivacyWarning, PodcastDht}; use serde::{Deserialize, Serialize}; use serde_json::Value; -use super::fetch::{FeedFetcher, FetchErrorKind}; +use super::fetch::{FeedFetch, FeedFetcher, FetchErrorKind}; use super::runner::{self, SubscribeUrlError}; +use super::search; use super::{ CheckpointOutcome, EpisodeListItem, EpisodeQuery, EpisodeSort, FetchState, PlayedFilter, PodcastListFilter, PodcastStore, PodcastStoreError, PodcastSummary, ProgressSession, @@ -681,6 +682,99 @@ pub(crate) async fn set_share( }))) } +// --------------------------------------------------------------------------- +// Podcasts found in the federation +// --------------------------------------------------------------------------- + +/// A podcast from a public search hit: its id and the origin feed URL +/// (`PodcastSearchHit::feed_url`). +#[derive(Debug, Clone, Deserialize)] +struct FoundPodcastRequest { + podcast_id: String, + feed_url: String, +} + +/// The found podcast of a request. The id must hash from the URL, like a +/// valid card's origin URL: a claimed moved URL or a URL of another podcast +/// is refused (422), so the subscription gets the card's id. +fn found_podcast(body: Value) -> ApiResult<(PodcastId, FeedUrl)> { + let request: FoundPodcastRequest = decode(body)?; + let podcast_id = parse_podcast_id(&request.podcast_id)?; + let feed_url = FeedUrl::parse(&request.feed_url) + .map_err(|error| ApiError::bad_request(format!("invalid feed URL: {error}")))?; + if PodcastId::from_feed_url(&feed_url) != podcast_id { + return Err(ApiError::new( + 422, + "the feed URL is not the URL this podcast id comes from", + )); + } + Ok((podcast_id, feed_url)) +} + +/// Seasons and episodes of a found podcast before subscribing: `{ +/// "podcast_id", "feed_url" }` from the search hit. The feed is read +/// through the SSRF-guarded fetcher and nothing is stored. +pub(crate) async fn preview_found( + store: &PodcastStore, + fetcher: &FeedFetcher, + user_id: i64, + body: Value, +) -> ApiResult { + let (podcast_id, feed_url) = found_podcast(body)?; + let document = match fetcher.fetch(&feed_url, &Default::default()).await { + Ok(FeedFetch::Fetched(document)) => document, + Ok(FeedFetch::NotModified) => { + return Err(ApiError::new( + 502, + "the feed could not be loaded: unexpected 304 Not Modified", + )); + } + Err(error) => return Err(anyhow::Error::from(SubscribeUrlError::Fetch(error)).into()), + }; + let known = search::known_podcast(store, user_id, &podcast_id, &feed_url).await?; + Ok(search::preview( + &podcast_id, + &feed_url, + document.moved_permanently, + &document.feed, + known.as_ref(), + )) +} + +/// "Subscribe" on a found podcast: `{ "podcast_id", "feed_url" }` from the +/// search hit. +/// +/// The subscription is the account's own and private, made like "add RSS" +/// with the origin URL (fetch first, then `runner::subscribe_url`): its id +/// is the card's id, or the account's existing podcast when the URL is a +/// known feed URL or alias (progress and history continue). Redirects and +/// `itunes:new-feed-url` of the feed itself become aliases as usual. When +/// the account is already subscribed nothing is fetched or written. +pub(crate) async fn subscribe_found( + store: &PodcastStore, + fetcher: &FeedFetcher, + user_id: i64, + body: Value, + now_ms: i64, +) -> ApiResult { + let (podcast_id, feed_url) = found_podcast(body)?; + if let Some(known) = search::known_podcast(store, user_id, &podcast_id, &feed_url).await? + && known.subscribed + { + return Ok(SubscribeResponse { + podcast: podcast_view(store, user_id, &known.podcast_id).await?, + already_subscribed: true, + new_episodes: 0, + }); + } + let subscription = runner::subscribe_url(store, fetcher, user_id, &feed_url, now_ms).await?; + Ok(SubscribeResponse { + podcast: podcast_view(store, user_id, &subscription.podcast_id).await?, + already_subscribed: subscription.already_subscribed, + new_episodes: subscription.refresh.new_episodes, + }) +} + // --------------------------------------------------------------------------- // Episodes // --------------------------------------------------------------------------- diff --git a/src/podcasts/http.rs b/src/podcasts/http.rs index a464837..64904ce 100644 --- a/src/podcasts/http.rs +++ b/src/podcasts/http.rs @@ -16,6 +16,12 @@ //! * `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 /discovery/preview` `{podcast_id, feed_url}` — seasons and +//! episodes of a podcast found in the public search, read from its feed +//! (nothing stored). +//! * `POST /discovery/subscribe` `{podcast_id, feed_url}` — subscribe +//! (private) to a found podcast with its origin feed URL; the id must hash +//! from the URL (422 otherwise). //! * `POST /episodes/{episode_id}/restart|played|unplayed` — explicit //! progress actions. //! * `POST /{podcast_id}/refresh` — manual feed refresh of a subscribed @@ -511,6 +517,45 @@ async fn subscribe_url_handler( api_response(api::subscribe_url(&store, fetcher, user_id, body, now_ms()).await) } +/// What a `/discovery/...` route does with a found podcast. +#[derive(Debug, Clone, Copy)] +enum FoundRoute { + Preview, + Subscribe, +} + +/// A podcast from a public search hit: read its feed for a preview, or +/// subscribe. Both fetch the feed, so they share the feed request limits. +async fn found_handler( + state: State, + route: FoundRoute, + auth_ctx: auth::AuthContext, + session: Session, + db: Database, + request: cot::request::Request, +) -> cot::Result { + let Some(user_id) = signed_in(&auth_ctx, &session, &db).await else { + return Ok(unauthorized()); + }; + let body = match json_body(request).await { + Ok(body) => body, + Err(error) => return Ok(api_error(error)), + }; + let Some(_permit) = state.feed_fetch(user_id) else { + return Ok(too_busy(FEEDS_BUSY)); + }; + let store = state.store().await?; + let fetcher = state.fetcher().await?; + match route { + FoundRoute::Preview => { + api_response(api::preview_found(&store, fetcher, user_id, body).await) + } + FoundRoute::Subscribe => { + api_response(api::subscribe_found(&store, fetcher, user_id, body, now_ms()).await) + } + } +} + /// What a `/feeds/{podcast_id}...` route does. #[derive(Debug, Clone, Copy)] enum PodcastRoute { @@ -696,6 +741,15 @@ impl App for PodcastsApp { let subscribe_state = self.state.clone(); let episodes_state = self.state.clone(); let share_state = self.state.clone(); + let found_route = |route: FoundRoute| { + let state = self.state.clone(); + move |auth_ctx: auth::AuthContext, + session: Session, + db: Database, + request: cot::request::Request| { + found_handler(state.clone(), route, auth_ctx, session, db, request) + } + }; let podcast_route = |route: PodcastRoute| { let state = self.state.clone(); move |auth_ctx: auth::AuthContext, @@ -744,6 +798,16 @@ impl App for PodcastsApp { ), "podcasts_feeds", ), + Route::with_handler_and_name( + "/discovery/preview", + post(found_route(FoundRoute::Preview)), + "podcasts_discovery_preview", + ), + Route::with_handler_and_name( + "/discovery/subscribe", + post(found_route(FoundRoute::Subscribe)), + "podcasts_discovery_subscribe", + ), Route::with_handler_and_name( "/feeds/{podcast_id}/episodes", get(