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, clap::Subcommand)]
13pub enum StationCommand {
14 Add {
15 name: String,
16 url: String,
17 #[arg(long = "backup-url")]
18 backups: Vec<String>,
19 },
20 Edit {
21 uuid: String,
22 #[arg(long)]
23 name: Option<String>,
24 #[arg(long)]
25 url: Option<String>,
26 #[arg(long = "backup-url")]
27 backups: Vec<String>,
28 },
29 Remove {
30 uuid: String,
31 #[arg(long)]
32 keep_references: bool,
33 },
34 Backups {
35 uuid: String,
36 #[arg(long)]
37 add: Vec<String>,
38 #[arg(long)]
39 remove: Vec<String>,
40 },
41}
42
43pub enum StationChange {
44 Added(Station),
45 Updated(Station),
46 Removed {
47 uuid: String,
48 placeholder_kept: bool,
49 },
50 Backups {
51 uuid: String,
52 urls: Vec<String>,
53 },
54}
55
56pub fn change_station(store: &mut Store, command: StationCommand) -> Result<StationChange> {
57 Ok(match command {
58 StationCommand::Add { name, url, backups } => {
59 StationChange::Added(add_station(store, name, url, &backups)?)
60 }
61 StationCommand::Edit {
62 uuid,
63 name,
64 url,
65 backups,
66 } => StationChange::Updated(edit_station(store, &uuid, name, url, &backups)?),
67 StationCommand::Remove {
68 uuid,
69 keep_references,
70 } => {
71 let placeholder_kept = store.remove_custom(&uuid, keep_references)?;
72 StationChange::Removed {
73 uuid,
74 placeholder_kept,
75 }
76 }
77 StationCommand::Backups { uuid, add, remove } => StationChange::Backups {
78 urls: store.update_backups(&uuid, &add, &remove)?,
79 uuid,
80 },
81 })
82}
83
84pub use crate::config::normalized_url;
85
86pub fn add_station(
87 store: &mut Store,
88 name: String,
89 url: String,
90 backups: &[String],
91) -> Result<Station> {
92 validate(&name, &url, backups)?;
93 let station = Station {
94 stationuuid: uuid::Uuid::new_v4().to_string(),
95 name: name.trim().into(),
96 url: url.clone(),
97 url_resolved: url,
98 active: true,
99 custom: true,
100 lastcheckok: 1,
101 ..Station::default()
102 };
103 store.save_custom(&station, Some(backups))?;
104 Ok(station)
105}
106
107pub fn edit_station(
108 store: &mut Store,
109 uuid: &str,
110 name: Option<String>,
111 url: Option<String>,
112 backups: &[String],
113) -> Result<Station> {
114 store.edit_custom(uuid, (!backups.is_empty()).then_some(backups), |station| {
115 if let Some(name) = name {
116 station.name = name.trim().into();
117 }
118 if let Some(url) = url {
119 station.url = url.clone();
120 station.url_resolved = url;
121 }
122 validate(&station.name, station.primary_url(), backups)
123 })
124}
125
126fn validate(name: &str, url: &str, backups: &[String]) -> Result<()> {
127 if name.trim().is_empty() {
128 bail!(DomainError::new(ErrorCode::EmptyStationName));
129 }
130 validate_url(url)?;
131 for backup in backups {
132 validate_url(backup)?;
133 }
134 Ok(())
135}
136
137pub fn open_recordings(
138 dir: &std::path::Path,
139 stop: &std::sync::Arc<std::sync::atomic::AtomicBool>,
140) -> Result<()> {
141 std::fs::create_dir_all(dir)?;
142 let opener = if cfg!(target_os = "macos") {
143 "open"
144 } else {
145 "xdg-open"
146 };
147 let mut command = std::process::Command::new(opener);
148 command.arg(dir);
149 crate::process::open_directory(command, std::time::Duration::from_secs(5), stop)
150}
151
152pub fn delete_recording(store: &Store, id: &str, index_only: bool) -> Result<()> {
155 let record = store.recording(id)?;
156 if matches!(record.status.as_str(), "recording" | "finalizing") || record.recovery_pending {
157 bail!(DomainError::new(ErrorCode::RecordingInUse));
158 }
159 if !index_only {
160 for path in [
161 std::path::PathBuf::from(&record.path),
162 std::path::PathBuf::from(format!("{}.json", record.path)),
163 ] {
164 match std::fs::remove_file(&path) {
165 Ok(()) => {}
166 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
167 Err(error) => {
168 return Err(
169 anyhow::Error::new(error).context(format!("{} ({id})", path.display()))
170 );
171 }
172 }
173 }
174 }
175 store.remove_recording_index(id)
176}
177
178#[cfg(test)]
179mod tests {
180 use super::*;
181 use rusqlite::hooks::{AuthAction, AuthContext, Authorization, TransactionOperation};
182
183 #[test]
184 fn editing_cannot_recreate_a_station_removed_before_the_write_lock() -> Result<()> {
185 let dir = tempfile::tempdir()?;
186 let path = dir.path().join("radio.db");
187 let mut store = Store::open(&path)?;
188 let station = add_station(&mut store, "old".into(), "https://example.test".into(), &[])?;
189 let id = station.stationuuid.clone();
190 store
192 .conn
193 .authorizer(Some(move |context: AuthContext<'_>| {
194 if matches!(
195 context.action,
196 AuthAction::Transaction {
197 operation: TransactionOperation::Begin
198 }
199 ) {
200 Store::open(&path)
201 .unwrap()
202 .remove_custom(&id, false)
203 .unwrap();
204 }
205 Authorization::Allow
206 }))?;
207 assert!(
208 edit_station(
209 &mut store,
210 &station.stationuuid,
211 Some("new".into()),
212 None,
213 &[]
214 )
215 .is_err()
216 );
217 assert!(store.station(&station.stationuuid).is_err());
218 Ok(())
219 }
220}