Skip to main content

sonos_cli/cli/
run.rs

1use std::io::IsTerminal;
2
3use sonos_sdk::{SeekTarget, SonosSystem};
4
5use super::{
6    format_duration_human, format_time_ms, parse_duration, playback_icon, playback_label,
7    require_speaker_only, resolve_group, resolve_speaker, validate_seek_time, Commands,
8    GlobalFlags, OnOff, QueueAction,
9};
10use crate::config::Config;
11use crate::diagnostics;
12use crate::errors::CliError;
13use crate::liveness::{CommandOutput, Probes};
14
15/// Run a command and report both what it printed and whether a speaker
16/// actually answered while producing it.
17///
18/// Most arms return [`CommandOutput::live`]: they end in a SOAP call whose
19/// error is propagated with `?`, so reaching `Ok` is itself proof of contact.
20/// The read-only listings (`speakers`, `groups`, `status`) are the exceptions —
21/// they tolerate per-field failure by design, which is exactly how a total
22/// discovery failure used to render as success.
23pub fn run_command(
24    cmd: Commands,
25    system: &SonosSystem,
26    config: &Config,
27    global: &GlobalFlags,
28) -> Result<CommandOutput, CliError> {
29    let spk = || resolve_speaker(system, config, global);
30
31    match cmd {
32        Commands::Speakers => cmd_speakers(system),
33        Commands::Groups => cmd_groups(system),
34        Commands::Status => cmd_status(system, config, global),
35        Commands::Join => cmd_join(system, config, global),
36        Commands::Leave => cmd_leave(system, config, global),
37        Commands::Bass { level } => cmd_bass(system, config, global, level),
38        Commands::Treble { level } => cmd_treble(system, config, global, level),
39        Commands::Loudness { state } => cmd_loudness(system, config, global, state),
40        Commands::Sleep { duration } => cmd_sleep(system, config, global, &duration),
41        Commands::Queue { action } => cmd_queue(system, config, global, action),
42        Commands::Config { .. } => unreachable!("config commands dispatched before discovery"),
43
44        Commands::Play => {
45            let s = spk()?;
46            s.play()?;
47            Ok(CommandOutput::live(format!("Playing ({})", s.name)))
48        }
49        Commands::Pause => {
50            let s = spk()?;
51            s.pause()?;
52            Ok(CommandOutput::live(format!("Paused ({})", s.name)))
53        }
54        Commands::Stop => {
55            let s = spk()?;
56            s.stop()?;
57            Ok(CommandOutput::live(format!("Stopped ({})", s.name)))
58        }
59        Commands::Next => {
60            let s = spk()?;
61            s.next()?;
62            Ok(CommandOutput::live(format!("Next track ({})", s.name)))
63        }
64        Commands::Previous => {
65            let s = spk()?;
66            s.previous()?;
67            Ok(CommandOutput::live(format!("Previous track ({})", s.name)))
68        }
69        Commands::Seek { position } => {
70            validate_seek_time(&position)?;
71            let s = spk()?;
72            s.seek(SeekTarget::Time(position.clone()))?;
73            Ok(CommandOutput::live(format!(
74                "Seeked to {} ({})",
75                position, s.name
76            )))
77        }
78        Commands::Mode { mode } => {
79            let s = spk()?;
80            s.set_play_mode(mode.to_sdk())?;
81            Ok(CommandOutput::live(format!(
82                "Mode set to {:?} ({})",
83                mode, s.name
84            )))
85        }
86        Commands::Volume { level } => cmd_volume(system, config, global, level),
87        Commands::Mute => cmd_mute(system, config, global, true),
88        Commands::Unmute => cmd_mute(system, config, global, false),
89    }
90}
91
92// -- Command handlers ---------------------------------------------------------
93
94fn cmd_speakers(system: &SonosSystem) -> Result<CommandOutput, CliError> {
95    let speakers = system.speakers();
96    if speakers.is_empty() {
97        eprintln!("{}", diagnostics::discovery_hint());
98        // No speaker was claimed, so there is nothing unvalidated to flag; the
99        // hint above already says what went wrong. See `liveness::verdict`.
100        return Ok(CommandOutput::live("No speakers found"));
101    }
102    // Two probes per speaker. The visible symptom of a dead network is these
103    // two failing and each row collapsing to a bare cached name — so counting
104    // them is exactly the evidence that the row is unverified.
105    let mut probes = Probes::default();
106    let lines: Vec<String> = speakers
107        .iter()
108        .map(|s| {
109            let state = probes.record(s.playback_state.fetch());
110            let vol = probes.record(s.volume.fetch());
111            // `group()` reads the in-memory topology, not the network — not a probe.
112            let group_name = s
113                .group()
114                .and_then(|g| g.coordinator().map(|c| c.name))
115                .unwrap_or_default();
116
117            let state_str = state
118                .as_ref()
119                .map(|st| format!("{} {}", playback_icon(st), playback_label(st)))
120                .unwrap_or_default();
121            let vol_str = vol.map(|v| format!("vol:{}", v.0)).unwrap_or_default();
122
123            let mut parts = vec![s.name.clone()];
124            if !state_str.is_empty() {
125                parts.push(state_str);
126            }
127            if !vol_str.is_empty() {
128                parts.push(vol_str);
129            }
130            if !group_name.is_empty() {
131                parts.push(format!("({group_name})"));
132            }
133            parts.join("   ")
134        })
135        .collect();
136    Ok(CommandOutput::new(lines.join("\n"), probes.verdict()))
137}
138
139fn cmd_groups(system: &SonosSystem) -> Result<CommandOutput, CliError> {
140    let groups = system.groups();
141    if groups.is_empty() {
142        eprintln!("{}", diagnostics::discovery_hint());
143        return Ok(CommandOutput::live("No groups found"));
144    }
145    let mut probes = Probes::default();
146    let lines: Vec<String> = groups
147        .iter()
148        .map(|g| {
149            let coord = g.coordinator();
150            let coord_name = coord
151                .as_ref()
152                .map(|c| c.name.clone())
153                .unwrap_or_else(|| "unknown".to_string());
154
155            // A group with no coordinator attempts nothing on the speaker, so
156            // it must not be counted as two failures.
157            let state = coord
158                .as_ref()
159                .and_then(|c| probes.record(c.playback_state.fetch()));
160            let track = coord
161                .as_ref()
162                .and_then(|c| probes.record(c.current_track.fetch()));
163            let vol = probes.record(g.volume.fetch());
164
165            let state_str = state
166                .as_ref()
167                .map(|st| format!("{} {}", playback_icon(st), playback_label(st)))
168                .unwrap_or_default();
169            let track_str = track
170                .as_ref()
171                .map(|t| {
172                    let d = t.display();
173                    if d == "Unknown" {
174                        t.uri
175                            .as_deref()
176                            .filter(|u| !u.is_empty() && !u.starts_with("x-rincon:"))
177                            .map(|_| "Playing (no metadata)".to_string())
178                            .unwrap_or(d)
179                    } else {
180                        d
181                    }
182                })
183                .unwrap_or_default();
184            let vol_str = vol.map(|v| format!("vol:{}", v.0)).unwrap_or_default();
185
186            let mut parts = vec![coord_name];
187            if !state_str.is_empty() {
188                parts.push(state_str);
189            }
190            if !track_str.is_empty() {
191                parts.push(track_str);
192            }
193            if !vol_str.is_empty() {
194                parts.push(vol_str);
195            }
196            parts.join("   ")
197        })
198        .collect();
199    Ok(CommandOutput::new(lines.join("\n"), probes.verdict()))
200}
201
202fn cmd_volume(
203    system: &SonosSystem,
204    config: &Config,
205    global: &GlobalFlags,
206    level: u8,
207) -> Result<CommandOutput, CliError> {
208    // Explicit --speaker (without --group) → Speaker.set_volume(u8)
209    if global.speaker.is_some() && global.group.is_none() {
210        let s = resolve_speaker(system, config, global)?;
211        s.set_volume(level)?;
212        return Ok(CommandOutput::live(format!(
213            "Volume set to {} ({})",
214            level, s.name
215        )));
216    }
217    // Otherwise → Group.set_volume(u16) via GroupRenderingControl
218    let g = resolve_group(system, config, global)?;
219    let name = g
220        .coordinator()
221        .map(|c| c.name)
222        .unwrap_or_else(|| "unknown".to_string());
223    g.set_volume(level as u16)?;
224    Ok(CommandOutput::live(format!(
225        "Volume set to {level} ({name})"
226    )))
227}
228
229fn cmd_mute(
230    system: &SonosSystem,
231    config: &Config,
232    global: &GlobalFlags,
233    muted: bool,
234) -> Result<CommandOutput, CliError> {
235    let label = if muted { "Muted" } else { "Unmuted" };
236    // Explicit --speaker (without --group) → Speaker.set_mute(bool)
237    if global.speaker.is_some() && global.group.is_none() {
238        let s = resolve_speaker(system, config, global)?;
239        s.set_mute(muted)?;
240        return Ok(CommandOutput::live(format!("{} ({})", label, s.name)));
241    }
242    // Otherwise → Group.set_mute(bool) via GroupRenderingControl
243    let g = resolve_group(system, config, global)?;
244    let name = g
245        .coordinator()
246        .map(|c| c.name)
247        .unwrap_or_else(|| "unknown".to_string());
248    g.set_mute(muted)?;
249    Ok(CommandOutput::live(format!("{label} ({name})")))
250}
251
252fn cmd_status(
253    system: &SonosSystem,
254    config: &Config,
255    global: &GlobalFlags,
256) -> Result<CommandOutput, CliError> {
257    let spk = resolve_speaker(system, config, global)?;
258    // Same bug as `speakers`, one row wide: with every fetch failing this
259    // printed "<name> unknown" and exited 0.
260    //
261    // A non-coordinator speaker answers NOT_IMPLEMENTED for track and
262    // position — a real reply from a real speaker that arrives here as an
263    // `Err`. That is fine: `volume` still succeeds, and one success is enough
264    // for `Live`, so a partially-answering speaker is never reported as dead.
265    let mut probes = Probes::default();
266    let state = probes.record(spk.playback_state.fetch());
267    let track = probes.record(spk.current_track.fetch());
268    let pos = probes.record(spk.position.fetch());
269    let vol = probes.record(spk.volume.fetch());
270
271    let state_str = state
272        .as_ref()
273        .map(|st| format!("{} {}", playback_icon(st), playback_label(st)))
274        .unwrap_or_else(|| "unknown".to_string());
275    let track_str = track
276        .as_ref()
277        .map(|t| {
278            let d = t.display();
279            if d == "Unknown" {
280                t.uri
281                    .as_deref()
282                    .filter(|u| !u.is_empty() && !u.starts_with("x-rincon:"))
283                    .map(|_| "Playing (no metadata)".to_string())
284                    .unwrap_or(d)
285            } else {
286                d
287            }
288        })
289        .unwrap_or_default();
290    let pos_str = pos
291        .as_ref()
292        .map(|p| {
293            format!(
294                "{}/{}",
295                format_time_ms(p.position_ms),
296                format_time_ms(p.duration_ms)
297            )
298        })
299        .unwrap_or_default();
300    let vol_str = vol.map(|v| format!("vol:{}", v.0)).unwrap_or_default();
301
302    let mut parts = vec![spk.name.clone(), state_str];
303    if !track_str.is_empty() {
304        parts.push(track_str);
305    }
306    if !pos_str.is_empty() {
307        parts.push(pos_str);
308    }
309    if !vol_str.is_empty() {
310        parts.push(vol_str);
311    }
312    Ok(CommandOutput::new(parts.join("  "), probes.verdict()))
313}
314
315fn cmd_join(
316    system: &SonosSystem,
317    config: &Config,
318    global: &GlobalFlags,
319) -> Result<CommandOutput, CliError> {
320    let raw_speaker = global
321        .speaker
322        .as_deref()
323        .ok_or_else(|| CliError::Validation("--speaker is required for join".into()))?;
324    let raw_group = global
325        .group
326        .as_deref()
327        .ok_or_else(|| CliError::Validation("--group is required for join".into()))?;
328    let speaker_name = config.resolve_alias(raw_speaker);
329    let group_name = config.resolve_alias(raw_group);
330    let spk = system
331        .speaker(speaker_name)
332        .ok_or_else(|| CliError::SpeakerNotFound(speaker_name.into()))?;
333    let grp = system
334        .group(group_name)
335        .ok_or_else(|| CliError::GroupNotFound(group_name.into()))?;
336    grp.add_speaker(&spk)?;
337    Ok(CommandOutput::live(format!(
338        "{speaker_name} joined {group_name}"
339    )))
340}
341
342fn cmd_leave(
343    system: &SonosSystem,
344    config: &Config,
345    global: &GlobalFlags,
346) -> Result<CommandOutput, CliError> {
347    let raw_speaker = global
348        .speaker
349        .as_deref()
350        .ok_or_else(|| CliError::Validation("--speaker is required for leave".into()))?;
351    let speaker_name = config.resolve_alias(raw_speaker);
352    let spk = system
353        .speaker(speaker_name)
354        .ok_or_else(|| CliError::SpeakerNotFound(speaker_name.into()))?;
355    let group_name = spk
356        .group()
357        .and_then(|g| g.coordinator().map(|c| c.name))
358        .unwrap_or_else(|| "its group".into());
359    spk.leave_group()?;
360    Ok(CommandOutput::live(format!(
361        "{speaker_name} left {group_name}"
362    )))
363}
364
365fn cmd_bass(
366    system: &SonosSystem,
367    config: &Config,
368    global: &GlobalFlags,
369    level: i8,
370) -> Result<CommandOutput, CliError> {
371    let spk = require_speaker_only(system, config, global, "bass")?;
372    spk.set_bass(level)?;
373    Ok(CommandOutput::live(format!(
374        "Bass set to {} ({})",
375        level, spk.name
376    )))
377}
378
379fn cmd_treble(
380    system: &SonosSystem,
381    config: &Config,
382    global: &GlobalFlags,
383    level: i8,
384) -> Result<CommandOutput, CliError> {
385    let spk = require_speaker_only(system, config, global, "treble")?;
386    spk.set_treble(level)?;
387    Ok(CommandOutput::live(format!(
388        "Treble set to {} ({})",
389        level, spk.name
390    )))
391}
392
393fn cmd_loudness(
394    system: &SonosSystem,
395    config: &Config,
396    global: &GlobalFlags,
397    state: OnOff,
398) -> Result<CommandOutput, CliError> {
399    let spk = require_speaker_only(system, config, global, "loudness")?;
400    let enabled = matches!(state, OnOff::On);
401    spk.set_loudness(enabled)?;
402    if enabled {
403        Ok(CommandOutput::live(format!(
404            "Loudness enabled ({})",
405            spk.name
406        )))
407    } else {
408        Ok(CommandOutput::live(format!(
409            "Loudness disabled ({})",
410            spk.name
411        )))
412    }
413}
414
415fn cmd_sleep(
416    system: &SonosSystem,
417    config: &Config,
418    global: &GlobalFlags,
419    duration: &str,
420) -> Result<CommandOutput, CliError> {
421    let spk = resolve_speaker(system, config, global)?;
422    if duration == "cancel" {
423        spk.cancel_sleep_timer()?;
424        Ok(CommandOutput::live(format!(
425            "Sleep timer cancelled ({})",
426            spk.name
427        )))
428    } else {
429        let hh_mm_ss = parse_duration(duration)?;
430        let human = format_duration_human(duration);
431        spk.configure_sleep_timer(&hh_mm_ss)?;
432        Ok(CommandOutput::live(format!(
433            "Sleep timer set for {} ({})",
434            human, spk.name
435        )))
436    }
437}
438
439fn cmd_queue(
440    system: &SonosSystem,
441    config: &Config,
442    global: &GlobalFlags,
443    action: Option<QueueAction>,
444) -> Result<CommandOutput, CliError> {
445    let spk = resolve_speaker(system, config, global)?;
446    match action {
447        None => {
448            let info = spk.get_media_info()?;
449            if info.nr_tracks == 0 {
450                return Ok(CommandOutput::live(format!(
451                    "queue is empty ({})",
452                    spk.name
453                )));
454            }
455            Ok(CommandOutput::live(format!(
456                "{} — {} tracks",
457                spk.name, info.nr_tracks
458            )))
459        }
460        Some(QueueAction::Add { uri }) => {
461            spk.add_uri_to_queue(&uri, "", 0, false)?;
462            Ok(CommandOutput::live(format!(
463                "Added to queue ({})",
464                spk.name
465            )))
466        }
467        Some(QueueAction::Clear) => {
468            if std::io::stdin().is_terminal() && !global.no_input {
469                eprint!("Clear queue for {}? [y/N] ", spk.name);
470                let mut input = String::new();
471                std::io::stdin()
472                    .read_line(&mut input)
473                    .map_err(|e| CliError::Validation(e.to_string()))?;
474                if !input.trim().eq_ignore_ascii_case("y") {
475                    return Ok(CommandOutput::live("Cancelled"));
476                }
477            }
478            spk.remove_all_tracks_from_queue()?;
479            Ok(CommandOutput::live(format!("Queue cleared ({})", spk.name)))
480        }
481    }
482}