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