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