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    fn millis(value: &str) -> Option<u64> {
298        let (clock, fraction) = value
299            .split_once('.')
300            .map_or((value, None), |(c, f)| (c, Some(f)));
301        let mut seconds = 0u64;
302        for (index, field) in clock.split(':').enumerate() {
303            if index >= 3 || field.is_empty() || !field.bytes().all(|c| c.is_ascii_digit()) {
304                return None;
305            }
306            let part = field.parse::<u64>().ok()?;
307            if index > 0 && part >= 60 {
308                return None;
309            }
310            seconds = seconds.checked_mul(60)?.checked_add(part)?;
311        }
312        let mut result = seconds.checked_mul(1000)?;
313        if let Some(fraction) = fraction {
314            if fraction.is_empty() || !fraction.bytes().all(|c| c.is_ascii_digit()) {
315                return None;
316            }
317            for (digit, weight) in fraction.bytes().zip([100, 10, 1]) {
318                result = result.checked_add(u64::from(digit - b'0') * weight)?;
319            }
320        }
321        (result <= i64::MAX as u64).then_some(result)
322    }
323    millis(value).ok_or_else(|| error(crate::t!("podcast_invalid_time")))
324}
325
326#[cfg(test)]
327mod time_tests {
328    #[test]
329    fn validates_user_clock_fields_before_combining_them() {
330        for (v, ms) in [
331            ("65", 65000),
332            ("01:02.3456", 62345),
333            ("2:03:04", 7384000),
334            ("9223372036854775.807", i64::MAX as u64),
335        ] {
336            assert_eq!(super::parse_time(v).unwrap(), ms);
337        }
338        for v in [
339            "1:-1",
340            "1:2:3:4",
341            "1:60",
342            "+2",
343            "1e3",
344            "1.5:20",
345            "1::20",
346            "NaN",
347            "9223372036854775.808",
348        ] {
349            assert!(super::parse_time(v).is_err(), "{v}");
350        }
351    }
352}
353pub(super) fn page_result<T: Serialize>(items: &[T], total: usize, p: crate::cli::Page) -> Value {
354    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})
355}
356pub fn refresh(
357    config: &Config,
358    store: &Store,
359    id: Option<&str>,
360    stop: &Arc<AtomicBool>,
361) -> Result<Value> {
362    if stop.load(std::sync::atomic::Ordering::Relaxed) {
363        return Err(DomainError::new(ErrorCode::Cancelled).into());
364    }
365    let feeds = if let Some(id) = id {
366        vec![store.podcast_feed(id)?]
367    } else {
368        store.podcast_feeds()?
369    };
370    refresh_feeds(config, store, &feeds, stop)
371}
372pub(super) fn refresh_feeds(
373    config: &Config,
374    store: &Store,
375    feeds: &[Feed],
376    stop: &Arc<AtomicBool>,
377) -> Result<Value> {
378    let mut results = vec![];
379    for batch in feeds.chunks(4) {
380        let fetched = std::thread::scope(|scope| {
381            let tasks: Vec<_> = batch
382                .iter()
383                .map(|f| scope.spawn(move || fetch(config, &f.url, Some(f), stop)))
384                .collect();
385            tasks
386                .into_iter()
387                .map(|t| {
388                    t.join()
389                        .unwrap_or_else(|_| Err(error(crate::t!("podcast_network"))))
390                })
391                .collect::<Vec<_>>()
392        });
393        for (f, fetched) in batch.iter().cloned().zip(fetched) {
394            if stop.load(std::sync::atomic::Ordering::Relaxed) {
395                return Err(DomainError::new(ErrorCode::Cancelled).into());
396            }
397            let result = fetched.and_then(|p| {
398                if stop.load(std::sync::atomic::Ordering::Relaxed) {
399                    return Err(DomainError::new(ErrorCode::Cancelled).into());
400                }
401                store.podcast_refresh_merge(&f, p)
402            });
403            match result {
404                Ok(()) => {
405                    if stop.load(std::sync::atomic::Ordering::Relaxed) {
406                        return Err(DomainError::new(ErrorCode::Cancelled).into());
407                    }
408                    results.push(json!({"id":f.id,"title":f.title,"ok":true}));
409                }
410                Err(e) => {
411                    if e.downcast_ref::<DomainError>()
412                        .is_some_and(|e| e.code == ErrorCode::Cancelled)
413                    {
414                        return Err(e);
415                    }
416                    if stop.load(std::sync::atomic::Ordering::Relaxed) {
417                        return Err(DomainError::new(ErrorCode::Cancelled).into());
418                    }
419                    let mut f = f;
420                    f.error = Some(e.to_string());
421                    f.failures = f.failures.saturating_add(1);
422                    f.refreshed_at = Some(crate::timestamp::now());
423                    store.podcast_refresh_error(&f)?;
424                    results
425                        .push(json!({"id":f.id,"title":f.title,"ok":false,"error":e.to_string()}));
426                }
427            }
428        }
429    }
430    Ok(json!(results))
431}
432pub(super) fn episode_value(
433    store: &Store,
434    e: &Episode,
435    is_file: impl FnOnce(&str) -> bool,
436) -> Result<Value> {
437    let feed = store.podcast_feed(&e.feed_id)?;
438    let (saved, queued) = store.conn.query_row(
439        "SELECT EXISTS(SELECT 1 FROM podcast_saved WHERE episode_id=?1),
440                EXISTS(SELECT 1 FROM podcast_queue WHERE episode_id=?1)",
441        [&e.id],
442        |r| Ok((r.get(0)?, r.get(1)?)),
443    )?;
444    Ok(episode_details(
445        e,
446        &feed.title,
447        &feed.author,
448        saved,
449        queued,
450        store.podcast_download(&e.id)?.as_ref(),
451        is_file,
452    ))
453}
454pub(super) fn episode_details(
455    e: &Episode,
456    feed_title: &str,
457    author: &str,
458    saved: bool,
459    queued: bool,
460    download: Option<&Download>,
461    is_file: impl FnOnce(&str) -> bool,
462) -> Value {
463    let mut value = json!(e);
464    value["author"] = json!(author);
465    value["feed_title"] = json!(feed_title);
466    value["saved"] = json!(saved);
467    value["queued"] = json!(queued);
468    if let Some(d) = download {
469        value["download_state"] = json!(if d.phase() == DownloadState::Complete
470            && d.offline_path_if(e, is_file).is_none()
471        {
472            "stale"
473        } else {
474            &d.state
475        });
476    }
477    value
478}
479
480pub fn manage(
481    config: &Config,
482    store: &Store,
483    action: Action,
484    stop: &Arc<AtomicBool>,
485) -> Result<Value> {
486    let files = Arc::new(super::download_files::DownloadFiles::new(stop.clone()));
487    manage_with_files(config, store, action, stop, &files)
488}
489
490pub(super) fn manage_with_files(
491    config: &Config,
492    store: &Store,
493    mut action: Action,
494    stop: &Arc<AtomicBool>,
495    files: &Arc<super::download_files::DownloadFiles>,
496) -> Result<Value> {
497    if let Some(id) = action.episode_id_mut() {
498        *id = store.podcast_episode_id(id)?;
499    }
500    Ok(match action {
501        Action::Chapters { id } => {
502            super::extras::chapters(config, &store.podcast_episode(&id)?, stop)?
503        }
504        Action::Bookmarks { id } => {
505            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();
506            json!({"items":rows,"total":rows.len()})
507        }
508        Action::Bookmark { id, time, note } => json!(
509            store.podcast_add_bookmark(
510                &id,
511                parse_time(
512                    time.as_deref()
513                        .ok_or_else(|| error(crate::t!("podcast_invalid_time")))?
514                )?,
515                &note
516            )?
517        ),
518        Action::BookmarkEdit { id, note } => {
519            store.podcast_edit_bookmark(&id, note.as_deref())?;
520            json!({"id":id,"removed":note.is_none()})
521        }
522        Action::Settings { id, key, value } => match (key, value) {
523            (None, None) => json!(store.podcast_settings(&id)?),
524            (Some(key), Some(value)) => json!(store.podcast_set_setting(&id, &key, &value)?),
525            _ => return Err(error(crate::t!("podcast_invalid_setting"))),
526        },
527        Action::Jump { .. } | Action::Sleep { .. } => {
528            return Err(error(crate::t!("podcast_playback_only")));
529        }
530        Action::Library { options } => store.podcast_library_with_files(&options, files)?,
531        Action::Save { id, remove } => {
532            store.podcast_save_episode(&id, remove)?;
533            json!({"id":id,"saved":!remove})
534        }
535        Action::Dismiss { id } => {
536            store.podcast_dismiss_inbox(&id)?;
537            json!({"id":id,"dismissed":true})
538        }
539        Action::MarkBatch { ids, unplayed } => {
540            let tx = rusqlite::Transaction::new_unchecked(
541                &store.conn,
542                rusqlite::TransactionBehavior::Immediate,
543            )?;
544            for id in &ids {
545                let mut e = store.podcast_episode(id)?;
546                e.mark(!unplayed);
547                Store::write_podcast_progress(&tx, &e.id, &e.progress())?;
548            }
549            tx.commit()?;
550            json!({"marked":ids.len()})
551        }
552        Action::Resume | Action::Relative { .. } => {
553            return Err(error(crate::t!("podcast_playback_only")));
554        }
555        Action::Browse { country } => directory::home(&directory::country(config, &country)?),
556        Action::Categories { country } => {
557            directory::categories(&directory::country(config, &country)?)
558        }
559        Action::Charts {
560            country,
561            category,
562            limit,
563            random,
564        } => directory::charts(
565            config,
566            store,
567            &directory::country(config, &country)?,
568            category.as_deref(),
569            limit,
570            random,
571            stop,
572        )?,
573        Action::Search {
574            query,
575            country,
576            limit,
577        } => {
578            let country = directory::country(config, &country)?;
579            let mut rows = search(config, &query, &country, limit.into(), stop)?;
580            directory::annotate_subscriptions(store, &mut rows)?;
581            json!(rows)
582        }
583        Action::Discover { url } => json!(discover(config, &url, stop)?),
584        Action::Preview { url } => {
585            let subscription_url = url.clone();
586            let resolved = if feed::is_apple_url(&url) {
587                let urls = discover(config, &url, stop)?;
588                if urls.len() != 1 {
589                    return Err(error(crate::t!("podcast_no_public_feed")));
590                }
591                urls[0].clone()
592            } else {
593                url
594            };
595            let mut value = json!(fetch(config, &resolved, None, stop)?);
596            value["subscription_url"] = json!(subscription_url);
597            value
598        }
599        Action::Add { url } => {
600            let urls = discover(config, &url, stop)?;
601            if urls.len() != 1 {
602                return Err(error(crate::t!("podcast_choose_feed")));
603            }
604            let p = fetch(config, &urls[0], None, stop)?
605                .ok_or_else(|| error(crate::t!("podcast_invalid_feed")))?;
606            if stop.load(std::sync::atomic::Ordering::Relaxed) {
607                return Err(DomainError::new(ErrorCode::Cancelled).into());
608            }
609            json!(store.podcast_subscribe(&p, &url)?)
610        }
611        Action::List { page: p, query } => store.read_snapshot(|store| {
612            let query = query.to_lowercase();
613            let feeds: Vec<_> = store
614                .podcast_feeds()?
615                .into_iter()
616                .filter(|feed| feed.title.to_lowercase().contains(&query))
617                .collect();
618            let total = feeds.len();
619            let limit = if p.all { total } else { usize::from(p.limit) };
620            let mut rows = Vec::new();
621            for feed in feeds.into_iter().skip(p.offset).take(limit) {
622                let mut value = json!(feed);
623                value["unplayed_count"] = json!(store.podcast_unplayed_count(&feed.id)?);
624                value["sort"] = json!(store.podcast_settings(&feed.id)?.sort);
625                rows.push(value);
626            }
627            Ok(page_result(&rows, total, p))
628        })?,
629        Action::Episodes { id, query, page: p } => {
630            let (items, total) = store.podcast_episodes_page(&id, &query, &p)?;
631            let items = items
632                .iter()
633                .map(|e| episode_value(store, e, |path| files.is_file(path)))
634                .collect::<Result<Vec<_>>>()?;
635            let mut value = page_result(&items, total, p);
636            value["feed_title"] = json!(store.podcast_feed(&id)?.title);
637            value
638        }
639        Action::Refresh { id } => refresh(config, store, id.as_deref(), stop)?,
640        Action::Unsubscribe { id } => {
641            store.podcast_unsubscribe(&id)?;
642            json!({"id":id,"subscribed":false})
643        }
644        Action::Mark { id, state } => {
645            let mut e = store.podcast_episode(&id)?;
646            e.mark(state == "played");
647            store.podcast_save_progress(&id, &e.progress())?;
648            json!(store.podcast_episode(&id)?)
649        }
650        Action::Subtitles {
651            id,
652            file,
653            transcribe,
654        } => {
655            super::transcript::manage(config, store, &id, file.as_deref(), transcribe, stop, None)?
656        }
657        Action::Download { id } => json!(super::download::foreground(config, store, &id, stop)?),
658        Action::Downloads { action } => match action {
659            DownloadAction::Stats => {
660                let rows = store.podcast_downloads()?;
661                let bytes: u64 = rows.iter().map(|d| d.bytes).sum();
662                let directory = config
663                    .settings
664                    .podcasts
665                    .directory
666                    .clone()
667                    .unwrap_or_else(|| config.data_dir.join("podcasts"));
668                json!({"downloads":rows.len(),"bytes":bytes,"completed":rows.iter().filter(|d| d.phase() == DownloadState::Complete).count(),"available_bytes":fs2::available_space(directory).ok()})
669            }
670            DownloadAction::List => {
671                let mut rows = Vec::new();
672                for d in store.podcast_downloads()? {
673                    let mut value =
674                        episode_value(store, &store.podcast_episode(&d.episode_id)?, |path| {
675                            files.is_file(path)
676                        })?;
677                    value
678                        .as_object_mut()
679                        .unwrap()
680                        .extend(json!(d).as_object().unwrap().clone());
681                    rows.push(value);
682                }
683                json!(rows)
684            }
685            DownloadAction::Resume { id } => {
686                json!(super::download::foreground(config, store, &id, stop)?)
687            }
688            DownloadAction::Pause { ref id }
689            | DownloadAction::Cancel { ref id }
690            | DownloadAction::Remove { ref id } => {
691                let d = store.podcast_download_transaction(id, |current| {
692                    let mut d = current.ok_or_else(|| error(crate::t!("podcast_not_found")))?;
693                    if matches!(action, DownloadAction::Remove { .. }) {
694                        super::download::remove(config, store, &mut d)?;
695                        return Ok(d);
696                    }
697                    if d.phase() == DownloadState::Complete {
698                        return Ok(d);
699                    }
700                    d.set_phase(if matches!(action, DownloadAction::Pause { .. }) {
701                        DownloadState::Paused
702                    } else {
703                        DownloadState::Cancelled
704                    });
705                    d.retry_at = None;
706                    d.generation = d.generation.saturating_add(1);
707                    store.podcast_save_download(&d)?;
708                    Ok(d)
709                })?;
710                json!(d)
711            }
712        },
713        Action::Queue {
714            action: QueueAction::Start { .. },
715        } => return Err(error(crate::t!("podcast_playback_only"))),
716        Action::Queue {
717            action: QueueAction::List,
718        } => files.read_page(store, |store| {
719            let items = store
720                .podcast_queue()?
721                .iter()
722                .map(|e| episode_value(store, e, |path| files.observed_file(path)))
723                .collect::<Result<Vec<_>>>()?;
724            Ok(json!(items))
725        })?,
726        Action::Queue { action } => {
727            json!(store.podcast_queue_update(action)?)
728        }
729        Action::Export { file, overwrite } => {
730            let feeds = store.podcast_feeds()?;
731            let mut text = String::from(
732                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><opml version=\"2.0\"><head><title>radio-cli</title></head><body>",
733            );
734            for f in &feeds {
735                text.push_str(&format!(
736                    "<outline type=\"rss\" text=\"{}\" xmlUrl=\"{}\" htmlUrl=\"{}\"/>",
737                    quick_xml::escape::escape(&f.title),
738                    quick_xml::escape::escape(&f.url),
739                    quick_xml::escape::escape(&f.website)
740                ));
741            }
742            text.push_str("</body></opml>");
743            write_export(&file, overwrite, |f| {
744                std::io::Write::write_all(f, text.as_bytes())
745            })?;
746            json!({"exported":feeds.len()})
747        }
748        Action::Import { file, dry_run } => {
749            if stop.load(std::sync::atomic::Ordering::Relaxed) {
750                return Err(DomainError::new(ErrorCode::Cancelled).into());
751            }
752            use std::io::Read;
753            let mut data = Vec::new();
754            std::fs::File::open(file)?
755                .take(10 * 1024 * 1024 + 1)
756                .read_to_end(&mut data)?;
757            let urls = opml(&data)?;
758            if dry_run {
759                json!({"urls":urls})
760            } else {
761                let mut results = vec![];
762                for batch in urls.chunks(4) {
763                    let fetched = std::thread::scope(|scope| {
764                        let tasks: Vec<_> = batch
765                            .iter()
766                            .map(|u| scope.spawn(move || fetch(config, u, None, stop)))
767                            .collect();
768                        tasks
769                            .into_iter()
770                            .map(|t| {
771                                t.join()
772                                    .unwrap_or_else(|_| Err(error(crate::t!("podcast_network"))))
773                            })
774                            .collect::<Vec<_>>()
775                    });
776                    for (u, fetched) in batch.iter().zip(fetched) {
777                        if stop.load(std::sync::atomic::Ordering::Relaxed) {
778                            return Err(DomainError::new(ErrorCode::Cancelled).into());
779                        }
780                        match fetched.and_then(|p| {
781                            if stop.load(std::sync::atomic::Ordering::Relaxed) {
782                                return Err(DomainError::new(ErrorCode::Cancelled).into());
783                            }
784                            store.podcast_subscribe(
785                                &p.ok_or_else(|| error(crate::t!("podcast_invalid_feed")))?,
786                                u,
787                            )
788                        }) {
789                            Ok(f) => results.push(json!({"id":f.id,"ok":true})),
790                            Err(e) => {
791                                if e.downcast_ref::<DomainError>()
792                                    .is_some_and(|e| e.code == ErrorCode::Cancelled)
793                                {
794                                    return Err(e);
795                                }
796                                if stop.load(std::sync::atomic::Ordering::Relaxed) {
797                                    return Err(DomainError::new(ErrorCode::Cancelled).into());
798                                }
799                                results.push(json!({"ok":false,"error":e.to_string()}));
800                            }
801                        }
802                    }
803                }
804                json!(results)
805            }
806        }
807        Action::AutoNext { state } => {
808            store.set_meta("podcast_auto_next", &state)?;
809            json!({"auto_next":state=="on"})
810        }
811        Action::Speed { rate } => {
812            valid_speed(rate)?;
813            store.set_meta("podcast_speed", &rate.to_string())?;
814            json!({"speed":rate})
815        }
816        Action::Seek { .. } | Action::Play { .. } => {
817            return Err(error(crate::t!("podcast_playback_only")));
818        }
819    })
820}
821fn write_export(
822    path: &std::path::Path,
823    overwrite: bool,
824    write: impl FnOnce(&mut std::fs::File) -> std::io::Result<()>,
825) -> Result<()> {
826    use std::io::ErrorKind;
827    use std::os::unix::fs::PermissionsExt;
828
829    let mut target = path.to_owned();
830    let mut builder = tempfile::Builder::new();
831    let mut existing = None;
832    if overwrite {
833        match std::fs::symlink_metadata(path) {
834            Ok(_) => {
835                target = path.canonicalize()?;
836                anyhow::ensure!(
837                    std::fs::metadata(&target)?.is_file(),
838                    "{}",
839                    crate::t!("podcast_file_exists")
840                );
841                existing = Some(std::fs::OpenOptions::new().write(true).open(&target)?);
842            }
843            Err(e) if e.kind() == ErrorKind::NotFound => (),
844            Err(e) => return Err(e.into()),
845        }
846    }
847    if existing.is_none() {
848        builder.permissions(std::fs::Permissions::from_mode(0o666));
849    }
850    let directory = target
851        .parent()
852        .filter(|p| !p.as_os_str().is_empty())
853        .unwrap_or(std::path::Path::new("."));
854    let mut temp = builder.tempfile_in(directory)?;
855    let permissions = existing
856        .as_ref()
857        .map(|source| crate::files::prepare_replacement_permissions(source, temp.as_file()))
858        .transpose()?;
859    write(temp.as_file_mut())?;
860    if let Some(permissions) = permissions {
861        temp.as_file().set_permissions(permissions)?;
862    }
863    temp.as_file().sync_all()?;
864    if existing.is_some() {
865        temp.persist(target)?;
866    } else {
867        temp.persist_noclobber(target)?;
868    }
869    Ok(())
870}
871
872#[cfg(test)]
873mod export_tests {
874    use super::*;
875    use std::{
876        io::Write,
877        os::unix::fs::{PermissionsExt, symlink},
878    };
879
880    #[cfg(target_os = "linux")]
881    #[test]
882    fn overwrite_preserves_named_acl_entries_and_removes_inherited_grants() -> Result<()> {
883        use rustix::fs::{XattrFlags, getxattr, removexattr, setxattr};
884        use rustix::io::Errno;
885
886        // Linux POSIX ACL xattr version 2. Only the named user has group-class
887        // read permission; chmod(0640) alone gives that permission to the group.
888        let named_reader = |uid: u32| {
889            let mut bytes = 2u32.to_le_bytes().to_vec();
890            for (tag, permissions, id) in [
891                (1u16, 6u16, u32::MAX), // owner
892                (2, 4, uid),            // named user
893                (4, 0, u32::MAX),       // owning group
894                (16, 4, u32::MAX),      // mask
895                (32, 0, u32::MAX),      // other
896            ] {
897                bytes.extend(tag.to_le_bytes());
898                bytes.extend(permissions.to_le_bytes());
899                bytes.extend(id.to_le_bytes());
900            }
901            bytes
902        };
903        let dir = tempfile::tempdir()?;
904        let target = dir.path().join("feeds.opml");
905        std::fs::write(&target, b"old")?;
906        let access = c"system.posix_acl_access";
907        let original = named_reader(65534);
908        match setxattr(&target, access, &original, XattrFlags::empty()) {
909            Err(Errno::NOTSUP) => return Ok(()),
910            result => result?,
911        }
912        setxattr(
913            dir.path(),
914            c"system.posix_acl_default",
915            &named_reader(65533),
916            XattrFlags::empty(),
917        )?;
918        for extended in [true, false] {
919            if !extended {
920                removexattr(&target, access)?;
921            }
922            let mode = std::fs::metadata(&target)?.permissions().mode();
923            write_export(&target, true, |f| f.write_all(b"new"))?;
924            assert_eq!(std::fs::metadata(&target)?.permissions().mode(), mode);
925            let mut bytes = [0; 128];
926            let acl = getxattr(&target, access, &mut bytes[..]);
927            if extended {
928                assert_eq!(mode & 0o777, 0o640);
929                assert_eq!(&bytes[..acl?], original);
930            } else {
931                assert_eq!(acl, Err(Errno::NODATA));
932            }
933            assert_eq!(std::fs::read(&target)?, b"new");
934        }
935        Ok(())
936    }
937
938    #[cfg(target_os = "macos")]
939    #[test]
940    fn overwrite_preserves_darwin_access_entries() -> Result<()> {
941        use std::process::Command;
942        let dir = tempfile::tempdir()?;
943        let target = dir.path().join("feeds.opml");
944        std::fs::write(&target, b"old")?;
945        anyhow::ensure!(
946            Command::new("/bin/chmod")
947                .args(["+a", "everyone allow read"])
948                .arg(&target)
949                .status()?
950                .success()
951        );
952        let entries = || -> Result<Vec<String>> {
953            let listing = Command::new("/bin/ls").arg("-le").arg(&target).output()?;
954            anyhow::ensure!(listing.status.success());
955            Ok(String::from_utf8(listing.stdout)?
956                .lines()
957                .skip(1)
958                .map(str::to_owned)
959                .collect())
960        };
961        let before = entries()?;
962        assert!(!before.is_empty());
963        write_export(&target, true, |f| f.write_all(b"new"))?;
964        assert_eq!(entries()?, before);
965        Ok(())
966    }
967
968    #[test]
969    fn interrupted_export_preserves_the_old_file_and_its_symlink() -> Result<()> {
970        let dir = tempfile::tempdir()?;
971        let file = dir.path().join("old");
972        let link = dir.path().join("link");
973        std::fs::write(&file, b"old")?;
974        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o4640))?;
975        symlink(&file, &link)?;
976        assert!(
977            write_export(&link, true, |f| {
978                f.write_all(b"incomplete")?;
979                Err(std::io::Error::other("disk full"))
980            })
981            .is_err()
982        );
983        assert_eq!(std::fs::read(&link)?, b"old");
984        write_export(&link, true, |f| f.write_all(b"new"))?;
985        assert!(link.is_symlink());
986        assert_eq!(std::fs::read(&file)?, b"new");
987        assert_eq!(
988            std::fs::metadata(file)?.permissions().mode() & 0o7777,
989            0o4640
990        );
991        Ok(())
992    }
993}
994fn opml(data: &[u8]) -> Result<Vec<String>> {
995    use quick_xml::{Reader, events::Event};
996    if data.len() > 10 * 1024 * 1024 {
997        return Err(error(crate::t!("podcast_limit")));
998    }
999    let mut reader = Reader::from_reader(data);
1000    let mut depth = 0;
1001    let mut root = false;
1002    let mut urls = vec![];
1003    let mut seen = std::collections::HashSet::new();
1004    loop {
1005        let event = reader
1006            .read_event()
1007            .map_err(|_| error(crate::t!("podcast_invalid_feed")))?;
1008        match &event {
1009            Event::Start(e) | Event::Empty(e) => {
1010                if depth == 0 && (root || e.local_name().as_ref() != "opml") {
1011                    return Err(error(crate::t!("podcast_invalid_feed")));
1012                }
1013                root = true;
1014                if e.local_name().as_ref() == "outline" {
1015                    for a in e.attributes() {
1016                        let a = a.map_err(|_| error(crate::t!("podcast_invalid_feed")))?;
1017                        if a.key.as_ref() == "xmlUrl" {
1018                            let value = a
1019                                .normalized_value(quick_xml::XmlVersion::Implicit1_0)
1020                                .map_err(|_| error(crate::t!("podcast_invalid_feed")))?;
1021                            let u = super::feed::url(&value, None)?.to_string();
1022                            if seen.insert(u.clone()) {
1023                                urls.push(u);
1024                            }
1025                        }
1026                    }
1027                }
1028                if matches!(event, Event::Start(_)) {
1029                    depth += 1;
1030                }
1031                if depth > 64 || urls.len() > 10000 {
1032                    return Err(error(crate::t!("podcast_limit")));
1033                }
1034            }
1035            Event::End(_) => {
1036                if depth == 0 {
1037                    return Err(error(crate::t!("podcast_invalid_feed")));
1038                }
1039                depth -= 1;
1040            }
1041            Event::DocType(_) => return Err(error(crate::t!("podcast_invalid_feed"))),
1042            Event::Eof => break,
1043            _ => {}
1044        }
1045    }
1046    if !root || depth != 0 {
1047        return Err(error(crate::t!("podcast_invalid_feed")));
1048    }
1049    Ok(urls)
1050}