1use std::time::Duration;
4
5use idevice::{IdeviceService, lockdown::LockdownClient};
6use serde_json::{Value, json};
7
8use crate::{
9 config::Config,
10 device::{conn, discovery},
11 fields,
12 reply::{Fail, Res},
13};
14
15async fn lockdown_value(client: &mut LockdownClient, key: &str) -> Option<String> {
16 tokio::time::timeout(Duration::from_secs(5), client.get_value(Some(key), None))
17 .await
18 .ok()?
19 .ok()?
20 .into_string()
21}
22
23async fn describe(route: &conn::Route) -> (Option<String>, Option<String>) {
25 if let Some(identity) = &route.identity {
26 return (identity.ios_version.clone(), identity.model.clone());
27 }
28 let connect = tokio::time::timeout(
29 Duration::from_secs(8),
30 LockdownClient::connect(&*route.provider),
31 )
32 .await;
33 let Ok(Ok(mut client)) = connect else {
34 return (None, None);
35 };
36 let version = lockdown_value(&mut client, "ProductVersion").await;
37 let model = lockdown_value(&mut client, "ProductType").await;
38 (version, model)
39}
40
41pub async fn cmd_devices(only: Option<String>) -> Res {
42 let chosen = only
43 .or_else(|| std::env::var("IPH_UDID").ok().filter(|u| !u.is_empty()))
44 .or_else(|| Config::load().ok().and_then(|c| c.udid));
45 let (found, discovery_error) = match discovery::read().await {
46 Ok(found) => (found, None),
47 Err(e) => (discovery::Discovery::default(), Some(format!("{e:#}"))),
48 };
49 let mut list = conn::summarize(found.devices.iter().map(|d| d.mux.clone()));
50 let cached = chosen
51 .as_ref()
52 .filter(|u| !list.iter().any(|d| &d.udid == *u) && conn::recall_ip(u).is_some())
53 .cloned();
54 if let Some(udid) = &cached {
55 list.push(conn::DeviceEntry {
56 udid: udid.clone(),
57 connection: "wifi".into(),
58 });
59 }
60 if list.is_empty()
61 && let Some(e) = &discovery_error
62 {
63 return Err(Fail::not_sent("usbmuxd_unreachable", e));
64 }
65 let mut mux = conn::mux_connect().await.ok();
66 let mut out: Vec<Value> = Vec::new();
67 for d in &list {
68 let contact = chosen.as_ref().is_none_or(|c| *c == d.udid);
69 let listed = cached.as_ref() != Some(&d.udid);
70 let mut entry = json!({ "udid": d.udid, "connection": d.connection,
71 "source": if listed { "usbmuxd" } else { "cached_wifi_address" },
72 "transport": if d.connection == "wifi" { "tcp" } else { "usbmuxd" },
73 "listed_by_usbmuxd": listed });
74 if !listed {
75 entry["ip"] = json!(conn::recall_ip(&d.udid).map(|ip| ip.to_string()));
76 }
77 if contact {
78 let paired = match mux.as_mut() {
79 Some(m) => tokio::time::timeout(Duration::from_secs(4), m.get_pair_record(&d.udid))
80 .await
81 .is_ok_and(|r| r.is_ok()),
82 None => false,
83 };
84 let mut version = None;
85 let mut model = None;
86 if paired {
87 let snapshot = match &discovery_error {
88 Some(e) => Err(anyhow::anyhow!(e.clone())),
89 None => Ok(found.clone()),
90 };
91 match conn::route_from(&d.udid, snapshot).await {
92 Ok(route) => {
93 entry["connection"] = json!(route.connection);
94 entry["transport"] = json!(if route.address.is_some() {
95 "tcp"
96 } else {
97 "usbmuxd"
98 });
99 entry["source"] = json!(route.source);
100 if let Some(ip) = route.address {
101 entry["ip"] = json!(ip.to_string());
102 }
103 (version, model) = describe(&route).await;
104 }
105 Err(e) => {
106 entry["connection_error"] = json!(format!("{e:#}"));
107 }
108 }
109 }
110 entry["ios_version"] = json!(version);
111 entry["model"] = json!(model);
112 entry["paired"] = json!(paired);
113 entry["ready"] = json!(paired && version.is_some());
114 entry["state"] = json!(if !paired {
115 "not paired"
116 } else if version.is_none() {
117 "unreachable"
118 } else {
119 "ready"
120 });
121 } else {
122 entry["state"] = json!("not selected");
123 entry["ready"] = json!(false);
124 }
125 out.push(entry);
126 }
127 Ok(
128 fields! { "count": out.len(), "selected": chosen, "devices": out,
129 "discovery_error": discovery_error, "discovery_warnings": found.warnings },
130 )
131}