1use crate::{
2 config::Config,
3 directory::Directory,
4 engine::Engine,
5 model::{Filter, Station},
6 recorder,
7 store::Store,
8};
9use anyhow::{Result, bail};
10use clap::{Args, CommandFactory, Parser, Subcommand};
11use std::{
12 io::{self, IsTerminal},
13 path::PathBuf,
14 sync::{
15 Arc,
16 atomic::{AtomicBool, Ordering},
17 },
18 thread,
19 time::Duration,
20};
21
22#[derive(Parser)]
23#[command(
24 name = "radio",
25 version,
26 about = crate::t!("cli_about")
27)]
28pub struct Cli {
29 #[arg(long, global = true)]
30 pub lang: Option<String>,
31 #[arg(long, global = true)]
32 pub config: Option<PathBuf>,
33 #[arg(long, global = true)]
34 pub data_dir: Option<PathBuf>,
35 #[arg(long, global = true)]
36 pub api_url: Option<String>,
37 #[arg(long, global = true)]
38 pub json: bool,
39 #[arg(long, global = true, conflicts_with = "json")]
41 pub json_v2: bool,
42 #[command(subcommand)]
43 pub command: Option<Action>,
44}
45
46impl Cli {
47 pub fn try_parse_localized() -> Result<Self, clap::Error> {
48 let args: Vec<_> = std::env::args_os().collect();
49 let preview = Self::command()
50 .disable_help_flag(true)
51 .arg(
52 clap::Arg::new("help")
53 .long("help")
54 .short('h')
55 .global(true)
56 .action(clap::ArgAction::SetTrue),
57 )
58 .disable_help_subcommand(true)
59 .disable_version_flag(true)
60 .ignore_errors(true)
61 .try_get_matches_from(&args)?;
62 let config = Config::load(
63 preview.get_one::<PathBuf>("config").map(PathBuf::as_path),
64 preview.get_one::<PathBuf>("data_dir").map(PathBuf::as_path),
65 None,
66 )
67 .ok();
68 crate::messages::preview(
69 preview.get_one::<String>("lang").map(String::as_str),
70 config.as_ref().and_then(|c| c.settings.language.as_deref()),
71 );
72 Self::try_parse_from(args)
73 }
74}
75
76#[derive(Args, Debug, Clone, Default)]
77pub struct Search {
78 #[arg(long, value_enum, default_value = "clickcount")]
79 pub sort: crate::model::Sort,
80 pub query: Option<String>,
81 #[arg(long)]
82 pub country: Option<String>,
83 #[arg(long)]
84 pub language: Option<String>,
85 #[arg(long)]
86 pub tag: Option<String>,
87 #[arg(long, default_value_t = 0)]
88 pub min_bitrate: u32,
89 #[arg(long, default_value_t=100, value_parser=clap::value_parser!(u16).range(1..=1000))]
90 pub limit: u16,
91 #[arg(long, default_value_t = 0)]
92 pub offset: usize,
93}
94impl Search {
95 pub fn filter(&self) -> Filter {
96 Filter {
97 sort: self.sort,
98 query: self.query.clone().unwrap_or_default(),
99 country: self.country.clone(),
100 language: self.language.clone(),
101 tag: self.tag.clone(),
102 min_bitrate: self.min_bitrate,
103 limit: usize::from(self.limit),
104 offset: self.offset,
105 ..Filter::default()
106 }
107 }
108}
109
110#[derive(Args, Debug, Clone)]
111pub struct Page {
112 #[arg(long, default_value_t=100, value_parser=clap::value_parser!(u16).range(1..=1000))]
113 pub limit: u16,
114 #[arg(long, default_value_t = 0)]
115 pub offset: usize,
116 #[arg(long)]
118 pub all: bool,
119}
120
121fn emit_page<T: serde::Serialize>(
122 items: &[T],
123 total: usize,
124 page: &Page,
125 json: bool,
126) -> Result<()> {
127 let has_more = page.offset.saturating_add(items.len()) < total;
128 if json {
129 emit(
130 &serde_json::json!({"items":items,"total":total,"offset":page.offset,"limit": if page.all { None } else { Some(page.limit) },"has_more":has_more}),
131 )?;
132 } else {
133 eprintln!(
134 "{} / {total} {} · offset {} · {}",
135 items.len(),
136 crate::t!("cli_items"),
137 page.offset,
138 if has_more {
139 crate::t!("cli_more")
140 } else {
141 crate::t!("cli_last")
142 }
143 );
144 }
145 Ok(())
146}
147
148fn list_stations(store: &Store, mut filter: Filter, page: &Page, json: bool) -> Result<()> {
149 let total = store.search_count(&filter)?;
150 filter.limit = usize::from(page.limit);
151 filter.offset = page.offset;
152 let mut rows = store.search(&filter)?;
153 while page.all && page.offset.saturating_add(rows.len()) < total {
154 filter.offset = page.offset.saturating_add(rows.len());
155 let next = store.search(&filter)?;
156 if next.is_empty() {
157 break;
158 }
159 rows.extend(next);
160 }
161 if !json {
162 print_stations(&rows, false)?;
163 }
164 emit_page(&rows, total, page, json)
165}
166
167#[derive(Subcommand)]
168pub enum Action {
169 Podcast {
170 #[command(subcommand)]
171 action: crate::podcast::Action,
172 },
173 Subtitles {
175 #[command(subcommand)]
176 action: crate::speech::Action,
177 },
178 Completions {
180 shell: clap_complete::Shell,
181 },
182 Man,
184 Countries(FacetArgs),
185 Languages(FacetArgs),
186 Tags(FacetArgs),
187 Tui,
188 Sync {
189 #[arg(long)]
190 accept_shrink: bool,
191 },
192 Search(Search),
193 Info {
194 uuid: String,
195 },
196 Play {
197 #[arg(value_name = "UUID|URL")]
199 uuid: String,
200 },
201 Random(Search),
202 Favorites {
203 #[command(subcommand)]
204 action: Favorite,
205 },
206 History(Page),
207 Station {
208 #[command(subcommand)]
209 action: StationAction,
210 },
211 Record {
212 uuid: String,
213 #[arg(long, value_parser=recorder::parse_duration)]
214 duration: Option<Duration>,
215 #[arg(long)]
216 output_dir: Option<PathBuf>,
217 },
218 Recordings {
219 #[command(subcommand)]
220 action: RecordingAction,
221 },
222 Doctor,
223 Devices,
225}
226
227#[derive(Args)]
228pub struct FacetArgs {
229 #[arg(long, default_value = "")]
230 pub prefix: String,
231}
232#[derive(Subcommand)]
233pub enum Favorite {
234 List(Page),
235 Add { uuid: String },
236 Remove { uuid: String },
237}
238#[derive(Clone, Subcommand)]
239pub enum StationAction {
240 List(Page),
241 Add {
242 name: String,
243 url: String,
244 #[arg(long)]
245 backup_url: Vec<String>,
246 },
247 Edit {
248 uuid: String,
249 #[arg(long)]
250 name: Option<String>,
251 #[arg(long)]
252 url: Option<String>,
253 #[arg(long)]
254 backup_url: Vec<String>,
255 },
256 Remove {
257 uuid: String,
258 #[arg(long)]
259 keep_references: bool,
260 },
261 Backups {
262 uuid: String,
263 #[arg(long)]
264 add: Vec<String>,
265 #[arg(long)]
266 remove: Vec<String>,
267 },
268}
269
270pub(crate) enum StationRequest {
271 List(Page),
272 Change(crate::service::StationCommand),
273}
274
275impl StationAction {
276 pub(crate) fn into_request(self) -> StationRequest {
277 use crate::service::StationCommand;
278 StationRequest::Change(match self {
279 Self::List(page) => return StationRequest::List(page),
280 Self::Add {
281 name,
282 url,
283 backup_url,
284 } => StationCommand::Add {
285 name,
286 url,
287 backups: backup_url,
288 },
289 Self::Edit {
290 uuid,
291 name,
292 url,
293 backup_url,
294 } => StationCommand::Edit {
295 uuid,
296 name,
297 url,
298 backups: backup_url,
299 },
300 Self::Remove {
301 uuid,
302 keep_references,
303 } => StationCommand::Remove {
304 uuid,
305 keep_references,
306 },
307 Self::Backups { uuid, add, remove } => StationCommand::Backups { uuid, add, remove },
308 })
309 }
310}
311#[derive(Subcommand)]
312pub enum RecordingAction {
313 List(Page),
314 Recover,
315 Play {
316 id: String,
317 },
318 Remove {
319 id: String,
320 #[arg(long)]
322 index_only: bool,
323 },
324 Open,
325}
326
327fn emit(value: &impl serde::Serialize) -> Result<()> {
328 if JSON_V2.get() {
329 JSON_DATA.set(Some(serde_json::to_value(value)?));
330 return Ok(());
331 }
332 println!("{}", serde_json::to_string_pretty(value)?);
333 Ok(())
334}
335fn print_stations(rows: &[Station], json: bool) -> Result<()> {
336 if json {
337 return emit(&rows);
338 }
339 for s in rows {
340 println!(
341 "{} {}{} [{}] {} kbps{}",
342 s.stationuuid,
343 if s.favorite { "★ " } else { "" },
344 crate::clean_text(&s.name),
345 crate::clean_text(&s.countrycode),
346 s.bitrate,
347 if s.active {
348 ""
349 } else {
350 crate::t!("cli_inactive")
351 }
352 );
353 }
354 Ok(())
355}
356
357pub fn run(cli: Cli) -> Result<()> {
358 JSON_V2.set(cli.json_v2);
359 JSON_DATA.set(None);
360 let v2 = cli.json_v2;
361 let result = run_inner(cli);
362 if v2 && result.is_ok() {
363 println!("{}", serde_json::json!({"ok":true,"data":JSON_DATA.take()}));
364 }
365 JSON_V2.set(false);
366 result
367}
368
369thread_local! {
370 static JSON_V2: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
371 static JSON_DATA: std::cell::Cell<Option<serde_json::Value>> = const { std::cell::Cell::new(None) };
372}
373
374fn run_inner(mut cli: Cli) -> Result<()> {
375 cli.json |= cli.json_v2;
376 let preview_config = Config::load(cli.config.as_deref(), cli.data_dir.as_deref(), None).ok();
377 crate::messages::preview(
378 cli.lang.as_deref(),
379 preview_config
380 .as_ref()
381 .and_then(|c| c.settings.language.as_deref()),
382 );
383 if let Some(Action::Completions { shell }) = cli.command.as_ref() {
384 let mut bytes = Vec::new();
385 clap_complete::generate(*shell, &mut Cli::command(), "radio", &mut bytes);
386 return emit_generated(bytes, cli.json);
387 }
388 if matches!(cli.command, Some(Action::Man)) {
389 let mut bytes = Vec::new();
390 clap_mangen::Man::new(Cli::command()).render(&mut bytes)?;
391 return emit_generated(bytes, cli.json);
392 }
393 if cli.json_v2 && matches!(cli.command, None | Some(Action::Tui)) {
394 bail!(
395 crate::error::DomainError::new(crate::error::ErrorCode::UsageError)
396 .with("detail", "--json-v2 requires a noninteractive subcommand")
397 );
398 }
399 let action = match cli.command {
400 Some(action) => action,
401 None if io::stdin().is_terminal() && io::stdout().is_terminal() => Action::Tui,
402 None => {
403 Cli::command().print_help()?;
404 println!();
405 return Ok(());
406 }
407 };
408 let config = Config::load(
409 cli.config.as_deref(),
410 cli.data_dir.as_deref(),
411 cli.api_url.as_deref(),
412 )?;
413 crate::messages::init(cli.lang.as_deref(), config.settings.language.as_deref());
414 config.prepare()?;
415 let stop = Arc::new(AtomicBool::new(false));
416 signal_hook::flag::register(signal_hook::consts::SIGINT, stop.clone())?;
417 signal_hook::flag::register(signal_hook::consts::SIGTERM, stop.clone())?;
418 let mut store = Store::open(&config.data_dir.join("radio.db"))?;
419 match action {
420 Action::Podcast { action } => match action {
421 crate::podcast::Action::Queue {
422 action: crate::podcast::QueueAction::Start { id, auto_next },
423 } => {
424 let mut engine = Engine::new(config, stop.clone())?;
425 engine.podcast_action(crate::podcast::Action::Queue {
426 action: crate::podcast::QueueAction::Start { id, auto_next },
427 })?;
428 playback_loop(&mut engine, &stop)?;
429 }
430 crate::podcast::Action::Resume => {
431 let mut engine = Engine::new(config, stop.clone())?;
432 engine.podcast_action(crate::podcast::Action::Resume)?;
433 playback_loop(&mut engine, &stop)?;
434 }
435 crate::podcast::Action::Play {
436 id,
437 from_start,
438 speed,
439 } => {
440 let mut engine = Engine::new(config, stop.clone())?;
441 engine.play_episode(&id, from_start, speed)?;
442 playback_loop(&mut engine, &stop)?;
443 }
444 crate::podcast::Action::Queue {
445 action: crate::podcast::QueueAction::Play { auto_next },
446 } => {
447 let mut engine = Engine::new(config, stop.clone())?;
448 engine.play_podcast_queue(auto_next)?;
449 playback_loop(&mut engine, &stop)?;
450 }
451 action => {
452 let _lock = if matches!(
453 &action,
454 crate::podcast::Action::Subtitles {
455 transcribe: true,
456 ..
457 } | crate::podcast::Action::Download { .. }
458 | crate::podcast::Action::Downloads {
459 action: crate::podcast::DownloadAction::Resume { .. }
460 | crate::podcast::DownloadAction::Remove { .. }
461 }
462 | crate::podcast::Action::Mark { .. }
463 | crate::podcast::Action::MarkBatch { .. }
464 ) {
465 Some(crate::process::MediaLock::acquire(&config.runtime_dir)?)
466 } else {
467 None
468 };
469 crate::podcast::set_cli_progress(
470 !cli.json && std::io::IsTerminal::is_terminal(&std::io::stderr()),
471 );
472 let mut value = crate::podcast::manage(&config, &store, action, &stop)?;
473 if cli.json {
474 emit(&value)?;
475 } else {
476 crate::podcast::sanitize_output(&mut value);
477 println!("{}", crate::podcast::text_output(&value));
478 }
479 }
480 },
481 Action::Completions { .. } | Action::Man => unreachable!(),
482 Action::Countries(ref args) | Action::Languages(ref args) | Action::Tags(ref args) => {
483 let kind = match action {
484 Action::Countries(_) => crate::model::FacetKind::Country,
485 Action::Languages(_) => crate::model::FacetKind::Language,
486 _ => crate::model::FacetKind::Tag,
487 };
488 let facets = store.facets(kind, &args.prefix)?;
489 if cli.json {
490 emit(&facets)?;
491 } else {
492 for facet in facets {
493 println!("{}\t{}", crate::clean_text(&facet.value), facet.count);
494 }
495 }
496 }
497 Action::Tui => {
498 drop(store);
499 crate::tui::run(config, stop)?;
500 }
501 Action::Doctor => doctor(&config, cli.json, &stop)?,
502 Action::Subtitles { action } => emit(&crate::speech::manage(&config, action, &stop)?)?,
503 Action::Devices => {
504 let devices = crate::player::audio_devices(&config, &stop)?;
505 if cli.json {
506 emit(&devices)?;
507 } else {
508 for device in devices {
509 println!(
510 "{}\t{}",
511 crate::clean_text(&device.name),
512 crate::clean_text(&device.description)
513 );
514 }
515 }
516 }
517 Action::Sync { accept_shrink } => {
518 let mut directory = Directory::new(&config, stop.clone())?;
519 let count = directory.sync_with_policy(
520 &mut store,
521 |n| eprintln!("{}", crate::t!("cli_sync_progress", "count" => n)),
522 accept_shrink,
523 )?;
524 if cli.json {
525 emit(&serde_json::json!({"stations":count,"last_sync":store.meta("last_sync")?}))?;
526 } else {
527 println!("{}", crate::t!("cli_sync_done", "count" => count));
528 }
529 }
530 Action::Search(search) => print_stations(&store.search(&search.filter())?, cli.json)?,
531 Action::Info { uuid } => emit(&store.station(&uuid)?)?,
532 Action::History(page) => list_stations(
533 &store,
534 Filter {
535 history: true,
536 ..Filter::default()
537 },
538 &page,
539 cli.json,
540 )?,
541 Action::Favorites { action } => match action {
542 Favorite::List(page) => list_stations(
543 &store,
544 Filter {
545 favorites: true,
546 ..Filter::default()
547 },
548 &page,
549 cli.json,
550 )?,
551 Favorite::Add { ref uuid } | Favorite::Remove { ref uuid } => {
552 let added = matches!(action, Favorite::Add { .. });
553 let station = store.station(uuid)?;
554 store.favorite(uuid, added)?;
555 if cli.json {
556 emit(&serde_json::json!({
557 "stationuuid": uuid,
558 "name": station.name,
559 "favorite": added,
560 }))?;
561 } else {
562 println!(
563 "{}:{}",
564 if added {
565 crate::t!("cli_favorited")
566 } else {
567 crate::t!("cli_unfavorited")
568 },
569 crate::clean_text(&station.name)
570 );
571 }
572 }
573 },
574 Action::Station { action } => match action.into_request() {
575 StationRequest::List(page) => list_stations(
576 &store,
577 Filter {
578 custom: true,
579 ..Filter::default()
580 },
581 &page,
582 cli.json,
583 )?,
584 StationRequest::Change(command) => {
585 use crate::service::StationChange;
586 match crate::service::change_station(&mut store, command)? {
587 StationChange::Added(station) => {
588 if cli.json {
589 emit(&station)?;
590 } else {
591 println!("{}", station.stationuuid);
592 }
593 }
594 StationChange::Updated(station) => emit(&station)?,
595 StationChange::Removed {
596 uuid,
597 placeholder_kept,
598 } => emit(
599 &serde_json::json!({"stationuuid":uuid,"removed":true,"placeholder_kept":placeholder_kept}),
600 )?,
601 StationChange::Backups { urls, .. } => emit(&urls)?,
602 }
603 }
604 },
605 Action::Recordings {
606 action: RecordingAction::Play { id },
607 } => {
608 drop(store);
609 let mut engine = Engine::new(config, stop.clone())?;
610 engine.play_recording(&id)?;
611 playback_loop(&mut engine, &stop)?;
612 }
613 Action::Recordings {
614 action: RecordingAction::Remove { id, index_only },
615 } => {
616 let _lock = crate::process::MediaLock::acquire(&config.runtime_dir)?;
617 crate::service::delete_recording(&store, &id, index_only)?;
618 emit(&serde_json::json!({"id":id,"removed":true,"index_only":index_only}))?;
619 }
620 Action::Recordings {
621 action: RecordingAction::Open,
622 } => {
623 crate::service::open_recordings(&config.recording_dir, &stop)?;
624 }
625 Action::Recordings {
626 action: RecordingAction::Recover,
627 } => {
628 let _lock = crate::process::MediaLock::acquire(&config.runtime_dir)?;
629 let warnings = recorder::recover(&store)?;
630 if cli.json {
631 emit(&serde_json::json!({"warnings": warnings}))?;
632 } else if warnings.is_empty() {
633 println!("{}", crate::t!("cli_recovered"));
634 } else {
635 for warning in &warnings {
636 eprintln!("{warning}");
637 }
638 }
639 if !warnings.is_empty() {
640 bail!("{}", crate::t!("cli_recovery_pending"));
641 }
642 }
643 Action::Recordings {
644 action: RecordingAction::List(page),
645 } => {
646 let total = store.recordings_count()?;
647 let mut records = store.recordings_page(usize::from(page.limit), page.offset)?;
648 while page.all && page.offset.saturating_add(records.len()) < total {
649 let next = store.recordings_page(
650 usize::from(page.limit),
651 page.offset.saturating_add(records.len()),
652 )?;
653 if next.is_empty() {
654 break;
655 }
656 records.extend(next);
657 }
658 emit_page(&records, total, &page, cli.json)?;
659 if !cli.json {
660 for r in records {
661 println!(
662 "{} {} {} {}",
663 r.id,
664 r.status,
665 crate::clean_text(&r.station_name),
666 crate::clean_text(&r.path)
667 );
668 if r.reconnects > 0 {
669 println!(
670 " {}",
671 crate::t!("recording_reconnected", "count" => r.reconnects)
672 );
673 }
674 if let Some(error) = r.error {
675 for line in error.lines() {
676 let line: String = line
680 .chars()
681 .filter(|c| !c.is_control() || *c == '\t')
682 .collect();
683 println!(" {line}");
684 }
685 }
686 }
687 }
688 }
689 Action::Play { uuid } => {
690 drop(store);
691 let mut engine = Engine::new(config, stop.clone())?;
692 engine.play(&uuid)?;
693 playback_loop(&mut engine, &stop)?;
694 }
695 Action::Random(search) => {
696 drop(store);
697 let mut engine = Engine::new(config, stop.clone())?;
698 if engine.store().count()? == 0 {
699 eprintln!("{}", crate::t!("cli_bootstrap"));
700 engine.bootstrap()?;
701 }
702 engine.random(search.filter())?;
703 playback_loop(&mut engine, &stop)?;
704 }
705 Action::Record {
706 uuid,
707 duration,
708 output_dir,
709 } => {
710 drop(store);
711 let mut engine = Engine::new(config, stop.clone())?;
712 eprintln!("{}", crate::t!("cli_probe"));
713 engine.standalone_record(&uuid, duration, output_dir.as_deref())?;
714 eprintln!(
715 "{} · Ctrl-C: {}",
716 engine.status().message,
717 engine.status().recording_path
718 );
719 while !stop.load(Ordering::Relaxed) && engine.status().recording() {
720 engine.tick()?;
721 thread::sleep(Duration::from_millis(100));
722 }
723 engine.shutdown()?;
724 if cli.json {
725 emit(&engine.store().recordings(1)?)?;
726 } else {
727 println!("{}", crate::clean_text(&engine.status().message));
728 }
729 if engine
730 .store()
731 .recordings(1)?
732 .first()
733 .is_some_and(|r| r.status != "complete")
734 {
735 bail!("{}", crate::t!("cli_recording_incomplete"));
736 }
737 }
738 }
739 Ok(())
740}
741
742fn emit_generated(bytes: Vec<u8>, json: bool) -> Result<()> {
743 if json {
744 emit(&String::from_utf8(bytes)?)
745 } else {
746 use std::io::Write;
747 io::stdout().write_all(&bytes)?;
748 Ok(())
749 }
750}
751
752fn playback_loop(engine: &mut Engine, stop: &AtomicBool) -> Result<()> {
753 let mut previous = String::new();
754 while !stop.load(Ordering::Relaxed) && !engine.playback_failed() && engine.playback_active() {
755 engine.tick()?;
756 let line = format!(
757 "{} | {} | {}",
758 engine
759 .status()
760 .station
761 .as_ref()
762 .map(|s| crate::clean_text(&s.name))
763 .unwrap_or_default(),
764 engine.status().title,
765 engine.status().message
766 );
767 if line != previous {
768 eprintln!("{line}");
769 previous = line;
770 }
771 thread::sleep(Duration::from_millis(100));
772 }
773 engine.shutdown()?;
774 if engine.playback_failed() {
775 if let Some(error) = engine.playback_error() {
776 return Err(error.clone().into());
777 }
778 bail!("{}", engine.status().message);
779 }
780 Ok(())
781}
782
783fn doctor(config: &Config, json: bool, stop: &Arc<AtomicBool>) -> Result<()> {
784 let (report, failed) = crate::service::doctor_report(config, stop)?;
785 if json {
786 emit(&report)?;
787 } else {
788 for check in report["checks"].as_array().into_iter().flatten() {
789 println!(
790 "{} {}: {}",
791 if check["ok"] == true { "OK" } else { "FAIL" },
792 check["name"].as_str().unwrap_or(""),
793 crate::clean_text(check["detail"].as_str().unwrap_or(""))
794 );
795 }
796 }
797 if failed {
798 if let Some(check) = report["checks"]
799 .as_array()
800 .into_iter()
801 .flatten()
802 .find(|check| check["code"] == "missing_dependency")
803 {
804 bail!(
805 crate::error::DomainError::new(crate::error::ErrorCode::MissingDependency)
806 .with("program", check["name"].as_str().unwrap_or(""))
807 );
808 }
809 bail!("{}", crate::t!("cli_doctor_failed"));
810 }
811 Ok(())
812}