1use crate::{
2 config::validate_url,
3 error::{DomainError, ErrorCode},
4 model::Station,
5 store::Store,
6};
7use anyhow::{Result, bail};
8
9pub fn normalized_url(url: &str) -> Result<String> {
10 validate_url(url)?;
11 let mut parsed = reqwest::Url::parse(url)?;
12 parsed.set_fragment(None);
13 Ok(parsed.into())
14}
15
16pub fn add_station(
17 store: &mut Store,
18 name: String,
19 url: String,
20 backups: &[String],
21) -> Result<Station> {
22 validate(&name, &url, backups)?;
23 let station = Station {
24 stationuuid: uuid::Uuid::new_v4().to_string(),
25 name: name.trim().into(),
26 url: url.clone(),
27 url_resolved: url,
28 active: true,
29 custom: true,
30 lastcheckok: 1,
31 ..Station::default()
32 };
33 store.save_custom(&station, Some(backups))?;
34 Ok(station)
35}
36
37pub fn edit_station(
38 store: &mut Store,
39 uuid: &str,
40 name: Option<String>,
41 url: Option<String>,
42 backups: &[String],
43) -> Result<Station> {
44 let mut station = store.station(uuid)?;
45 if !station.custom {
46 bail!(DomainError::new(ErrorCode::NotCustom));
47 }
48 if let Some(name) = name {
49 station.name = name.trim().into();
50 }
51 if let Some(url) = url {
52 station.url = url.clone();
53 station.url_resolved = url;
54 }
55 validate(&station.name, station.primary_url(), backups)?;
56 store.save_custom(&station, (!backups.is_empty()).then_some(backups))?;
57 store.station(uuid)
58}
59
60fn validate(name: &str, url: &str, backups: &[String]) -> Result<()> {
61 if name.trim().is_empty() {
62 bail!(DomainError::new(ErrorCode::EmptyStationName));
63 }
64 validate_url(url)?;
65 for backup in backups {
66 validate_url(backup)?;
67 }
68 Ok(())
69}
70
71pub fn open_recordings(
72 dir: &std::path::Path,
73 stop: &std::sync::Arc<std::sync::atomic::AtomicBool>,
74) -> Result<()> {
75 std::fs::create_dir_all(dir)?;
76 let opener = if cfg!(target_os = "macos") {
77 "open"
78 } else {
79 "xdg-open"
80 };
81 crate::process::output(
82 std::process::Command::new(opener).arg(dir),
83 std::time::Duration::from_secs(5),
84 stop,
85 )?;
86 Ok(())
87}
88
89pub fn delete_recording(store: &Store, id: &str, index_only: bool) -> Result<()> {
92 let record = store.recording(id)?;
93 if matches!(record.status.as_str(), "recording" | "finalizing") || record.recovery_pending {
94 bail!(DomainError::new(ErrorCode::RecordingInUse));
95 }
96 if !index_only {
97 for path in [
98 std::path::PathBuf::from(&record.path),
99 std::path::PathBuf::from(format!("{}.json", record.path)),
100 ] {
101 match std::fs::remove_file(&path) {
102 Ok(()) => {}
103 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
104 Err(error) => {
105 return Err(
106 anyhow::Error::new(error).context(format!("{} ({id})", path.display()))
107 );
108 }
109 }
110 }
111 }
112 store.remove_recording_index(id)
113}