1use std::time::Duration;
4
5use idevice::{IdeviceService, lockdown::LockdownClient};
6use serde_json::{Value, json};
7
8use crate::{config::Config, device::conn, fields, reply::{Fail, Res}};
9
10async fn lockdown_value(client: &mut LockdownClient, key: &str) -> Option<String> {
11 tokio::time::timeout(Duration::from_secs(5), client.get_value(Some(key), None))
12 .await
13 .ok()?
14 .ok()?
15 .into_string()
16}
17
18async fn describe(udid: &str) -> (Option<String>, Option<String>) {
20 let Ok(route) = conn::route(udid).await else {
21 return (None, None);
22 };
23 let connect = tokio::time::timeout(Duration::from_secs(8), LockdownClient::connect(&*route.provider)).await;
24 let Ok(Ok(mut client)) = connect else {
25 return (None, None);
26 };
27 let version = lockdown_value(&mut client, "ProductVersion").await;
28 let model = lockdown_value(&mut client, "ProductType").await;
29 (version, model)
30}
31
32pub async fn cmd_devices(only: Option<String>) -> Res {
33 let list = conn::list()
34 .await
35 .map_err(|e| Fail::not_sent("usbmuxd_unreachable", format!("{e:#}")))?;
36 let chosen = only
39 .or_else(|| std::env::var("IPH_UDID").ok().filter(|u| !u.is_empty()))
40 .or_else(|| Config::load().ok().and_then(|c| c.udid));
41 let mut mux = conn::mux_connect().await.ok();
42 let mut out: Vec<Value> = Vec::new();
43 for d in &list {
44 let contact = chosen.as_ref().is_none_or(|c| *c == d.udid);
45 let mut entry = json!({ "udid": d.udid, "connection": d.connection });
46 if contact {
47 let paired = match mux.as_mut() {
48 Some(m) => m.get_pair_record(&d.udid).await.is_ok(),
49 None => false,
50 };
51 let (version, model) = if paired { describe(&d.udid).await } else { (None, None) };
52 entry["ios_version"] = json!(version);
53 entry["model"] = json!(model);
54 entry["paired"] = json!(paired);
55 entry["ready"] = json!(paired && version.is_some());
56 entry["state"] = json!(if !paired {
57 "not paired"
58 } else if version.is_none() {
59 "unreachable"
60 } else {
61 "ready"
62 });
63 } else {
64 entry["state"] = json!("not selected");
65 entry["ready"] = json!(false);
66 }
67 out.push(entry);
68 }
69 Ok(fields! { "count": out.len(), "selected": chosen, "devices": out })
70}