Skip to main content

sonos_cli/
diagnostics.rs

1//! Platform-specific diagnostics for discovery failures.
2
3use std::io::IsTerminal;
4
5use crate::cli::GlobalFlags;
6
7/// Returns a platform-specific hint for when SSDP discovery finds no speakers.
8pub fn discovery_hint() -> &'static str {
9    if cfg!(target_os = "macos") {
10        "hint: this could mean:\n\
11         \x20 - no Sonos speakers are on this network\n\
12         \x20 - your terminal lacks Local Network access\n\
13         \x20   (System Settings > Privacy & Security > Local Network)\n\
14         \x20 - a firewall is blocking UDP multicast on port 1900"
15    } else if cfg!(target_os = "windows") {
16        "hint: this could mean:\n\
17         \x20 - no Sonos speakers are on this network\n\
18         \x20 - Network Discovery is disabled or your firewall is\n\
19         \x20   blocking UDP traffic on port 1900 (SSDP)"
20    } else {
21        "hint: this could mean:\n\
22         \x20 - no Sonos speakers are on this network\n\
23         \x20 - a firewall is blocking UDP multicast on port 1900\n\
24         \x20   (ufw: sudo ufw allow proto udp from any to 239.255.255.250 port 1900)"
25    }
26}
27
28/// Framed stderr banner for output that no speaker confirmed.
29///
30/// Printed with `eprintln!` rather than `tracing::warn!` on purpose. A
31/// `tracing` line is suppressed outright by `RUST_LOG=error`, and even when it
32/// survives it renders as one more lowercase log line among many — which is
33/// how the original failure went unnoticed. This is a user-facing verdict on
34/// the command's result, not a log event, so it goes to stderr unconditionally
35/// and is framed so it cannot be mistaken for log noise.
36///
37/// Reuses [`discovery_hint`] for the platform-specific causes rather than
38/// restating them.
39pub fn unvalidated_output_banner() -> String {
40    const RULE: &str = "────────────────────────────────────────────────────────────";
41    format!(
42        "{RULE}\n\
43         WARNING: no speaker responded — this output was not verified.\n\
44         \n\
45         Every request this command made failed. The names and values it\n\
46         printed came from the cached list of speakers on disk, not from any\n\
47         speaker, so they may be stale or simply wrong.\n\
48         \n\
49         {hint}\n\
50         \n\
51         Use --require-live to make this an error instead, or --offline to\n\
52         accept cached data quietly.\n\
53         {RULE}",
54        hint = discovery_hint()
55    )
56}
57
58/// One-line acknowledgement for `--offline`: the user already knows.
59pub fn unvalidated_output_note() -> &'static str {
60    "note: no speaker responded; showing cached data (--offline)"
61}
62
63/// On macOS/Windows, prompts the user to open the relevant settings pane.
64///
65/// Respects `--no-input` and TTY detection. Does nothing on Linux or when
66/// stdin is not a terminal.
67pub fn offer_open_settings(global: &GlobalFlags) {
68    if !can_prompt(global) {
69        return;
70    }
71
72    let (cmd, args, fallback) = if cfg!(target_os = "macos") {
73        (
74            "open",
75            "x-apple.systempreferences:com.apple.preference.security?Privacy_LocalNetwork",
76            "System Settings > Privacy & Security > Local Network",
77        )
78    } else if cfg!(target_os = "windows") {
79        (
80            "cmd",
81            "/C start ms-settings:privacy-localnetwork",
82            "Settings > Privacy & Security > Local Network",
83        )
84    } else {
85        return;
86    };
87
88    eprintln!();
89    eprint!("Open settings? [Y/n] ");
90
91    let mut input = String::new();
92    if std::io::stdin().read_line(&mut input).is_err() {
93        return;
94    }
95
96    let answer = input.trim();
97    if answer.is_empty() || answer.eq_ignore_ascii_case("y") {
98        let result = if cfg!(target_os = "windows") {
99            std::process::Command::new(cmd)
100                .args(args.split_whitespace())
101                .spawn()
102        } else {
103            std::process::Command::new(cmd).arg(args).spawn()
104        };
105
106        if result.is_err() {
107            eprintln!("Could not open settings. Navigate to {fallback} manually.");
108        }
109    }
110}
111
112fn can_prompt(global: &GlobalFlags) -> bool {
113    std::io::stdin().is_terminal() && !global.no_input
114}
115
116#[cfg(test)]
117mod tests {
118    use super::*;
119
120    #[test]
121    fn discovery_hint_lists_possible_causes() {
122        let hint = discovery_hint();
123        assert!(hint.starts_with("hint: this could mean:"));
124        assert!(hint.contains("no Sonos speakers are on this network"));
125    }
126
127    #[test]
128    #[cfg(target_os = "macos")]
129    fn discovery_hint_macos_mentions_local_network() {
130        let hint = discovery_hint();
131        assert!(hint.contains("Local Network"));
132        assert!(hint.contains("System Settings"));
133    }
134
135    #[test]
136    #[cfg(target_os = "windows")]
137    fn discovery_hint_windows_mentions_firewall() {
138        let hint = discovery_hint();
139        assert!(hint.contains("Network Discovery"));
140    }
141
142    #[test]
143    #[cfg(target_os = "linux")]
144    fn discovery_hint_linux_mentions_ufw() {
145        let hint = discovery_hint();
146        assert!(hint.contains("ufw"));
147        assert!(hint.contains("239.255.255.250"));
148    }
149
150    #[test]
151    fn no_input_flag_prevents_prompt() {
152        let global = GlobalFlags {
153            speaker: None,
154            group: None,
155            no_input: true,
156            ..Default::default()
157        };
158        assert!(!can_prompt(&global));
159    }
160
161    #[test]
162    fn discovery_failed_triggers_platform_hint() {
163        // SdkError::DiscoveryFailed is the variant that should route to
164        // platform-specific diagnostics in main.rs
165        let err =
166            sonos_sdk::SdkError::DiscoveryFailed("no Sonos devices found on the network".into());
167        assert!(matches!(err, sonos_sdk::SdkError::DiscoveryFailed(_)));
168
169        // And the hint it would display is our platform-specific one
170        let hint = discovery_hint();
171        assert!(hint.starts_with("hint:"));
172    }
173
174    #[test]
175    fn speaker_not_found_routes_to_platform_hint() {
176        // When resolve functions return "no speakers available", the
177        // recovery_hint() should return the platform-specific diagnostic
178        use crate::errors::CliError;
179        let err = CliError::SpeakerNotFound("no speakers available".into());
180        let hint = err.recovery_hint().expect("should have a recovery hint");
181        assert_eq!(hint, discovery_hint());
182    }
183
184    #[test]
185    fn group_not_found_routes_to_platform_hint() {
186        use crate::errors::CliError;
187        let err = CliError::GroupNotFound("no groups available".into());
188        let hint = err.recovery_hint().expect("should have a recovery hint");
189        assert_eq!(hint, discovery_hint());
190    }
191
192    #[test]
193    fn sdk_discovery_failed_uses_platform_hint() {
194        use crate::errors::CliError;
195        let err = CliError::Sdk(sonos_sdk::SdkError::DiscoveryFailed("test".into()));
196        let hint = err.recovery_hint().unwrap();
197        assert_eq!(hint, discovery_hint());
198    }
199
200    #[test]
201    fn sdk_non_network_error_uses_generic_hint() {
202        // Non-network SDK errors (e.g. lock poisoned) should get a
203        // generic hint, not the platform-specific one
204        use crate::errors::CliError;
205        let err = CliError::Sdk(sonos_sdk::SdkError::LockPoisoned);
206        let hint = err.recovery_hint().unwrap();
207        assert_ne!(
208            hint,
209            discovery_hint(),
210            "non-network SDK errors should use generic hint"
211        );
212    }
213}