Skip to main content

unifi_cli/api/
types.rs

1use serde::Deserialize;
2use std::fmt;
3
4#[cfg(test)]
5#[path = "tests.rs"]
6mod tests;
7
8// Integration API response wrapper (paginated)
9#[derive(Debug, Deserialize)]
10#[serde(rename_all = "camelCase")]
11pub struct PaginatedResponse<T> {
12    pub total_count: usize,
13    pub data: Vec<T>,
14}
15
16// Legacy API response wrapper (pub for standalone fetch in TUI)
17#[derive(Debug, Deserialize)]
18pub struct LegacyResponse<T> {
19    pub meta: LegacyMeta,
20    pub data: Vec<T>,
21}
22
23#[derive(Debug, Deserialize)]
24pub struct LegacyMeta {
25    pub rc: String,
26    pub msg: Option<String>,
27}
28
29// Site
30#[derive(Debug, Deserialize)]
31pub struct Site {
32    pub id: String,
33}
34
35// Client from Integration API
36#[derive(Debug, Deserialize)]
37#[serde(rename_all = "camelCase")]
38pub struct Client {
39    #[serde(alias = "macAddress")]
40    pub mac_address: Option<String>,
41    #[serde(alias = "ipAddress")]
42    pub ip_address: Option<String>,
43    pub name: Option<String>,
44    pub hostname: Option<String>,
45    #[serde(alias = "type")]
46    pub client_type: Option<String>,
47}
48
49impl Client {
50    pub fn display_name(&self) -> &str {
51        self.name
52            .as_deref()
53            .or(self.hostname.as_deref())
54            .unwrap_or("-")
55    }
56
57    pub fn clean_name(&self) -> String {
58        let name = self.display_name();
59        strip_mac_suffix(name, self.mac_address.as_deref())
60    }
61}
62
63// Client from Legacy stat/sta endpoint (richer data)
64#[derive(Debug, Deserialize)]
65pub struct LegacyClient {
66    #[serde(rename = "_id")]
67    pub id: String,
68    pub mac: Option<String>,
69    pub ip: Option<String>,
70    pub hostname: Option<String>,
71    pub name: Option<String>,
72    #[serde(default)]
73    pub is_wired: bool,
74    #[serde(default)]
75    pub blocked: bool,
76    #[serde(default)]
77    pub fixed_ap_enabled: bool,
78    pub fixed_ap_mac: Option<String>,
79    pub uptime: Option<u64>,
80    pub tx_bytes: Option<u64>,
81    pub rx_bytes: Option<u64>,
82    pub signal: Option<i32>,
83    pub ap_mac: Option<String>,
84    #[serde(rename = "essid")]
85    pub ssid: Option<String>,
86}
87
88impl LegacyClient {
89    pub fn display_name(&self) -> &str {
90        self.name
91            .as_deref()
92            .or(self.hostname.as_deref())
93            .unwrap_or("-")
94    }
95
96    pub fn clean_name(&self) -> String {
97        let name = self.display_name();
98        strip_mac_suffix(name, self.mac.as_deref())
99    }
100}
101
102// Device from Integration API
103#[derive(Debug, Deserialize)]
104#[serde(rename_all = "camelCase")]
105pub struct Device {
106    pub mac_address: Option<String>,
107    pub ip_address: Option<String>,
108    pub name: Option<String>,
109    pub model: Option<String>,
110    pub state: Option<String>,
111    pub firmware_version: Option<String>,
112}
113
114// Device from Legacy stat/device endpoint (richer data)
115#[derive(Debug, Deserialize)]
116pub struct LegacyDevice {
117    pub mac: Option<String>,
118    pub ip: Option<String>,
119    pub name: Option<String>,
120    pub model: Option<String>,
121    #[serde(rename = "type")]
122    pub device_type: Option<String>,
123    pub state: Option<u32>,
124    pub version: Option<String>,
125    pub uptime: Option<u64>,
126    pub num_sta: Option<u32>,
127    #[serde(default)]
128    pub upgradable: bool,
129    pub upgrade_to_firmware: Option<String>,
130}
131
132impl LegacyDevice {
133    pub fn state_str(&self) -> &str {
134        match self.state {
135            Some(1) => "ONLINE",
136            Some(0) => "OFFLINE",
137            Some(2) => "ADOPTING",
138            Some(4) => "UPGRADING",
139            Some(5) => "PROVISIONING",
140            _ => "UNKNOWN",
141        }
142    }
143}
144
145// Network from Integration API
146#[derive(Debug, Deserialize)]
147#[serde(rename_all = "camelCase")]
148pub struct Network {
149    pub name: Option<String>,
150    #[serde(default)]
151    pub enabled: bool,
152    pub vlan_id: Option<u16>,
153    #[serde(default)]
154    pub default: bool,
155}
156
157// Health subsystem from Legacy stat/health
158#[derive(Debug, Deserialize)]
159pub struct HealthSubsystem {
160    pub subsystem: String,
161    pub status: Option<String>,
162    pub num_sta: Option<u32>,
163    pub num_ap: Option<u32>,
164    #[serde(rename = "num_sw")]
165    pub num_switches: Option<u32>,
166    pub wan_ip: Option<String>,
167    pub isp_name: Option<String>,
168}
169
170// Sysinfo from Legacy stat/sysinfo
171#[derive(Debug, Deserialize)]
172pub struct SysInfo {
173    pub hostname: Option<String>,
174    pub version: Option<String>,
175    pub timezone: Option<String>,
176    pub uptime: Option<u64>,
177}
178
179// Host system info from /api/system (UniFi OS level)
180#[derive(Debug, Deserialize)]
181#[serde(rename_all = "camelCase")]
182pub struct HostSystem {
183    pub device_state: Option<String>,
184    pub name: Option<String>,
185}
186
187impl HostSystem {
188    pub fn update_available(&self) -> bool {
189        self.device_state.as_deref() == Some("updateAvailable")
190    }
191}
192
193/// Strip trailing MAC suffix from display names.
194/// UniFi appends " XX:XX" (last 2 bytes of MAC) to hostnames when no user name is set.
195pub fn strip_mac_suffix(name: &str, mac: Option<&str>) -> String {
196    if let Some(mac) = mac {
197        let clean_mac = normalize_mac(mac);
198        // Check for " XX:XX" suffix (last 4 hex chars of MAC with colon)
199        if clean_mac.len() >= 4 {
200            let last4 = &clean_mac[clean_mac.len() - 4..];
201            let suffix = format!(" {}:{}", &last4[..2], &last4[2..]);
202            if let Some(stripped) = name.strip_suffix(&suffix) {
203                return stripped.to_string();
204            }
205            // Also try without colon in suffix
206            let suffix_no_colon = format!(" {last4}");
207            if let Some(stripped) = name.strip_suffix(&suffix_no_colon) {
208                return stripped.to_string();
209            }
210        }
211    }
212    name.to_string()
213}
214
215pub fn normalize_mac(mac: &str) -> String {
216    mac.to_lowercase().replace([':', '-'], "")
217}
218
219pub fn format_mac(mac: &str) -> String {
220    let clean = normalize_mac(mac);
221    if clean.len() != 12 {
222        return mac.to_string();
223    }
224    format!(
225        "{}:{}:{}:{}:{}:{}",
226        &clean[0..2],
227        &clean[2..4],
228        &clean[4..6],
229        &clean[6..8],
230        &clean[8..10],
231        &clean[10..12]
232    )
233}
234
235pub fn format_bytes(bytes: u64) -> String {
236    const KB: u64 = 1024;
237    const MB: u64 = KB * 1024;
238    const GB: u64 = MB * 1024;
239
240    if bytes >= GB {
241        format!("{:.1} GB", bytes as f64 / GB as f64)
242    } else if bytes >= MB {
243        format!("{:.1} MB", bytes as f64 / MB as f64)
244    } else if bytes >= KB {
245        format!("{:.1} KB", bytes as f64 / KB as f64)
246    } else {
247        format!("{bytes} B")
248    }
249}
250
251pub fn format_uptime(seconds: u64) -> String {
252    let days = seconds / 86400;
253    let hours = (seconds % 86400) / 3600;
254    let minutes = (seconds % 3600) / 60;
255
256    if days > 0 {
257        format!("{days}d {hours}h {minutes}m")
258    } else if hours > 0 {
259        format!("{hours}h {minutes}m")
260    } else {
261        format!("{minutes}m")
262    }
263}
264
265// Event from Legacy stat/event endpoint
266#[derive(Debug, Deserialize)]
267pub struct Event {
268    pub key: Option<String>,
269    pub msg: Option<String>,
270    pub subsystem: Option<String>,
271    pub time: Option<u64>,
272    pub datetime: Option<String>,
273}
274
275// Port entry from Legacy stat/device port_table
276#[derive(Debug, Deserialize)]
277pub struct PortEntry {
278    pub port_idx: Option<u32>,
279    pub name: Option<String>,
280    pub media: Option<String>,
281    #[serde(default)]
282    pub up: bool,
283    pub speed: Option<u32>,
284    #[serde(default)]
285    pub full_duplex: bool,
286    #[serde(default)]
287    pub poe_enable: bool,
288    pub poe_power: Option<f64>,
289    #[serde(default)]
290    pub port_poe: bool,
291    pub tx_bytes: Option<u64>,
292    pub rx_bytes: Option<u64>,
293}
294
295// Device with port_table from Legacy stat/device endpoint
296#[derive(Debug, Deserialize)]
297pub struct DeviceWithPorts {
298    pub mac: Option<String>,
299    pub name: Option<String>,
300    pub model: Option<String>,
301    #[serde(default)]
302    pub port_table: Vec<PortEntry>,
303}
304
305// --- Protect API types ---
306
307/// Camera from Protect Integration API
308#[derive(Debug, Deserialize)]
309#[serde(rename_all = "camelCase")]
310pub struct ProtectCamera {
311    pub id: String,
312    pub name: Option<String>,
313    pub mac: Option<String>,
314    pub state: Option<String>,
315    pub model_key: Option<String>,
316    #[serde(default)]
317    pub is_mic_enabled: bool,
318    pub video_mode: Option<String>,
319    pub feature_flags: Option<ProtectFeatureFlags>,
320}
321
322#[derive(Debug, Deserialize)]
323#[serde(rename_all = "camelCase")]
324pub struct ProtectFeatureFlags {
325    #[serde(default)]
326    pub has_hdr: bool,
327    #[serde(default)]
328    pub has_mic: bool,
329    #[serde(default)]
330    pub has_speaker: bool,
331    #[serde(default)]
332    pub has_led_status: bool,
333    #[serde(default)]
334    pub smart_detect_types: Vec<String>,
335    #[serde(default)]
336    pub video_modes: Vec<String>,
337}
338
339/// Full camera from direct Protect API (cookie auth)
340#[derive(Debug, Deserialize)]
341#[serde(rename_all = "camelCase")]
342pub struct ProtectCameraFull {
343    pub id: String,
344    pub name: Option<String>,
345    pub mac: Option<String>,
346    pub host: Option<String>,
347    pub state: Option<String>,
348    #[serde(rename = "type")]
349    pub camera_type: Option<String>,
350    pub market_name: Option<String>,
351    pub platform: Option<String>,
352    pub firmware_version: Option<String>,
353    pub hardware_revision: Option<String>,
354    pub uptime: Option<u64>,
355    pub up_since: Option<u64>,
356    pub last_seen: Option<u64>,
357    #[serde(default)]
358    pub is_recording: bool,
359    #[serde(default)]
360    pub is_motion_detected: bool,
361    #[serde(default)]
362    pub is_dark: bool,
363    pub video_codec: Option<String>,
364    pub current_resolution: Option<String>,
365    pub video_mode: Option<String>,
366    pub hdr_type: Option<String>,
367    pub phy_rate: Option<f64>,
368    #[serde(default)]
369    pub is_mic_enabled: bool,
370    #[serde(default)]
371    pub is_poor_network: bool,
372    pub last_motion: Option<u64>,
373    pub hq_bytes_per_day: Option<u64>,
374    pub lq_bytes_per_day: Option<u64>,
375    pub model_key: Option<String>,
376    #[serde(default)]
377    pub channels: Vec<CameraChannel>,
378    pub stats: Option<CameraStats>,
379    pub wifi_connection_state: Option<WifiConnectionState>,
380    pub feature_flags: Option<ProtectFeatureFlags>,
381    pub recording_settings: Option<RecordingSettings>,
382}
383
384#[derive(Debug, Deserialize)]
385#[serde(rename_all = "camelCase")]
386pub struct CameraChannel {
387    pub id: u32,
388    pub name: Option<String>,
389    #[serde(default)]
390    pub enabled: bool,
391    pub width: Option<u32>,
392    pub height: Option<u32>,
393    pub fps: Option<u32>,
394    pub bitrate: Option<u64>,
395    #[serde(default)]
396    pub is_rtsp_enabled: bool,
397    pub rtsp_alias: Option<String>,
398}
399
400#[derive(Debug, Deserialize)]
401#[serde(rename_all = "camelCase")]
402pub struct CameraStats {
403    pub wifi: Option<WifiStats>,
404    pub storage: Option<StorageStats>,
405}
406
407#[derive(Debug, Deserialize)]
408#[serde(rename_all = "camelCase")]
409pub struct WifiStats {
410    pub channel: Option<u32>,
411    pub frequency: Option<u32>,
412    pub signal_quality: Option<i32>,
413    pub signal_strength: Option<i32>,
414}
415
416#[derive(Debug, Deserialize)]
417#[serde(rename_all = "camelCase")]
418pub struct StorageStats {
419    pub used: Option<u64>,
420    pub rate: Option<f64>,
421}
422
423#[derive(Debug, Deserialize)]
424#[serde(rename_all = "camelCase")]
425pub struct WifiConnectionState {
426    pub channel: Option<u32>,
427    pub frequency: Option<u32>,
428    pub signal_quality: Option<i32>,
429    pub signal_strength: Option<i32>,
430    pub ssid: Option<String>,
431    pub ap_name: Option<String>,
432    pub connectivity: Option<String>,
433}
434
435#[derive(Debug, Deserialize)]
436#[serde(rename_all = "camelCase")]
437pub struct RecordingSettings {
438    pub mode: Option<String>,
439    #[serde(default)]
440    pub enable_motion_detection: bool,
441}
442
443/// RTSPS stream URLs keyed by quality level
444pub type RtspsStreams = std::collections::HashMap<String, Option<String>>;
445
446// Error types
447#[derive(Debug)]
448pub enum ApiError {
449    Http(reqwest::Error),
450    Api { status: u16, message: String },
451    NotFound(String),
452    Auth(String),
453    Other(String),
454}
455
456/// Scan a single error string for TLS certificate failure markers. rustls
457/// reports these as "invalid peer certificate: <reason>", so "certificate" is
458/// the reliable marker; "self-signed" is matched defensively.
459fn text_indicates_cert_failure(s: &str) -> bool {
460    let s = s.to_lowercase();
461    s.contains("certificate") || s.contains("self-signed")
462}
463
464/// Walk a reqwest error's source chain looking for a TLS certificate failure.
465/// reqwest's own Display is only "error sending request for url (...)", so the
466/// cert cause must be read from the nested chain. The top-level Display and the
467/// Debug form are deliberately not scanned: both embed the request URL, so a
468/// controller hostname containing a word like "certificate" would otherwise be
469/// misread as a certificate failure on any unrelated network error.
470fn reqwest_is_cert_failure(e: &reqwest::Error) -> bool {
471    use std::error::Error;
472    let mut source: Option<&dyn std::error::Error> = e.source();
473    while let Some(err) = source {
474        if text_indicates_cert_failure(&err.to_string()) {
475            return true;
476        }
477        source = err.source();
478    }
479    false
480}
481
482impl ApiError {
483    /// True when the error indicates a TLS certificate verification failure, so
484    /// callers can offer the `--accept-invalid-certs` opt-out.
485    pub fn is_tls_cert_error(&self) -> bool {
486        match self {
487            ApiError::Http(e) => reqwest_is_cert_failure(e),
488            other => text_indicates_cert_failure(&other.to_string()),
489        }
490    }
491}
492
493impl fmt::Display for ApiError {
494    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
495        match self {
496            ApiError::Http(e) => {
497                write!(f, "HTTP error: {e}")?;
498                // Certificate failures are checked first because reqwest also
499                // classifies a failed TLS handshake as a connect error.
500                if reqwest_is_cert_failure(e) {
501                    write!(
502                        f,
503                        "\n  Hint: TLS certificate verification failed. For a trusted controller \
504                         with a self-signed cert, run 'unifi config init' to trust it \
505                         interactively, or pass --accept-invalid-certs (or set \
506                         UNIFI_ACCEPT_INVALID_CERTS=true or accept_invalid_certs = true in config)"
507                    )?;
508                } else if e.is_connect() {
509                    write!(
510                        f,
511                        "\n  Hint: Check that the host is reachable and the URL is correct"
512                    )?;
513                } else if e.is_timeout() {
514                    write!(f, "\n  Hint: Request timed out. Is the controller running?")?;
515                } else {
516                    let msg = e.to_string().to_lowercase();
517                    if msg.contains("dns") || msg.contains("resolve") {
518                        write!(
519                            f,
520                            "\n  Hint: Could not resolve hostname. Check the host value"
521                        )?;
522                    }
523                }
524                Ok(())
525            }
526            ApiError::Api { status, message } => write!(f, "API error ({status}): {message}"),
527            ApiError::NotFound(msg) => write!(f, "Not found: {msg}"),
528            ApiError::Auth(msg) => {
529                write!(f, "Authentication error: {msg}")?;
530                write!(
531                    f,
532                    "\n  Hint: Check your API key. Generate one in UniFi Settings > API"
533                )
534            }
535            ApiError::Other(msg) => write!(f, "{msg}"),
536        }
537    }
538}
539
540impl std::error::Error for ApiError {
541    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
542        match self {
543            ApiError::Http(e) => Some(e),
544            _ => None,
545        }
546    }
547}
548
549impl From<reqwest::Error> for ApiError {
550    fn from(e: reqwest::Error) -> Self {
551        if e.status()
552            .is_some_and(|s| s.as_u16() == 401 || s.as_u16() == 403)
553        {
554            ApiError::Auth(e.to_string())
555        } else if e.status().is_some_and(|s| s.as_u16() == 404) {
556            ApiError::NotFound(e.to_string())
557        } else {
558            ApiError::Http(e)
559        }
560    }
561}