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.
+8 -2
View File
@@ -115,9 +115,15 @@
<template x-if="$store.podcasts.found.preview">
<div>
<div class="podcast-found-status" x-show="$store.podcasts.found.preview.moved">{{ t.player_podcast_found_moved }}</div>
<div class="podcast-chips podcast-found-seasons">
<div class="podcast-chips podcast-found-seasons" role="group" aria-label="{{ t.player_podcast_season }}">
<button class="podcast-chip" type="button"
:class="{ active: $store.podcasts.found.season === 'all' }"
@click="$store.podcasts.selectFoundSeason('all')">{{ t.player_podcast_all_seasons }}</button>
<template x-for="season in $store.podcasts.found.preview.seasons" :key="$store.podcasts.seasonValue(season)">
<span class="podcast-chip" x-text="`${$store.podcasts.seasonLabel(season)} · ${season.episode_count}`"></span>
<button class="podcast-chip" type="button"
:class="{ active: $store.podcasts.found.season === $store.podcasts.seasonValue(season) }"
@click="$store.podcasts.selectFoundSeason($store.podcasts.seasonValue(season))"
x-text="`${$store.podcasts.seasonLabel(season)} · ${season.episode_count}`"></button>
</template>
</div>
<ul class="podcast-found-episodes">
+45 -7
View File
@@ -3703,6 +3703,8 @@ document.addEventListener('alpine:init', () => {
shareDialog: null,
found: null,
_foundToken: 0,
_foundAbort: null,
_foundPreviewSeq: 0,
busy: {},
expanded: {},
_searchTimer: null,
@@ -4063,15 +4065,18 @@ document.addEventListener('alpine:init', () => {
},
foundMore(preview) {
const more = Number(preview?.episode_count || 0) - (preview?.episodes?.length || 0);
const listed = Number.isInteger(preview?.listed_count) ? preview.listed_count : Number(preview?.episode_count || 0);
const more = listed - (preview?.episodes?.length || 0);
return more > 0 ? T.podcastFoundMore.replace('{count}', String(more)) : '';
},
openFound(hit) {
if (GUEST || !hit?.podcast_id || !hit.feed_url) return;
this._abortFoundPreview();
this._foundToken += 1;
this.found = {
hit,
season: 'all',
preview: null,
previewLoading: false,
previewError: '',
@@ -4085,28 +4090,60 @@ document.addEventListener('alpine:init', () => {
},
closeFound() {
// An abandoned preview is cancelled: the server stops reading
// the feed and frees the account's feed-request slot.
this._abortFoundPreview();
this._foundToken += 1;
this.found = null;
},
_foundBody(hit) {
_abortFoundPreview() {
if (this._foundAbort) {
try { this._foundAbort.abort(); } catch {}
}
this._foundAbort = null;
},
_foundBody(hit, extra = {}) {
// The card's id and origin URL, exactly as found: the server
// checks that the id comes from this URL.
return {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ podcast_id: hit.podcast_id, feed_url: hit.feed_url }),
body: JSON.stringify({ podcast_id: hit.podcast_id, feed_url: hit.feed_url, ...extra }),
};
},
selectFoundSeason(value) {
const found = this.found;
if (!found || typeof value !== 'string') return;
// The same chip again shows every season.
const season = found.season === value ? 'all' : value;
this.found = { ...found, season };
this.loadFoundPreview();
},
async loadFoundPreview() {
const found = this.found;
if (!found || found.previewLoading) return;
if (!found) return;
// A newer request (another season, Try again) replaces the
// running one.
this._abortFoundPreview();
const controller = typeof AbortController === 'function' ? new AbortController() : null;
this._foundAbort = controller;
this._foundPreviewSeq += 1;
const seq = this._foundPreviewSeq;
const token = this._foundToken;
const current = () => token === this._foundToken && seq === this._foundPreviewSeq;
this.found = { ...found, previewLoading: true, previewError: '' };
const season = found.season && found.season !== 'all' ? { season: found.season } : {};
try {
const preview = await this._json('/api/podcasts/discovery/preview', this._foundBody(found.hit));
if (token !== this._foundToken) return;
const preview = await this._json('/api/podcasts/discovery/preview', {
...this._foundBody(found.hit, season),
...(controller ? { signal: controller.signal } : {}),
});
if (!current()) return;
this._foundAbort = null;
this.found = {
...this.found,
preview: {
@@ -4121,7 +4158,8 @@ document.addEventListener('alpine:init', () => {
localPodcastId: this.found.localPodcastId || preview?.local_podcast_id || null,
};
} catch (error) {
if (token !== this._foundToken) return;
if (!current()) return;
this._foundAbort = null;
this.found = { ...this.found, previewLoading: false, previewError: error.message };
}
},
-1
View File
@@ -7207,7 +7207,6 @@ button.user-stat:hover {
}
.podcast-found-preview { margin: 8px 0; }
.podcast-found-seasons { margin: 8px 0; }
.podcast-found-seasons .podcast-chip { cursor: default; }
.podcast-found-status {
color: var(--text-secondary);
font-size: 13px;
+67 -1
View File
@@ -799,7 +799,7 @@ function podcastsStore(stores = {}, overrides = {}) {
podcastFetchError: 'Last check failed', podcastLastChecked: 'Checked', podcastNeverChecked: 'Not checked yet',
podcastJamBlocked: 'jam blocked', podcastRequestFailed: 'request failed',
},
URLSearchParams, URL, GUEST: false,
URLSearchParams, URL, AbortController, GUEST: false,
fetch: async (url, init = {}) => {
calls.push({url, init});
if (overrides.respond) return overrides.respond(url, init);
@@ -1311,3 +1311,69 @@ test('a found podcast is previewed, then subscribed with the card id and origin
await new Promise(resolve => setImmediate(resolve));
assert.equal(store.found, null);
});
test('the seasons of a found podcast can be browsed, and an abandoned preview is cancelled', async () => {
const pending = [];
const {store, calls} = podcastsStore({}, {
T: Object.assign({}, FOUND_T, {podcastAllSeasons: 'All seasons'}),
respond: (url, init) => new Promise((resolve, reject) => {
pending.push(resolve);
init.signal?.addEventListener('abort', () => reject(Object.assign(new Error('aborted'), {name: 'AbortError'})));
}),
});
const tick = () => new Promise(resolve => setImmediate(resolve));
const answer = (index, preview) => pending[index]({ok: true, status: 200, json: async () => preview});
const body = index => JSON.parse(calls[index].init.body);
const hit = store.foundHit(foundEntity());
const preview = (extra = {}) => Object.assign({
podcast_id: POD_A, feed_url: hit.feed_url, moved: false, title: 'Night Radio', episode_count: 4,
seasons: [{season: 1, episode_count: 2}, {season: 2, episode_count: 1}, {season: null, episode_count: 1}],
listed_count: 4, episodes: [{title: 'Newest', season: 2}], subscribed: false, local_podcast_id: null,
}, extra);
store.openFound(hit);
assert.equal(store.found.season, 'all');
assert.equal(calls[0].init.signal.aborted, false);
answer(0, preview());
await tick();
assert.equal(store.foundMore(store.found.preview), 'and 3 more');
// A season chip lists that season; choosing another one cancels the
// request still running.
store.selectFoundSeason('1');
assert.equal(store.found.season, '1');
assert.deepEqual(body(1), {podcast_id: POD_A, feed_url: hit.feed_url, season: '1'});
store.selectFoundSeason('none');
assert.equal(calls[1].init.signal.aborted, true);
assert.deepEqual(body(2), {podcast_id: POD_A, feed_url: hit.feed_url, season: 'none'});
await tick();
// The cancelled request shows no error.
assert.equal(store.found.previewError, '');
answer(2, preview({listed_count: 1, episodes: [{title: 'Bonus', season: null}]}));
await tick();
assert.equal(store.found.previewLoading, false);
assert.equal(store.found.preview.episodes[0].title, 'Bonus');
assert.equal(store.foundMore(store.found.preview), '');
// The same chip again shows every season.
store.selectFoundSeason('none');
assert.equal(store.found.season, 'all');
assert.deepEqual(body(3), {podcast_id: POD_A, feed_url: hit.feed_url});
store.selectFoundSeason({season: 1});
assert.equal(calls.length, 4, 'only season values from the chips');
// Closing the card cancels its preview.
store.closeFound();
assert.equal(calls[3].init.signal.aborted, true);
assert.equal(store.found, null);
// So does opening another card.
store.openFound(hit);
store.openFound(store.foundHit(foundEntity({podcast_id: POD_B})));
assert.equal(calls[4].init.signal.aborted, true);
assert.equal(calls[5].init.signal.aborted, false);
assert.equal(body(5).podcast_id, POD_B);
answer(5, preview({podcast_id: POD_B}));
await tick();
assert.equal(store.found.hit.podcast_id, POD_B);
assert.equal(store.found.preview.podcast_id, POD_B);
assert.equal(store.found.previewError, '');
});