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