Browse a found podcast by season and cancel abandoned previews

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
sanapachandClaude Opus 5.5 committed 2026-11-20 15:12:52 +02:00
1 parent 2ea3f7b337
commit 12617a6d52
7 files changed
+215 -19

No files matched your search

+34 -2
View File
@@ -708,6 +708,34 @@ struct FoundPodcastRequest {
feed_url: String,
}
/// The season a preview lists: `{"season": "2"}`, `"none"` (episodes
/// without a season) or absent / `"all"`.
#[derive(Debug, Clone, Default, Deserialize)]
struct PreviewSeasonRequest {
#[serde(default)]
season: Option<String>,
}
fn preview_season(body: &Value) -> ApiResult<SeasonFilter> {
let request: PreviewSeasonRequest = decode(body.clone())?;
Ok(
match request
.season
.as_deref()
.map(str::trim)
.filter(|v| !v.is_empty())
{
None | Some("all") => SeasonFilter::Any,
Some("none") => SeasonFilter::NoSeason,
Some(value) => SeasonFilter::Season(
value
.parse()
.map_err(|_| ApiError::bad_request("invalid season"))?,
),
},
)
}
/// 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.
@@ -726,8 +754,10 @@ fn found_podcast(body: Value) -> ApiResult<(PodcastId, FeedUrl)> {
}
/// 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. `subscribed`
/// "podcast_id", "feed_url" }` from the search hit, optionally `"season"`
/// to list the episodes of one season (`"none"`: without a season). The
/// feed is read through the SSRF-guarded fetcher and nothing is stored.
/// `subscribed`
/// also holds when the account follows the feed under the address it
/// moved to (a permanent redirect or the feed's `itunes:new-feed-url`).
pub(crate) async fn preview_found(
@@ -736,6 +766,7 @@ pub(crate) async fn preview_found(
user_id: i64,
body: Value,
) -> ApiResult<search::PodcastPreview> {
let season = preview_season(&body)?;
let (podcast_id, feed_url) = found_podcast(body)?;
let document = runner::fetch_to_subscribe(fetcher, &feed_url).await?;
let urls = runner::document_urls(&feed_url, &document);
@@ -746,6 +777,7 @@ pub(crate) async fn preview_found(
document.moved_permanently,
&document.feed,
known.as_ref(),
season,
))
}
+33 -6
View File
@@ -29,11 +29,11 @@ use music_dht::podcast_dht::{FederatedSearchHit, PodcastSearchHit, merge_search_
use music_dht::{LibraryItem, normalize_name};
use serde::Serialize;
use super::{PodcastStore, PodcastSummary};
use super::{PodcastStore, PodcastSummary, SeasonFilter};
/// Podcast hits asked from the overlay per search.
pub(crate) const PODCAST_SEARCH_LIMIT: usize = 20;
/// Episodes listed in a preview (newest first).
/// Episodes listed in a preview (newest first), per season filter.
pub(crate) const PREVIEW_EPISODES: usize = 50;
/// Longest URL kept from a card or a feed.
const MAX_URL_BYTES: usize = 2048;
@@ -209,25 +209,38 @@ pub(crate) struct PodcastPreview {
pub(crate) link: Option<String>,
pub(crate) episode_count: usize,
pub(crate) seasons: Vec<PreviewSeason>,
/// Newest first, at most [`PREVIEW_EPISODES`].
/// Episodes of the requested season (all episodes without a filter).
pub(crate) listed_count: usize,
/// The newest of them, at most [`PREVIEW_EPISODES`].
pub(crate) episodes: Vec<PreviewEpisode>,
pub(crate) subscribed: bool,
pub(crate) local_podcast_id: Option<String>,
}
/// The preview of a parsed feed (`known`: the account's podcast for it).
/// The preview of a parsed feed (`known`: the account's podcast for it),
/// listing the episodes of `season`.
pub(crate) fn preview(
podcast_id: &PodcastId,
feed_url: &FeedUrl,
moved: bool,
feed: &ParsedFeed,
known: Option<&PodcastSummary>,
season: SeasonFilter,
) -> PodcastPreview {
let mut seasons: BTreeMap<Option<u32>, usize> = BTreeMap::new();
for episode in &feed.episodes {
*seasons.entry(episode.season).or_default() += 1;
}
let mut episodes: Vec<&_> = feed.episodes.iter().collect();
let mut episodes: Vec<&_> = feed
.episodes
.iter()
.filter(|episode| match season {
SeasonFilter::Any => true,
SeasonFilter::Season(number) => episode.season == Some(number),
SeasonFilter::NoSeason => episode.season.is_none(),
})
.collect();
let listed_count = episodes.len();
// Newest first; undated episodes keep their document order at the end.
episodes.sort_by_key(|episode| std::cmp::Reverse(episode.published_at_ms));
PodcastPreview {
@@ -250,6 +263,7 @@ pub(crate) fn preview(
episode_count: *count,
})
.collect(),
listed_count,
episodes: episodes
.into_iter()
.take(PREVIEW_EPISODES)
@@ -420,7 +434,8 @@ mod tests {
music_dht::podcast::feed::parse_feed_with_base(xml.as_bytes(), Some(url.as_str()))
.unwrap();
let id = PodcastId::from_feed_url(&url);
let preview = preview(&id, &url, false, &feed, None);
let preview_of = |season| preview(&id, &url, false, &feed, None, season);
let preview = preview_of(SeasonFilter::Any);
assert_eq!(preview.title, "Preview Show");
assert_eq!(preview.link, None, "only http(s) links");
assert_eq!(preview.episode_count, 3);
@@ -432,6 +447,18 @@ mod tests {
assert_eq!(seasons, vec![(Some(1), 1), (Some(2), 1), (None, 1)]);
let titles: Vec<_> = preview.episodes.iter().map(|e| e.title.as_str()).collect();
assert_eq!(titles, vec!["New", "Old", "Bonus"]);
assert_eq!(preview.listed_count, 3);
assert!(!preview.subscribed && preview.local_podcast_id.is_none());
// One season (older seasons stay reachable), or the episodes
// without a season; the season groups stay complete.
let first = preview_of(SeasonFilter::Season(1));
let titles: Vec<_> = first.episodes.iter().map(|e| e.title.as_str()).collect();
assert_eq!(titles, vec!["Old"]);
assert_eq!((first.listed_count, first.seasons.len()), (1, 3));
let unnumbered = preview_of(SeasonFilter::NoSeason);
assert_eq!(unnumbered.episodes[0].title, "Bonus");
assert_eq!(unnumbered.listed_count, 1);
assert!(preview_of(SeasonFilter::Season(9)).episodes.is_empty());
}
}
+28
View File
@@ -463,6 +463,34 @@ async fn postgres_subscribing_from_a_card_keeps_the_card_id() {
preview.local_podcast_id.as_deref(),
Some(show.podcast_id.as_str())
);
// One season at a time; a bad season is refused before any fetch.
let mut seasonal = body(&show);
seasonal["season"] = json!("1");
let first = api::preview_found(&store, &fetcher, user, seasonal)
.await
.unwrap();
assert_eq!(first.listed_count, 2);
assert!(
first
.episodes
.iter()
.all(|episode| episode.season == Some(1))
);
let mut unnumbered = body(&show);
unnumbered["season"] = json!("none");
let none = api::preview_found(&store, &fetcher, user, unnumbered)
.await
.unwrap();
assert_eq!(none.listed_count, 1);
assert!(none.episodes.iter().all(|episode| episode.season.is_none()));
let requests = server.requests("/show.xml").len();
let mut bad = body(&show);
bad["season"] = json!("first");
let error = api::preview_found(&store, &fetcher, user, bad)
.await
.unwrap_err();
assert_eq!(error.status, 400);
assert_eq!(server.requests("/show.xml").len(), requests);
// Another account subscribing from the same card gets its own podcast
// with the same id; the first account's state is untouched.