Skip to main content

radio_cli/podcast/
feed.rs

1use super::*;
2use crate::config::Config;
3use anyhow::Result;
4use quick_xml::{NsReader, events::Event, name::ResolveResult};
5use reqwest::{
6    Url,
7    blocking::{Client, Response},
8};
9use scraper::{Html, Selector};
10use std::{
11    cell::Cell,
12    error::Error as _,
13    io::{self, BufRead, Read},
14    sync::{
15        Arc,
16        atomic::{AtomicBool, Ordering},
17    },
18    time::Duration,
19};
20const LIMIT: u64 = 10 * 1024 * 1024;
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct Preview {
23    pub feed: Feed,
24    pub episodes: Vec<Episode>,
25}
26pub(crate) fn url(value: &str, base: Option<&Url>) -> Result<Url> {
27    let mut u = match base {
28        Some(b) => b.join(value),
29        None => Url::parse(value),
30    }
31    .map_err(|_| error(crate::t!("podcast_invalid_url")))?;
32    if !matches!(u.scheme(), "http" | "https")
33        || u.host_str().is_none()
34        || !u.username().is_empty()
35        || u.password().is_some()
36    {
37        return Err(error(crate::t!("podcast_invalid_url")));
38    }
39    u.set_fragment(None);
40    Ok(u)
41}
42pub(super) fn redirect_policy() -> reqwest::redirect::Policy {
43    reqwest::redirect::Policy::custom(|a| {
44        if a.previous().len() >= 5
45            || !matches!(a.url().scheme(), "http" | "https")
46            || !a.url().username().is_empty()
47            || a.url().password().is_some()
48        {
49            a.stop()
50        } else {
51            a.follow()
52        }
53    })
54}
55pub(crate) fn client(config: &Config) -> Result<Client> {
56    Client::builder()
57        .user_agent(crate::USER_AGENT)
58        .connect_timeout(Duration::from_secs(config.settings.connect_timeout_secs))
59        .timeout(Duration::from_secs(config.settings.request_timeout_secs))
60        .redirect(redirect_policy())
61        .build()
62        .map_err(network_error)
63}
64pub(crate) fn body(mut r: Response, stop: &AtomicBool) -> Result<(Url, Vec<u8>)> {
65    if !r.status().is_success() {
66        return Err(error(&format!(
67            "{} {}",
68            crate::t!("podcast_http"),
69            r.status().as_u16()
70        )));
71    }
72    let base = r.url().clone();
73    let mut data = Vec::new();
74    let mut buf = [0; 16384];
75    loop {
76        if stop.load(Ordering::Relaxed) {
77            return Err(DomainError::new(ErrorCode::Cancelled).into());
78        }
79        let n = r
80            .read(&mut buf)
81            .map_err(|e| error(&format!("{}: {}", crate::t!("podcast_network"), e.kind())))?;
82        if n == 0 {
83            break;
84        }
85        if data.len() as u64 + n as u64 > LIMIT {
86            return Err(error(crate::t!("podcast_limit")));
87        }
88        data.extend_from_slice(&buf[..n]);
89    }
90    Ok((base, data))
91}
92pub fn fetch(
93    config: &Config,
94    value: &str,
95    old: Option<&Feed>,
96    stop: &Arc<AtomicBool>,
97) -> Result<Option<Preview>> {
98    let client = Client::builder()
99        .user_agent(crate::USER_AGENT)
100        .connect_timeout(Duration::from_secs(config.settings.connect_timeout_secs))
101        .timeout(Duration::from_secs(config.settings.request_timeout_secs))
102        .redirect(reqwest::redirect::Policy::none())
103        .build()
104        .map_err(network_error)?;
105    let mut current = url(value, None)?;
106    let mut canonical = current.clone();
107    let mut visited = Vec::new();
108    for _ in 0..=5 {
109        if stop.load(Ordering::Relaxed) {
110            return Err(DomainError::new(ErrorCode::Cancelled).into());
111        }
112        if visited.contains(&current) {
113            return Err(error(crate::t!("podcast_invalid_url")));
114        }
115        visited.push(current.clone());
116        let mut req = client.get(current.clone());
117        // Validators are only reusable for the URL that supplied them.
118        if let Some(f) = old.filter(|f| f.url == current.as_str()) {
119            if let Some(v) = &f.etag {
120                req = req.header("If-None-Match", v);
121            }
122            if let Some(v) = &f.modified {
123                req = req.header("If-Modified-Since", v);
124            }
125        }
126        let r = req.send().map_err(network_error)?;
127        if r.status() == 304 && old.is_some() {
128            return Ok(None);
129        }
130        if matches!(r.status().as_u16(), 301 | 302 | 303 | 307 | 308) {
131            let next = r
132                .headers()
133                .get("location")
134                .and_then(|v| v.to_str().ok())
135                .ok_or_else(|| error(crate::t!("podcast_invalid_url")))?;
136            let next = url(next, Some(&current))?;
137            // Do not persist a permanent redirect reached through a temporary URL.
138            if matches!(r.status().as_u16(), 301 | 308) && canonical == current {
139                canonical = next.clone();
140            }
141            current = next;
142            continue;
143        }
144        let etag = r
145            .headers()
146            .get("etag")
147            .and_then(|v| v.to_str().ok())
148            .map(str::to_owned);
149        let modified = r
150            .headers()
151            .get("last-modified")
152            .and_then(|v| v.to_str().ok())
153            .map(str::to_owned);
154        let (base, data) = body(r, stop)?;
155        let mut p = parse(&data, &base)?;
156        if let Some(next) = p.feed.new_feed_url.as_deref() {
157            let next = url(next, Some(&base))?;
158            if next != current {
159                canonical = next.clone();
160                current = next;
161                continue;
162            }
163        }
164        p.feed.url = canonical.to_string();
165        if canonical == current {
166            p.feed.etag = etag;
167            p.feed.modified = modified;
168        }
169        p.feed.refreshed_at = Some(crate::timestamp::now());
170        return Ok(Some(p));
171    }
172    Err(error(crate::t!("podcast_limit")))
173}
174
175pub(crate) fn network_error(e: reqwest::Error) -> anyhow::Error {
176    // Sources can include signed URLs or proxy credentials. Only expose typed
177    // causes, using the standard I/O category instead of the source message.
178    let reason = if e.is_timeout() {
179        Some(crate::t!("podcast_network_timeout").to_owned())
180    } else {
181        std::iter::successors(e.source(), |&source| source.source())
182            .filter_map(|source| source.downcast_ref::<io::Error>())
183            .map(io::Error::kind)
184            .find(|kind| *kind != io::ErrorKind::Other)
185            .map(|kind| kind.to_string())
186            .or_else(|| {
187                e.is_connect()
188                    .then(|| crate::t!("podcast_network_connect").to_owned())
189            })
190    };
191    let mut message = format!("{}: {}", crate::t!("podcast_network"), e.without_url());
192    if let Some(reason) = reason {
193        message.push_str(": ");
194        message.push_str(&reason);
195    }
196    error(&message)
197}
198
199fn plain(value: &str) -> String {
200    Html::parse_fragment(value)
201        .root_element()
202        .text()
203        .collect::<Vec<_>>()
204        .join(" ")
205        .split_whitespace()
206        .collect::<Vec<_>>()
207        .join(" ")
208}
209fn notes(value: &str) -> String {
210    fn walk(element: scraper::ElementRef<'_>, output: &mut String) {
211        let name = element.value().name();
212        if matches!(name, "script" | "style") {
213            return;
214        }
215        let block = matches!(
216            name,
217            "p" | "div" | "li" | "ul" | "ol" | "h1" | "h2" | "h3" | "br"
218        );
219        if block && !output.ends_with('\n') {
220            output.push('\n');
221        }
222        if name == "li" {
223            output.push_str("• ");
224        }
225        for child in element.children() {
226            if let Some(text) = child.value().as_text() {
227                output.push_str(&text.split_whitespace().collect::<Vec<_>>().join(" "));
228                output.push(' ');
229            } else if let Some(child) = scraper::ElementRef::wrap(child) {
230                walk(child, output);
231            }
232        }
233        if name == "a"
234            && let Some(href) = element
235                .value()
236                .attr("href")
237                .filter(|u| u.starts_with("https://") || u.starts_with("http://"))
238        {
239            output.push_str(&format!(" ({href}) "));
240        }
241        if block && !output.ends_with('\n') {
242            output.push('\n');
243        }
244    }
245    let html = Html::parse_fragment(value);
246    let mut output = String::new();
247    walk(html.root_element(), &mut output);
248    output
249        .lines()
250        .map(str::trim)
251        .filter(|s| !s.is_empty())
252        .collect::<Vec<_>>()
253        .join("\n\n")
254}
255// Feed producers use non-canonical clock fields. Keep their permissive
256// duration and chapter parsing independent of the interactive command grammar.
257fn duration(value: &str) -> Option<u64> {
258    let mut seconds = 0f64;
259    for part in value.trim().split(':') {
260        seconds = seconds * 60. + part.parse::<f64>().ok()?;
261    }
262    (seconds.is_finite() && (0.0..=i64::MAX as f64 / 1000.).contains(&seconds))
263        .then_some((seconds * 1000.) as u64)
264}
265fn published(value: &str) -> Option<String> {
266    let strict = |s: &str| {
267        jiff::fmt::rfc2822::parse(s)
268            .map(|date| date.timestamp())
269            .or_else(|_| s.parse::<jiff::Timestamp>())
270            .ok()
271    };
272    if let Some(d) = strict(value) {
273        return Some(crate::timestamp::format(d));
274    }
275    let value = value.split_once(',').map_or(value, |(_, rest)| rest.trim());
276    let mut parts: Vec<String> = value.split_whitespace().map(str::to_owned).collect();
277    if let Some(zone) = parts.last_mut() {
278        *zone = match zone.as_str() {
279            "UTC" => "+0000".into(),
280            "CEST" => "+0200".into(),
281            z if (z.starts_with('+') || z.starts_with('-')) && z.len() == 6 => z.replace(':', ""),
282            z => z.into(),
283        };
284    }
285    strict(&parts.join(" ")).map(crate::timestamp::format)
286}
287
288struct Node {
289    name: String,
290    text: String,
291    base: Url,
292    html: bool,
293    updated: Option<String>,
294}
295#[derive(Clone, Copy, PartialEq, Eq)]
296enum Scope {
297    Feed,
298    Episode,
299    Other,
300}
301fn scope(stack: &[Node]) -> Scope {
302    match stack {
303        [feed] if feed.name == "feed" => Scope::Feed,
304        [rss, channel] if rss.name == "rss" && channel.name == "channel" => Scope::Feed,
305        [feed, entry] if feed.name == "feed" && entry.name == "entry" => Scope::Episode,
306        [rss, channel, item]
307            if rss.name == "rss" && channel.name == "channel" && item.name == "item" =>
308        {
309            Scope::Episode
310        }
311        _ => Scope::Other,
312    }
313}
314pub(crate) fn parse(data: &[u8], base: &Url) -> Result<Preview> {
315    if data.len() as u64 > LIMIT {
316        return Err(error(crate::t!("podcast_limit")));
317    }
318    if data.starts_with(&[0xff, 0xfe]) || data.starts_with(&[0xfe, 0xff]) {
319        return Err(error(crate::t!("podcast_invalid_feed")));
320    }
321    parse_reader(data, base, None)?.ok_or_else(|| error(crate::t!("podcast_invalid_feed")))
322}
323
324pub(super) const PLAY_LIMIT: u64 = 32 * 1024 * 1024;
325
326pub(super) struct DirectPlay<'a> {
327    pub stop: &'a AtomicBool,
328    pub feed_recognized: Cell<bool>,
329}
330
331/// A direct play probe can encounter other XML media, such as a DASH manifest.
332pub(super) fn parse_reader(
333    mut input: impl BufRead,
334    base: &Url,
335    direct_play: Option<&DirectPlay<'_>>,
336) -> Result<Option<Preview>> {
337    if direct_play.is_some() {
338        // The network can split the UTF-8 BOM across multiple buffers.
339        if input.fill_buf()?.first() == Some(&0xef) {
340            let mut bom = [0; 3];
341            input.read_exact(&mut bom)?;
342            if bom != [0xef, 0xbb, 0xbf] {
343                return Ok(None);
344            }
345        }
346        // A raw media stream can run indefinitely without an XML delimiter.
347        if input
348            .fill_buf()?
349            .iter()
350            .find(|b| !b.is_ascii_whitespace())
351            .is_some_and(|b| *b != b'<')
352        {
353            return Ok(None);
354        }
355    }
356    let invalid = || error(crate::t!("podcast_invalid_feed"));
357    let mut reader = NsReader::from_reader(input);
358    let mut buffer = Vec::new();
359    reader.config_mut().check_end_names = true;
360    let mut stack: Vec<Node> = vec![];
361    let mut f = Feed {
362        url: base.to_string(),
363        ..Default::default()
364    };
365    let mut episodes = vec![];
366    let mut current: Option<Episode> = None;
367    let mut count = 0;
368    let mut root = String::new();
369    loop {
370        if direct_play.is_some_and(|play| play.stop.load(Ordering::Relaxed)) {
371            return Err(DomainError::new(ErrorCode::Cancelled).into());
372        }
373        buffer.clear();
374        let event = reader.read_event_into(&mut buffer).map_err(|_| invalid())?;
375        if direct_play.is_some() && reader.buffer_position() > PLAY_LIMIT {
376            return Err(error(crate::t!("podcast_limit")));
377        }
378        let empty = matches!(event, Event::Empty(_));
379        match event {
380            Event::Start(e) | Event::Empty(e) => {
381                let name = e.local_name().as_ref().to_owned();
382                if stack.is_empty() {
383                    if direct_play.is_some()
384                        && root.is_empty()
385                        && !matches!(name.as_str(), "rss" | "feed")
386                    {
387                        return Ok(None);
388                    }
389                    if !root.is_empty() || !matches!(name.as_str(), "rss" | "feed") {
390                        return Err(invalid());
391                    }
392                    root = name.clone();
393                    if let Some(play) = direct_play {
394                        play.feed_recognized.set(true);
395                    }
396                }
397                if stack.len() >= 64 {
398                    return Err(error(crate::t!("podcast_limit")));
399                }
400                let parent_base = stack.last().map(|n| &n.base).unwrap_or(base);
401                let mut attrs = std::collections::HashMap::new();
402                for a in e.attributes() {
403                    let a = a.map_err(|_| invalid())?;
404                    attrs.insert(
405                        a.key.as_ref().to_owned(),
406                        a.normalized_value(quick_xml::XmlVersion::Implicit1_0)
407                            .map_err(|_| invalid())?
408                            .into_owned(),
409                    );
410                }
411                let node_base = if let Some(b) = attrs.get("xml:base") {
412                    url(b, Some(parent_base))?
413                } else {
414                    parent_base.clone()
415                };
416                let attr_url = |key: &str| {
417                    attrs
418                        .get(key)
419                        .and_then(|v| url(v, Some(&node_base)).ok())
420                        .map(|u| u.to_string())
421                };
422                let parent_scope = scope(&stack);
423                if parent_scope == Scope::Feed
424                    && ((root == "feed" && name == "entry") || (root == "rss" && name == "item"))
425                {
426                    count += 1;
427                    if count > 10000 || current.is_some() {
428                        return Err(error(crate::t!("podcast_limit")));
429                    }
430                    current = Some(Episode::default());
431                }
432                if let Some(ep) = current.as_mut() {
433                    let ns = reader.resolver().resolve_element(e.name()).0;
434                    if name == "chapters"
435                        && parent_scope == Scope::Episode
436                        && matches!(ns, ResolveResult::Bound(ns) if ns.as_ref() == "https://podcastindex.org/namespace/1.0")
437                    {
438                        ep.chapters_url = attr_url("url");
439                    } else if name == "chapter"
440                        && matches!(ns, ResolveResult::Bound(ns) if ns.as_ref() == "http://podlove.org/simple-chapters")
441                        && let Some(position_ms) = attrs.get("start").and_then(|v| duration(v))
442                    {
443                        ep.chapters.push(Chapter {
444                            title: crate::clean_text(
445                                attrs.get("title").map(String::as_str).unwrap_or(""),
446                            ),
447                            position_ms,
448                        });
449                    }
450                }
451                if parent_scope == Scope::Episode
452                    && name == "transcript"
453                    && matches!(reader.resolver().resolve_element(e.name()).0, ResolveResult::Bound(ns) if ns.as_ref() == "https://podcastindex.org/namespace/1.0")
454                    && let Some(ep) = current.as_mut()
455                    && let Some(url) = attr_url("url")
456                {
457                    ep.transcripts.push(Transcript {
458                        url,
459                        mime: attrs.get("type").cloned().unwrap_or_default(),
460                        language: attrs.get("language").cloned(),
461                    });
462                }
463                if parent_scope == Scope::Episode
464                    && (name == "enclosure"
465                        || (name == "link" && attrs.get("rel").is_some_and(|r| r == "enclosure")))
466                {
467                    if let Some(ep) = current.as_mut() {
468                        let mime = attrs.get("type").cloned().unwrap_or_default();
469                        if ep.url.is_empty()
470                            && (mime.is_empty()
471                                || mime.starts_with("audio/")
472                                || mime == "application/octet-stream"
473                                || mime == "application/ogg")
474                            && let Some(u) = attr_url(if name == "link" { "href" } else { "url" })
475                        {
476                            ep.url = u;
477                            ep.mime = mime;
478                            ep.bytes = attrs.get("length").and_then(|v| v.parse().ok());
479                        }
480                    }
481                } else if parent_scope == Scope::Feed
482                    && name == "image"
483                    && let Some(u) = attr_url("href")
484                {
485                    f.image = u;
486                } else if matches!(parent_scope, Scope::Feed | Scope::Episode)
487                    && name == "link"
488                    && attrs.get("rel").is_none_or(|v| v == "alternate")
489                    && let Some(u) = attr_url("href")
490                {
491                    if let Some(e) = current.as_mut() {
492                        e.website = u;
493                    } else {
494                        f.website = u;
495                    }
496                }
497                stack.push(Node {
498                    name,
499                    text: String::new(),
500                    base: node_base,
501                    // XHTML tags are consumed by the XML reader. Only HTML
502                    // needs another parsing pass after XML entity decoding.
503                    html: root != "feed"
504                        || attrs
505                            .get("type")
506                            .is_some_and(|t| matches!(t.as_str(), "html" | "text/html")),
507                    updated: None,
508                });
509                if !empty {
510                    continue;
511                }
512                finish(&mut stack, &mut f, &mut current, &mut episodes);
513            }
514            Event::End(_) => finish(&mut stack, &mut f, &mut current, &mut episodes),
515            Event::Text(t) => {
516                if direct_play.is_some() && root.is_empty() && !t.as_ref().trim().is_empty() {
517                    return Ok(None);
518                }
519                if let Some(n) = stack.last_mut() {
520                    n.text.push_str(t.as_ref());
521                }
522            }
523            Event::CData(t) => {
524                if let Some(n) = stack.last_mut() {
525                    n.text.push_str(t.as_ref());
526                }
527            }
528            Event::GeneralRef(t) => {
529                if let Some(n) = stack.last_mut() {
530                    let t = t.as_ref();
531                    let v = quick_xml::escape::unescape(&format!("&{t};"))
532                        .map_err(|_| invalid())?
533                        .into_owned();
534                    n.text.push_str(&v);
535                }
536            }
537            Event::DocType(_) => return Err(invalid()),
538            Event::Eof => break,
539            _ => {}
540        }
541        if direct_play.is_some() && episodes.len() == 300 {
542            return Ok(Some(Preview { feed: f, episodes }));
543        }
544    }
545    if !stack.is_empty() || root.is_empty() || f.title.is_empty() || episodes.is_empty() {
546        return Err(invalid());
547    }
548    Ok(Some(Preview { feed: f, episodes }))
549}
550fn finish(
551    stack: &mut Vec<Node>,
552    f: &mut Feed,
553    current: &mut Option<Episode>,
554    episodes: &mut Vec<Episode>,
555) {
556    let Some(n) = stack.pop() else { return };
557    let text = n.text.trim();
558    let display_text = || {
559        if n.html {
560            plain(text)
561        } else {
562            text.split_whitespace().collect::<Vec<_>>().join(" ")
563        }
564    };
565    let parent = stack.last().map(|n| n.name.as_str()).unwrap_or("");
566    let parent_scope = scope(stack);
567    let resolved = || {
568        url(text, Some(&n.base))
569            .map(|u| u.to_string())
570            .unwrap_or_default()
571    };
572    if let Some(e) = current.as_mut() {
573        if parent_scope == Scope::Episode {
574            match n.name.as_str() {
575                "title" => e.title = display_text(),
576                "guid" | "id" if !text.is_empty() => e.guid = Some(text.into()),
577                "description" | "summary" | "content" => {
578                    e.description = if n.html { notes(text) } else { text.to_owned() }
579                }
580                "pubDate" | "published" => {
581                    e.published = published(text);
582                }
583                "updated" => {
584                    stack.last_mut().unwrap().updated = text
585                        .parse::<jiff::Timestamp>()
586                        .ok()
587                        .map(crate::timestamp::format);
588                }
589                "link" if !text.is_empty() => e.website = resolved(),
590                "duration" => e.duration_ms = duration(text),
591                _ => {}
592            }
593        }
594        if parent_scope == Scope::Feed && matches!(n.name.as_str(), "item" | "entry") {
595            let mut e = current.take().unwrap();
596            e.published = e.published.or(n.updated);
597            if !e.url.is_empty() {
598                e.source_order = Some(episodes.len() as u64);
599                episodes.push(e);
600            }
601        }
602    } else {
603        let nested_feed_field = stack
604            .split_last()
605            .is_some_and(|(_, ancestors)| scope(ancestors) == Scope::Feed);
606        match n.name.as_str() {
607            "new-feed-url" if parent_scope == Scope::Feed => f.new_feed_url = Some(resolved()),
608            "title" if parent_scope == Scope::Feed => f.title = display_text(),
609            "author" | "managingEditor" if parent_scope == Scope::Feed => f.author = display_text(),
610            "name" if parent == "author" && nested_feed_field => f.author = display_text(),
611            "description" | "subtitle" if parent_scope == Scope::Feed => {
612                f.description = if n.html { notes(text) } else { text.to_owned() }
613            }
614            "link" if parent_scope == Scope::Feed && !text.is_empty() => f.website = resolved(),
615            "url" if parent == "image" && nested_feed_field && f.image.is_empty() => {
616                f.image = resolved()
617            }
618            "logo" | "icon" if parent_scope == Scope::Feed => f.image = resolved(),
619            _ => {}
620        }
621    }
622    if let Some(parent) = stack.last_mut().filter(|p| {
623        !matches!(
624            p.name.as_str(),
625            "rss" | "channel" | "feed" | "item" | "entry"
626        )
627    }) && parent.text.len().saturating_add(n.text.len()) <= 1024 * 1024
628    {
629        parent.text.push_str(&n.text);
630    }
631}
632pub(crate) fn is_apple_url(value: &str) -> bool {
633    url(value, None).is_ok_and(|u| {
634        matches!(
635            u.host_str(),
636            Some("podcasts.apple.com" | "itunes.apple.com")
637        )
638    })
639}
640pub fn discover(config: &Config, value: &str, stop: &Arc<AtomicBool>) -> Result<Vec<String>> {
641    let u = url(value, None)?;
642    if matches!(
643        u.host_str(),
644        Some("podcasts.apple.com" | "itunes.apple.com")
645    ) && let Some(id) = u
646        .path_segments()
647        .and_then(|s| {
648            s.filter_map(|p| p.strip_prefix("id").map(str::to_owned))
649                .next_back()
650        })
651        .or_else(|| {
652            u.query_pairs()
653                .find(|(k, _)| k == "id")
654                .map(|(_, v)| v.into_owned())
655        })
656    {
657        let country = u
658            .path_segments()
659            .and_then(|mut p| p.next())
660            .filter(|p| p.len() == 2 && p.bytes().all(|c| c.is_ascii_alphabetic()));
661        let mut args = vec![("id", id.as_str())];
662        if let Some(country) = country {
663            args.push(("country", country));
664        }
665        return apple(config, "lookup", &args, stop).map(|v| {
666            v.into_iter()
667                .filter_map(|v| {
668                    v["feedUrl"]
669                        .as_str()
670                        .and_then(|s| url(s, None).ok())
671                        .map(|u| u.to_string())
672                })
673                .collect()
674        });
675    }
676    let (base, data) = body(
677        client(config)?
678            .get(u.clone())
679            .send()
680            .map_err(network_error)?,
681        stop,
682    )?;
683    if parse(&data, &base).is_ok() {
684        return Ok(vec![u.to_string()]);
685    }
686    let html = Html::parse_document(&String::from_utf8_lossy(&data));
687    let mut found = vec![];
688    let base = html
689        .select(&Selector::parse("head base[href]").unwrap())
690        .next()
691        .and_then(|e| url(e.value().attr("href")?, Some(&base)).ok())
692        .unwrap_or(base);
693    for e in html.select(&Selector::parse("head link[href]").unwrap()) {
694        let rel = e.value().attr("rel").unwrap_or("");
695        let mime = e.value().attr("type").unwrap_or("").to_ascii_lowercase();
696        if rel
697            .split_whitespace()
698            .any(|r| r.eq_ignore_ascii_case("alternate") || r.eq_ignore_ascii_case("feed"))
699            && matches!(
700                mime.as_str(),
701                "application/rss+xml" | "application/atom+xml"
702            )
703            && let Some(u) = e
704                .value()
705                .attr("href")
706                .and_then(|s| url(s, Some(&base)).ok())
707            && !found.contains(&u.to_string())
708        {
709            found.push(u.to_string());
710        }
711    }
712    Ok(found)
713}
714fn apple(
715    config: &Config,
716    endpoint: &str,
717    args: &[(&str, &str)],
718    stop: &Arc<AtomicBool>,
719) -> Result<Vec<serde_json::Value>> {
720    use std::sync::{Mutex, OnceLock};
721    use std::time::Instant;
722    type Cache = std::collections::HashMap<String, (Instant, Vec<serde_json::Value>)>;
723    static CACHE: OnceLock<Mutex<Cache>> = OnceLock::new();
724    static LAST: Mutex<Option<Instant>> = Mutex::new(None);
725    let key = format!("{endpoint}{args:?}");
726    let cache = CACHE.get_or_init(Mutex::default);
727    if let Some((at, v)) = cache.lock().unwrap().get(&key)
728        && at.elapsed() < Duration::from_secs(600)
729    {
730        return Ok(v.clone());
731    }
732    {
733        let mut last = LAST.lock().unwrap();
734        if let Some(at) = *last {
735            let wait = (at + Duration::from_secs(3)).saturating_duration_since(Instant::now());
736            if !wait.is_zero() {
737                return Err(error(&format!(
738                    "{} ({}s)",
739                    crate::t!("podcast_rate_limited"),
740                    wait.as_secs().saturating_add(1)
741                )));
742            }
743        }
744        *last = Some(Instant::now());
745    }
746    let r = client(config)?
747        .get(format!("https://itunes.apple.com/{endpoint}"))
748        .query(args)
749        .send()
750        .map_err(network_error)?;
751    if r.status() == 429 {
752        let seconds = r
753            .headers()
754            .get("retry-after")
755            .and_then(|v| v.to_str().ok())
756            .and_then(|v| v.parse::<u64>().ok())
757            .unwrap_or(60)
758            .min(3600);
759        *LAST.lock().unwrap() = Some(Instant::now() + Duration::from_secs(seconds));
760        return Err(error(crate::t!("podcast_rate_limited")));
761    }
762    let (_, data) = body(r, stop)?;
763    let value: serde_json::Value =
764        serde_json::from_slice(&data).map_err(|_| error(crate::t!("podcast_invalid_feed")))?;
765    let rows = value["results"].as_array().cloned().unwrap_or_default();
766    let mut c = cache.lock().unwrap();
767    if c.len() > 100 {
768        c.clear();
769    }
770    c.insert(key, (Instant::now(), rows.clone()));
771    Ok(rows)
772}
773pub fn search(
774    config: &Config,
775    query: &str,
776    country: &str,
777    limit: usize,
778    stop: &Arc<AtomicBool>,
779) -> Result<Vec<serde_json::Value>> {
780    apple(
781        config,
782        "search",
783        &[
784            ("term", query),
785            ("media", "podcast"),
786            ("entity", "podcast"),
787            ("country", country),
788            ("limit", &limit.to_string()),
789        ],
790        stop,
791    )
792}
793
794#[cfg(test)]
795mod tests {
796    use super::*;
797    fn parse_xml(xml: &str) -> Result<Preview> {
798        parse(
799            xml.as_bytes(),
800            &Url::parse("https://example.test/a/feed").unwrap(),
801        )
802    }
803    #[test]
804    fn direct_feeds_accept_a_utf8_bom_split_across_reads() {
805        let base = Url::parse("https://example.test/feed").unwrap();
806        let stop = AtomicBool::new(false);
807        for xml in [
808            "<rss><channel><title>Show</title><item><enclosure url='/audio'/></item></channel></rss>",
809            "<feed><title>Show</title><entry><link rel='enclosure' href='/audio'/></entry></feed>",
810        ] {
811            let document = format!("\u{feff}<?xml version='1.0'?>{xml}");
812            for capacity in [1, 2, 3] {
813                let play = DirectPlay {
814                    stop: &stop,
815                    feed_recognized: Cell::new(false),
816                };
817                let reader = io::BufReader::with_capacity(capacity, document.as_bytes());
818                let preview = parse_reader(reader, &base, Some(&play))
819                    .unwrap()
820                    .expect("feed");
821                assert_eq!(preview.episodes[0].url, "https://example.test/audio");
822            }
823        }
824    }
825
826    #[test]
827    fn transcript_namespace_aliases_and_relative_urls_are_preserved() {
828        let p = parse_xml(r#"<rss xmlns:p="https://podcastindex.org/namespace/1.0" xmlns:other="https://example.test"><channel><title>Show</title><item><title>Episode</title><enclosure url="audio.mp3"/><p:transcript url="captions.vtt" type="text/vtt" language="zh"/><other:transcript url="wrong.srt" type="application/x-subrip"/></item></channel></rss>"#).unwrap();
829        assert_eq!(p.episodes[0].transcripts.len(), 1);
830        assert!(p.episodes[0].transcripts[0].url.ends_with("/captions.vtt"));
831        assert_eq!(p.episodes[0].transcripts[0].language.as_deref(), Some("zh"));
832    }
833
834    #[test]
835    fn atom_source_metadata_stays_separate_from_entry_identity_and_content() {
836        for source_first in [false, true] {
837            let source = r#"<source xml:base="https://source.test/">
838                <id>shared-source</id><title>Source title</title>
839                <updated>2026-02-01T00:00:00Z</updated>
840                <link rel="alternate" href="source"/>
841                <link rel="enclosure" href="source.mp3" type="audio/mpeg"/>
842                <logo>source.jpg</logo><author><name>Source author</name></author>
843                </source>"#;
844            let entries = ["one", "two"].map(|id| {
845                let fields = format!(
846                    r#"<id>{id}</id><title>Episode {id}</title>
847                    <published>2026-01-01T00:00:00Z</published>
848                    <summary>Episode description</summary>
849                    <link rel="alternate" href="{id}"/>
850                    <link rel="enclosure" href="{id}.mp3" type="audio/mpeg"/>"#
851                );
852                if source_first {
853                    format!("<entry>{source}{fields}</entry>")
854                } else {
855                    format!("<entry>{fields}{source}</entry>")
856                }
857            });
858            let p = parse_xml(&format!(
859                r#"<feed xmlns="http://www.w3.org/2005/Atom">
860                <title>Show</title><author><name>Show author</name></author>
861                <logo>show.jpg</logo>{}</feed>"#,
862                entries.join("")
863            ))
864            .unwrap();
865            assert_eq!(p.feed.author, "Show author");
866            assert_eq!(p.feed.image, "https://example.test/a/show.jpg");
867            for (episode, id) in p.episodes.iter().zip(["one", "two"]) {
868                assert_eq!(episode.guid.as_deref(), Some(id));
869                assert_eq!(episode.title, format!("Episode {id}"));
870                assert_eq!(episode.description, "Episode description");
871                assert_eq!(
872                    episode.published.as_deref(),
873                    Some("2026-01-01T00:00:00+00:00")
874                );
875                assert_eq!(episode.website, format!("https://example.test/a/{id}"));
876                assert_eq!(episode.url, format!("https://example.test/a/{id}.mp3"));
877            }
878            let dir = tempfile::tempdir().unwrap();
879            let store = crate::store::Store::open(&dir.path().join("radio.db")).unwrap();
880            let feed = store.podcast_subscribe(&p, &p.feed.url).unwrap();
881            assert_eq!(store.podcast_episodes(&feed.id).unwrap().len(), 2);
882        }
883    }
884    #[test]
885    fn rss_episode_images_never_replace_or_supply_show_artwork() {
886        for show_image in ["", r#"<itunes:image href="show.jpg"/>"#] {
887            for show_first in [false, true] {
888                let episodes = r#"<item><title>One</title><enclosure url="one.mp3"/>
889                    <itunes:image href="one.jpg"/></item>
890                    <item><title>Two</title><enclosure url="two.mp3"/>
891                    <itunes:image href="two.jpg"/></item>"#;
892                let content = if show_first {
893                    format!("{show_image}{episodes}")
894                } else {
895                    format!("{episodes}{show_image}")
896                };
897                let p = parse_xml(&format!(
898                    r#"<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd">
899                    <channel><title>Show</title>{content}</channel></rss>"#
900                ))
901                .unwrap();
902                assert_eq!(p.episodes.len(), 2);
903                assert_eq!(
904                    p.feed.image,
905                    if show_image.is_empty() {
906                        ""
907                    } else {
908                        "https://example.test/a/show.jpg"
909                    }
910                );
911            }
912        }
913        let p = parse_xml(
914            r#"<rss><channel><title>Show</title><image>
915            <title>Image title</title><url>rss.jpg</url><link>https://image.test/</link>
916            </image><link>https://show.test/</link>
917            <item><title>Episode</title><enclosure url="one.mp3"/></item>
918            </channel></rss>"#,
919        )
920        .unwrap();
921        assert_eq!(p.feed.title, "Show");
922        assert_eq!(p.feed.website, "https://show.test/");
923        assert_eq!(p.feed.image, "https://example.test/a/rss.jpg");
924    }
925    #[test]
926    fn rss_metadata_entities_cdata_and_relative_enclosures() {
927        let p=parse_xml(r#"<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"><channel><title>节目 &amp; 测试</title><itunes:author>作者</itunes:author><item><title><![CDATA[第 <b>一</b> 集]]></title><guid>opaque</guid><itunes:duration>1:02:03</itunes:duration><enclosure url="../audio.m4a?a=1&amp;b=2" type="audio/mp4" length="123"/></item></channel></rss>"#).unwrap();
928        assert_eq!(p.feed.title, "节目 & 测试");
929        assert_eq!(p.feed.author, "作者");
930        assert_eq!(p.episodes[0].title, "第 一 集");
931        assert_eq!(p.episodes[0].duration_ms, Some(3723000));
932        assert_eq!(p.episodes[0].bytes, Some(123));
933        assert_eq!(p.episodes[0].url, "https://example.test/audio.m4a?a=1&b=2");
934    }
935    #[test]
936    fn atom_enclosures_respect_xml_base_and_unknown_duration() {
937        let p=parse_xml(r#"<feed xmlns="http://www.w3.org/2005/Atom" xml:base="https://media.test/"><title>Atom</title><entry><id>x</id><title>one</title><link rel="enclosure" href="one.mp3" type="audio/mpeg"/></entry></feed>"#).unwrap();
938        assert_eq!(p.episodes[0].url, "https://media.test/one.mp3");
939        assert_eq!(p.episodes[0].duration_ms, None);
940    }
941    #[test]
942    fn atom_publication_dates_prefer_published_independently_of_tag_order() {
943        let published = "<published>2026-01-01T00:00:00Z</published>";
944        let updated = "<updated>2026-03-01T00:00:00Z</updated>";
945        for (dates, expected) in [
946            (format!("{published}{updated}"), "2026-01-01T00:00:00+00:00"),
947            (format!("{updated}{published}"), "2026-01-01T00:00:00+00:00"),
948            (published.into(), "2026-01-01T00:00:00+00:00"),
949            (updated.into(), "2026-03-01T00:00:00+00:00"),
950            (
951                format!("{updated}<published>invalid</published>"),
952                "2026-03-01T00:00:00+00:00",
953            ),
954            (
955                format!("<published>invalid</published>{updated}"),
956                "2026-03-01T00:00:00+00:00",
957            ),
958            (
959                format!("{published}<updated>invalid</updated>"),
960                "2026-01-01T00:00:00+00:00",
961            ),
962        ] {
963            let p = parse_xml(&format!(
964                r#"<feed xmlns="http://www.w3.org/2005/Atom"><title>Show</title>
965                <entry><id>one</id><title>One</title>{dates}<link rel="enclosure" href="one.mp3"/></entry>
966                <entry><id>two</id><title>Two</title><published>2026-02-01T00:00:00Z</published>
967                <link rel="enclosure" href="two.mp3"/></entry></feed>"#
968            )).unwrap();
969            assert_eq!(
970                p.episodes[0].published.as_deref(),
971                Some(expected),
972                "{dates}"
973            );
974            let dir = tempfile::tempdir().unwrap();
975            let store = crate::store::Store::open(&dir.path().join("radio.db")).unwrap();
976            let feed = store.podcast_subscribe(&p, &p.feed.url).unwrap();
977            let (page, total) = store
978                .podcast_episodes_page(
979                    &feed.id,
980                    "",
981                    &crate::cli::Page {
982                        offset: 0,
983                        limit: 1,
984                        all: false,
985                    },
986                )
987                .unwrap();
988            assert_eq!(total, 2);
989            assert_eq!(
990                page[0].guid.as_deref(),
991                Some(if expected.contains("01-01") {
992                    "two"
993                } else {
994                    "one"
995                })
996            );
997        }
998    }
999    #[test]
1000    fn atom_text_constructs_preserve_literal_markup() {
1001        for (kind, content) in [
1002            ("", "Show &lt;test&gt; &amp;lt;literal&amp;gt;"),
1003            (
1004                r#" type="text""#,
1005                "Show &lt;test&gt; &amp;lt;literal&amp;gt;",
1006            ),
1007            (r#" type="text""#, "<![CDATA[Show <test> &lt;literal&gt;]]>"),
1008            (
1009                r#" type="html""#,
1010                "&lt;b&gt;Show&lt;/b&gt; &amp;lt;test&amp;gt; &amp;amp;lt;literal&amp;amp;gt;",
1011            ),
1012            (
1013                r#" type="xhtml""#,
1014                r#"<div xmlns="http://www.w3.org/1999/xhtml"><b>Show</b> &lt;test&gt; &amp;lt;literal&amp;gt;</div>"#,
1015            ),
1016        ] {
1017            let p = parse_xml(&format!(
1018                r#"<feed xmlns="http://www.w3.org/2005/Atom">
1019                <title{kind}>{content}</title><subtitle{kind}>{content}</subtitle>
1020                <entry><id>one</id><title{kind}>{content}</title>
1021                <summary{kind}>{content}</summary>
1022                <link rel="enclosure" href="one.mp3" type="audio/mpeg"/>
1023                </entry></feed>"#,
1024            ))
1025            .unwrap();
1026            let expected = "Show <test> &lt;literal&gt;";
1027            assert_eq!(p.feed.title, expected, "{kind}: {content}");
1028            assert_eq!(p.feed.description, expected);
1029            assert_eq!(p.episodes[0].title, expected);
1030            assert_eq!(p.episodes[0].description, expected);
1031        }
1032    }
1033    #[test]
1034    fn malformed_external_entities_and_missing_audio_are_rejected() {
1035        for xml in [
1036            "<!DOCTYPE rss SYSTEM 'http://bad.test/dtd'><rss/>",
1037            "<rss><channel><title>x</title><item><enclosure url='file:///etc/passwd'/></item></channel></rss>",
1038            "<rss><channel><title>x</title><item><enclosure url='https://example.test/a'/></channel>",
1039            "<html><title>x</title></html>",
1040        ] {
1041            assert!(parse_xml(xml).is_err(), "{xml}");
1042        }
1043        let xml = format!("<rss>{}</rss>", "<a>".repeat(65));
1044        assert!(parse_xml(&xml).is_err());
1045    }
1046}
1047
1048#[cfg(test)]
1049mod tolerant_date_tests {
1050    use super::*;
1051    #[test]
1052    fn tolerant_dates_preserve_offsets_without_inventing_timezones() {
1053        for s in [
1054            "Tue, 01 Jan 2024 10:00:00 +0800",
1055            "Monday, 01 Jan 2024 10:00:00 GMT",
1056            "Mon, 01 Jan 2024 10:00:00 UTC",
1057            "Mon, 01 Jan 2024 10:00:00 CEST",
1058            "Mon, 01 Jan 2024 10:00:00 +08:00",
1059        ] {
1060            assert!(published(s).is_some(), "{s}");
1061        }
1062        assert!(published("2024-01-01T10:00:00").is_none());
1063        assert_eq!(duration("01:02.5"), Some(62500));
1064        assert_eq!(duration("NaN"), None);
1065        assert_eq!(duration("-1"), None);
1066    }
1067}
1068
1069#[cfg(test)]
1070mod chapter_tests {
1071    use super::*;
1072    #[test]
1073    fn chapters_and_ogg_use_their_declared_namespaces_and_media_times() {
1074        let p = parse(br#"<rss xmlns:p="https://podcastindex.org/namespace/1.0" xmlns:c="http://podlove.org/simple-chapters"><channel><title>Show</title><item><title>Episode</title><enclosure url="audio.ogg" type="application/ogg"/><p:chapters url="chapters.json" type="application/json+chapters"/><c:chapters><c:chapter start="00:01.5" title="Intro"/></c:chapters></item></channel></rss>"#, &Url::parse("https://chapters.test/feed").unwrap()).unwrap();
1075        assert_eq!(p.episodes[0].chapters[0].position_ms, 1500);
1076        assert_eq!(
1077            p.episodes[0].chapters_url.as_deref(),
1078            Some("https://chapters.test/chapters.json")
1079        );
1080    }
1081}