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    store.edit_custom(uuid, (!backups.is_empty()).then_some(backups), |station| {
113        if let Some(name) = name {
114            station.name = name.trim().into();
115        }
116        if let Some(url) = url {
117            station.url = url.clone();
118            station.url_resolved = url;
119        }
120        validate(&station.name, station.primary_url(), backups)
121    })
122}
123
124fn validate(name: &str, url: &str, backups: &[String]) -> Result<()> {
125    if name.trim().is_empty() {
126        bail!(DomainError::new(ErrorCode::EmptyStationName));
127    }
128    validate_url(url)?;
129    for backup in backups {
130        validate_url(backup)?;
131    }
132    Ok(())
133}
134
135pub fn open_recordings(
136    dir: &std::path::Path,
137    stop: &std::sync::Arc<std::sync::atomic::AtomicBool>,
138) -> Result<()> {
139    std::fs::create_dir_all(dir)?;
140    let opener = if cfg!(target_os = "macos") {
141        "open"
142    } else {
143        "xdg-open"
144    };
145    let mut command = std::process::Command::new(opener);
146    command.arg(dir);
147    crate::process::open_directory(command, std::time::Duration::from_secs(5), stop)
148}
149
150/// Delete files first and the index last. Missing files make retries idempotent;
151/// other filesystem errors retain the index for diagnosis and another attempt.
152pub fn delete_recording(store: &Store, id: &str, index_only: bool) -> Result<()> {
153    let record = store.recording(id)?;
154    if matches!(record.status.as_str(), "recording" | "finalizing") || record.recovery_pending {
155        bail!(DomainError::new(ErrorCode::RecordingInUse));
156    }
157    if !index_only {
158        for path in [
159            std::path::PathBuf::from(&record.path),
160            std::path::PathBuf::from(format!("{}.json", record.path)),
161        ] {
162            match std::fs::remove_file(&path) {
163                Ok(()) => {}
164                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
165                Err(error) => {
166                    return Err(
167                        anyhow::Error::new(error).context(format!("{} ({id})", path.display()))
168                    );
169                }
170            }
171        }
172    }
173    store.remove_recording_index(id)
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179    use rusqlite::hooks::{AuthAction, AuthContext, Authorization, TransactionOperation};
180
181    #[test]
182    fn editing_cannot_recreate_a_station_removed_before_the_write_lock() -> Result<()> {
183        let dir = tempfile::tempdir()?;
184        let path = dir.path().join("radio.db");
185        let mut store = Store::open(&path)?;
186        let station = add_station(&mut store, "old".into(), "https://example.test".into(), &[])?;
187        let id = station.stationuuid.clone();
188        // Commit the removal at the last point before the editor acquires its lock.
189        store
190            .conn
191            .authorizer(Some(move |context: AuthContext<'_>| {
192                if matches!(
193                    context.action,
194                    AuthAction::Transaction {
195                        operation: TransactionOperation::Begin
196                    }
197                ) {
198                    Store::open(&path)
199                        .unwrap()
200                        .remove_custom(&id, false)
201                        .unwrap();
202                }
203                Authorization::Allow
204            }))?;
205        assert!(
206            edit_station(
207                &mut store,
208                &station.stationuuid,
209                Some("new".into()),
210                None,
211                &[]
212            )
213            .is_err()
214        );
215        assert!(store.station(&station.stationuuid).is_err());
216        Ok(())
217    }
218}