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::model::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::model::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}
182impl Action {
183    pub(crate) fn polls_browse(&self) -> bool {
184        matches!(
185            self,
186            Self::List { .. }
187                | Self::Bookmarks { .. }
188                | Self::Library { .. }
189                | Self::Episodes { .. }
190                | Self::Downloads {
191                    action: DownloadAction::List
192                }
193                | Self::Queue {
194                    action: QueueAction::List
195                }
196        )
197    }
198
199    pub(crate) fn is_query(&self) -> bool {
200        matches!(
201            self,
202            Self::Chapters { .. }
203                | Self::Bookmarks { .. }
204                | Self::Library { .. }
205                | Self::List { .. }
206                | Self::Episodes { .. }
207                | Self::Search { .. }
208                | Self::Browse { .. }
209                | Self::Categories { .. }
210                | Self::Charts { .. }
211                | Self::Discover { .. }
212                | Self::Preview { .. }
213                | Self::Downloads {
214                    action: DownloadAction::List
215                }
216                | Self::Queue {
217                    action: QueueAction::List
218                }
219        )
220    }
221
222    /// Only actions that target a single episode may inherit the TUI player.
223    pub(crate) fn episode_id_mut(&mut self) -> Option<&mut String> {
224        match self {
225            Self::Jump { id, .. }
226            | Self::Chapters { id }
227            | Self::Bookmarks { id }
228            | Self::Bookmark { id, .. }
229            | Self::Save { id, .. }
230            | Self::Dismiss { id }
231            | Self::Play { id, .. }
232            | Self::Mark { id, .. }
233            | Self::Subtitles { id, .. }
234            | Self::Download { id } => Some(id),
235            Self::Queue {
236                action:
237                    QueueAction::Add { id }
238                    | QueueAction::Remove { id }
239                    | QueueAction::Start { id, .. }
240                    | QueueAction::Next { id, .. }
241                    | QueueAction::Move { id, .. }
242                    | QueueAction::MoveAdjacent { id, .. },
243            } => Some(id),
244            Self::Downloads {
245                action:
246                    DownloadAction::Pause { id }
247                    | DownloadAction::Resume { id }
248                    | DownloadAction::Cancel { id }
249                    | DownloadAction::Remove { id },
250            } => Some(id),
251            _ => None,
252        }
253    }
254}
255
256pub fn parse_time(value: &str) -> Result<u64> {
257    fn millis(value: &str) -> Option<u64> {
258        let (clock, fraction) = value
259            .split_once('.')
260            .map_or((value, None), |(c, f)| (c, Some(f)));
261        let mut seconds = 0u64;
262        for (index, field) in clock.split(':').enumerate() {
263            if index >= 3 || field.is_empty() || !field.bytes().all(|c| c.is_ascii_digit()) {
264                return None;
265            }
266            let part = field.parse::<u64>().ok()?;
267            if index > 0 && part >= 60 {
268                return None;
269            }
270            seconds = seconds.checked_mul(60)?.checked_add(part)?;
271        }
272        let mut result = seconds.checked_mul(1000)?;
273        if let Some(fraction) = fraction {
274            if fraction.is_empty() || !fraction.bytes().all(|c| c.is_ascii_digit()) {
275                return None;
276            }
277            for (digit, weight) in fraction.bytes().zip([100, 10, 1]) {
278                result = result.checked_add(u64::from(digit - b'0') * weight)?;
279            }
280        }
281        (result <= i64::MAX as u64).then_some(result)
282    }
283    millis(value).ok_or_else(|| error(crate::t!("podcast_invalid_time")))
284}
285
286#[cfg(test)]
287mod time_tests {
288    #[test]
289    fn validates_user_clock_fields_before_combining_them() {
290        for (v, ms) in [
291            ("65", 65000),
292            ("01:02.3456", 62345),
293            ("2:03:04", 7384000),
294            ("9223372036854775.807", i64::MAX as u64),
295        ] {
296            assert_eq!(super::parse_time(v).unwrap(), ms);
297        }
298        for v in [
299            "1:-1",
300            "1:2:3:4",
301            "1:60",
302            "+2",
303            "1e3",
304            "1.5:20",
305            "1::20",
306            "NaN",
307            "9223372036854775.808",
308        ] {
309            assert!(super::parse_time(v).is_err(), "{v}");
310        }
311    }
312}
313pub fn refresh(
314    config: &Config,
315    store: &Store,
316    id: Option<&str>,
317    stop: &Arc<AtomicBool>,
318) -> Result<Value> {
319    if stop.load(std::sync::atomic::Ordering::Relaxed) {
320        return Err(DomainError::new(ErrorCode::Cancelled).into());
321    }
322    let feeds = if let Some(id) = id {
323        vec![store.podcast_feed(id)?]
324    } else {
325        store.podcast_feeds()?
326    };
327    refresh_feeds(config, store, &feeds, stop)
328}
329fn fetch_batches<T: Sync>(
330    items: &[T],
331    stop: &Arc<AtomicBool>,
332    fetch_one: impl Fn(&T) -> Result<Option<Preview>> + Sync,
333    mut handle: impl FnMut(&T, Result<Option<Preview>>) -> Result<Value>,
334) -> Result<Value> {
335    let mut results = Vec::with_capacity(items.len());
336    for batch in items.chunks(4) {
337        let fetched = std::thread::scope(|scope| {
338            let tasks: Vec<_> = batch
339                .iter()
340                .map(|item| scope.spawn(|| fetch_one(item)))
341                .collect();
342            tasks
343                .into_iter()
344                .map(|t| {
345                    t.join()
346                        .unwrap_or_else(|_| Err(error(crate::t!("podcast_network"))))
347                })
348                .collect::<Vec<_>>()
349        });
350        for (item, fetched) in batch.iter().zip(fetched) {
351            crate::error::check_cancelled(stop)?;
352            results.push(handle(item, fetched)?);
353        }
354    }
355    Ok(json!(results))
356}
357
358fn is_cancelled(e: &anyhow::Error) -> bool {
359    e.downcast_ref::<DomainError>()
360        .is_some_and(|e| e.code == ErrorCode::Cancelled)
361}
362
363pub(super) fn refresh_feeds(
364    config: &Config,
365    store: &Store,
366    feeds: &[Feed],
367    stop: &Arc<AtomicBool>,
368) -> Result<Value> {
369    fetch_batches(
370        feeds,
371        stop,
372        |f| fetch(config, &f.url, Some(f), stop),
373        |f, fetched| {
374            let result = fetched.and_then(|p| {
375                crate::error::check_cancelled(stop)?;
376                store.podcast_refresh_merge(f, p)
377            });
378            match result {
379                Ok(()) => {
380                    crate::error::check_cancelled(stop)?;
381                    Ok(json!({"id":f.id,"title":f.title,"ok":true}))
382                }
383                Err(e) => {
384                    if is_cancelled(&e) {
385                        return Err(e);
386                    }
387                    crate::error::check_cancelled(stop)?;
388                    let mut f = f.clone();
389                    f.error = Some(e.to_string());
390                    f.failures = f.failures.saturating_add(1);
391                    f.refreshed_at = Some(crate::timestamp::now());
392                    store.podcast_refresh_error(&f)?;
393                    Ok(json!({"id":f.id,"title":f.title,"ok":false,"error":e.to_string()}))
394                }
395            }
396        },
397    )
398}
399pub fn manage(
400    config: &Config,
401    store: &Store,
402    action: Action,
403    stop: &Arc<AtomicBool>,
404) -> Result<Value> {
405    let files = Arc::new(super::download_files::DownloadFiles::new(stop.clone()));
406    manage_with_files(config, store, action, stop, &files)
407}
408
409pub(super) fn manage_with_files(
410    config: &Config,
411    store: &Store,
412    mut action: Action,
413    stop: &Arc<AtomicBool>,
414    files: &Arc<super::download_files::DownloadFiles>,
415) -> Result<Value> {
416    if let Some(id) = action.episode_id_mut() {
417        *id = store.podcast_episode_id(id)?;
418    }
419    Ok(match action {
420        Action::Chapters { id } => {
421            super::extras::chapters(config, &store.podcast_episode(&id)?, stop)?
422        }
423        Action::Bookmarks { id } => {
424            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();
425            json!({"items":rows,"total":rows.len()})
426        }
427        Action::Bookmark { id, time, note } => json!(
428            store.podcast_add_bookmark(
429                &id,
430                parse_time(
431                    time.as_deref()
432                        .ok_or_else(|| error(crate::t!("podcast_invalid_time")))?
433                )?,
434                &note
435            )?
436        ),
437        Action::BookmarkEdit { id, note } => {
438            store.podcast_edit_bookmark(&id, note.as_deref())?;
439            json!({"id":id,"removed":note.is_none()})
440        }
441        Action::Settings { id, key, value } => match (key, value) {
442            (None, None) => json!(store.podcast_settings(&id)?),
443            (Some(key), Some(value)) => json!(store.podcast_set_setting(&id, &key, &value)?),
444            _ => return Err(error(crate::t!("podcast_invalid_setting"))),
445        },
446        Action::Jump { .. } | Action::Sleep { .. } => {
447            return Err(error(crate::t!("podcast_playback_only")));
448        }
449        Action::Library { options } => store.podcast_library_with_files(&options, files)?,
450        Action::Save { id, remove } => {
451            store.podcast_save_episode(&id, remove)?;
452            json!({"id":id,"saved":!remove})
453        }
454        Action::Dismiss { id } => {
455            store.podcast_dismiss_inbox(&id)?;
456            json!({"id":id,"dismissed":true})
457        }
458        Action::MarkBatch { ids, unplayed } => {
459            let tx = rusqlite::Transaction::new_unchecked(
460                &store.conn,
461                rusqlite::TransactionBehavior::Immediate,
462            )?;
463            for id in &ids {
464                let mut e = store.podcast_episode(id)?;
465                e.mark(!unplayed);
466                Store::write_podcast_progress(&tx, &e.id, &e.progress())?;
467            }
468            tx.commit()?;
469            json!({"marked":ids.len()})
470        }
471        Action::Resume | Action::Relative { .. } => {
472            return Err(error(crate::t!("podcast_playback_only")));
473        }
474        Action::Browse { country } => directory::home(&directory::country(config, &country)?),
475        Action::Categories { country } => {
476            directory::categories(&directory::country(config, &country)?)
477        }
478        Action::Charts {
479            country,
480            category,
481            limit,
482            random,
483        } => directory::charts(
484            config,
485            store,
486            &directory::country(config, &country)?,
487            category.as_deref(),
488            limit,
489            random,
490            stop,
491        )?,
492        Action::Search {
493            query,
494            country,
495            limit,
496        } => {
497            let country = directory::country(config, &country)?;
498            let mut rows = search(config, &query, &country, limit.into(), stop)?;
499            directory::annotate_subscriptions(store, &mut rows)?;
500            json!(rows)
501        }
502        Action::Discover { url } => json!(discover(config, &url, stop)?),
503        Action::Preview { url } => {
504            let subscription_url = url.clone();
505            let resolved = if feed::is_apple_url(&url) {
506                let urls = discover(config, &url, stop)?;
507                if urls.len() != 1 {
508                    return Err(error(crate::t!("podcast_no_public_feed")));
509                }
510                urls[0].clone()
511            } else {
512                url
513            };
514            let mut value = json!(fetch(config, &resolved, None, stop)?);
515            value["subscription_url"] = json!(subscription_url);
516            value
517        }
518        Action::Add { url } => {
519            let urls = discover(config, &url, stop)?;
520            if urls.len() != 1 {
521                return Err(error(crate::t!("podcast_choose_feed")));
522            }
523            let p = fetch(config, &urls[0], None, stop)?
524                .ok_or_else(|| error(crate::t!("podcast_invalid_feed")))?;
525            if stop.load(std::sync::atomic::Ordering::Relaxed) {
526                return Err(DomainError::new(ErrorCode::Cancelled).into());
527            }
528            json!(store.podcast_subscribe(&p, &url)?)
529        }
530        Action::List { page: p, query } => store.read_snapshot(|store| {
531            let (rows, total) = store.podcast_feeds_page_details(&query, &p)?;
532            Ok(page_result(&rows, total, p))
533        })?,
534        Action::Episodes { id, query, page: p } => files.read_page_with(|| {
535            store.read_snapshot(|store| {
536                let (feed_title, items, total) =
537                    store.podcast_episodes_details_page(&id, &query, &p, |path| {
538                        files.observed_file(path)
539                    })?;
540                let mut value = page_result(&items, total, p.clone());
541                value["feed_title"] = json!(feed_title);
542                Ok(value)
543            })
544        })?,
545        Action::Refresh { id } => refresh(config, store, id.as_deref(), stop)?,
546        Action::Unsubscribe { id } => {
547            store.podcast_unsubscribe(&id)?;
548            json!({"id":id,"subscribed":false})
549        }
550        Action::Mark { id, state } => {
551            let mut e = store.podcast_episode(&id)?;
552            e.mark(state == "played");
553            store.podcast_save_progress(&id, &e.progress())?;
554            json!(store.podcast_episode(&id)?)
555        }
556        Action::Subtitles {
557            id,
558            file,
559            transcribe,
560        } => {
561            super::transcript::manage(config, store, &id, file.as_deref(), transcribe, stop, None)?
562        }
563        Action::Download { id } => json!(super::download::foreground(config, store, &id, stop)?),
564        Action::Downloads { action } => match action {
565            DownloadAction::Stats => {
566                let rows = store.podcast_downloads()?;
567                let bytes: u64 = rows.iter().map(|d| d.bytes).sum();
568                let directory = config
569                    .settings
570                    .podcasts
571                    .directory
572                    .clone()
573                    .unwrap_or_else(|| config.data_dir.join("podcasts"));
574                json!({"downloads":rows.len(),"bytes":bytes,"completed":rows.iter().filter(|d| d.phase() == DownloadState::Complete).count(),"available_bytes":fs2::available_space(directory).ok()})
575            }
576            DownloadAction::List => files.read_page_with(|| {
577                store.read_snapshot(|store| {
578                    Ok(json!(store.podcast_downloads_details(|path| {
579                        files.observed_file(path)
580                    })?))
581                })
582            })?,
583            DownloadAction::Resume { id } => {
584                json!(super::download::foreground(config, store, &id, stop)?)
585            }
586            DownloadAction::Pause { ref id }
587            | DownloadAction::Cancel { ref id }
588            | DownloadAction::Remove { ref id } => {
589                let d = store.podcast_download_transaction(id, |current| {
590                    let mut d = current.ok_or_else(|| error(crate::t!("podcast_not_found")))?;
591                    if matches!(action, DownloadAction::Remove { .. }) {
592                        super::download::remove(config, store, &mut d)?;
593                        return Ok(d);
594                    }
595                    if d.phase() == DownloadState::Complete {
596                        return Ok(d);
597                    }
598                    d.set_phase(if matches!(action, DownloadAction::Pause { .. }) {
599                        DownloadState::Paused
600                    } else {
601                        DownloadState::Cancelled
602                    });
603                    d.retry_at = None;
604                    d.generation = d.generation.saturating_add(1);
605                    store.podcast_save_download(&d)?;
606                    Ok(d)
607                })?;
608                json!(d)
609            }
610        },
611        Action::Queue {
612            action: QueueAction::Start { .. },
613        } => return Err(error(crate::t!("podcast_playback_only"))),
614        Action::Queue {
615            action: QueueAction::List,
616        } => files.read_page_with(|| {
617            store.read_snapshot(|store| {
618                Ok(json!(
619                    store.podcast_queue_details(|path| files.observed_file(path))?
620                ))
621            })
622        })?,
623        Action::Queue { action } => {
624            json!(store.podcast_queue_update(action)?)
625        }
626        Action::Export { file, overwrite } => {
627            let feeds = store.podcast_feeds()?;
628            let mut text = String::from(
629                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><opml version=\"2.0\"><head><title>radio-cli</title></head><body>",
630            );
631            let xml_safe = |value: &str| {
632                let cleaned: String = value
633                    .chars()
634                    .filter(|&c| c >= '\x20' || matches!(c, '\t' | '\n' | '\r'))
635                    .collect();
636                quick_xml::escape::escape(&cleaned).into_owned()
637            };
638            for f in &feeds {
639                text.push_str(&format!(
640                    "<outline type=\"rss\" text=\"{}\" xmlUrl=\"{}\" htmlUrl=\"{}\"/>",
641                    xml_safe(&f.title),
642                    xml_safe(&f.url),
643                    xml_safe(&f.website)
644                ));
645            }
646            text.push_str("</body></opml>");
647            write_export(&file, overwrite, |f| {
648                std::io::Write::write_all(f, text.as_bytes())
649            })?;
650            json!({"exported":feeds.len()})
651        }
652        Action::Import { file, dry_run } => {
653            crate::error::check_cancelled(stop)?;
654            use std::io::Read;
655            let mut data = Vec::new();
656            std::fs::File::open(file)?
657                .take(10 * 1024 * 1024 + 1)
658                .read_to_end(&mut data)?;
659            let urls = opml(&data)?;
660            if dry_run {
661                json!({"urls":urls})
662            } else {
663                fetch_batches(
664                    &urls,
665                    stop,
666                    |u| fetch(config, u, None, stop),
667                    |u, fetched| match fetched.and_then(|p| {
668                        crate::error::check_cancelled(stop)?;
669                        store.podcast_subscribe(
670                            &p.ok_or_else(|| error(crate::t!("podcast_invalid_feed")))?,
671                            u,
672                        )
673                    }) {
674                        Ok(f) => Ok(json!({"id":f.id,"ok":true})),
675                        Err(e) => {
676                            if is_cancelled(&e) {
677                                return Err(e);
678                            }
679                            crate::error::check_cancelled(stop)?;
680                            Ok(json!({"ok":false,"error":e.to_string()}))
681                        }
682                    },
683                )?
684            }
685        }
686        Action::AutoNext { state } => {
687            store.set_meta("podcast_auto_next", &state)?;
688            json!({"auto_next":state=="on"})
689        }
690        Action::Speed { rate } => {
691            valid_speed(rate)?;
692            store.set_meta("podcast_speed", &rate.to_string())?;
693            json!({"speed":rate})
694        }
695        Action::Seek { .. } | Action::Play { .. } => {
696            return Err(error(crate::t!("podcast_playback_only")));
697        }
698    })
699}
700fn write_export(
701    path: &std::path::Path,
702    overwrite: bool,
703    write: impl FnOnce(&mut std::fs::File) -> std::io::Result<()>,
704) -> Result<()> {
705    use std::io::ErrorKind;
706    use std::os::unix::fs::PermissionsExt;
707
708    let mut target = path.to_owned();
709    let mut builder = tempfile::Builder::new();
710    let mut existing = None;
711    if overwrite {
712        match std::fs::symlink_metadata(path) {
713            Ok(_) => {
714                target = path.canonicalize()?;
715                anyhow::ensure!(
716                    std::fs::metadata(&target)?.is_file(),
717                    "{}",
718                    crate::t!("podcast_file_exists")
719                );
720                existing = Some(std::fs::OpenOptions::new().write(true).open(&target)?);
721            }
722            Err(e) if e.kind() == ErrorKind::NotFound => (),
723            Err(e) => return Err(e.into()),
724        }
725    }
726    if existing.is_none() {
727        builder.permissions(std::fs::Permissions::from_mode(0o666));
728    }
729    let directory = target
730        .parent()
731        .filter(|p| !p.as_os_str().is_empty())
732        .unwrap_or(std::path::Path::new("."));
733    let mut temp = builder.tempfile_in(directory)?;
734    let permissions = existing
735        .as_ref()
736        .map(|source| crate::files::prepare_replacement_permissions(source, temp.as_file()))
737        .transpose()?;
738    write(temp.as_file_mut())?;
739    if let Some(permissions) = permissions {
740        temp.as_file().set_permissions(permissions)?;
741    }
742    temp.as_file().sync_all()?;
743    if existing.is_some() {
744        temp.persist(target)?;
745    } else {
746        temp.persist_noclobber(target)?;
747    }
748    Ok(())
749}
750
751#[cfg(test)]
752mod export_tests {
753    use super::*;
754    use std::{
755        io::Write,
756        os::unix::fs::{PermissionsExt, symlink},
757    };
758
759    #[cfg(target_os = "linux")]
760    #[test]
761    fn overwrite_preserves_named_acl_entries_and_removes_inherited_grants() -> Result<()> {
762        use rustix::fs::{XattrFlags, getxattr, removexattr, setxattr};
763        use rustix::io::Errno;
764
765        // Linux POSIX ACL xattr version 2. Only the named user has group-class
766        // read permission; chmod(0640) alone gives that permission to the group.
767        let named_reader = |uid: u32| {
768            let mut bytes = 2u32.to_le_bytes().to_vec();
769            for (tag, permissions, id) in [
770                (1u16, 6u16, u32::MAX), // owner
771                (2, 4, uid),            // named user
772                (4, 0, u32::MAX),       // owning group
773                (16, 4, u32::MAX),      // mask
774                (32, 0, u32::MAX),      // other
775            ] {
776                bytes.extend(tag.to_le_bytes());
777                bytes.extend(permissions.to_le_bytes());
778                bytes.extend(id.to_le_bytes());
779            }
780            bytes
781        };
782        let dir = tempfile::tempdir()?;
783        let target = dir.path().join("feeds.opml");
784        std::fs::write(&target, b"old")?;
785        let access = c"system.posix_acl_access";
786        let original = named_reader(65534);
787        match setxattr(&target, access, &original, XattrFlags::empty()) {
788            Err(Errno::NOTSUP) => return Ok(()),
789            result => result?,
790        }
791        setxattr(
792            dir.path(),
793            c"system.posix_acl_default",
794            &named_reader(65533),
795            XattrFlags::empty(),
796        )?;
797        for extended in [true, false] {
798            if !extended {
799                removexattr(&target, access)?;
800            }
801            let mode = std::fs::metadata(&target)?.permissions().mode();
802            write_export(&target, true, |f| f.write_all(b"new"))?;
803            assert_eq!(std::fs::metadata(&target)?.permissions().mode(), mode);
804            let mut bytes = [0; 128];
805            let acl = getxattr(&target, access, &mut bytes[..]);
806            if extended {
807                assert_eq!(mode & 0o777, 0o640);
808                assert_eq!(&bytes[..acl?], original);
809            } else {
810                assert_eq!(acl, Err(Errno::NODATA));
811            }
812            assert_eq!(std::fs::read(&target)?, b"new");
813        }
814        Ok(())
815    }
816
817    #[cfg(target_os = "macos")]
818    #[test]
819    fn overwrite_preserves_darwin_access_entries() -> Result<()> {
820        use std::process::Command;
821        let dir = tempfile::tempdir()?;
822        let target = dir.path().join("feeds.opml");
823        std::fs::write(&target, b"old")?;
824        anyhow::ensure!(
825            Command::new("/bin/chmod")
826                .args(["+a", "everyone allow read"])
827                .arg(&target)
828                .status()?
829                .success()
830        );
831        let entries = || -> Result<Vec<String>> {
832            let listing = Command::new("/bin/ls").arg("-le").arg(&target).output()?;
833            anyhow::ensure!(listing.status.success());
834            Ok(String::from_utf8(listing.stdout)?
835                .lines()
836                .skip(1)
837                .map(str::to_owned)
838                .collect())
839        };
840        let before = entries()?;
841        assert!(!before.is_empty());
842        write_export(&target, true, |f| f.write_all(b"new"))?;
843        assert_eq!(entries()?, before);
844        Ok(())
845    }
846
847    #[test]
848    fn interrupted_export_preserves_the_old_file_and_its_symlink() -> Result<()> {
849        let dir = tempfile::tempdir()?;
850        let file = dir.path().join("old");
851        let link = dir.path().join("link");
852        std::fs::write(&file, b"old")?;
853        std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o4640))?;
854        symlink(&file, &link)?;
855        assert!(
856            write_export(&link, true, |f| {
857                f.write_all(b"incomplete")?;
858                Err(std::io::Error::other("disk full"))
859            })
860            .is_err()
861        );
862        assert_eq!(std::fs::read(&link)?, b"old");
863        write_export(&link, true, |f| f.write_all(b"new"))?;
864        assert!(link.is_symlink());
865        assert_eq!(std::fs::read(&file)?, b"new");
866        assert_eq!(
867            std::fs::metadata(file)?.permissions().mode() & 0o7777,
868            0o4640
869        );
870        Ok(())
871    }
872}
873#[cfg(test)]
874pub(crate) fn opml_for_test(data: &[u8]) -> Result<Vec<String>> {
875    opml(data)
876}
877
878fn opml(data: &[u8]) -> Result<Vec<String>> {
879    use quick_xml::{Reader, events::Event};
880    if data.len() > 10 * 1024 * 1024 {
881        return Err(error(crate::t!("podcast_limit")));
882    }
883    let mut reader = Reader::from_reader(data);
884    let mut depth = 0;
885    let mut root = false;
886    let mut urls = vec![];
887    let mut seen = std::collections::HashSet::new();
888    loop {
889        let event = reader
890            .read_event()
891            .map_err(|_| error(crate::t!("podcast_invalid_feed")))?;
892        match &event {
893            Event::Start(e) | Event::Empty(e) => {
894                if depth == 0 && (root || e.local_name().as_ref() != "opml") {
895                    return Err(error(crate::t!("podcast_invalid_feed")));
896                }
897                root = true;
898                if e.local_name().as_ref() == "outline" {
899                    for a in e.attributes() {
900                        let a = a.map_err(|_| error(crate::t!("podcast_invalid_feed")))?;
901                        if a.key.as_ref() == "xmlUrl" {
902                            let value = a
903                                .normalized_value(quick_xml::XmlVersion::Implicit1_0)
904                                .map_err(|_| error(crate::t!("podcast_invalid_feed")))?;
905                            let u = super::feed::url(&value, None)?.to_string();
906                            if seen.insert(u.clone()) {
907                                urls.push(u);
908                            }
909                        }
910                    }
911                }
912                if matches!(event, Event::Start(_)) {
913                    depth += 1;
914                }
915                if depth > 64 || urls.len() > 10000 {
916                    return Err(error(crate::t!("podcast_limit")));
917                }
918            }
919            Event::End(_) => {
920                if depth == 0 {
921                    return Err(error(crate::t!("podcast_invalid_feed")));
922                }
923                depth -= 1;
924            }
925            Event::DocType(_) => return Err(error(crate::t!("podcast_invalid_feed"))),
926            Event::Eof => break,
927            _ => {}
928        }
929    }
930    if !root || depth != 0 {
931        return Err(error(crate::t!("podcast_invalid_feed")));
932    }
933    Ok(urls)
934}