Skip to main content

radio_cli/
cli.rs

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