Skip to content

Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.

Drive: Duplicate, verified live — Apple's v1/item/copy with the item_id from its folder's listing, the copy named 'Name 2' as Finder names it

Yashwanth Kamireddi3711c6d6e334
diff --git a/.uiverify/drive-info.mjs b/.uiverify/drive-info.mjs
index a15d472..6cd771a 100644
--- a/.uiverify/drive-info.mjs
+++ b/.uiverify/drive-info.mjs
@@ -26,6 +26,15 @@ const offered = await page.getByRole("menuitem").allInnerTexts();
ok(JSON.stringify(offered) === JSON.stringify(["Open", "Get Info", "Rename", "Move to Folder…", "Delete"]),
`a right-click on a folder offers its menu ${JSON.stringify(offered)}`);
await page.keyboard.press("Escape");
+await page.locator(".drive-row", { hasText: "Semester Plan" }).click({ button: "right" });
+await page.waitForTimeout(150);
+const forFile = await page.getByRole("menuitem").allInnerTexts();
+ok(JSON.stringify(forFile) === JSON.stringify(["Download a Copy", "Get Info", "Duplicate", "Rename", "Move to Folder…", "Delete"]),
+ `a file's menu adds Duplicate ${JSON.stringify(forFile)}`);
+await page.getByRole("menuitem", { name: "Duplicate" }).click();
+await page.waitForTimeout(200);
+ok(JSON.stringify(await page.evaluate(() => window.__dups)) === JSON.stringify(["FILE::d"]), "Duplicate asks Apple for a copy of that file");
+await page.keyboard.press("Escape");
await page.waitForTimeout(100);
ok((await page.getByRole("menu").count()) === 0, "and Escape puts it away");
// A click selects, as in Finder; it does not download. A double-click opens.
diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjs
index 84896ea..b4a4b6a 100644
--- a/.uiverify/stub.mjs
+++ b/.uiverify/stub.mjs
@@ -188,6 +188,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note
case "contact_save": (window.__contactSaves ??= []).push(args); return "C-new";
case "contact_delete": return null;
case "contacts_list": return !contactsFixture ? [] : contactList;
+ case "drive_duplicate": (window.__dups ??= []).push(args.drivewsid); return null;
case "storage_info": return { usedBytes: 182196857, totalBytes: 5368709120 };
case "drive_children": return !driveFixture ? [] : driveItems;
case "drive_trash": return !driveFixture ? [] : (window.__trash ??= [
diff --git a/crates/quince-icloud/src/drive.rs b/crates/quince-icloud/src/drive.rs
index 66d49c0..89aeaf6 100644
--- a/crates/quince-icloud/src/drive.rs
+++ b/crates/quince-icloud/src/drive.rs
@@ -404,6 +404,68 @@ pub async fn delete(
Ok(())
}
+/// Duplicate a file as icloud.com does: `POST {docws}/v1/item/copy/{item_id}` with
+/// `{info_to_update:{}}`. Apple names the copy as Finder would — "Plan 2.pdf" — in the same
+/// folder. `item_id` is not the drivewsid's tail (that answers 404): it is a field of the
+/// item in its folder's listing, so the listing is read first. Measured on a real account.
+pub async fn duplicate(
+ http: &reqwest::Client,
+ docws_root: &str,
+ drivews_root: &str,
+ params: Vec<(String, String)>,
+ item: &DriveItem,
+) -> Result<()> {
+ let parent = parent_of(item);
+ let url = format!(
+ "{}/retrieveItemDetailsInFolders",
+ drivews_root.trim_end_matches('/')
+ );
+ let body = json!([{ "drivewsid": parent, "partialData": false }]);
+ let response = http.post(url).query(&params).json(&body).send().await?;
+ if response.status().as_u16() == 450 {
+ return Err(Error::ReauthRequired);
+ }
+ let listing: Value = response
+ .json()
+ .await
+ .map_err(|e| Error::Protocol(format!("Drive listing: {e}")))?;
+ let item_id = listing
+ .pointer("/0/items")
+ .and_then(Value::as_array)
+ .and_then(|items| {
+ items.iter().find(|i| {
+ i.get("drivewsid").and_then(Value::as_str) == Some(item.drivewsid.as_str())
+ })
+ })
+ .and_then(|i| i.get("item_id").and_then(Value::as_str))
+ .ok_or_else(|| {
+ Error::Refused("That item is no longer in its folder, so it was not duplicated.".into())
+ })?
+ .to_string();
+ let url = format!(
+ "{}/v1/item/copy/{item_id}",
+ docws_root.trim_end_matches('/')
+ );
+ let response = http
+ .post(url)
+ .query(&params)
+ .json(&json!({ "info_to_update": {} }))
+ .send()
+ .await?;
+ let status = response.status();
+ if status.as_u16() == 450 {
+ return Err(Error::ReauthRequired);
+ }
+ if !status.is_success() {
+ let text = response.text().await.unwrap_or_default();
+ return Err(Error::Protocol(format!(
+ "Drive refused the copy ({status}): {}",
+ text.chars().take(200).collect::<String>()
+ )));
+ }
+ Ok(())
+}
+
/// Drive's Recently Deleted, as icloud.com lists it: a folder Apple names `TRASH_ROOT`.
pub const TRASH: &str = "TRASH_ROOT";
diff --git a/probe/examples/drive_copy.rs b/probe/examples/drive_copy.rs
new file mode 100644
index 0000000..7b3f8d3
--- /dev/null
+++ b/probe/examples/drive_copy.rs
@@ -0,0 +1,57 @@
+//! Live, throwaway file only: upload, duplicate as Quince does, list what came back,
+//! then delete both for good.
+use anyhow::{anyhow, Result};
+#[tokio::main]
+async fn main() -> Result<()> {
+ let dir = std::path::PathBuf::from(std::env::var("HOME")?).join(".local/share/quince-probe");
+ let mut client = quince_auth::Client::new(&dir)?;
+ if !client.resume().await? {
+ return Err(anyhow!("no session"));
+ }
+ let drivews = client
+ .session()
+ .service_url("drivews")
+ .ok_or_else(|| anyhow!("no drivews"))?;
+ let docws = client
+ .session()
+ .service_url("docws")
+ .ok_or_else(|| anyhow!("no docws"))?;
+ let http = client.http().clone();
+ let p = client.service_params();
+ let tmp = std::env::temp_dir().join("quince-copy-test.txt");
+ std::fs::write(&tmp, b"Quince duplicate test. Safe to delete.")?;
+ let item = quince_icloud::drive::upload(
+ &http,
+ &docws,
+ &drivews,
+ p.clone(),
+ quince_core::drive::ROOT,
+ &tmp,
+ std::sync::Arc::new(|_, _| {}),
+ )
+ .await?;
+ quince_icloud::drive::duplicate(&http, &docws, &drivews, p.clone(), &item).await?;
+ println!("duplicated through quince_icloud::drive::duplicate");
+ let mut lib = quince_core::Library::open(
+ &std::env::temp_dir().join(format!("qcp-{}", uuid::Uuid::new_v4())),
+ )?;
+ quince_icloud::drive::sync_folder(
+ &http,
+ &drivews,
+ p.clone(),
+ &mut lib,
+ quince_core::drive::ROOT,
+ )
+ .await?;
+ for i in lib
+ .drive_children(quince_core::drive::ROOT)?
+ .into_iter()
+ .filter(|i| i.name.starts_with("quince-copy-test"))
+ {
+ println!("in root: {} {}", i.drivewsid, i.display_name());
+ quince_icloud::drive::delete(&http, &drivews, p.clone(), &i).await?;
+ quince_icloud::drive::delete_forever(&http, &drivews, p.clone(), &i).await?;
+ println!(" removed for good");
+ }
+ Ok(())
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index c2da490..f25dffe 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -1713,6 +1713,44 @@ async fn drive_delete(
resync_drive_folder(&http, &root, params, &data, parent).await
}
+/// Duplicate a file into its own folder, named as Finder names a copy.
+#[tauri::command]
+async fn drive_duplicate(
+ drivewsid: String,
+ auth: State<'_, Auth>,
+ data: State<'_, Data>,
+) -> UiResult<()> {
+ let item = {
+ let library = data.0.lock().await;
+ library
+ .drive_item(&drivewsid)
+ .map_err(|e| e.to_string())?
+ .ok_or("That item is no longer in the local library.")?
+ };
+ let (http, drivews, docws, params) = {
+ let client = auth.client.lock().await;
+ let session = client.session();
+ (
+ client.http().clone(),
+ session
+ .service_url("drivews")
+ .ok_or("Apple hasn't offered iCloud Drive for this account.")?,
+ session
+ .service_url("docws")
+ .ok_or("Apple hasn't offered iCloud Drive for this account.")?,
+ client.service_params(),
+ )
+ };
+ quince_icloud::drive::duplicate(&http, &docws, &drivews, params.clone(), &item)
+ .await
+ .map_err(|e| e.to_string())?;
+ let parent = item
+ .parent_id
+ .as_deref()
+ .unwrap_or(quince_core::drive::ROOT);
+ resync_drive_folder(&http, &drivews, params, &data, parent).await
+}
+
/// How much iCloud storage is used and how much there is, for "X GB available".
#[tauri::command]
async fn storage_info(auth: State<'_, Auth>) -> UiResult<quince_icloud::drive::Storage> {
@@ -2200,6 +2238,7 @@ fn main() {
drive_delete,
drive_trash,
storage_info,
+ drive_duplicate,
drive_put_back,
drive_delete_forever,
drive_move,
diff --git a/src/lib/ipc.ts b/src/lib/ipc.ts
index a2befed..a2f962c 100644
--- a/src/lib/ipc.ts
+++ b/src/lib/ipc.ts
@@ -167,6 +167,7 @@ export const api = {
invoke<void>("drive_rename", { drivewsid, name }),
driveDelete: (drivewsid: string) => invoke<void>("drive_delete", { drivewsid }),
driveTrash: () => invoke<DriveItem[]>("drive_trash"),
+ driveDuplicate: (drivewsid: string) => invoke<void>("drive_duplicate", { drivewsid }),
storageInfo: () => invoke<{ usedBytes: number; totalBytes: number }>("storage_info"),
drivePutBack: (item: DriveItem) => invoke<void>("drive_put_back", { item }),
driveDeleteForever: (item: DriveItem) => invoke<void>("drive_delete_forever", { item }),
diff --git a/src/screens/DriveView.tsx b/src/screens/DriveView.tsx
index 20c1d4f..1191526 100644
--- a/src/screens/DriveView.tsx
+++ b/src/screens/DriveView.tsx
@@ -422,6 +422,28 @@ export function DriveView() {
[refresh]
);
+ /**
+ * Duplicate, as Finder: the copy lands beside the original as "Name 2", and shows as being
+ * made at once — Apple decides its name, so the row is a stand-in until it answers.
+ */
+ const duplicate = useCallback(
+ async (item: DriveItem) => {
+ setError(null);
+ const key = `copy-${Date.now()}`;
+ const ext = item.extension ? `.${item.extension}` : "";
+ setPending((p) => [...p, { key, folder: here.id, name: `${item.name} copy${ext}`, doing: "Duplicating…" }]);
+ try {
+ await api.driveDuplicate(item.drivewsid);
+ await refresh();
+ } catch (e) {
+ setError(messageOf(e));
+ } finally {
+ setPending((p) => p.filter((x) => x.key !== key));
+ }
+ },
+ [refresh, here.id]
+ );
+
const move = useCallback(
async (item: DriveItem, destinationId: string) => {
setMoving(null);
@@ -892,6 +914,7 @@ export function DriveView() {
{ label: isContainer(menu.item) ? "Open" : "Download a Copy", run: () => (isContainer(menu.item) ? enter(menu.item) : void download(menu.item)) },
{ label: "Get Info", run: () => setInfo(menu.item) },
null,
+ ...(isContainer(menu.item) ? [] : [{ label: "Duplicate", run: () => void duplicate(menu.item) }]),
{ label: "Rename", run: () => setRenaming(menu.item.drivewsid) },
{ label: "Move to Folder…", run: () => setMoving(menu.item) },
null,