Skip to main content

radio_cli/podcast/
commands.rs

1use super::*;
2use crate::{config::Config, store::Store};
3use anyhow::Result;
4use clap::Subcommand;
5use serde_json::{Value, json};
6use std::{
7    path::PathBuf,
8    sync::{Arc, atomic::AtomicBool},
9};
10#[derive(Debug, Clone, Subcommand)]
11pub enum Action {
12    Chapters {
13        id: String,
14    },
15    Bookmarks {
16        id: String,
17    },
18    Bookmark {
19        id: String,
20        #[arg(long)]
21        time: Option<String>,
22        #[arg(long, default_value = "")]
23        note: String,
24    },
25    BookmarkEdit {
26        id: String,
27        #[arg(long)]
28        note: Option<String>,
29    },
30    Settings {
31        id: String,
32        key: Option<String>,
33        value: Option<String>,
34    },
35    Jump {
36        id: String,
37        time: String,
38    },
39    Sleep {
40        #[arg(default_value = "30")]
41        value: String,
42    },
43    Library {
44        #[command(flatten)]
45        options: LibraryQuery,
46    },
47    Save {
48        id: String,
49        #[arg(long)]
50        remove: bool,
51    },
52    Dismiss {
53        id: String,
54    },
55    MarkBatch {
56        #[arg(required = true)]
57        ids: Vec<String>,
58        #[arg(long)]
59        unplayed: bool,
60    },
61    Resume,
62    Relative {
63        seconds: f64,
64    },
65    /// Open the discovery page without requiring a search term.
66    Browse {
67        #[arg(long, default_value = "")]
68        country: String,
69    },
70    /// List categories available for regional charts.
71    Categories {
72        #[arg(long, default_value = "")]
73        country: String,
74    },
75    /// Browse Apple Podcasts' regional charts, optionally in random order.
76    Charts {
77        #[arg(long, default_value = "")]
78        country: String,
79        #[arg(long, value_parser = directory::category_id)]
80        category: Option<String>,
81        #[arg(long, default_value_t = 25, value_parser = clap::value_parser!(u16).range(1..=100))]
82        limit: u16,
83        #[arg(long)]
84        random: bool,
85    },
86    Search {
87        query: String,
88        #[arg(long, default_value = "")]
89        country: String,
90        #[arg(long,default_value_t=25,value_parser=clap::value_parser!(u16).range(1..=200))]
91        limit: u16,
92    },
93    Discover {
94        url: String,
95    },
96    Preview {
97        url: String,
98    },
99    Add {
100        url: String,
101    },
102    List {
103        #[command(flatten)]
104        page: crate::cli::Page,
105        #[arg(long, default_value = "")]
106        query: String,
107    },
108    Episodes {
109        id: String,
110        #[arg(long, default_value = "")]
111        query: String,
112        #[command(flatten)]
113        page: crate::cli::Page,
114    },
115    Refresh {
116        id: Option<String>,
117    },
118    Unsubscribe {
119        id: String,
120    },
121    Play {
122        id: String,
123        #[arg(long)]
124        from_start: bool,
125        #[arg(long)]
126        speed: Option<f64>,
127    },
128    Mark {
129        id: String,
130        #[arg(value_parser=["played","unplayed"])]
131        state: String,
132    },
133    /// Fetch, import, or locally generate timed episode captions.
134    Subtitles {
135        id: String,
136        #[arg(long, conflicts_with = "transcribe")]
137        file: Option<PathBuf>,
138        #[arg(long)]
139        transcribe: bool,
140    },
141    Download {
142        id: String,
143    },
144    Downloads {
145        #[command(subcommand)]
146        action: DownloadAction,
147    },
148    Queue {
149        #[command(subcommand)]
150        action: QueueAction,
151    },
152    Import {
153        file: PathBuf,
154        #[arg(long)]
155        dry_run: bool,
156    },
157    Export {
158        file: PathBuf,
159        #[arg(long)]
160        overwrite: bool,
161    },
162    Seek {
163        time: String,
164    },
165    Speed {
166        rate: f64,
167    },
168    AutoNext {
169        #[arg(value_parser=["on","off"])]
170        state: String,
171    },
172}
173#[derive(Debug, Clone, Subcommand)]
174pub enum DownloadAction {
175    List,
176    Stats,
177    Pause { id: String },
178    Resume { id: String },
179    Cancel { id: String },
180    Remove { id: String },
181}
182#[derive(Debug, Clone, Subcommand)]
183pub enum QueueAction {
184    Start {
185        id: String,
186        #[arg(long)]
187        auto_next: bool,
188    },
189    Next {
190        id: String,
191        #[arg(skip)]
192        after: Option<String>,
193    },
194    List,
195    Add {
196        id: String,
197    },
198    Remove {
199        id: String,
200    },
201    Move {
202        id: String,
203        position: usize,
204    },
205    Clear,
206    Play {
207        #[arg(long)]
208        auto_next: bool,
209    },
210}
211impl Action {
212    pub(crate) fn is_query(&self) -> bool {
213        matches!(
214            self,
215            Self::Chapters { .. }
216                | Self::Bookmarks { .. }
217                | Self::Library { .. }
218                | Self::List { .. }
219                | Self::Episodes { .. }
220                | Self::Search { .. }
221                | Self::Browse { .. }
222                | Self::Categories { .. }
223                | Self::Charts { .. }
224                | Self::Discover { .. }
225                | Self::Preview { .. }
226                | Self::Downloads {
227                    action: DownloadAction::List
228                }
229                | Self::Queue {
230                    action: QueueAction::List
231                }
232        )
233    }
234
235    /// Only actions that target a single episode may inherit the TUI player.
236    pub(crate) fn episode_id_mut(&mut self) -> Option<&mut String> {
237        match self {
238            Self::Jump { id, .. }
239            | Self::Chapters { id }
240            | Self::Bookmarks { id }
241            | Self::Bookmark { id, .. }
242            | Self::Save { id, .. }
243            | Self::Dismiss { id }
244            | Self::Play { id, .. }
245            | Self::Mark { id, .. }
246            | Self::Subtitles { id, .. }
247            | Self::Download { id } => Some(id),
248            Self::Queue {
249                action:
250                    QueueAction::Add { id }
251                    | QueueAction::Remove { id }
252                    | QueueAction::Start { id, .. }
253                    | QueueAction::Next { id, .. }
254                    | QueueAction::Move { id, .. },
255            } => Some(id),
256            Self::Downloads {
257                action:
258                    DownloadAction::Pause { id }
259                    | DownloadAction::Resume { id }
260                    | DownloadAction::Cancel { id }
261                    | DownloadAction::Remove { id },
262            } => Some(id),
263            _ => None,
264        }
265    }
266}
267
268pub fn valid_speed(rate: f64) -> Result<f64> {
269    if !rate.is_finite() || !(0.5..=3.).contains(&rate) {
270        return Err(error(crate::t!("podcast_invalid_speed")));
271    }
272    Ok(rate)
273}
274pub fn parse_time(value: &str) -> Result<u64> {
275    let mut seconds = 0f64;
276    for part in value.split(':') {
277        seconds = seconds * 60.
278            + part
279                .parse::<f64>()
280                .map_err(|_| error(crate::t!("podcast_invalid_time")))?;
281    }
282    if !seconds.is_finite() || seconds < 0. || seconds > i64::MAX as f64 / 1000. {
283        return Err(error(crate::t!("podcast_invalid_time")));
284    }
285    Ok((seconds * 1000.) as u64)
286}
287fn page<T: Serialize>(items: &[T], p: crate::cli::Page) -> Value {
288    let limit = if p.all {
289        items.len()
290    } else {
291        usize::from(p.limit)
292    };
293    page_result(
294        &items.iter().skip(p.offset).take(limit).collect::<Vec<_>>(),
295        items.len(),
296        p,
297    )
298}
299pub(super) fn page_result<T: Serialize>(items: &[T], total: usize, p: crate::cli::Page) -> Value {
300    json!({"items":items,"total":total,"offset":p.offset,"limit":if p.all {None}else{Some(p.limit)},"has_more":p.offset.saturating_add(items.len())<total})
301}
302pub fn refresh(
303    config: &Config,
304    store: &Store,
305    id: Option<&str>,
306    stop: &Arc<AtomicBool>,
307) -> Result<Value> {
308    if stop.load(std::sync::atomic::Ordering::Relaxed) {
309        return Err(DomainError::new(ErrorCode::Cancelled).into());
310    }
311    let feeds = if let Some(id) = id {
312        vec![store.podcast_feed(id)?]
313    } else {
314        store.podcast_feeds()?
315    };
316    refresh_feeds(config, store, &feeds, stop)
317}
318pub(super) fn refresh_feeds(
319    config: &Config,
320    store: &Store,
321    feeds: &[Feed],
322    stop: &Arc<AtomicBool>,
323) -> Result<Value> {
324    let mut results = vec![];
325    for batch in feeds.chunks(4) {
326        let fetched = std::thread::scope(|scope| {
327            let tasks: Vec<_> = batch
328                .iter()
329                .map(|f| scope.spawn(move || fetch(config, &f.url, Some(f), stop)))
330                .collect();
331            tasks
332                .into_iter()
333                .map(|t| {
334                    t.join()
335                        .unwrap_or_else(|_| Err(error(crate::t!("podcast_network"))))
336                })
337                .collect::<Vec<_>>()
338        });
339        for (f, fetched) in batch.iter().cloned().zip(fetched) {
340            if stop.load(std::sync::atomic::Ordering::Relaxed) {
341                return Err(DomainError::new(ErrorCode::Cancelled).into());
342            }
343            let result = fetched.and_then(|p| {
344                if stop.load(std::sync::atomic::Ordering::Relaxed) {
345                    return Err(DomainError::new(ErrorCode::Cancelled).into());
346                }
347                store.podcast_refresh_merge(&f, p)
348            });
349            match result {
350                Ok(()) => {
351                    if stop.load(std::sync::atomic::Ordering::Relaxed) {
352                        return Err(DomainError::new(ErrorCode::Cancelled).into());
353                    }
354                    results.push(json!({"id":f.id,"title":f.title,"ok":true}));
355                }
356                Err(e) => {
357                    if e.downcast_ref::<DomainError>()
358                        .is_some_and(|e| e.code == ErrorCode::Cancelled)
359                    {
360                        return Err(e);
361                    }
362                    if stop.load(std::sync::atomic::Ordering::Relaxed) {
363                        return Err(DomainError::new(ErrorCode::Cancelled).into());
364                    }
365                    let mut f = f;
366                    f.error = Some(e.to_string());
367                    f.failures = f.failures.saturating_add(1);
368                    f.refreshed_at = Some(chrono::Utc::now().to_rfc3339());
369                    store.podcast_refresh_error(&f)?;
370                    results
371                        .push(json!({"id":f.id,"title":f.title,"ok":false,"error":e.to_string()}));
372                }
373            }
374        }
375    }
376    Ok(json!(results))
377}
378pub(super) fn episode_value(store: &Store, e: &Episode) -> Result<Value> {
379    let mut value = json!(e);
380    let feed = store.podcast_feed(&e.feed_id)?;
381    value["author"] = json!(feed.author);
382    value["feed_title"] = json!(feed.title);
383    value["saved"] = json!(store.conn.query_row(
384        "SELECT EXISTS(SELECT 1 FROM podcast_saved WHERE episode_id=?1)",
385        [&e.id],
386        |r| r.get::<_, bool>(0)
387    )?);
388    value["queued"] = json!(store.conn.query_row(
389        "SELECT EXISTS(SELECT 1 FROM podcast_queue WHERE episode_id=?1)",
390        [&e.id],
391        |r| r.get::<_, bool>(0)
392    )?);
393    if let Some(d) = store.podcast_download(&e.id)? {
394        value["download_state"] = json!(d.state);
395    }
396    Ok(value)
397}
398pub fn manage(
399    config: &Config,
400    store: &Store,
401    mut action: Action,
402    stop: &Arc<AtomicBool>,
403) -> Result<Value> {
404    if let Some(id) = action.episode_id_mut() {
405        *id = store.podcast_episode_id(id)?;
406    }
407    Ok(match action {
408        Action::Chapters { id } => {
409            super::extras::chapters(config, &store.podcast_episode(&id)?, stop)?
410        }
411        Action::Bookmarks { id } => {
412            let rows: Vec<_> = store.podcast_bookmarks(&id)?.iter().map(|b| json!({"id":b.episode_id,"bookmark_id":b.id,"title":b.note,"position_ms":b.position_ms,"kind":"bookmark"})).collect();
413            json!({"items":rows,"total":rows.len()})
414        }
415        Action::Bookmark { id, time, note } => json!(
416            store.podcast_add_bookmark(
417                &id,
418                parse_time(
419                    time.as_deref()
420                        .ok_or_else(|| error(crate::t!("podcast_invalid_time")))?
421                )?,
422                &note
423            )?
424        ),
425        Action::BookmarkEdit { id, note } => {
426            store.podcast_edit_bookmark(&id, note.as_deref())?;
427            json!({"id":id,"removed":note.is_none()})
428        }
429        Action::Settings { id, key, value } => match (key, value) {
430            (None, None) => json!(store.podcast_settings(&id)?),
431            (Some(key), Some(value)) => json!(store.podcast_set_setting(&id, &key, &value)?),
432            _ => return Err(error(crate::t!("podcast_invalid_setting"))),
433        },
434        Action::Jump { .. } | Action::Sleep { .. } => {
435            return Err(error(crate::t!("podcast_playback_only")));
436        }
437        Action::Library { options } => store.podcast_library(&options)?,
438        Action::Save { id, remove } => {
439            store.podcast_save_episode(&id, remove)?;
440            json!({"id":id,"saved":!remove})
441        }
442        Action::Dismiss { id } => {
443            store.podcast_dismiss_inbox(&id)?;
444            json!({"id":id,"dismissed":true})
445        }
446        Action::MarkBatch { ids, unplayed } => {
447            let tx = rusqlite::Transaction::new_unchecked(
448                &store.conn,
449                rusqlite::TransactionBehavior::Immediate,
450            )?;
451            for id in &ids {
452                let e = store.podcast_episode(id)?;
453                let mut progress = e.progress();
454                progress.position_ms = if unplayed {
455                    0
456                } else {
457                    e.observed_duration_ms
458                        .or(e.duration_ms)
459                        .unwrap_or(e.position_ms)
460                };
461                progress.completed = !unplayed;
462                Store::write_podcast_progress(&tx, &e.id, &progress)?;
463            }
464            tx.commit()?;
465            json!({"marked":ids.len()})
466        }
467        Action::Resume | Action::Relative { .. } => {
468            return Err(error(crate::t!("podcast_playback_only")));
469        }
470        Action::Browse { country } => directory::home(&directory::country(config, &country)?),
471        Action::Categories { country } => {
472            directory::categories(&directory::country(config, &country)?)
473        }
474        Action::Charts {
475            country,
476            category,
477            limit,
478            random,
479        } => directory::charts(
480            config,
481            store,
482            &directory::country(config, &country)?,
483            category.as_deref(),
484            limit,
485            random,
486            stop,
487        )?,
488        Action::Search {
489            query,
490            country,
491            limit,
492        } => {
493            let country = directory::country(config, &country)?;
494            let mut rows = search(config, &query, &country, limit.into(), stop)?;
495            directory::annotate_subscriptions(store, &mut rows)?;
496            json!(rows)
497        }
498        Action::Discover { url } => json!(discover(config, &url, stop)?),
499        Action::Preview { url } => {
500            let subscription_url = url.clone();
501            let resolved = if feed::is_apple_url(&url) {
502                let urls = discover(config, &url, stop)?;
503                if urls.len() != 1 {
504                    return Err(error(crate::t!("podcast_no_public_feed")));
505                }
506                urls[0].clone()
507            } else {
508                url
509            };
510            let mut value = json!(fetch(config, &resolved, None, stop)?);
511            value["subscription_url"] = json!(subscription_url);
512            value
513        }
514        Action::Add { url } => {
515            let urls = discover(config, &url, stop)?;
516            if urls.len() != 1 {
517                return Err(error(crate::t!("podcast_choose_feed")));
518            }
519            let p = fetch(config, &urls[0], None, stop)?
520                .ok_or_else(|| error(crate::t!("podcast_invalid_feed")))?;
521            if stop.load(std::sync::atomic::Ordering::Relaxed) {
522                return Err(DomainError::new(ErrorCode::Cancelled).into());
523            }
524            json!(store.podcast_subscribe(&p, &url)?)
525        }
526        Action::List { page: p, query } => {
527            let query = query.to_lowercase();
528            let feeds: Vec<_> = store
529                .podcast_feeds()?
530                .into_iter()
531                .filter(|feed| feed.title.to_lowercase().contains(&query))
532                .collect();
533            let mut rows = Vec::new();
534            for feed in feeds {
535                let mut value = json!(feed);
536                value["unplayed_count"] = json!(store.podcast_unplayed_count(&feed.id)?);
537                value["sort"] = json!(store.podcast_settings(&feed.id)?.sort);
538                rows.push(value);
539            }
540            page(&rows, p)
541        }
542        Action::Episodes { id, query, page: p } => {
543            let (items, total) = store.podcast_episodes_page(&id, &query, &p)?;
544            let items = items
545                .iter()
546                .map(|e| episode_value(store, e))
547                .collect::<Result<Vec<_>>>()?;
548            let mut value = page_result(&items, total, p);
549            value["feed_title"] = json!(store.podcast_feed(&id)?.title);
550            value
551        }
552        Action::Refresh { id } => refresh(config, store, id.as_deref(), stop)?,
553        Action::Unsubscribe { id } => {
554            store.podcast_unsubscribe(&id)?;
555            json!({"id":id,"subscribed":false})
556        }
557        Action::Mark { id, state } => {
558            let e = store.podcast_episode(&id)?;
559            store.podcast_progress(
560                &e,
561                if state == "played" {
562                    e.observed_duration_ms.unwrap_or(e.position_ms)
563                } else {
564                    0
565                },
566                e.observed_duration_ms,
567                state == "played",
568            )?;
569            json!(store.podcast_episode(&id)?)
570        }
571        Action::Subtitles {
572            id,
573            file,
574            transcribe,
575        } => {
576            super::transcript::manage(config, store, &id, file.as_deref(), transcribe, stop, None)?
577        }
578        Action::Download { id } => json!(super::download::foreground(config, store, &id, stop)?),
579        Action::Downloads { action } => match action {
580            DownloadAction::Stats => {
581                let rows = store.podcast_downloads()?;
582                let bytes: u64 = rows.iter().map(|d| d.bytes).sum();
583                let directory = config
584                    .settings
585                    .podcasts
586                    .directory
587                    .clone()
588                    .unwrap_or_else(|| config.data_dir.join("podcasts"));
589                json!({"downloads":rows.len(),"bytes":bytes,"completed":rows.iter().filter(|d| d.state=="complete").count(),"available_bytes":fs2::available_space(directory).ok()})
590            }
591            DownloadAction::List => {
592                let mut rows = Vec::new();
593                for d in store.podcast_downloads()? {
594                    let mut value = episode_value(store, &store.podcast_episode(&d.episode_id)?)?;
595                    value
596                        .as_object_mut()
597                        .unwrap()
598                        .extend(json!(d).as_object().unwrap().clone());
599                    rows.push(value);
600                }
601                json!(rows)
602            }
603            DownloadAction::Resume { id } => {
604                json!(super::download::foreground(config, store, &id, stop)?)
605            }
606            DownloadAction::Pause { ref id }
607            | DownloadAction::Cancel { ref id }
608            | DownloadAction::Remove { ref id } => {
609                let d = store.podcast_download_transaction(id, |current| {
610                    let mut d = current.ok_or_else(|| error(crate::t!("podcast_not_found")))?;
611                    let remove = matches!(action, DownloadAction::Remove { .. });
612                    if remove {
613                        if d.state == "downloading" {
614                            return Err(error(crate::t!("podcast_download_busy")));
615                        }
616                        let path = if d.path.is_empty() {
617                            download_path(config, id)
618                        } else {
619                            PathBuf::from(&d.path)
620                        };
621                        for path in [path.clone(), path.with_extension("part")] {
622                            if path.exists() {
623                                std::fs::remove_file(path)?;
624                            }
625                        }
626                        d.state = "removed".into();
627                        d.bytes = 0;
628                    } else {
629                        d.state = if matches!(action, DownloadAction::Pause { .. }) {
630                            "paused"
631                        } else {
632                            "cancelled"
633                        }
634                        .into();
635                    }
636                    d.generation = d.generation.saturating_add(1);
637                    store.podcast_save_download(&d)?;
638                    Ok(d)
639                })?;
640                json!(d)
641            }
642        },
643        Action::Queue {
644            action: QueueAction::Start { .. },
645        } => return Err(error(crate::t!("podcast_playback_only"))),
646        Action::Queue { action } => {
647            json!(store.podcast_queue_update(action)?)
648        }
649        Action::Export { file, overwrite } => {
650            use std::io::Write;
651            let feeds = store.podcast_feeds()?;
652            let mut text = String::from(
653                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><opml version=\"2.0\"><head><title>radio-cli</title></head><body>",
654            );
655            for f in &feeds {
656                text.push_str(&format!(
657                    "<outline type=\"rss\" text=\"{}\" xmlUrl=\"{}\" htmlUrl=\"{}\"/>",
658                    quick_xml::escape::escape(&f.title),
659                    quick_xml::escape::escape(&f.url),
660                    quick_xml::escape::escape(&f.website)
661                ));
662            }
663            text.push_str("</body></opml>");
664            let mut options = std::fs::OpenOptions::new();
665            options.write(true);
666            if overwrite {
667                options.create(true).truncate(true);
668            } else {
669                options.create_new(true);
670            }
671            options.open(file)?.write_all(text.as_bytes())?;
672            json!({"exported":feeds.len()})
673        }
674        Action::Import { file, dry_run } => {
675            if stop.load(std::sync::atomic::Ordering::Relaxed) {
676                return Err(DomainError::new(ErrorCode::Cancelled).into());
677            }
678            use std::io::Read;
679            let mut data = Vec::new();
680            std::fs::File::open(file)?
681                .take(10 * 1024 * 1024 + 1)
682                .read_to_end(&mut data)?;
683            let urls = opml(&data)?;
684            if dry_run {
685                json!({"urls":urls})
686            } else {
687                let mut results = vec![];
688                for batch in urls.chunks(4) {
689                    let fetched = std::thread::scope(|scope| {
690                        let tasks: Vec<_> = batch
691                            .iter()
692                            .map(|u| scope.spawn(move || fetch(config, u, None, stop)))
693                            .collect();
694                        tasks
695                            .into_iter()
696                            .map(|t| {
697                                t.join()
698                                    .unwrap_or_else(|_| Err(error(crate::t!("podcast_network"))))
699                            })
700                            .collect::<Vec<_>>()
701                    });
702                    for (u, fetched) in batch.iter().zip(fetched) {
703                        if stop.load(std::sync::atomic::Ordering::Relaxed) {
704                            return Err(DomainError::new(ErrorCode::Cancelled).into());
705                        }
706                        match fetched.and_then(|p| {
707                            if stop.load(std::sync::atomic::Ordering::Relaxed) {
708                                return Err(DomainError::new(ErrorCode::Cancelled).into());
709                            }
710                            store.podcast_subscribe(
711                                &p.ok_or_else(|| error(crate::t!("podcast_invalid_feed")))?,
712                                u,
713                            )
714                        }) {
715                            Ok(f) => results.push(json!({"id":f.id,"ok":true})),
716                            Err(e) => {
717                                if e.downcast_ref::<DomainError>()
718                                    .is_some_and(|e| e.code == ErrorCode::Cancelled)
719                                {
720                                    return Err(e);
721                                }
722                                if stop.load(std::sync::atomic::Ordering::Relaxed) {
723                                    return Err(DomainError::new(ErrorCode::Cancelled).into());
724                                }
725                                results.push(json!({"ok":false,"error":e.to_string()}));
726                            }
727                        }
728                    }
729                }
730                json!(results)
731            }
732        }
733        Action::AutoNext { state } => {
734            store.set_meta("podcast_auto_next", &state)?;
735            json!({"auto_next":state=="on"})
736        }
737        Action::Speed { rate } => {
738            valid_speed(rate)?;
739            store.set_meta("podcast_speed", &rate.to_string())?;
740            json!({"speed":rate})
741        }
742        Action::Seek { .. } | Action::Play { .. } => {
743            return Err(error(crate::t!("podcast_playback_only")));
744        }
745    })
746}
747fn opml(data: &[u8]) -> Result<Vec<String>> {
748    use quick_xml::{Reader, events::Event};
749    if data.len() > 10 * 1024 * 1024 {
750        return Err(error(crate::t!("podcast_limit")));
751    }
752    let mut reader = Reader::from_reader(data);
753    let mut depth = 0;
754    let mut root = false;
755    let mut urls = vec![];
756    loop {
757        match reader
758            .read_event()
759            .map_err(|_| error(crate::t!("podcast_invalid_feed")))?
760        {
761            Event::Start(e) | Event::Empty(e) => {
762                let empty =
763                    data.get(reader.buffer_position().saturating_sub(2) as usize) == Some(&b'/');
764                if depth == 0 && (root || e.local_name().as_ref() != "opml") {
765                    return Err(error(crate::t!("podcast_invalid_feed")));
766                }
767                root = true;
768                if e.local_name().as_ref() == "outline" {
769                    for a in e.attributes() {
770                        let a = a.map_err(|_| error(crate::t!("podcast_invalid_feed")))?;
771                        if a.key.as_ref() == "xmlUrl" {
772                            let value = a
773                                .normalized_value(quick_xml::XmlVersion::Implicit1_0)
774                                .map_err(|_| error(crate::t!("podcast_invalid_feed")))?;
775                            let u = super::feed::url(&value, None)?.to_string();
776                            if !urls.contains(&u) {
777                                urls.push(u);
778                            }
779                        }
780                    }
781                }
782                if !empty {
783                    depth += 1;
784                }
785                if depth > 64 || urls.len() > 10000 {
786                    return Err(error(crate::t!("podcast_limit")));
787                }
788            }
789            Event::End(_) => {
790                if depth == 0 {
791                    return Err(error(crate::t!("podcast_invalid_feed")));
792                }
793                depth -= 1;
794            }
795            Event::DocType(_) => return Err(error(crate::t!("podcast_invalid_feed"))),
796            Event::Eof => break,
797            _ => {}
798        }
799    }
800    if !root || depth != 0 {
801        return Err(error(crate::t!("podcast_invalid_feed")));
802    }
803    Ok(urls)
804}