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