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