Recognize subscriptions under a feed's newer address

Subscribing to an older address whose feed announces a newer one this
device already follows (itunes:new-feed-url without a redirect) reports
the existing subscription instead of adding a second one, and a card
whose feed moved to a followed address reads «Уже подписан» once its
episodes were read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
sanapachandClaude Opus 5.5 committed 2026-11-20 15:13:07 +02:00
1 parent 744d56e06b
commit fd6827126f
8 files changed
+198 -25

No files matched your search

+1 -1
View File
@@ -251,7 +251,7 @@ pub fn perform(state: &mut AppState, runtime: &mut Runtime, effect: Effect) -> O
feed_url,
} => {
tokio::spawn(async move {
let result = discovery::preview(&services.fetcher, &feed_url)
let result = discovery::preview_for(&services, &feed_url)
.await
.map(Box::new)
.map_err(err_string);
+15 -3
View File
@@ -46,7 +46,7 @@ pub fn card_key(state: &mut AppState, popup: Popup, key: KeyCode) -> Option<Effe
match key {
KeyCode::Esc | KeyCode::Char('q') => return None,
KeyCode::Enter | KeyCode::Char('s') => {
if let Some(id) = subscribed_id(state, &hit) {
if let Some(id) = subscribed_id(state, &hit, preview.as_ref()) {
// «Уже подписан»: show the subscription instead.
return reveal_podcast(state, id, hit.title());
}
@@ -76,10 +76,22 @@ pub fn card_key(state: &mut AppState, popup: Popup, key: KeyCode) -> Option<Effe
effect
}
/// The id under which this device is subscribed to the card's podcast.
fn subscribed_id(state: &AppState, hit: &PodcastHit) -> Option<PodcastId> {
/// The id under which this device is subscribed to the card's podcast: the
/// card's id, the id its origin URL resolves to here (a feed alias), or —
/// once the feed was read — the podcast followed under the newer address
/// the feed moved to.
pub fn subscribed_id(
state: &AppState,
hit: &PodcastHit,
preview: Option<&Loadable<FeedPreview>>,
) -> Option<PodcastId> {
let moved = match preview {
Some(Loadable::Ready(preview)) => preview.subscribed_as.as_ref(),
_ => None,
};
hit.ids()
.into_iter()
.chain(moved)
.find(|id| state.podcasts.podcast(id).is_some())
.cloned()
}
+33
View File
@@ -2680,6 +2680,38 @@ mod podcast_discovery {
);
assert_eq!(state.active_tab, Tab::Podcasts);
// Subscribed under the newer address the card's feed moved to:
// known once the feed was read (`e`), then Enter opens it too.
let unknown = claimed_hit();
assert!(!unknown.ids().contains(&&podcast_id()));
let mut state = search_state(vec![fx::row("Test Show", 0, 3, 0)], vec![unknown]);
assert!(!state.podcasts.subscribed_to(&state.search.fed_podcasts[0]));
let popup = open_card_at(&mut state, 2);
let card_id = state.search.fed_podcasts[0].hit.podcast_id.clone();
assert!(matches!(
card_key(&mut state, popup, KeyCode::Char('e')),
Some(Effect::PodcastPreview { .. })
));
preview_loaded(
&mut state,
card_id,
Ok(Box::new(FeedPreview {
title: "Test Show".into(),
episode_count: 1,
seasons: Vec::new(),
episodes: Vec::new(),
moved_to: Some(FeedUrl::parse("https://example.test/feed.xml").unwrap()),
subscribed_as: Some(podcast_id()),
})),
);
let popup = state.popup.take().unwrap();
let effect = card_key(&mut state, popup, KeyCode::Enter);
assert!(
matches!(&effect, Some(Effect::PodcastLoadEpisodes { query, .. }) if query.podcast_id == podcast_id()),
"{effect:?}"
);
assert!(!state.podcasts.subscribing);
// Not subscribed: an unsubscribed podcast is not in the rows.
let state = search_state(Vec::new(), vec![claimed_hit()]);
assert!(!state.podcasts.subscribed_to(&state.search.fed_podcasts[0]));
@@ -2721,6 +2753,7 @@ mod podcast_discovery {
seasons: Vec::new(),
episodes: Vec::new(),
moved_to: None,
subscribed_as: None,
};
// A preview of another card is ignored.
preview_loaded(&mut state, podcast_id(), Ok(Box::new(feed.clone())));
+19
View File
@@ -150,6 +150,10 @@ pub struct FeedPreview {
pub episodes: Vec<PreviewEpisode>,
/// The feed answered from, or announced, another address.
pub moved_to: Option<FeedUrl>,
/// This device is subscribed to the podcast under `moved_to` (it
/// followed the feed's newer address, the card names the older one):
/// the card shows «Уже подписан». Set by [`preview_for`].
pub subscribed_as: Option<PodcastId>,
}
/// Reads the feed at `url` (a card's origin URL) for a preview. Nothing is
@@ -199,9 +203,24 @@ pub async fn preview(fetcher: &Fetcher, url: &FeedUrl) -> Result<FeedPreview> {
.collect(),
episodes,
moved_to,
subscribed_as: None,
})
}
/// [`preview`], plus whether this device already follows the podcast under
/// the newer address the feed moved to (`subscribed_as`). The store is only
/// read.
pub async fn preview_for(services: &Services, url: &FeedUrl) -> Result<FeedPreview> {
let mut preview = preview(&services.fetcher, url).await?;
if let Some(moved) = preview.moved_to.clone() {
let store = std::sync::Arc::clone(&services.store);
preview.subscribed_as =
tokio::task::spawn_blocking(move || refresh::subscribed_podcast(&store, &moved))
.await??;
}
Ok(preview)
}
/// A search hit for `feed_url` as one publisher would announce it (tests of
/// the search UI and of subscribing from a card).
#[cfg(test)]
+81 -2
View File
@@ -12,8 +12,8 @@ use music_dht::podcast::{FeedUrl, PodcastId};
use music_dht::podcast_dht::{ClaimedFeedUrl, FederatedSearchHit, SearchHitKind};
use super::discovery::{
PODCAST_SEARCH_TIMEOUT, PodcastHit, podcast_hits, preview, resolve_local_ids, search,
subscribe_from_hit, test_hit,
PODCAST_SEARCH_TIMEOUT, PodcastHit, podcast_hits, preview, preview_for, resolve_local_ids,
search, subscribe_from_hit, test_hit,
};
use super::publication::{Publication, check_share, reconcile, set_shared};
use super::publication_tests::{Node, wait_for};
@@ -194,6 +194,85 @@ async fn hits_resolve_to_the_podcast_a_feed_alias_belongs_to() {
assert_eq!(hits[1].local_id, hits[1].hit.podcast_id);
}
#[tokio::test]
async fn a_card_for_an_older_address_finds_the_subscription_under_the_newer_one() {
use furumi_library::podcasts::PodcastListFilter;
// The user follows the feed under its newer address; a long-standing
// publisher's card names the older one (the card's origin).
let f = fixture();
let feed = |announce: Option<&str>| {
let announce = announce
.map(|url| format!("<itunes:new-feed-url>{url}</itunes:new-feed-url>"))
.unwrap_or_default();
format!(
"<?xml version=\"1.0\"?><rss version=\"2.0\" \
xmlns:itunes=\"http://www.itunes.com/dtds/podcast-1.0.dtd\"><channel>\
<title>Test Show</title>{announce}{}</channel></rss>",
item("a", "Pilot", 1, "Sat, 01 Jun 2024 10:00:00 GMT"),
)
};
let subscribed_rows = || {
f.services
.store
.list_podcasts(PodcastListFilter::Subscribed)
.unwrap()
.len()
};
// 1. The old address redirects permanently to the new one.
f.server
.set("/old.xml", Route::redirect(301, &f.server.url("/new.xml")));
f.server
.set("/new.xml", Route::new(feed(None), "application/rss+xml"));
let followed = subscribe(&f.services, &f.server.url("/new.xml"), NOW)
.await
.unwrap();
let card = test_hit(&f.server.url("/old.xml"), "Test Show");
let url = card.feed_url.clone();
let preview = preview_for(&f.services, &url).await.unwrap();
assert_eq!(preview.subscribed_as.as_ref(), Some(&followed.podcast_id));
let report = subscribe_from_hit(&f.services, &card, NOW).await.unwrap();
assert!(report.already_subscribed);
assert_eq!(report.podcast_id, followed.podcast_id);
assert_eq!(subscribed_rows(), 1);
// 2. The old address only announces the new one (itunes:new-feed-url,
// no redirect): no second subscription for the same podcast.
let new_url = f.server.url("/new2.xml");
f.server
.set("/new2.xml", Route::new(feed(None), "application/rss+xml"));
f.server.set(
"/old2.xml",
Route::new(feed(Some(&new_url)), "application/rss+xml"),
);
let followed = subscribe(&f.services, &new_url, NOW).await.unwrap();
let kinds = f.log.kinds().len();
let card = test_hit(&f.server.url("/old2.xml"), "Test Show");
let url = card.feed_url.clone();
let preview = preview_for(&f.services, &url).await.unwrap();
assert_eq!(preview.moved_to, Some(FeedUrl::parse(&new_url).unwrap()));
assert_eq!(preview.subscribed_as.as_ref(), Some(&followed.podcast_id));
let report = subscribe_from_hit(&f.services, &card, NOW).await.unwrap();
assert!(report.already_subscribed);
assert_eq!(report.podcast_id, followed.podcast_id);
assert_eq!(subscribed_rows(), 2, "one row per podcast");
assert_eq!(f.log.kinds().len(), kinds, "nothing was written");
// A card whose feed moved to an address this device does not follow
// is not marked.
f.server.set(
"/elsewhere.xml",
Route::new(
feed(Some("https://feeds.example.test/unknown.xml")),
"application/rss+xml",
),
);
let url = FeedUrl::parse(&f.server.url("/elsewhere.xml")).unwrap();
let preview = preview_for(&f.services, &url).await.unwrap();
assert!(preview.moved_to.is_some());
assert_eq!(preview.subscribed_as, None);
}
#[tokio::test]
async fn preview_reads_seasons_and_episodes_without_storing_anything() {
let f = fixture();
+46 -18
View File
@@ -109,24 +109,8 @@ pub async fn subscribe_url(
url: FeedUrl,
now_ms: i64,
) -> Result<SubscribeReport> {
let store = Arc::clone(&services.store);
let lookup = url.clone();
let existing = blocking(move || {
let id = store.resolve_podcast_id(&lookup)?;
let subscribed = store
.subscription(&id)?
.is_some_and(|record| record.subscribed);
let title = store.podcast(&id)?.map(|summary| summary.meta.title);
Ok(subscribed.then_some((id, title)))
})
.await?;
if let Some((podcast_id, title)) = existing {
return Ok(SubscribeReport {
podcast_id,
title: title.unwrap_or_default(),
already_subscribed: true,
new_episodes: 0,
});
if let Some(report) = already_subscribed(services, &url).await? {
return Ok(report);
}
let response = services
@@ -146,6 +130,18 @@ pub async fn subscribe_url(
// The feed's own address: where its permanent redirects lead.
let moved_permanently = response.moved_permanently_to.is_some();
let landed = response.moved_permanently_to.unwrap_or(final_url);
// An older address of a feed this device follows under the newer one it
// announces (`itunes:new-feed-url`, no redirect): the same podcast, not
// a second subscription. Nothing is written.
if let Some(announced) = feed
.new_feed_url
.as_deref()
.and_then(|announced| FeedUrl::parse(announced).ok())
.filter(|announced| *announced != url && *announced != landed)
&& let Some(report) = already_subscribed(services, &announced).await?
{
return Ok(report);
}
let store = Arc::clone(&services.store);
let log = Arc::clone(&services.log);
@@ -207,6 +203,38 @@ pub async fn subscribe_url(
Ok(report)
}
/// The subscription `url` belongs to on this device (directly or as a
/// known feed alias), as an "already subscribed" report.
async fn already_subscribed(services: &Services, url: &FeedUrl) -> Result<Option<SubscribeReport>> {
let store = Arc::clone(&services.store);
let lookup = url.clone();
blocking(move || {
let Some(podcast_id) = subscribed_podcast(&store, &lookup)? else {
return Ok(None);
};
let title = store
.podcast(&podcast_id)?
.map(|summary| summary.meta.title);
Ok(Some(SubscribeReport {
podcast_id,
title: title.unwrap_or_default(),
already_subscribed: true,
new_episodes: 0,
}))
})
.await
}
/// The podcast `url` resolves to on this device (feed aliases included),
/// when it is subscribed. Blocking.
pub(crate) fn subscribed_podcast(store: &PodcastStore, url: &FeedUrl) -> Result<Option<PodcastId>> {
let id = store.resolve_podcast_id(url)?;
let subscribed = store
.subscription(&id)?
.is_some_and(|record| record.subscribed);
Ok(subscribed.then_some(id))
}
fn knows(store: &PodcastStore, url: &FeedUrl) -> Result<bool> {
let id = store.resolve_podcast_id(url)?;
Ok(store.podcast(&id)?.is_some() || store.subscription(&id)?.is_some())
+1
View File
@@ -351,6 +351,7 @@ mod tests {
duration_ms: Some(2_700_000),
}],
moved_to: None,
subscribed_as: None,
})),
scroll: 0,
});
+2 -1
View File
@@ -24,7 +24,8 @@ pub(super) fn draw(
preview: Option<&Loadable<FeedPreview>>,
scroll: u16,
) {
let subscribed = state.podcasts.subscribed_to(hit);
let subscribed =
crate::app::update::podcast_discovery::subscribed_id(state, hit, preview).is_some();
let subscribing = state.podcasts.subscribing;
let lines = card_lines(state, hit, preview, subscribed, subscribing);