diff --git a/Cargo.lock b/Cargo.lock index af3aca9..3852279 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -359,6 +359,18 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "async-compression" +version = "0.4.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ad47a740fb906fffdd891e8b6d5fde2511600f7bfaebd68939fa08a14999459" +dependencies = [ + "compression-codecs", + "compression-core", + "futures-io", + "pin-project-lite", +] + [[package]] name = "async-executor" version = "1.14.1" @@ -466,6 +478,21 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "async_zip" +version = "0.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d8c50d65ce1b0e0cb65a785ff615f78860d7754290647d3b983208daa4f85e6" +dependencies = [ + "async-compression", + "crc32fast", + "futures-lite", + "pin-project", + "thiserror 2.0.21", + "tokio", + "tokio-util", +] + [[package]] name = "atomic-waker" version = "1.1.2" @@ -947,6 +974,22 @@ dependencies = [ "memchr", ] +[[package]] +name = "compression-codecs" +version = "0.4.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84f840cff84d10085260e460023934d0af699e71212b09b2a41452e8bd9cda43" +dependencies = [ + "compression-core", + "flate2", +] + +[[package]] +name = "compression-core" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ebdda89edc534bf8d5dd2857562633b6495557e5846552ade994b99ed13c36a" + [[package]] name = "concurrent-queue" version = "2.5.0" @@ -2935,6 +2978,7 @@ version = "0.1.68" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f5d7799c8497cef60ddfd38f7d92e267b9fa5d0b18e7691d31041453007400ca" dependencies = [ + "async_zip", "base64 0.22.1", "chrono", "futures", @@ -6905,6 +6949,7 @@ checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" dependencies = [ "bytes", "futures-core", + "futures-io", "futures-sink", "futures-util", "pin-project-lite", @@ -7058,6 +7103,7 @@ dependencies = [ "idevice", "jiff", "nusb", + "plist", "tempfile", "tokio", "tunal-core", diff --git a/Cargo.toml b/Cargo.toml index d8cec4b..3fba8b0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,8 +35,9 @@ base64 = "0.23" hmac = "0.13" sha1 = "0.11" futures-lite = "2" -idevice = { version = "0.1.68", default-features = false, features = ["ring", "usbmuxd", "afc", "pair"] } +idevice = { version = "0.1.68", default-features = false, features = ["ring", "usbmuxd", "afc", "pair", "house_arrest", "installation_proxy"] } tokio = { version = "1", features = ["rt-multi-thread", "net", "time", "sync"] } +plist = "1.10" russh = { version = "0.65", default-features = false, features = ["ring", "flate2", "rsa"] } russh-sftp = "3" secrecy = "0.10" diff --git a/crates/tunal-devices/Cargo.toml b/crates/tunal-devices/Cargo.toml index f5003eb..6a9a331 100644 --- a/crates/tunal-devices/Cargo.toml +++ b/crates/tunal-devices/Cargo.toml @@ -11,6 +11,7 @@ jiff.workspace = true tunal-core = { path = "../tunal-core" } futures-lite.workspace = true idevice.workspace = true +plist.workspace = true tokio.workspace = true [dev-dependencies] diff --git a/crates/tunal-devices/src/ios/apps.rs b/crates/tunal-devices/src/ios/apps.rs new file mode 100644 index 0000000..cd9a0ab --- /dev/null +++ b/crates/tunal-devices/src/ios/apps.rs @@ -0,0 +1,163 @@ +//! App document folders: `ios:///Apps` lists the installed apps that share files +//! (installation_proxy), and `ios:///Apps//` is `` inside that +//! app's Documents folder, reached over house_arrest with the same AFC calls as the media folder. + +use idevice::afc::AfcClient; +use idevice::house_arrest::HouseArrestClient; +use idevice::installation_proxy::InstallationProxyClient; +use idevice::provider::IdeviceProvider; +use idevice::{IdeviceError, IdeviceService}; +use plist::{Dictionary, Value}; +use tunal_core::Uri; + +use super::SCHEME; + +/// The virtual folder at the device root that holds the apps. +pub const APPS: &str = "Apps"; +/// Where house_arrest puts an app's shared files, inside its AFC root. +const DOCUMENTS: &str = "/Documents"; + +/// An installed app that shares its Documents folder. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct App { + pub bundle_id: String, + pub name: String, +} + +/// Which AFC root a path of an `ios://` URI lives in. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Container { + /// The media folder (photos, downloads …), the device root. + Media, + /// The virtual `Apps` folder itself. + AppList, + /// One app's container, by bundle id. + App(String), +} + +/// Splits an `ios://` path into its container and the AFC path inside it. `None` for +/// paths that aren't UTF-8 (AFC paths are). A real `Apps` folder in the media root (none +/// on a stock device) is hidden behind the virtual one. +pub fn container(uri: &Uri) -> Option<(Container, String)> { + let path = std::str::from_utf8(uri.path()).ok()?; + let trimmed = path.trim_end_matches('/'); + let Some(rest) = trimmed + .strip_prefix('/') + .and_then(|p| p.strip_prefix(APPS)) + .filter(|r| r.is_empty() || r.starts_with('/')) + else { + return Some((Container::Media, path.to_owned())); + }; + let rest = rest.trim_start_matches('/'); + if rest.is_empty() { + return Some((Container::AppList, "/".into())); + } + let (bundle_id, inner) = rest.split_once('/').unwrap_or((rest, "")); + let inner = inner.trim_start_matches('/'); + let afc = if inner.is_empty() { + DOCUMENTS.to_owned() + } else { + format!("{DOCUMENTS}/{inner}") + }; + Some((Container::App(bundle_id.to_owned()), afc)) +} + +/// True for the folders we make up (`Apps`, and each app's own folder): they can't be +/// renamed, deleted or written as files, and new folders can't be made beside the apps. +pub fn is_fixed(uri: &Uri) -> bool { + match container(uri) { + Some((Container::AppList, _)) => true, + Some((Container::App(_), path)) => path == DOCUMENTS, + _ => false, + } +} + +/// `ios:///Apps`. +pub fn apps_uri(udid: &str) -> Uri { + Uri::new(SCHEME, udid, format!("/{APPS}")) +} + +/// `ios:///Apps/`: the app's Documents folder. +pub fn app_uri(udid: &str, bundle_id: &str) -> Uri { + apps_uri(udid).join(bundle_id.as_bytes()) +} + +/// installation_proxy `Browse` options: user apps, only the keys we read. +pub fn browse_options() -> Value { + let mut options = Dictionary::new(); + options.insert("ApplicationType".into(), "User".into()); + let attributes = [ + "CFBundleIdentifier", + "CFBundleDisplayName", + "CFBundleName", + "UIFileSharingEnabled", + ]; + options.insert( + "ReturnAttributes".into(), + Value::Array(attributes.iter().map(|&a| a.into()).collect()), + ); + Value::Dictionary(options) +} + +/// The apps of a `Browse` answer that share files, by name. An app without a display name +/// goes by its bundle name, then its bundle id. +pub fn file_sharing_apps(list: &[Value]) -> Vec { + let mut apps: Vec = list + .iter() + .filter_map(Value::as_dictionary) + .filter(|d| { + d.get("UIFileSharingEnabled") + .is_some_and(|v| v.as_boolean() == Some(true) || v.as_string() == Some("YES")) + }) + .filter_map(|d| { + let text = |key: &str| { + d.get(key) + .and_then(Value::as_string) + .filter(|s| !s.is_empty()) + }; + let bundle_id = text("CFBundleIdentifier").filter(|b| !b.contains('/'))?; + let name = text("CFBundleDisplayName") + .or_else(|| text("CFBundleName")) + .unwrap_or(bundle_id); + Some(App { + bundle_id: bundle_id.to_owned(), + name: name.to_owned(), + }) + }) + .collect(); + apps.sort_by(|a, b| { + a.name + .to_lowercase() + .cmp(&b.name.to_lowercase()) + .then_with(|| a.bundle_id.cmp(&b.bundle_id)) + }); + apps +} + +/// The installed apps that share files. +pub(super) async fn list(provider: &dyn IdeviceProvider) -> Result, IdeviceError> { + let mut proxy = InstallationProxyClient::connect(provider).await?; + let list = proxy.browse(Some(browse_options())).await?; + Ok(file_sharing_apps(&list)) +} + +/// An AFC client on the app's container: Documents only, or the whole container where the +/// device allows it (apps built for development). +pub(super) async fn vend( + provider: &dyn IdeviceProvider, + bundle_id: &str, +) -> Result { + let documents = HouseArrestClient::connect(provider) + .await? + .vend_documents(bundle_id) + .await; + match documents { + Err(IdeviceError::UnexpectedResponse(_)) => { + HouseArrestClient::connect(provider) + .await? + .vend_container(bundle_id) + .await + } + other => other, + } +} diff --git a/crates/tunal-devices/src/ios/location.rs b/crates/tunal-devices/src/ios/location.rs index 4ac4a3d..42f0903 100644 --- a/crates/tunal-devices/src/ios/location.rs +++ b/crates/tunal-devices/src/ios/location.rs @@ -1,7 +1,9 @@ -//! The `Location` side of [`IosLocation`]: AFC calls on the device's shared client; file -//! streams get an AFC connection of their own so listing goes on during a transfer. +//! The `Location` side of [`IosLocation`]: AFC calls on the device's shared client (or the +//! app's, under `Apps`); file streams get an AFC connection of their own so listing goes on +//! during a transfer. use std::collections::HashMap; +use std::collections::hash_map::Entry as Slot; use std::io::{self, Read, Write}; use std::sync::Arc; use std::time::{Duration, SystemTime}; @@ -18,6 +20,7 @@ use tunal_core::{ display_name, mime, }; +use super::apps::{self, APPS, Container}; use super::{Device, IosLocation, SCHEME, lock}; /// Bytes per AFC read while streaming a file from the device. @@ -33,42 +36,98 @@ impl IosLocation { .ok_or(CoreError::NotFound) } - /// Runs `op` on the device's AFC client with the AFC path of `uri`. + /// Runs `op` on the AFC client of the container holding `uri` (the media folder or an + /// app's) with the AFC path inside it. fn run( &self, uri: &Uri, op: impl AsyncFnOnce(&mut AfcClient, String) -> std::result::Result, ) -> Result { let d = self.device(uri)?; - let path = afc_path(uri)?; - let mut guard = lock(&d.afc); - let Some(afc) = guard.as_mut() else { - return Err(problem_error(&d)); - }; - let result = self.rt.block_on(op(afc, path)); - if let Err(IdeviceError::Socket(_)) = result { - // Lost the connection: the device is going away, or will need a replug. - guard.take(); - d.set_problem(Some("Lost the connection to the iPhone".into())); + let (container, path) = apps::container(uri).ok_or(CoreError::NotFound)?; + match container { + Container::Media => { + let mut guard = lock(&d.afc); + let Some(afc) = guard.as_mut() else { + return Err(problem_error(&d)); + }; + let result = self.rt.block_on(op(afc, path)); + if let Err(IdeviceError::Socket(_)) = result { + // Lost the connection: the device is going away, or will need a replug. + guard.take(); + d.set_problem(Some("Lost the connection to the iPhone".into())); + } + result.map_err(core_error) + } + // Made up: nothing to ask the device. + Container::AppList => Err(CoreError::PermissionDenied), + Container::App(bundle_id) => { + if lock(&d.afc).is_none() { + return Err(problem_error(&d)); + } + let mut containers = lock(&d.containers); + let afc = match containers.entry(bundle_id.clone()) { + Slot::Occupied(slot) => slot.into_mut(), + Slot::Vacant(slot) => slot.insert( + self.rt + .block_on(apps::vend(&d.provider, &bundle_id)) + .map_err(vend_error)?, + ), + }; + let result = self.rt.block_on(op(afc, path)); + if let Err(IdeviceError::Socket(_)) = result { + containers.remove(&bundle_id); + } + result.map_err(core_error) + } } - result.map_err(core_error) } /// Opens `uri` on a fresh AFC connection. fn open(&self, uri: &Uri, mode: AfcFopenMode) -> Result { let d = self.device(uri)?; - let path = afc_path(uri)?; + let (container, path) = apps::container(uri).ok_or(CoreError::NotFound)?; if lock(&d.afc).is_none() { return Err(problem_error(&d)); } + let afc = match container { + Container::Media => self + .rt + .block_on(AfcClient::connect(&d.provider)) + .map_err(core_error)?, + Container::AppList => return Err(CoreError::PermissionDenied), + Container::App(bundle_id) => self + .rt + .block_on(apps::vend(&d.provider, &bundle_id)) + .map_err(vend_error)?, + }; self.rt - .block_on(async { - let afc = AfcClient::connect(&d.provider).await?; - afc.open_owned(path, mode).await - }) + .block_on(afc.open_owned(path, mode)) .map_err(core_error) } + /// The `Apps` folder: one folder per file-sharing app, named by bundle id. + fn list_apps(&self, dir: &Uri) -> Result> { + let d = self.device(dir)?; + if lock(&d.afc).is_none() { + return Err(problem_error(&d)); + } + let list = self + .rt + .block_on(apps::list(&d.provider)) + .map_err(core_error)?; + let entries = list + .iter() + .map(|app| { + let mut entry = folder(app.bundle_id.clone().into_bytes()); + entry.display_name = app.name.clone(); + entry + }) + .collect(); + *lock(&d.apps) = list; + Ok(entries) + } + fn exists(&self, uri: &Uri) -> Result { match self.run(uri, async |afc, path| afc.get_file_info_raw(path).await) { Ok(_) => Ok(true), @@ -91,10 +150,24 @@ impl Location for IosLocation { } fn list(&self, dir: &Uri, sink: &mut ListSink<'_>) -> Result<()> { + let at = apps::container(dir).ok_or(CoreError::NotFound)?; + if at.0 == Container::AppList { + let entries = self.list_apps(dir)?; + return if sink(entries).is_break() { + Err(CoreError::Cancelled) + } else { + Ok(()) + }; + } + let media_root = at == (Container::Media, "/".into()); let names = self.run(dir, async |afc, path| afc.list_dir(path).await)?; let mut chunk = Vec::new(); + if media_root { + chunk.push(folder(APPS.into())); + } for name in names { - if name == "." || name == ".." { + // A real `Apps` in the media root is hidden behind ours. + if name == "." || name == ".." || (media_root && name == APPS) { continue; } let child = dir.join(name.as_bytes()); @@ -115,8 +188,22 @@ impl Location for IosLocation { } fn stat(&self, uri: &Uri) -> Result { + let name = uri.file_name().unwrap_or(b"").to_vec(); + if apps::container(uri).is_some_and(|(c, _)| c == Container::AppList) { + self.device(uri)?; + return Ok(folder(name)); + } let info = self.run(uri, async |afc, path| afc.get_file_info_raw(path).await)?; - Ok(to_entry(uri.file_name().unwrap_or(b"").to_vec(), &info)) + let mut entry = to_entry(name, &info); + if apps::is_fixed(uri) { + // An app's folder goes by the app's name, once the `Apps` listing has it. + let d = self.device(uri)?; + let apps = lock(&d.apps); + if let Some(app) = apps.iter().find(|a| a.bundle_id.as_bytes() == entry.name) { + entry.display_name = app.name.clone(); + } + } + Ok(entry) } fn open_read(&self, uri: &Uri) -> Result> { @@ -131,6 +218,9 @@ impl Location for IosLocation { } fn open_write(&self, uri: &Uri, mode: WriteMode) -> Result> { + if apps::is_fixed(uri) { + return Err(CoreError::PermissionDenied); + } match self.stat(uri) { Ok(_) if mode == WriteMode::CreateNew => return Err(CoreError::Exists), Ok(e) if e.kind == Kind::Dir => return Err(CoreError::Exists), @@ -145,6 +235,9 @@ impl Location for IosLocation { } fn mkdir(&self, uri: &Uri) -> Result<()> { + if apps::is_fixed(uri) { + return Err(CoreError::PermissionDenied); + } if self.exists(uri)? { return Err(CoreError::Exists); } @@ -152,17 +245,25 @@ impl Location for IosLocation { } fn rename(&self, from: &Uri, to: &Uri) -> Result<()> { - if from.authority() != to.authority() { + if apps::is_fixed(from) || apps::is_fixed(to) { + return Err(CoreError::PermissionDenied); + } + // Another device or another container: the job copies and deletes instead. + let (from_container, _) = apps::container(from).ok_or(CoreError::NotFound)?; + let (to_container, target) = apps::container(to).ok_or(CoreError::NotFound)?; + if from.authority() != to.authority() || from_container != to_container { return Err(CoreError::Unsupported); } if self.exists(to)? { return Err(CoreError::Exists); } - let target = afc_path(to)?; self.run(from, async |afc, path| afc.rename(path, target).await) } fn delete(&self, uri: &Uri) -> Result<()> { + if apps::is_fixed(uri) { + return Err(CoreError::PermissionDenied); + } self.run(uri, async |afc, path| afc.remove(path).await) } } @@ -209,10 +310,20 @@ impl Drop for Upload { } } -/// AFC paths are UTF-8, rooted at the media folder. -fn afc_path(uri: &Uri) -> Result { - let path = String::from_utf8(uri.path().to_vec()).map_err(|_| CoreError::NotFound)?; - Ok(if path.is_empty() { "/".into() } else { path }) +/// A folder entry for a name we make up (`Apps`, an app). +fn folder(name: Vec) -> Entry { + Entry { + display_name: display_name(&name), + hidden: false, + mime: mime::mime_type(&name, &Kind::Dir), + name, + kind: Kind::Dir, + size: 0, + mtime: None, + mode: 0, + uid: 0, + gid: 0, + } } fn to_entry(name: Vec, info: &HashMap) -> Entry { @@ -263,6 +374,16 @@ fn core_error(e: IdeviceError) -> CoreError { } } +/// house_arrest says no: the app is gone or doesn't share its files. +fn vend_error(e: IdeviceError) -> CoreError { + match e { + IdeviceError::UnexpectedResponse(_) => { + CoreError::Remote("This app doesn't share its files".into()) + } + e => core_error(e), + } +} + fn io_error(e: IdeviceError) -> io::Error { io::Error::other(e.to_string()) } diff --git a/crates/tunal-devices/src/ios/mod.rs b/crates/tunal-devices/src/ios/mod.rs index e06d126..2eb5c26 100644 --- a/crates/tunal-devices/src/ios/mod.rs +++ b/crates/tunal-devices/src/ios/mod.rs @@ -1,7 +1,9 @@ //! iPhones and iPads through the system usbmuxd (D-006): each trusted device is an -//! `ios:///` location on its AFC media folder. All calls block; run them off the -//! UI thread. No usbmuxd socket means no devices, never an error. +//! `ios:///` location on its AFC media folder, plus a virtual `Apps` folder with +//! the apps that share files (see [`apps`]). All calls block; run them off the UI thread. No +//! usbmuxd socket means no devices, never an error. +pub mod apps; mod location; use std::collections::{HashMap, HashSet}; @@ -19,6 +21,7 @@ use tokio::runtime::Runtime; use tunal_core::Uri; use crate::DevicePlace; +use apps::App; pub const SCHEME: &str = "ios"; /// Our name towards usbmuxd and lockdown. @@ -48,6 +51,10 @@ struct Device { provider: UsbmuxdProvider, name: Mutex, afc: Mutex>, + /// The file-sharing apps of the last `Apps` listing, for their names. + apps: Mutex>, + /// AFC clients on app containers (house_arrest), by bundle id, opened on first use. + containers: Mutex>, /// Shown instead of the files until the device is ready (trust, connecting, failure). problem: Mutex>, gone: AtomicBool, @@ -71,20 +78,32 @@ impl IosLocation { }) } - /// Sidebar entries, devices by name. + /// Sidebar entries, devices by name; a connected device is followed by its `Apps` folder. pub fn places(&self) -> Vec { - let mut out: Vec = lock(&self.devices) + let mut devices: Vec<(String, String, bool)> = lock(&self.devices) .values() - .map(|d| DevicePlace { - name: lock(&d.name).clone(), - uri: Uri::new(SCHEME, &d.udid, "/"), + .map(|d| { + ( + lock(&d.name).clone(), + d.udid.clone(), + lock(&d.afc).is_some(), + ) }) .collect(); - out.sort_by(|a, b| { - a.name - .cmp(&b.name) - .then(a.uri.authority().cmp(b.uri.authority())) - }); + devices.sort(); + let mut out = Vec::new(); + for (name, udid, connected) in devices { + out.push(DevicePlace { + name, + uri: Uri::new(SCHEME, &udid, "/"), + }); + if connected { + out.push(DevicePlace { + name: apps::APPS.into(), + uri: apps::apps_uri(&udid), + }); + } + } out } @@ -132,6 +151,8 @@ impl IosLocation { provider: dev.to_provider(self.addr.clone(), LABEL), name: Mutex::new("iPhone".into()), afc: Mutex::new(None), + apps: Mutex::default(), + containers: Mutex::default(), problem: Mutex::new(Some(CONNECTING.into())), gone: AtomicBool::new(false), }); @@ -248,6 +269,7 @@ impl Device { fn close(&self) { self.gone.store(true, Ordering::Relaxed); lock(&self.afc).take(); + lock(&self.containers).clear(); } } diff --git a/crates/tunal-devices/tests/ios_apps.rs b/crates/tunal-devices/tests/ios_apps.rs new file mode 100644 index 0000000..17ae396 --- /dev/null +++ b/crates/tunal-devices/tests/ios_apps.rs @@ -0,0 +1,193 @@ +//! iPhone app folders: `ios://` paths to containers and the installation_proxy app list. + +use plist::{Dictionary, Value}; +use tunal_core::Uri; +use tunal_devices::ios::apps::{ + App, Container, app_uri, apps_uri, browse_options, container, file_sharing_apps, is_fixed, +}; + +const UDID: &str = "00008110-001A2B3C4D5E6F70"; + +fn at(path: &str) -> (Container, String) { + container(&Uri::new("ios", UDID, path)).expect("UTF-8 path") +} + +fn app(id: &str) -> Container { + Container::App(id.into()) +} + +// ------------------------------------------------------------ URIs + +#[test] +fn uris_format_and_parse_back() { + let apps = apps_uri(UDID); + assert_eq!(apps.to_string(), format!("ios://{UDID}/Apps")); + let one = app_uri(UDID, "com.example.Notes"); + assert_eq!( + one.to_string(), + format!("ios://{UDID}/Apps/com.example.Notes") + ); + assert_eq!(Uri::parse(&one.to_string()), Some(one.clone())); + assert_eq!( + one.parent(), + Some(apps.clone()), + "up from an app is the app list" + ); + assert_eq!( + apps.parent(), + Some(Uri::new("ios", UDID, "/")), + "up from Apps is the device" + ); + assert_eq!(one.file_name(), Some(&b"com.example.Notes"[..])); +} + +#[test] +fn media_paths_stay_as_they_are() { + assert_eq!(at("/"), (Container::Media, "/".into())); + assert_eq!( + at("/DCIM/100APPLE"), + (Container::Media, "/DCIM/100APPLE".into()) + ); + assert_eq!( + at("/Appstore notes"), + (Container::Media, "/Appstore notes".into()), + "only the whole name Apps is ours" + ); + assert_eq!( + at("/Downloads/Apps"), + (Container::Media, "/Downloads/Apps".into()) + ); +} + +#[test] +fn app_paths_map_into_documents() { + assert_eq!(at("/Apps"), (Container::AppList, "/".into())); + assert_eq!(at("/Apps/"), (Container::AppList, "/".into())); + assert_eq!( + at("/Apps/com.example.Notes"), + (app("com.example.Notes"), "/Documents".into()) + ); + assert_eq!( + at("/Apps/com.example.Notes/"), + (app("com.example.Notes"), "/Documents".into()) + ); + assert_eq!( + at("/Apps/com.example.Notes/Inbox/a b.txt"), + (app("com.example.Notes"), "/Documents/Inbox/a b.txt".into()) + ); + let joined = app_uri(UDID, "org.example.Player").join("song.mp3".as_bytes()); + assert_eq!( + container(&joined), + Some((app("org.example.Player"), "/Documents/song.mp3".into())) + ); +} + +#[test] +fn non_utf8_paths_have_no_container() { + assert_eq!( + container(&Uri::new("ios", UDID, b"/caf\xe9".to_vec())), + None + ); +} + +#[test] +fn only_the_made_up_folders_are_fixed() { + let fixed = |p: &str| is_fixed(&Uri::new("ios", UDID, p)); + assert!(fixed("/Apps")); + assert!(fixed("/Apps/com.example.Notes")); + assert!( + fixed("/Apps/New folder"), + "nothing can be made beside the apps" + ); + assert!(!fixed("/Apps/com.example.Notes/Inbox")); + assert!(!fixed("/")); + assert!(!fixed("/DCIM")); +} + +// ------------------------------------------------------------ app list + +fn dict(pairs: &[(&str, Value)]) -> Value { + let mut d = Dictionary::new(); + for (k, v) in pairs { + d.insert((*k).into(), v.clone()); + } + Value::Dictionary(d) +} + +fn s(text: &str) -> Value { + Value::String(text.into()) +} + +#[test] +fn browse_asks_for_user_apps_and_the_keys_we_read() { + let options = browse_options(); + let options = options.as_dictionary().expect("a dictionary"); + assert_eq!(options.get("ApplicationType"), Some(&s("User"))); + let attributes: Vec<&str> = options + .get("ReturnAttributes") + .and_then(Value::as_array) + .expect("an array") + .iter() + .filter_map(Value::as_string) + .collect(); + for key in [ + "CFBundleIdentifier", + "CFBundleDisplayName", + "UIFileSharingEnabled", + ] { + assert!(attributes.contains(&key), "{key}"); + } +} + +#[test] +fn keeps_file_sharing_apps_by_name() { + let list = vec![ + dict(&[ + ("CFBundleIdentifier", s("com.example.zed")), + ("CFBundleDisplayName", s("Zed Reader")), + ("UIFileSharingEnabled", Value::Boolean(true)), + ]), + dict(&[ + ("CFBundleIdentifier", s("com.example.hidden")), + ("CFBundleDisplayName", s("Hidden")), + ("UIFileSharingEnabled", Value::Boolean(false)), + ]), + dict(&[ + ("CFBundleIdentifier", s("com.example.nokey")), + ("CFBundleDisplayName", s("No key")), + ]), + dict(&[ + ("CFBundleIdentifier", s("org.example.player")), + ("CFBundleName", s("audio player")), + ("UIFileSharingEnabled", s("YES")), + ]), + dict(&[ + ("CFBundleIdentifier", s("net.example.bare")), + ("CFBundleDisplayName", s("")), + ("UIFileSharingEnabled", Value::Boolean(true)), + ]), + dict(&[ + ("CFBundleDisplayName", s("No id")), + ("UIFileSharingEnabled", Value::Boolean(true)), + ]), + dict(&[ + ("CFBundleIdentifier", s("bad/id")), + ("UIFileSharingEnabled", Value::Boolean(true)), + ]), + s("not a dictionary"), + ]; + let named = |bundle_id: &str, name: &str| App { + bundle_id: bundle_id.into(), + name: name.into(), + }; + assert_eq!( + file_sharing_apps(&list), + vec![ + named("org.example.player", "audio player"), + named("net.example.bare", "net.example.bare"), + named("com.example.zed", "Zed Reader"), + ], + "sharing apps only, by name ignoring case; display name, else bundle name, else id" + ); + assert!(file_sharing_apps(&[]).is_empty()); +} diff --git a/crates/tunal/src/devices_bridge.rs b/crates/tunal/src/devices_bridge.rs index 8b341fe..1fc5d28 100644 --- a/crates/tunal/src/devices_bridge.rs +++ b/crates/tunal/src/devices_bridge.rs @@ -15,6 +15,8 @@ use crate::shell::places::Place; /// Material Symbols `smartphone`. const PHONE: &str = "\u{e32c}"; +/// Material Symbols `apps`, for an iPhone's `Apps` folder. +const APPS: &str = "\u{e5c3}"; thread_local! { static SHELL: RefCell> = const { RefCell::new(Weak::new()) }; @@ -79,9 +81,9 @@ pub fn attach(shell: &Rc, backends: Backends) { } } -/// True for sidebar entries that can be ejected. +/// True for sidebar entries that can be ejected: the iPhones themselves, not their `Apps`. pub fn can_eject(uri: &Uri) -> bool { - uri.scheme() == ios::SCHEME + uri.scheme() == ios::SCHEME && uri.path() == b"/" } /// Closes the device at `uri`; it shows again once replugged. @@ -106,7 +108,11 @@ fn show(lists: &Mutex, update: impl FnOnce(&mut Lists)) { .into_iter() .map(|p| Place { name: p.name, - glyph: PHONE, + glyph: if p.uri.scheme() == ios::SCHEME && !can_eject(&p.uri) { + APPS + } else { + PHONE + }, uri: p.uri, }) .collect(); diff --git a/docs/real-world-checks.md b/docs/real-world-checks.md index fce6d05..a98588c 100644 --- a/docs/real-world-checks.md +++ b/docs/real-world-checks.md @@ -22,6 +22,7 @@ Run Tunal from a terminal so its stderr is visible; the lines named below are pr 3. Open it. Expect: the Photos (DCIM) and other AFC folders list. 4. Copy a photo to your PC, then a small file into a folder that accepts files (for example Downloads or Books), both by paste and by drag. 5. Unplug while a copy runs. Expect: an error toast, no hang; the place disappears. +6. iPhone: Apps folder lists file-sharing apps (the `Apps` folder in the phone and the `Apps` entry under it in Devices, by app name); open one, copy a file in and out. ## 3. Android phone