Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
iCloud Drive folder: new folders, rename, move, delete
Yashwanth Kamireddi2414416ba541
diff --git a/crates/quince-vfs/src/fuse.rs b/crates/quince-vfs/src/fuse.rsindex c3db673..2bc21a2 100644--- a/crates/quince-vfs/src/fuse.rs+++ b/crates/quince-vfs/src/fuse.rs@@ -7,8 +7,8 @@use crate::{is_thumbnailer, named, Cache, Inodes, Remote, Store};use fuser::{Config, Errno, FileAttr, FileHandle, FileType, Filesystem, FopenFlags, Generation, INodeNo,- LockOwner, MountOption, OpenAccMode, OpenFlags, ReplyAttr, ReplyData, ReplyDirectory,- ReplyEntry, ReplyOpen, ReplyStatfs, Request,+ LockOwner, MountOption, OpenAccMode, OpenFlags, RenameFlags, ReplyAttr, ReplyData,+ ReplyDirectory, ReplyEmpty, ReplyEntry, ReplyOpen, ReplyStatfs, Request,};use quince_core::drive::DriveItem;use std::ffi::OsStr;@@ -24,6 +24,9 @@ const TTL: Duration = Duration::from_secs(1);/// is told it could not be read (and can ask again).const LIST_WAIT: Duration = Duration::from_secs(30);+/// How long a change (a new folder, a rename, a delete) may take at Apple.+const CHANGE_WAIT: Duration = Duration::from_secs(60);+pub struct DriveFs {remote: Arc<dyn Remote>,store: Arc<dyn Store>,@@ -113,6 +116,39 @@ impl DriveFs {});}+ /// A change made at Apple, waited for (the file manager waits on it too), then the folders+ /// it touched read again so the library — and so the next listing — is Apple's.+ fn change<T: Send + 'static>(+ &self,+ work: crate::Fut<T>,+ touched: &[&DriveItem],+ ) -> Result<T, Errno> {+ let done = self+ .rt+ .block_on(async { tokio::time::timeout(CHANGE_WAIT, work).await })+ .map_err(|_| Errno::ETIMEDOUT)?+ .map_err(|e| {+ quiet_note(&e);+ Errno::EIO+ })?;+ for folder in touched {+ let (remote, id) = (Arc::clone(&self.remote), folder.drivewsid.clone());+ let _ = self+ .rt+ .block_on(async move { tokio::time::timeout(LIST_WAIT, remote.list(&id)).await });+ }+ Ok(done)+ }++ /// The item called `name` in folder `parent`.+ fn child(&self, parent: INodeNo, name: &OsStr) -> Result<(u64, DriveItem), Errno> {+ self.children(parent)?+ .into_iter()+ .find(|(n, ..)| OsStr::new(n) == name)+ .map(|(_, ino, item)| (ino, item))+ .ok_or(Errno::ENOENT)+ }+fn item(&self, ino: INodeNo) -> Option<DriveItem> {self.inodes.lock()@@ -149,7 +185,7 @@ impl DriveFs {} else {FileType::RegularFile},- perm: if dir { 0o555 } else { 0o444 },+ perm: if dir { 0o755 } else { 0o444 },nlink: if dir { 2 } else { 1 },uid: self.uid,gid: self.gid,@@ -197,6 +233,50 @@ impl DriveFs {}}+impl DriveFs {+ /// A file or (an empty) folder deleted, into Apple's Recently Deleted.+ fn remove(&self, parent: INodeNo, name: &OsStr, folder: bool, reply: ReplyEmpty) {+ let Some(from) = self.item(parent) else {+ return reply.error(Errno::ENOENT);+ };+ let (ino, item) = match self.child(parent, name) {+ Ok(c) => c,+ Err(e) => return reply.error(e),+ };+ if folder != item.is_container() {+ return reply.error(if folder {+ Errno::ENOTDIR+ } else {+ Errno::EISDIR+ });+ }+ // A folder goes only when empty, as on any disk: Apple would take everything in it,+ // and a file manager or `rm -r` empties it first, file by file.+ if folder+ && !self+ .children(INodeNo(ino))+ .map(|c| c.is_empty())+ .unwrap_or(false)+ {+ return reply.error(Errno::ENOTEMPTY);+ }+ match self.change(self.remote.delete(&item), &[&from]) {+ Ok(()) => reply.ok(),+ Err(e) => reply.error(e),+ }+ }+}++/// Why a change failed, said in a development build (see the app's quiet!): never a name.+fn quiet_note(e: &str) {+ if cfg!(debug_assertions) {+ eprintln!(+ "drive folder: a change was refused: {}",+ e.chars().take(120).collect::<String>()+ );+ }+}+impl Filesystem for DriveFs {fn lookup(&self, _req: &Request, parent: INodeNo, name: &OsStr, reply: ReplyEntry) {match self.children(parent) {@@ -313,6 +393,84 @@ impl Filesystem for DriveFs {});}+ fn mkdir(+ &self,+ _req: &Request,+ parent: INodeNo,+ name: &OsStr,+ _mode: u32,+ _umask: u32,+ reply: ReplyEntry,+ ) {+ let Some(folder) = self.item(parent) else {+ return reply.error(Errno::ENOENT);+ };+ let Some(name) = name.to_str() else {+ return reply.error(Errno::EINVAL);+ };+ if self.child(parent, OsStr::new(name)).is_ok() {+ return reply.error(Errno::EEXIST);+ }+ match self.change(self.remote.mkdir(&folder, name), &[&folder]) {+ Ok(_) => match self.child(parent, OsStr::new(name)) {+ Ok((ino, item)) => reply.entry(&TTL, &self.attr(ino, &item), Generation(0)),+ Err(e) => reply.error(e),+ },+ Err(e) => reply.error(e),+ }+ }++ fn unlink(&self, _req: &Request, parent: INodeNo, name: &OsStr, reply: ReplyEmpty) {+ self.remove(parent, name, false, reply);+ }++ fn rmdir(&self, _req: &Request, parent: INodeNo, name: &OsStr, reply: ReplyEmpty) {+ self.remove(parent, name, true, reply);+ }++ fn rename(+ &self,+ _req: &Request,+ parent: INodeNo,+ name: &OsStr,+ newparent: INodeNo,+ newname: &OsStr,+ _flags: RenameFlags,+ reply: ReplyEmpty,+ ) {+ let (Some(from), Some(to)) = (self.item(parent), self.item(newparent)) else {+ return reply.error(Errno::ENOENT);+ };+ let (_, item) = match self.child(parent, name) {+ Ok(c) => c,+ Err(e) => return reply.error(e),+ };+ let Some(newname) = newname.to_str() else {+ return reply.error(Errno::EINVAL);+ };+ // Over something already there is not done yet: replacing a file is a write, and+ // nothing is ever overwritten before writes keep a copy of what they replace.+ if self.child(newparent, OsStr::new(newname)).is_ok() {+ return reply.error(Errno::EEXIST);+ }+ if parent != newparent {+ if let Err(e) = self.change(self.remote.move_to(&item, &to), &[&from, &to]) {+ return reply.error(e);+ }+ }+ if name != OsStr::new(newname) {+ // Moved, it is found again in its new folder under its old name, then renamed.+ let moved = match self.child(newparent, name) {+ Ok((_, i)) => i,+ Err(e) => return reply.error(e),+ };+ if let Err(e) = self.change(self.remote.rename(&moved, newname), &[&to]) {+ return reply.error(e);+ }+ }+ reply.ok();+ }+fn statfs(&self, _req: &Request, _ino: INodeNo, reply: ReplyStatfs) {// Read-only: nothing free to write into, as a mounted disc says.reply.statfs(0, 0, 0, 0, 0, 4096, 255, 4096);@@ -339,7 +497,6 @@ pub fn mount(fs: DriveFs, at: &Path) -> std::io::Result<fuser::BackgroundSessionconfig.mount_options = vec![MountOption::FSName("quince".into()),MountOption::Subtype("quince".into()),- MountOption::RO,MountOption::NoSuid,MountOption::NoDev,MountOption::NoAtime,diff --git a/crates/quince-vfs/src/lib.rs b/crates/quince-vfs/src/lib.rsindex 6ed19fa..9c23865 100644--- a/crates/quince-vfs/src/lib.rs+++ b/crates/quince-vfs/src/lib.rs@@ -25,6 +25,22 @@ pub trait Remote: Send + Sync + 'static {fn list(&self, folder: &str) -> Fut<Vec<DriveItem>>;/// `len` bytes of a file from `offset` (fewer only at its end).fn read(&self, item: &DriveItem, offset: u64, len: u64) -> Fut<Vec<u8>>;+ /// A new folder in `parent`, as Apple made it. Read-only by default.+ fn mkdir(&self, _parent: &DriveItem, _name: &str) -> Fut<DriveItem> {+ Box::pin(async { Err("read-only".to_string()) })+ }+ /// An item given a new name in its folder.+ fn rename(&self, _item: &DriveItem, _name: &str) -> Fut<()> {+ Box::pin(async { Err("read-only".to_string()) })+ }+ /// An item moved into another folder, its name kept.+ fn move_to(&self, _item: &DriveItem, _folder: &DriveItem) -> Fut<()> {+ Box::pin(async { Err("read-only".to_string()) })+ }+ /// An item deleted — into Apple's Recently Deleted, where it can be put back for 30 days.+ fn delete(&self, _item: &DriveItem) -> Fut<()> {+ Box::pin(async { Err("read-only".to_string()) })+ }/// Apple's own pictures of a folder's files, by item id: for a file manager's thumbnails,/// so it never downloads a file to draw one. None by default.fn thumbnails(&self, _folder: &str) -> Fut<HashMap<String, Vec<u8>>> {diff --git a/crates/quince-vfs/tests/changes.rs b/crates/quince-vfs/tests/changes.rsnew file mode 100644index 0000000..4061da3--- /dev/null+++ b/crates/quince-vfs/tests/changes.rs@@ -0,0 +1,226 @@+//! Changes through the folder, as a file manager or a shell makes them: a new folder, a+//! rename, a move, a delete — each made at Apple and then shown as Apple has it. A folder+//! with something in it is not deleted whole; nothing is replaced by a rename. Skipped where+//! FUSE is not available.+#![cfg(target_os = "linux")]++use quince_core::drive::DriveItem;+use quince_vfs::{fuse, Cache, Fut, Remote, Store, ROOT};+use std::collections::HashMap;+use std::sync::{Arc, Mutex};++fn item(id: &str, parent: &str, name: &str, ext: Option<&str>, kind: &str) -> DriveItem {+ DriveItem {+ drivewsid: id.into(),+ parent_id: Some(parent.into()),+ name: name.into(),+ extension: ext.map(Into::into),+ kind: kind.into(),+ size: Some(if kind == "FILE" { 3 } else { 0 }),+ child_count: Some(0),+ created_at: Some(1_700_000_000),+ modified_at: Some(1_700_000_100),+ etag: Some("e1".into()),+ }+}++/// Apple's Drive, and the library that mirrors it after every change.+#[derive(Default)]+struct World {+ folders: Mutex<HashMap<String, Vec<DriveItem>>>,+ deleted: Mutex<Vec<String>>,+ next: Mutex<u32>,+}+struct Apple(Arc<World>);+struct Library(Arc<World>);++impl Store for Library {+ fn children(&self, folder: &str) -> Option<Vec<DriveItem>> {+ Some(+ self.0+ .folders+ .lock()+ .unwrap()+ .get(folder)+ .cloned()+ .unwrap_or_default(),+ )+ }+}++impl Remote for Apple {+ fn list(&self, folder: &str) -> Fut<Vec<DriveItem>> {+ let out = self+ .0+ .folders+ .lock()+ .unwrap()+ .get(folder)+ .cloned()+ .unwrap_or_default();+ Box::pin(async move { Ok(out) })+ }+ fn read(&self, _: &DriveItem, _: u64, len: u64) -> Fut<Vec<u8>> {+ Box::pin(async move { Ok(vec![b'x'; len as usize]) })+ }+ fn mkdir(&self, parent: &DriveItem, name: &str) -> Fut<DriveItem> {+ let mut n = self.0.next.lock().unwrap();+ *n += 1;+ let made = item(+ &format!("FOLDER::z::new{n}"),+ &parent.drivewsid,+ name,+ None,+ "FOLDER",+ );+ self.0+ .folders+ .lock()+ .unwrap()+ .entry(parent.drivewsid.clone())+ .or_default()+ .push(made.clone());+ Box::pin(async move { Ok(made) })+ }+ fn rename(&self, it: &DriveItem, name: &str) -> Fut<()> {+ let mut folders = self.0.folders.lock().unwrap();+ for list in folders.values_mut() {+ for x in list.iter_mut().filter(|x| x.drivewsid == it.drivewsid) {+ match name.rsplit_once('.') {+ Some((stem, ext)) if x.kind == "FILE" => {+ x.name = stem.into();+ x.extension = Some(ext.into());+ }+ _ => x.name = name.into(),+ }+ }+ }+ Box::pin(async { Ok(()) })+ }+ fn move_to(&self, it: &DriveItem, to: &DriveItem) -> Fut<()> {+ let mut folders = self.0.folders.lock().unwrap();+ let mut moved = None;+ for list in folders.values_mut() {+ if let Some(i) = list.iter().position(|x| x.drivewsid == it.drivewsid) {+ moved = Some(list.remove(i));+ }+ }+ let mut m = moved.unwrap();+ m.parent_id = Some(to.drivewsid.clone());+ folders.entry(to.drivewsid.clone()).or_default().push(m);+ Box::pin(async { Ok(()) })+ }+ fn delete(&self, it: &DriveItem) -> Fut<()> {+ for list in self.0.folders.lock().unwrap().values_mut() {+ list.retain(|x| x.drivewsid != it.drivewsid);+ }+ self.0.deleted.lock().unwrap().push(it.drivewsid.clone());+ Box::pin(async { Ok(()) })+ }+}++fn names(dir: &std::path::Path) -> Vec<String> {+ let mut n: Vec<String> = std::fs::read_dir(dir)+ .unwrap()+ .map(|e| e.unwrap().file_name().into_string().unwrap())+ .collect();+ n.sort();+ n+}++#[test]+fn changes_through_the_folder_are_made_at_apple() {+ if !std::path::Path::new("/dev/fuse").exists() {+ eprintln!("no FUSE here; skipped");+ return;+ }+ let world = Arc::new(World::default());+ world.folders.lock().unwrap().insert(+ ROOT.into(),+ vec![+ item("FILE::z::a", ROOT, "Notes", Some("txt"), "FILE"),+ item("FILE::z::b", ROOT, "Plan", Some("pdf"), "FILE"),+ ],+ );+ let rt = tokio::runtime::Runtime::new().unwrap();+ let cache = tempfile::tempdir().unwrap();+ let at = tempfile::tempdir().unwrap();+ let fs = fuse::DriveFs::new(+ Arc::new(Apple(Arc::clone(&world))),+ Arc::new(Library(Arc::clone(&world))),+ Arc::new(Cache::new(cache.path()).unwrap()),+ rt.handle().clone(),+ );+ let session = fuse::mount(fs, at.path()).expect("mounted");+ let root = at.path();++ std::fs::create_dir(root.join("Trips")).unwrap();+ assert_eq!(+ names(root),+ ["Notes.txt", "Plan.pdf", "Trips"],+ "a new folder"+ );+ assert_eq!(+ std::fs::create_dir(root.join("Trips"))+ .unwrap_err()+ .raw_os_error(),+ Some(libc::EEXIST),+ "not twice"+ );++ std::fs::rename(root.join("Plan.pdf"), root.join("Plan 2026.pdf")).unwrap();+ assert_eq!(+ names(root),+ ["Notes.txt", "Plan 2026.pdf", "Trips"],+ "renamed in place"+ );++ std::fs::rename(root.join("Plan 2026.pdf"), root.join("Trips/Plan 2026.pdf")).unwrap();+ assert_eq!(+ names(&root.join("Trips")),+ ["Plan 2026.pdf"],+ "moved into a folder"+ );+ std::fs::rename(root.join("Trips/Plan 2026.pdf"), root.join("Itinerary.pdf")).unwrap();+ assert_eq!(+ names(root),+ ["Itinerary.pdf", "Notes.txt", "Trips"],+ "moved back out under a new name"+ );++ let clash = std::fs::rename(root.join("Itinerary.pdf"), root.join("Notes.txt")).unwrap_err();+ assert_eq!(+ clash.raw_os_error(),+ Some(libc::EEXIST),+ "a rename never replaces what is there"+ );+ assert_eq!(names(root), ["Itinerary.pdf", "Notes.txt", "Trips"]);++ std::fs::rename(root.join("Itinerary.pdf"), root.join("Trips/Itinerary.pdf")).unwrap();+ let full = std::fs::remove_dir(root.join("Trips")).unwrap_err();+ assert_eq!(+ full.raw_os_error(),+ Some(libc::ENOTEMPTY),+ "a folder with something in it is not deleted whole"+ );+ std::fs::remove_file(root.join("Trips/Itinerary.pdf")).unwrap();+ std::fs::remove_dir(root.join("Trips")).unwrap();+ assert_eq!(+ names(root),+ ["Notes.txt"],+ "deleted, file then folder, as rm -r does"+ );+ assert_eq!(+ world.deleted.lock().unwrap().len(),+ 2,+ "each a delete at Apple (into Recently Deleted)"+ );+ assert_eq!(+ std::fs::remove_dir(root.join("Notes.txt"))+ .unwrap_err()+ .raw_os_error(),+ Some(libc::ENOTDIR)+ );++ drop(session);+}diff --git a/crates/quince-vfs/tests/mount.rs b/crates/quince-vfs/tests/mount.rsindex 4f95e6c..2b057d0 100644--- a/crates/quince-vfs/tests/mount.rs+++ b/crates/quince-vfs/tests/mount.rs@@ -191,7 +191,11 @@ fn a_mounted_drive_reads_like_a_folder() {// Read-only, for now: a write is refused, never half-done.let err = std::fs::write(at.path().join("Note.txt"), b"x").unwrap_err();- assert_eq!(err.raw_os_error(), Some(libc::EROFS), "{err}");+ // Refused by the file's own permissions (read-only until writes are kept), never half-done.+ assert!(+ matches!(err.raw_os_error(), Some(libc::EROFS | libc::EACCES)),+ "{err}"+ );assert_eq!(std::fs::read(at.path().join("Note.txt")).unwrap(), note);// Apple's picture of the film is in the thumbnail cache, named and stamped so that GLib —diff --git a/probe/examples/drive_mount_live.rs b/probe/examples/drive_mount_live.rsindex 88d9e21..ac6c1cf 100644--- a/probe/examples/drive_mount_live.rs+++ b/probe/examples/drive_mount_live.rs@@ -34,6 +34,61 @@ impl Remote for Apple {Ok(items)})}+ fn mkdir(&self, parent: &DriveItem, name: &str) -> Fut<DriveItem> {+ let (http, root, p, parent, name) = (+ self.http.clone(),+ self.drivews.clone(),+ self.params.clone(),+ parent.drivewsid.clone(),+ name.to_string(),+ );+ Box::pin(async move {+ quince_icloud::drive::create_folder(&http, &root, p, &parent, &name)+ .await+ .map_err(|e| e.to_string())+ })+ }+ fn rename(&self, item: &DriveItem, name: &str) -> Fut<()> {+ let (http, root, p, item, name) = (+ self.http.clone(),+ self.drivews.clone(),+ self.params.clone(),+ item.clone(),+ name.to_string(),+ );+ Box::pin(async move {+ quince_icloud::drive::rename(&http, &root, p, &item, &name)+ .await+ .map_err(|e| e.to_string())+ })+ }+ fn move_to(&self, item: &DriveItem, folder: &DriveItem) -> Fut<()> {+ let (http, root, p, item, to) = (+ self.http.clone(),+ self.drivews.clone(),+ self.params.clone(),+ item.clone(),+ folder.drivewsid.clone(),+ );+ Box::pin(async move {+ quince_icloud::drive::move_to(&http, &root, p, &item, &to)+ .await+ .map_err(|e| e.to_string())+ })+ }+ fn delete(&self, item: &DriveItem) -> Fut<()> {+ let (http, root, p, item) = (+ self.http.clone(),+ self.drivews.clone(),+ self.params.clone(),+ item.clone(),+ );+ Box::pin(async move {+ quince_icloud::drive::delete(&http, &root, p, &item)+ .await+ .map_err(|e| e.to_string())+ })+ }fn read(&self, item: &DriveItem, offset: u64, len: u64) -> Fut<Vec<u8>> {let known = self.links.lock().unwrap().get(&item.drivewsid).cloned();let (http, docws, p, item) = (@@ -98,6 +153,7 @@ fn main() -> Result<()> {client.service_params(),))})?;+ let (apple_http, apple_drivews, apple_params) = (http.clone(), drivews.clone(), params.clone());let library = Arc::new(Mutex::new(HashMap::new()));let apple = Arc::new(Apple {http,@@ -120,6 +176,22 @@ fn main() -> Result<()> {drop(session);let _ = std::fs::remove_dir_all(&cache);println!("unmounted");+ // This probe's own throwaways, and nothing else, cleared from Recently Deleted.+ if std::env::var("QUINCE_PURGE_TEST").is_ok() {+ let (http, drivews, params) = (apple_http, apple_drivews, apple_params);+ rt.block_on(async {+ let trash = quince_icloud::drive::trash(&http, &drivews, params.clone()).await?;+ let mine: Vec<_> = trash+ .into_iter()+ .filter(|i| i.name.starts_with("Quince mount test"))+ .collect();+ println!("throwaways in Recently Deleted: {}", mine.len());+ if !mine.is_empty() {+ quince_icloud::drive::delete_forever_many(&http, &drivews, params, &mine).await?;+ }+ anyhow::Ok(())+ })?;+ }Ok(())}diff --git a/src-tauri/src/mount.rs b/src-tauri/src/mount.rsindex 02590b2..5d7897b 100644--- a/src-tauri/src/mount.rs+++ b/src-tauri/src/mount.rs@@ -1,6 +1,7 @@//! iCloud Drive as a folder on this computer (quince-vfs), served by the app itself: its//! signed-in session, its library, and what it learns kept in the library for the window too.-//! Off until it is turned on in Settings; read-only for now. See docs/mount-design.md.+//! Off until it is turned on in Settings. Folders can be made, items renamed, moved and deleted+//! (into Recently Deleted); a file's own bytes are not written yet. See docs/mount-design.md.use crate::{Auth, Data};use quince_core::drive::DriveItem;@@ -59,6 +60,46 @@ impl Remote for AppRemote {})}+ fn mkdir(&self, parent: &DriveItem, name: &str) -> Fut<DriveItem> {+ let (app, parent, name) = (self.app.clone(), parent.drivewsid.clone(), name.to_string());+ Box::pin(async move {+ let (http, root, params) = context(&app, "drivews").await?;+ quince_icloud::drive::create_folder(&http, &root, params, &parent, &name)+ .await+ .map_err(|e| e.to_string())+ })+ }++ fn rename(&self, item: &DriveItem, name: &str) -> Fut<()> {+ let (app, item, name) = (self.app.clone(), item.clone(), name.to_string());+ Box::pin(async move {+ let (http, root, params) = context(&app, "drivews").await?;+ quince_icloud::drive::rename(&http, &root, params, &item, &name)+ .await+ .map_err(|e| e.to_string())+ })+ }++ fn move_to(&self, item: &DriveItem, folder: &DriveItem) -> Fut<()> {+ let (app, item, to) = (self.app.clone(), item.clone(), folder.drivewsid.clone());+ Box::pin(async move {+ let (http, root, params) = context(&app, "drivews").await?;+ quince_icloud::drive::move_to(&http, &root, params, &item, &to)+ .await+ .map_err(|e| e.to_string())+ })+ }++ fn delete(&self, item: &DriveItem) -> Fut<()> {+ let (app, item) = (self.app.clone(), item.clone());+ Box::pin(async move {+ let (http, root, params) = context(&app, "drivews").await?;+ quince_icloud::drive::delete(&http, &root, params, &item)+ .await+ .map_err(|e| e.to_string())+ })+ }+fn thumbnails(&self, folder: &str) -> Fut<HashMap<String, Vec<u8>>> {let (app, folder) = (self.app.clone(), folder.to_string());Box::pin(async move { crate::folder_thumbnails(&app, &folder).await })