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    #[command(skip)]
206    MoveAdjacent {
207        id: String,
208        up: bool,
209    },
210    Clear,
211    Play {
212        #[arg(long)]
213        auto_next: bool,
214    },
215}
216impl Action {
217    pub(crate) fn polls_browse(&self) -> bool {
218        matches!(
219            self,
220            Self::List { .. }
221                | Self::Bookmarks { .. }
222                | Self::Library { .. }
223                | Self::Episodes { .. }
224                | Self::Downloads {
225                    action: DownloadAction::List
226                }
227                | Self::Queue {
228                    action: QueueAction::List
229                }
230        )
231    }
232
233    pub(crate) fn is_query(&self) -> bool {
234        matches!(
235            self,
236            Self::Chapters { .. }
237                | Self::Bookmarks { .. }
238                | Self::Library { .. }
239                | Self::List { .. }
240                | Self::Episodes { .. }
241                | Self::Search { .. }
242                | Self::Browse { .. }
243                | Self::Categories { .. }
244                | Self::Charts { .. }
245                | Self::Discover { .. }
246                | Self::Preview { .. }
247                | Self::Downloads {
248                    action: DownloadAction::List
249                }
250                | Self::Queue {
251                    action: QueueAction::List
252                }
253        )
254    }
255
256    /// Only actions that target a single episode may inherit the TUI player.
257    pub(crate) fn episode_id_mut(&mut self) -> Option<&mut String> {
258        match self {
259            Self::Jump { id, .. }
260            | Self::Chapters { id }
261            | Self::Bookmarks { id }
262            | Self::Bookmark { id, .. }
263            | Self::Save { id, .. }
264            | Self::Dismiss { id }
265            | Self::Play { id, .. }
266            | Self::Mark { id, .. }
267            | Self::Subtitles { id, .. }
268            | Self::Download { id } => Some(id),
269            Self::Queue {
270                action:
271                    QueueAction::Add { id }
272                    | QueueAction::Remove { id }
273                    | QueueAction::Start { id, .. }
274                    | QueueAction::Next { id, .. }
275                    | QueueAction::Move { id, .. }
276                    | QueueAction::MoveAdjacent { id, .. },
277            } => Some(id),
278            Self::Downloads {
279                action:
280                    DownloadAction::Pause { id }
281                    | DownloadAction::Resume { id }
282                    | DownloadAction::Cancel { id }
283                    | DownloadAction::Remove { id },
284            } => Some(id),
285            _ => None,
286        }
287    }
288}
289
290pub fn valid_speed(rate: f64) -> Result<f64> {
291    if !rate.is_finite() || !(0.5..=3.).contains(&rate) {
292        return Err(error(crate::t!("podcast_invalid_speed")));
293    }
294    Ok(rate)
295}
296pub fn parse_time(value: &str) -> Result<u64> {
297    let mut seconds = 0f64;
298    for part in value.split(':') {
299        seconds = seconds * 60.
300            + part
301                .parse::<f64>()
302                .map_err(|_| error(crate::t!("podcast_invalid_time")))?;
303    }
304    if !seconds.is_finite() || seconds < 0. || seconds > i64::MAX as f64 / 1000. {
305        return Err(error(crate::t!("podcast_invalid_time")));
306    }
307    Ok((seconds * 1000.) as u64)
308}
309fn page<T: Serialize>(items: &[T], p: crate::cli::Page) -> Value {
310    let limit = if p.all {
311        items.len()
312    } else {
313        usize::from(p.limit)
314    };
315    page_result(
316        &items.iter().skip(p.offset).take(limit).collect::<Vec<_>>(),
317        items.len(),
318        p,
319    )
320}
321pub(super) fn page_result<T: Serialize>(items: &[T], total: usize, p: crate::cli::Page) -> Value {
322    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})
323}
324pub fn refresh(
325    config: &Config,
326    store: &Store,
327    id: Option<&str>,
328    stop: &Arc<AtomicBool>,
329) -> Result<Value> {
330    if stop.load(std::sync::atomic::Ordering::Relaxed) {
331        return Err(DomainError::new(ErrorCode::Cancelled).into());
332    }
333    let feeds = if let Some(id) = id {
334        vec![store.podcast_feed(id)?]
335    } else {
336        store.podcast_feeds()?
337    };
338    refresh_feeds(config, store, &feeds, stop)
339}
340pub(super) fn refresh_feeds(
341    config: &Config,
342    store: &Store,
343    feeds: &[Feed],
344    stop: &Arc<AtomicBool>,
345) -> Result<Value> {
346    let mut results = vec![];
347    for batch in feeds.chunks(4) {
348        let fetched = std::thread::scope(|scope| {
349            let tasks: Vec<_> = batch
350                .iter()
351                .map(|f| scope.spawn(move || fetch(config, &f.url, Some(f), stop)))
352                .collect();
353            tasks
354                .into_iter()
355                .map(|t| {
356                    t.join()
357                        .unwrap_or_else(|_| Err(error(crate::t!("podcast_network"))))
358                })
359                .collect::<Vec<_>>()
360        });
361        for (f, fetched) in batch.iter().cloned().zip(fetched) {
362            if stop.load(std::sync::atomic::Ordering::Relaxed) {
363                return Err(DomainError::new(ErrorCode::Cancelled).into());
364            }
365            let result = fetched.and_then(|p| {
366                if stop.load(std::sync::atomic::Ordering::Relaxed) {
367                    return Err(DomainError::new(ErrorCode::Cancelled).into());
368                }
369                store.podcast_refresh_merge(&f, p)
370            });
371            match result {
372                Ok(()) => {
373                    if stop.load(std::sync::atomic::Ordering::Relaxed) {
374                        return Err(DomainError::new(ErrorCode::Cancelled).into());
375                    }
376                    results.push(json!({"id":f.id,"title":f.title,"ok":true}));
377                }
378                Err(e) => {
379                    if e.downcast_ref::<DomainError>()
380                        .is_some_and(|e| e.code == ErrorCode::Cancelled)
381                    {
382                        return Err(e);
383                    }
384                    if stop.load(std::sync::atomic::Ordering::Relaxed) {
385                        return Err(DomainError::new(ErrorCode::Cancelled).into());
386                    }
387                    let mut f = f;
388                    f.error = Some(e.to_string());
389                    f.failures = f.failures.saturating_add(1);
390                    f.refreshed_at = Some(chrono::Utc::now().to_rfc3339());
391                    store.podcast_refresh_error(&f)?;
392                    results
393                        .push(json!({"id":f.id,"title":f.title,"ok":false,"error":e.to_string()}));
394                }
395            }
396        }
397    }
398    Ok(json!(results))
399}
400pub(super) fn episode_value(
401    store: &Store,
402    e: &Episode,
403    is_file: impl FnOnce(&str) -> bool,
404) -> Result<Value> {
405    let mut value = json!(e);
406    let feed = store.podcast_feed(&e.feed_id)?;
407    value["author"] = json!(feed.author);
408    value["feed_title"] = json!(feed.title);
409    value["saved"] = json!(store.conn.query_row(
410        "SELECT EXISTS(SELECT 1 FROM podcast_saved WHERE episode_id=?1)",
411        [&e.id],
412        |r| r.get::<_, bool>(0)
413    )?);
414    value["queued"] = json!(store.conn.query_row(
415        "SELECT EXISTS(SELECT 1 FROM podcast_queue WHERE episode_id=?1)",
416        [&e.id],
417        |r| r.get::<_, bool>(0)
418    )?);
419    if let Some(d) = store.podcast_download(&e.id)? {
420        value["download_state"] = json!(if d.state == "complete"
421            && d.offline_path_if(e, is_file).is_none()
422        {
423            "stale"
424        } else {
425            &d.state
426        });
427    }
428    Ok(value)
429}
430pub fn manage(
431    config: &Config,
432    store: &Store,
433    action: Action,
434    stop: &Arc<AtomicBool>,
435) -> Result<Value> {
436    let files = Arc::new(super::download_files::DownloadFiles::new(stop.clone()));
437    manage_with_files(config, store, action, stop, &files)
438}
439
440pub(super) fn manage_with_files(
441    config: &Config,
442    store: &Store,
443    mut action: Action,
444    stop: &Arc<AtomicBool>,
445    files: &Arc<super::download_files::DownloadFiles>,
446) -> Result<Value> {
447    if let Some(id) = action.episode_id_mut() {
448        *id = store.podcast_episode_id(id)?;
449    }
450    Ok(match action {
451        Action::Chapters { id } => {
452            super::extras::chapters(config, &store.podcast_episode(&id)?, stop)?
453        }
454        Action::Bookmarks { id } => {
455            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();
456            json!({"items":rows,"total":rows.len()})
457        }
458        Action::Bookmark { id, time, note } => json!(
459            store.podcast_add_bookmark(
460                &id,
461                parse_time(
462                    time.as_deref()
463                        .ok_or_else(|| error(crate::t!("podcast_invalid_time")))?
464                )?,
465                &note
466            )?
467        ),
468        Action::BookmarkEdit { id, note } => {
469            store.podcast_edit_bookmark(&id, note.as_deref())?;
470            json!({"id":id,"removed":note.is_none()})
471        }
472        Action::Settings { id, key, value } => match (key, value) {
473            (None, None) => json!(store.podcast_settings(&id)?),
474            (Some(key), Some(value)) => json!(store.podcast_set_setting(&id, &key, &value)?),
475            _ => return Err(error(crate::t!("podcast_invalid_setting"))),
476        },
477        Action::Jump { .. } | Action::Sleep { .. } => {
478            return Err(error(crate::t!("podcast_playback_only")));
479        }
480        Action::Library { options } => store.podcast_library_with_files(&options, files)?,
481        Action::Save { id, remove } => {
482            store.podcast_save_episode(&id, remove)?;
483            json!({"id":id,"saved":!remove})
484        }
485        Action::Dismiss { id } => {
486            store.podcast_dismiss_inbox(&id)?;
487            json!({"id":id,"dismissed":true})
488        }
489        Action::MarkBatch { ids, unplayed } => {
490            let tx = rusqlite::Transaction::new_unchecked(
491                &store.conn,
492                rusqlite::TransactionBehavior::Immediate,
493            )?;
494            for id in &ids {
495                let e = store.podcast_episode(id)?;
496                let mut progress = e.progress();
497                progress.position_ms = if unplayed {
498                    0
499                } else {
500                    e.observed_duration_ms
501                        .or(e.duration_ms)
502                        .unwrap_or(e.position_ms)
503                };
504                progress.completed = !unplayed;
505                Store::write_podcast_progress(&tx, &e.id, &progress)?;
506            }
507            tx.commit()?;
508            json!({"marked":ids.len()})
509        }
510        Action::Resume | Action::Relative { .. } => {
511            return Err(error(crate::t!("podcast_playback_only")));
512        }
513        Action::Browse { country } => directory::home(&directory::country(config, &country)?),
514        Action::Categories { country } => {
515            directory::categories(&directory::country(config, &country)?)
516        }
517        Action::Charts {
518            country,
519            category,
520            limit,
521            random,
522        } => directory::charts(
523            config,
524            store,
525            &directory::country(config, &country)?,
526            category.as_deref(),
527            limit,
528            random,
529            stop,
530        )?,
531        Action::Search {
532            query,
533            country,
534            limit,
535        } => {
536            let country = directory::country(config, &country)?;
537            let mut rows = search(config, &query, &country, limit.into(), stop)?;
538            directory::annotate_subscriptions(store, &mut rows)?;
539            json!(rows)
540        }
541        Action::Discover { url } => json!(discover(config, &url, stop)?),
542        Action::Preview { url } => {
543            let subscription_url = url.clone();
544            let resolved = if feed::is_apple_url(&url) {
545                let urls = discover(config, &url, stop)?;
546                if urls.len() != 1 {
547                    return Err(error(crate::t!("podcast_no_public_feed")));
548                }
549                urls[0].clone()
550            } else {
551                url
552            };
553            let mut value = json!(fetch(config, &resolved, None, stop)?);
554            value["subscription_url"] = json!(subscription_url);
555            value
556        }
557        Action::Add { url } => {
558            let urls = discover(config, &url, stop)?;
559            if urls.len() != 1 {
560                return Err(error(crate::t!("podcast_choose_feed")));
561            }
562            let p = fetch(config, &urls[0], None, stop)?
563                .ok_or_else(|| error(crate::t!("podcast_invalid_feed")))?;
564            if stop.load(std::sync::atomic::Ordering::Relaxed) {
565                return Err(DomainError::new(ErrorCode::Cancelled).into());
566            }
567            json!(store.podcast_subscribe(&p, &url)?)
568        }
569        Action::List { page: p, query } => {
570            let query = query.to_lowercase();
571            let feeds: Vec<_> = store
572                .podcast_feeds()?
573                .into_iter()
574                .filter(|feed| feed.title.to_lowercase().contains(&query))
575                .collect();
576            let mut rows = Vec::new();
577            for feed in feeds {
578                let mut value = json!(feed);
579                value["unplayed_count"] = json!(store.podcast_unplayed_count(&feed.id)?);
580                value["sort"] = json!(store.podcast_settings(&feed.id)?.sort);
581                rows.push(value);
582            }
583            page(&rows, p)
584        }
585        Action::Episodes { id, query, page: p } => {
586            let (items, total) = store.podcast_episodes_page(&id, &query, &p)?;
587            let items = items
588                .iter()
589                .map(|e| episode_value(store, e, |path| files.is_file(path)))
590                .collect::<Result<Vec<_>>>()?;
591            let mut value = page_result(&items, total, p);
592            value["feed_title"] = json!(store.podcast_feed(&id)?.title);
593            value
594        }
595        Action::Refresh { id } => refresh(config, store, id.as_deref(), stop)?,
596        Action::Unsubscribe { id } => {
597            store.podcast_unsubscribe(&id)?;
598            json!({"id":id,"subscribed":false})
599        }
600        Action::Mark { id, state } => {
601            let e = store.podcast_episode(&id)?;
602            store.podcast_progress(
603                &e,
604                if state == "played" {
605                    e.observed_duration_ms.unwrap_or(e.position_ms)
606                } else {
607                    0
608                },
609                e.observed_duration_ms,
610                state == "played",
611            )?;
612            json!(store.podcast_episode(&id)?)
613        }
614        Action::Subtitles {
615            id,
616            file,
617            transcribe,
618        } => {
619            super::transcript::manage(config, store, &id, file.as_deref(), transcribe, stop, None)?
620        }
621        Action::Download { id } => json!(super::download::foreground(config, store, &id, stop)?),
622        Action::Downloads { action } => match action {
623            DownloadAction::Stats => {
624                let rows = store.podcast_downloads()?;
625                let bytes: u64 = rows.iter().map(|d| d.bytes).sum();
626                let directory = config
627                    .settings
628                    .podcasts
629                    .directory
630                    .clone()
631                    .unwrap_or_else(|| config.data_dir.join("podcasts"));
632                json!({"downloads":rows.len(),"bytes":bytes,"completed":rows.iter().filter(|d| d.state=="complete").count(),"available_bytes":fs2::available_space(directory).ok()})
633            }
634            DownloadAction::List => {
635                let mut rows = Vec::new();
636                for d in store.podcast_downloads()? {
637                    let mut value =
638                        episode_value(store, &store.podcast_episode(&d.episode_id)?, |path| {
639                            files.is_file(path)
640                        })?;
641                    value
642                        .as_object_mut()
643                        .unwrap()
644                        .extend(json!(d).as_object().unwrap().clone());
645                    rows.push(value);
646                }
647                json!(rows)
648            }
649            DownloadAction::Resume { id } => {
650                json!(super::download::foreground(config, store, &id, stop)?)
651            }
652            DownloadAction::Pause { ref id }
653            | DownloadAction::Cancel { ref id }
654            | DownloadAction::Remove { ref id } => {
655                let d = store.podcast_download_transaction(id, |current| {
656                    let mut d = current.ok_or_else(|| error(crate::t!("podcast_not_found")))?;
657                    let remove = matches!(action, DownloadAction::Remove { .. });
658                    if remove {
659                        if d.state == "downloading" {
660                            return Err(error(crate::t!("podcast_download_busy")));
661                        }
662                        let path = if d.path.is_empty() {
663                            download_path(config, id)
664                        } else {
665                            PathBuf::from(&d.path)
666                        };
667                        for path in [path.clone(), path.with_extension("part")] {
668                            if path.exists() {
669                                std::fs::remove_file(path)?;
670                            }
671                        }
672                        d.state = "removed".into();
673                        d.bytes = 0;
674                    } else {
675                        d.state = if matches!(action, DownloadAction::Pause { .. }) {
676                            "paused"
677                        } else {
678                            "cancelled"
679                        }
680                        .into();
681                    }
682                    d.generation = d.generation.saturating_add(1);
683                    store.podcast_save_download(&d)?;
684                    Ok(d)
685                })?;
686                json!(d)
687            }
688        },
689        Action::Queue {
690            action: QueueAction::Start { .. },
691        } => return Err(error(crate::t!("podcast_playback_only"))),
692        Action::Queue {
693            action: QueueAction::List,
694        } => files.read_page(store, |store| {
695            let items = store
696                .podcast_queue()?
697                .iter()
698                .map(|e| episode_value(store, e, |path| files.observed_file(path)))
699                .collect::<Result<Vec<_>>>()?;
700            Ok(json!(items))
701        })?,
702        Action::Queue { action } => {
703            json!(store.podcast_queue_update(action)?)
704        }
705        Action::Export { file, overwrite } => {
706            use std::io::Write;
707            let feeds = store.podcast_feeds()?;
708            let mut text = String::from(
709                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><opml version=\"2.0\"><head><title>radio-cli</title></head><body>",
710            );
711            for f in &feeds {
712                text.push_str(&format!(
713                    "<outline type=\"rss\" text=\"{}\" xmlUrl=\"{}\" htmlUrl=\"{}\"/>",
714                    quick_xml::escape::escape(&f.title),
715                    quick_xml::escape::escape(&f.url),
716                    quick_xml::escape::escape(&f.website)
717                ));
718            }
719            text.push_str("</body></opml>");
720            let mut options = std::fs::OpenOptions::new();
721            options.write(true);
722            if overwrite {
723                options.create(true).truncate(true);
724            } else {
725                options.create_new(true);
726            }
727            options.open(file)?.write_all(text.as_bytes())?;
728            json!({"exported":feeds.len()})
729        }
730        Action::Import { file, dry_run } => {
731            if stop.load(std::sync::atomic::Ordering::Relaxed) {
732                return Err(DomainError::new(ErrorCode::Cancelled).into());
733            }
734            use std::io::Read;
735            let mut data = Vec::new();
736            std::fs::File::open(file)?
737                .take(10 * 1024 * 1024 + 1)
738                .read_to_end(&mut data)?;
739            let urls = opml(&data)?;
740            if dry_run {
741                json!({"urls":urls})
742            } else {
743                let mut results = vec![];
744                for batch in urls.chunks(4) {
745                    let fetched = std::thread::scope(|scope| {
746                        let tasks: Vec<_> = batch
747                            .iter()
748                            .map(|u| scope.spawn(move || fetch(config, u, None, stop)))
749                            .collect();
750                        tasks
751                            .into_iter()
752                            .map(|t| {
753                                t.join()
754                                    .unwrap_or_else(|_| Err(error(crate::t!("podcast_network"))))
755                            })
756                            .collect::<Vec<_>>()
757                    });
758                    for (u, fetched) in batch.iter().zip(fetched) {
759                        if stop.load(std::sync::atomic::Ordering::Relaxed) {
760                            return Err(DomainError::new(ErrorCode::Cancelled).into());
761                        }
762                        match fetched.and_then(|p| {
763                            if stop.load(std::sync::atomic::Ordering::Relaxed) {
764                                return Err(DomainError::new(ErrorCode::Cancelled).into());
765                            }
766                            store.podcast_subscribe(
767                                &p.ok_or_else(|| error(crate::t!("podcast_invalid_feed")))?,
768                                u,
769                            )
770                        }) {
771                            Ok(f) => results.push(json!({"id":f.id,"ok":true})),
772                            Err(e) => {
773                                if e.downcast_ref::<DomainError>()
774                                    .is_some_and(|e| e.code == ErrorCode::Cancelled)
775                                {
776                                    return Err(e);
777                                }
778                                if stop.load(std::sync::atomic::Ordering::Relaxed) {
779                                    return Err(DomainError::new(ErrorCode::Cancelled).into());
780                                }
781                                results.push(json!({"ok":false,"error":e.to_string()}));
782                            }
783                        }
784                    }
785                }
786                json!(results)
787            }
788        }
789        Action::AutoNext { state } => {
790            store.set_meta("podcast_auto_next", &state)?;
791            json!({"auto_next":state=="on"})
792        }
793        Action::Speed { rate } => {
794            valid_speed(rate)?;
795            store.set_meta("podcast_speed", &rate.to_string())?;
796            json!({"speed":rate})
797        }
798        Action::Seek { .. } | Action::Play { .. } => {
799            return Err(error(crate::t!("podcast_playback_only")));
800        }
801    })
802}
803fn opml(data: &[u8]) -> Result<Vec<String>> {
804    use quick_xml::{Reader, events::Event};
805    if data.len() > 10 * 1024 * 1024 {
806        return Err(error(crate::t!("podcast_limit")));
807    }
808    let mut reader = Reader::from_reader(data);
809    let mut depth = 0;
810    let mut root = false;
811    let mut urls = vec![];
812    loop {
813        match reader
814            .read_event()
815            .map_err(|_| error(crate::t!("podcast_invalid_feed")))?
816        {
817            Event::Start(e) | Event::Empty(e) => {
818                let empty =
819                    data.get(reader.buffer_position().saturating_sub(2) as usize) == Some(&b'/');
820                if depth == 0 && (root || e.local_name().as_ref() != "opml") {
821                    return Err(error(crate::t!("podcast_invalid_feed")));
822                }
823                root = true;
824                if e.local_name().as_ref() == "outline" {
825                    for a in e.attributes() {
826                        let a = a.map_err(|_| error(crate::t!("podcast_invalid_feed")))?;
827                        if a.key.as_ref() == "xmlUrl" {
828                            let value = a
829                                .normalized_value(quick_xml::XmlVersion::Implicit1_0)
830                                .map_err(|_| error(crate::t!("podcast_invalid_feed")))?;
831                            let u = super::feed::url(&value, None)?.to_string();
832                            if !urls.contains(&u) {
833                                urls.push(u);
834                            }
835                        }
836                    }
837                }
838                if !empty {
839                    depth += 1;
840                }
841                if depth > 64 || urls.len() > 10000 {
842                    return Err(error(crate::t!("podcast_limit")));
843                }
844            }
845            Event::End(_) => {
846                if depth == 0 {
847                    return Err(error(crate::t!("podcast_invalid_feed")));
848                }
849                depth -= 1;
850            }
851            Event::DocType(_) => return Err(error(crate::t!("podcast_invalid_feed"))),
852            Event::Eof => break,
853            _ => {}
854        }
855    }
856    if !root || depth != 0 {
857        return Err(error(crate::t!("podcast_invalid_feed")));
858    }
859    Ok(urls)
860}