Skip to main content

radio_cli/
service.rs

1use crate::{
2    config::validate_url,
3    error::{DomainError, ErrorCode},
4    model::Station,
5    store::Store,
6};
7use anyhow::{Result, bail};
8
9mod diagnostics;
10pub(crate) use diagnostics::doctor_report;
11
12#[derive(Clone)]
13pub enum StationCommand {
14    Add {
15        name: String,
16        url: String,
17        backups: Vec<String>,
18    },
19    Edit {
20        uuid: String,
21        name: Option<String>,
22        url: Option<String>,
23        backups: Vec<String>,
24    },
25    Remove {
26        uuid: String,
27        keep_references: bool,
28    },
29    Backups {
30        uuid: String,
31        add: Vec<String>,
32        remove: Vec<String>,
33    },
34}
35
36pub enum StationChange {
37    Added(Station),
38    Updated(Station),
39    Removed {
40        uuid: String,
41        placeholder_kept: bool,
42    },
43    Backups {
44        uuid: String,
45        urls: Vec<String>,
46    },
47}
48
49pub fn change_station(store: &mut Store, command: StationCommand) -> Result<StationChange> {
50    Ok(match command {
51        StationCommand::Add { name, url, backups } => {
52            StationChange::Added(add_station(store, name, url, &backups)?)
53        }
54        StationCommand::Edit {
55            uuid,
56            name,
57            url,
58            backups,
59        } => StationChange::Updated(edit_station(store, &uuid, name, url, &backups)?),
60        StationCommand::Remove {
61            uuid,
62            keep_references,
63        } => {
64            let placeholder_kept = store.remove_custom(&uuid, keep_references)?;
65            StationChange::Removed {
66                uuid,
67                placeholder_kept,
68            }
69        }
70        StationCommand::Backups { uuid, add, remove } => StationChange::Backups {
71            urls: store.update_backups(&uuid, &add, &remove)?,
72            uuid,
73        },
74    })
75}
76
77pub fn normalized_url(url: &str) -> Result<String> {
78    validate_url(url)?;
79    let mut parsed = reqwest::Url::parse(url)?;
80    parsed.set_fragment(None);
81    Ok(parsed.into())
82}
83
84pub fn add_station(
85    store: &mut Store,
86    name: String,
87    url: String,
88    backups: &[String],
89) -> Result<Station> {
90    validate(&name, &url, backups)?;
91    let station = Station {
92        stationuuid: uuid::Uuid::new_v4().to_string(),
93        name: name.trim().into(),
94        url: url.clone(),
95        url_resolved: url,
96        active: true,
97        custom: true,
98        lastcheckok: 1,
99        ..Station::default()
100    };
101    store.save_custom(&station, Some(backups))?;
102    Ok(station)
103}
104
105pub fn edit_station(
106    store: &mut Store,
107    uuid: &str,
108    name: Option<String>,
109    url: Option<String>,
110    backups: &[String],
111) -> Result<Station> {
112    let mut station = store.station(uuid)?;
113    if !station.custom {
114        bail!(DomainError::new(ErrorCode::NotCustom));
115    }
116    if let Some(name) = name {
117        station.name = name.trim().into();
118    }
119    if let Some(url) = url {
120        station.url = url.clone();
121        station.url_resolved = url;
122    }
123    validate(&station.name, station.primary_url(), backups)?;
124    store.save_custom(&station, (!backups.is_empty()).then_some(backups))?;
125    store.station(uuid)
126}
127
128fn validate(name: &str, url: &str, backups: &[String]) -> Result<()> {
129    if name.trim().is_empty() {
130        bail!(DomainError::new(ErrorCode::EmptyStationName));
131    }
132    validate_url(url)?;
133    for backup in backups {
134        validate_url(backup)?;
135    }
136    Ok(())
137}
138
139pub fn open_recordings(
140    dir: &std::path::Path,
141    stop: &std::sync::Arc<std::sync::atomic::AtomicBool>,
142) -> Result<()> {
143    std::fs::create_dir_all(dir)?;
144    let opener = if cfg!(target_os = "macos") {
145        "open"
146    } else {
147        "xdg-open"
148    };
149    crate::process::output(
150        std::process::Command::new(opener).arg(dir),
151        std::time::Duration::from_secs(5),
152        stop,
153    )?;
154    Ok(())
155}
156
157/// Delete files first and the index last. Missing files make retries idempotent;
158/// other filesystem errors retain the index for diagnosis and another attempt.
159pub fn delete_recording(store: &Store, id: &str, index_only: bool) -> Result<()> {
160    let record = store.recording(id)?;
161    if matches!(record.status.as_str(), "recording" | "finalizing") || record.recovery_pending {
162        bail!(DomainError::new(ErrorCode::RecordingInUse));
163    }
164    if !index_only {
165        for path in [
166            std::path::PathBuf::from(&record.path),
167            std::path::PathBuf::from(format!("{}.json", record.path)),
168        ] {
169            match std::fs::remove_file(&path) {
170                Ok(()) => {}
171                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
172                Err(error) => {
173                    return Err(
174                        anyhow::Error::new(error).context(format!("{} ({id})", path.display()))
175                    );
176                }
177            }
178        }
179    }
180    store.remove_recording_index(id)
181}