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