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 Search {
13 query: String,
14 #[arg(long, default_value = "CN")]
15 country: String,
16 #[arg(long,default_value_t=25,value_parser=clap::value_parser!(u16).range(1..=200))]
17 limit: u16,
18 },
19 Discover {
20 url: String,
21 },
22 Preview {
23 url: String,
24 },
25 Add {
26 url: String,
27 },
28 List {
29 #[command(flatten)]
30 page: crate::cli::Page,
31 #[arg(long, default_value = "")]
32 query: String,
33 },
34 Episodes {
35 id: String,
36 #[arg(long, default_value = "")]
37 query: String,
38 #[command(flatten)]
39 page: crate::cli::Page,
40 },
41 Refresh {
42 id: Option<String>,
43 },
44 Unsubscribe {
45 id: String,
46 },
47 Play {
48 id: String,
49 #[arg(long)]
50 from_start: bool,
51 #[arg(long)]
52 speed: Option<f64>,
53 },
54 Mark {
55 id: String,
56 #[arg(value_parser=["played","unplayed"])]
57 state: String,
58 },
59 Download {
60 id: String,
61 },
62 Downloads {
63 #[command(subcommand)]
64 action: DownloadAction,
65 },
66 Queue {
67 #[command(subcommand)]
68 action: QueueAction,
69 },
70 Import {
71 file: PathBuf,
72 #[arg(long)]
73 dry_run: bool,
74 },
75 Export {
76 file: PathBuf,
77 #[arg(long)]
78 overwrite: bool,
79 },
80 Seek {
81 time: String,
82 },
83 Speed {
84 rate: f64,
85 },
86 AutoNext {
87 #[arg(value_parser=["on","off"])]
88 state: String,
89 },
90}
91#[derive(Debug, Clone, Subcommand)]
92pub enum DownloadAction {
93 List,
94 Pause { id: String },
95 Resume { id: String },
96 Cancel { id: String },
97 Remove { id: String },
98}
99#[derive(Debug, Clone, Subcommand)]
100pub enum QueueAction {
101 List,
102 Add {
103 id: String,
104 },
105 Remove {
106 id: String,
107 },
108 Move {
109 id: String,
110 position: usize,
111 },
112 Clear,
113 Play {
114 #[arg(long)]
115 auto_next: bool,
116 },
117}
118pub fn valid_speed(rate: f64) -> Result<f64> {
119 if !rate.is_finite() || !(0.5..=3.).contains(&rate) {
120 return Err(error(crate::t!("podcast_invalid_speed")));
121 }
122 Ok(rate)
123}
124pub fn parse_time(value: &str) -> Result<u64> {
125 let mut seconds = 0f64;
126 for part in value.split(':') {
127 seconds = seconds * 60.
128 + part
129 .parse::<f64>()
130 .map_err(|_| error(crate::t!("podcast_invalid_time")))?;
131 }
132 if !seconds.is_finite() || seconds < 0. || seconds > i64::MAX as f64 / 1000. {
133 return Err(error(crate::t!("podcast_invalid_time")));
134 }
135 Ok((seconds * 1000.) as u64)
136}
137fn page<T: Serialize>(items: &[T], p: crate::cli::Page) -> Value {
138 let limit = if p.all {
139 items.len()
140 } else {
141 usize::from(p.limit)
142 };
143 page_result(
144 &items.iter().skip(p.offset).take(limit).collect::<Vec<_>>(),
145 items.len(),
146 p,
147 )
148}
149fn page_result<T: Serialize>(items: &[T], total: usize, p: crate::cli::Page) -> Value {
150 json!({"items":items,"total":total,"offset":p.offset,"limit":if p.all {None}else{Some(p.limit)},"has_more":p.offset.saturating_add(items.len())<total})
151}
152pub fn refresh(
153 config: &Config,
154 store: &Store,
155 id: Option<&str>,
156 stop: &Arc<AtomicBool>,
157) -> Result<Value> {
158 if stop.load(std::sync::atomic::Ordering::Relaxed) {
159 return Err(DomainError::new(ErrorCode::Cancelled).into());
160 }
161 let feeds = if let Some(id) = id {
162 vec![store.podcast_feed(id)?]
163 } else {
164 store.podcast_feeds()?
165 };
166 let mut results = vec![];
167 for f in feeds {
168 if stop.load(std::sync::atomic::Ordering::Relaxed) {
169 return Err(DomainError::new(ErrorCode::Cancelled).into());
170 }
171 match fetch(config, &f.url, Some(&f), stop) {
172 Ok(p) => {
173 if stop.load(std::sync::atomic::Ordering::Relaxed) {
174 return Err(DomainError::new(ErrorCode::Cancelled).into());
175 }
176 store.podcast_refresh_merge(&f, p)?;
177 results.push(json!({"id":f.id,"ok":true}));
178 }
179 Err(e) => {
180 if e.downcast_ref::<DomainError>()
181 .is_some_and(|e| e.code == ErrorCode::Cancelled)
182 {
183 return Err(e);
184 }
185 if stop.load(std::sync::atomic::Ordering::Relaxed) {
186 return Err(DomainError::new(ErrorCode::Cancelled).into());
187 }
188 let mut f = f;
189 f.error = Some(e.to_string());
190 f.failures = f.failures.saturating_add(1);
191 f.refreshed_at = Some(chrono::Utc::now().to_rfc3339());
192 store.podcast_refresh_error(&f)?;
193 results.push(json!({"id":f.id,"ok":false,"error":e.to_string()}));
194 }
195 }
196 }
197 Ok(json!(results))
198}
199pub fn manage(
200 config: &Config,
201 store: &Store,
202 action: Action,
203 stop: &Arc<AtomicBool>,
204) -> Result<Value> {
205 Ok(match action {
206 Action::Search {
207 query,
208 country,
209 limit,
210 } => json!(search(config, &query, &country, limit.into(), stop)?),
211 Action::Discover { url } => json!(discover(config, &url, stop)?),
212 Action::Preview { url } => json!(fetch(config, &url, None, stop)?),
213 Action::Add { url } => {
214 let urls = discover(config, &url, stop)?;
215 if urls.len() != 1 {
216 return Err(error(crate::t!("podcast_choose_feed")));
217 }
218 let p = fetch(config, &urls[0], None, stop)?
219 .ok_or_else(|| error(crate::t!("podcast_invalid_feed")))?;
220 if stop.load(std::sync::atomic::Ordering::Relaxed) {
221 return Err(DomainError::new(ErrorCode::Cancelled).into());
222 }
223 json!(store.podcast_subscribe(&p, &url)?)
224 }
225 Action::List { page: p, query } => {
226 let query = query.to_lowercase();
227 let feeds: Vec<_> = store
228 .podcast_feeds()?
229 .into_iter()
230 .filter(|feed| feed.title.to_lowercase().contains(&query))
231 .collect();
232 page(&feeds, p)
233 }
234 Action::Episodes { id, query, page: p } => {
235 let (items, total) = store.podcast_episodes_page(&id, &query, &p)?;
236 page_result(&items, total, p)
237 }
238 Action::Refresh { id } => refresh(config, store, id.as_deref(), stop)?,
239 Action::Unsubscribe { id } => {
240 store.podcast_unsubscribe(&id)?;
241 json!({"id":id,"subscribed":false})
242 }
243 Action::Mark { id, state } => {
244 let e = store.podcast_episode(&id)?;
245 store.podcast_progress(
246 &e,
247 if state == "played" {
248 e.observed_duration_ms.unwrap_or(e.position_ms)
249 } else {
250 0
251 },
252 e.observed_duration_ms,
253 state == "played",
254 )?;
255 json!(store.podcast_episode(&id)?)
256 }
257 Action::Download { id } => json!(download(config, &id, stop)?),
258 Action::Downloads { action } => match action {
259 DownloadAction::List => json!(store.podcast_downloads()?),
260 DownloadAction::Resume { id } => json!(download(config, &id, stop)?),
261 DownloadAction::Pause { ref id }
262 | DownloadAction::Cancel { ref id }
263 | DownloadAction::Remove { ref id } => {
264 let d = store.podcast_download_transaction(id, |current| {
265 let mut d = current.ok_or_else(|| error(crate::t!("podcast_not_found")))?;
266 let remove = matches!(action, DownloadAction::Remove { .. });
267 if remove {
268 if d.state == "downloading" {
269 return Err(error(crate::t!("podcast_download_busy")));
270 }
271 let path = if d.path.is_empty() {
272 download_path(config, id)
273 } else {
274 PathBuf::from(&d.path)
275 };
276 for path in [path.clone(), path.with_extension("part")] {
277 if path.exists() {
278 std::fs::remove_file(path)?;
279 }
280 }
281 d.state = "removed".into();
282 d.bytes = 0;
283 } else {
284 d.state = if matches!(action, DownloadAction::Pause { .. }) {
285 "paused"
286 } else {
287 "cancelled"
288 }
289 .into();
290 }
291 d.generation = d.generation.saturating_add(1);
292 store.podcast_save_download(&d)?;
293 Ok(d)
294 })?;
295 json!(d)
296 }
297 },
298 Action::Queue { action } => {
299 json!(store.podcast_queue_update(action)?)
300 }
301 Action::Export { file, overwrite } => {
302 use std::io::Write;
303 let feeds = store.podcast_feeds()?;
304 let mut text = String::from(
305 "<?xml version=\"1.0\" encoding=\"UTF-8\"?><opml version=\"2.0\"><head><title>radio-cli</title></head><body>",
306 );
307 for f in &feeds {
308 text.push_str(&format!(
309 "<outline type=\"rss\" text=\"{}\" xmlUrl=\"{}\" htmlUrl=\"{}\"/>",
310 quick_xml::escape::escape(&f.title),
311 quick_xml::escape::escape(&f.url),
312 quick_xml::escape::escape(&f.website)
313 ));
314 }
315 text.push_str("</body></opml>");
316 let mut options = std::fs::OpenOptions::new();
317 options.write(true);
318 if overwrite {
319 options.create(true).truncate(true);
320 } else {
321 options.create_new(true);
322 }
323 options.open(file)?.write_all(text.as_bytes())?;
324 json!({"exported":feeds.len()})
325 }
326 Action::Import { file, dry_run } => {
327 if stop.load(std::sync::atomic::Ordering::Relaxed) {
328 return Err(DomainError::new(ErrorCode::Cancelled).into());
329 }
330 use std::io::Read;
331 let mut data = Vec::new();
332 std::fs::File::open(file)?
333 .take(10 * 1024 * 1024 + 1)
334 .read_to_end(&mut data)?;
335 let urls = opml(&data)?;
336 if dry_run {
337 json!({"urls":urls})
338 } else {
339 let mut results = vec![];
340 for u in urls {
341 if stop.load(std::sync::atomic::Ordering::Relaxed) {
342 return Err(DomainError::new(ErrorCode::Cancelled).into());
343 }
344 match fetch(config, &u, None, stop).and_then(|p| {
345 if stop.load(std::sync::atomic::Ordering::Relaxed) {
346 return Err(DomainError::new(ErrorCode::Cancelled).into());
347 }
348 store.podcast_subscribe(
349 &p.ok_or_else(|| error(crate::t!("podcast_invalid_feed")))?,
350 &u,
351 )
352 }) {
353 Ok(f) => results.push(json!({"id":f.id,"ok":true})),
354 Err(e) => {
355 if e.downcast_ref::<DomainError>()
356 .is_some_and(|e| e.code == ErrorCode::Cancelled)
357 {
358 return Err(e);
359 }
360 if stop.load(std::sync::atomic::Ordering::Relaxed) {
361 return Err(DomainError::new(ErrorCode::Cancelled).into());
362 }
363 results.push(json!({"ok":false,"error":e.to_string()}));
364 }
365 }
366 }
367 json!(results)
368 }
369 }
370 Action::AutoNext { state } => {
371 store.set_meta("podcast_auto_next", &state)?;
372 json!({"auto_next":state=="on"})
373 }
374 Action::Speed { rate } => {
375 valid_speed(rate)?;
376 store.set_meta("podcast_speed", &rate.to_string())?;
377 json!({"speed":rate})
378 }
379 Action::Seek { .. } | Action::Play { .. } => {
380 return Err(error(crate::t!("podcast_playback_only")));
381 }
382 })
383}
384fn opml(data: &[u8]) -> Result<Vec<String>> {
385 use quick_xml::{Reader, events::Event};
386 if data.len() > 10 * 1024 * 1024 {
387 return Err(error(crate::t!("podcast_limit")));
388 }
389 let mut reader = Reader::from_reader(data);
390 let mut depth = 0;
391 let mut root = false;
392 let mut urls = vec![];
393 loop {
394 match reader
395 .read_event()
396 .map_err(|_| error(crate::t!("podcast_invalid_feed")))?
397 {
398 Event::Start(e) | Event::Empty(e) => {
399 let empty =
400 data.get(reader.buffer_position().saturating_sub(2) as usize) == Some(&b'/');
401 if depth == 0 && (root || e.local_name().as_ref() != "opml") {
402 return Err(error(crate::t!("podcast_invalid_feed")));
403 }
404 root = true;
405 if e.local_name().as_ref() == "outline" {
406 for a in e.attributes() {
407 let a = a.map_err(|_| error(crate::t!("podcast_invalid_feed")))?;
408 if a.key.as_ref() == "xmlUrl" {
409 let value = a
410 .normalized_value(quick_xml::XmlVersion::Implicit1_0)
411 .map_err(|_| error(crate::t!("podcast_invalid_feed")))?;
412 let u = super::feed::url(&value, None)?.to_string();
413 if !urls.contains(&u) {
414 urls.push(u);
415 }
416 }
417 }
418 }
419 if !empty {
420 depth += 1;
421 }
422 if depth > 64 || urls.len() > 10000 {
423 return Err(error(crate::t!("podcast_limit")));
424 }
425 }
426 Event::End(_) => {
427 if depth == 0 {
428 return Err(error(crate::t!("podcast_invalid_feed")));
429 }
430 depth -= 1;
431 }
432 Event::DocType(_) => return Err(error(crate::t!("podcast_invalid_feed"))),
433 Event::Eof => break,
434 _ => {}
435 }
436 }
437 if !root || depth != 0 {
438 return Err(error(crate::t!("podcast_invalid_feed")));
439 }
440 Ok(urls)
441}