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.

Calendar: an answer with no calendars changes nothing (it wiped every event); fetch and store never straddle a save (CALENDAR_PASS); Reminders: a list is deleted only after every reminder was seen; Drive: a rename with an extension reads back as done; a download is written aside and moved in whole, never over an existing file

Yashwanth Kamireddi0908aaa9bbde
diff --git a/crates/quince-icloud/src/drive.rs b/crates/quince-icloud/src/drive.rs
index de9d4d2..fbf63cc 100644
--- a/crates/quince-icloud/src/drive.rs
+++ b/crates/quince-icloud/src/drive.rs
@@ -190,13 +190,50 @@ pub async fn download_to(
if let Some(parent) = destination.parent() {
tokio::fs::create_dir_all(parent).await.ok();
}
- let mut file = tokio::fs::File::create(destination).await?;
- let mut stream = response.bytes_stream();
- while let Some(chunk) = stream.next().await {
- file.write_all(&chunk?).await?;
+ // Into a file of its own beside the destination, moved into place only once it is all
+ // there and only if nothing has taken the name meanwhile. Written straight to the name,
+ // a download that broke off left a truncated file under the real one.
+ let partial = destination.with_extension(match destination.extension() {
+ Some(ext) => format!("{}.part", ext.to_string_lossy()),
+ None => "part".into(),
+ });
+ let written: Result<()> = async {
+ let mut file = tokio::fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(&partial)
+ .await?;
+ let mut stream = response.bytes_stream();
+ while let Some(chunk) = stream.next().await {
+ file.write_all(&chunk?).await?;
+ }
+ file.flush().await?;
+ file.sync_all().await?;
+ Ok(())
+ }
+ .await;
+ if let Err(e) = written {
+ tokio::fs::remove_file(&partial).await.ok();
+ return Err(e);
+ }
+ // A link, unlike a rename, refuses an existing name: nothing already there is replaced.
+ match tokio::fs::hard_link(&partial, destination).await {
+ Ok(()) => {
+ tokio::fs::remove_file(&partial).await.ok();
+ Ok(())
+ }
+ // A filesystem without links — a FAT or exFAT drive — takes a rename, checked first.
+ Err(e) if e.kind() != std::io::ErrorKind::AlreadyExists && !destination.exists() => {
+ tokio::fs::rename(&partial, destination).await.map_err(|e| {
+ let _ = std::fs::remove_file(&partial);
+ e.into()
+ })
+ }
+ Err(e) => {
+ tokio::fs::remove_file(&partial).await.ok();
+ Err(e.into())
+ }
}
- file.flush().await?;
- Ok(())
}
/// What a `createFolders` reply says happened.
@@ -346,7 +383,10 @@ pub async fn rename(
let after = folder_listing(http, root, &params, parent).await?;
match after.iter().find(|i| i.drivewsid == item.drivewsid) {
- Some(found) if found.name == name => Ok(()),
+ // Apple keeps a file's extension apart from its name: "final.pdf" comes back as
+ // "final" and "pdf". Compared whole, every rename of a file with an extension read as
+ // refused, and the old name was put back on screen.
+ Some(found) if found.name == name || found.display_name() == name => Ok(()),
Some(found) => Err(Error::Protocol(format!(
"Apple answered success but the name is still {:?}, not {name:?}",
found.name
@@ -1203,6 +1243,41 @@ mod write_tests {
assert!(err.to_string().contains("still"), "{err}");
}
+ /// Apple keeps the extension apart from the name: a rename to "final.pdf" reads back as
+ /// "final" + "pdf", which is the rename done — not "the name is still final".
+ #[tokio::test]
+ async fn a_rename_with_an_extension_reads_back_as_done() {
+ let server = MockServer::start().await;
+ let mut renamed = file();
+ renamed.name = "final".into();
+ renamed.extension = Some("pdf".into());
+ Mock::given(method("POST"))
+ .and(path("/retrieveItemDetailsInFolders"))
+ .respond_with(ResponseTemplate::new(200).set_body_json(listing_of(
+ "FOLDER::com.apple.CloudDocs::root",
+ &renamed,
+ "e2",
+ )))
+ .mount(&server)
+ .await;
+ Mock::given(method("POST"))
+ .and(path("/renameItems"))
+ .respond_with(
+ ResponseTemplate::new(200).set_body_json(serde_json::json!({"items": []})),
+ )
+ .mount(&server)
+ .await;
+ rename(
+ &reqwest::Client::new(),
+ &server.uri(),
+ vec![],
+ &file(),
+ "final.pdf",
+ )
+ .await
+ .unwrap();
+ }
+
#[tokio::test]
async fn deleting_moves_to_trash_rather_than_destroying() {
let server = MockServer::start().await;
diff --git a/crates/quince-icloud/src/reminders.rs b/crates/quince-icloud/src/reminders.rs
index 310c367..1ef5010 100644
--- a/crates/quince-icloud/src/reminders.rs
+++ b/crates/quince-icloud/src/reminders.rs
@@ -1784,6 +1784,10 @@ pub async fn delete_list_cloudkit(
// date — a "Daily test" ringing from a list deleted days before. Found from Apple's own
// records, so the completed copies Apple's server made of a repeating one go too.
let walk = client.all_records(ZONE, None).await?;
+ // Every reminder has to have been seen, or some would be left alive under a deleted list.
+ if !walk.complete {
+ return Err(Error::Refused("Apple's list of reminders didn't come back whole, so the list wasn't deleted. Try again in a moment.".into()));
+ }
for r in walk.records.iter().filter(|r| in_list(r, list_guid)) {
let Some(guid) = r.get("recordName").and_then(Value::as_str) else {
continue;
diff --git a/crates/quince-icloud/src/sync.rs b/crates/quince-icloud/src/sync.rs
index b7caa1c..2f60938 100644
--- a/crates/quince-icloud/src/sync.rs
+++ b/crates/quince-icloud/src/sync.rs
@@ -231,6 +231,13 @@ pub async fn delete_event(
/// Store a fetched window. Touches no network.
pub fn apply_calendar(library: &mut Library, snapshot: Snapshot) -> Result<SyncSummary> {
+ // Every iCloud account has a calendar. An answer with none is a broken answer, not an
+ // account emptied: stored, it deleted every calendar here and every event with them.
+ if snapshot.calendars.is_empty() {
+ return Err(crate::Error::Protocol(
+ "Apple's calendar answer carried no calendars, so nothing was changed.".into(),
+ ));
+ }
library.put_calendars(&snapshot.calendars)?;
// Drop events belonging to calendars Apple did not report: storing them would fail the
@@ -731,3 +738,15 @@ mod window_tests {
assert!(chunks(d("2026-06-01"), d("2026-01-01")).is_empty());
}
}
+
+#[cfg(test)]
+mod empty_answer_tests {
+ /// An answer with no calendars changes nothing: it used to delete every calendar stored
+ /// here, and every event with them.
+ #[test]
+ fn an_answer_with_no_calendars_is_refused() {
+ let mut library = quince_core::Library::in_memory().unwrap();
+ let empty = crate::calendar::Snapshot::default();
+ assert!(super::apply_calendar(&mut library, empty).is_err());
+ }
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index da4968f..72b9f57 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -75,6 +75,11 @@ async fn resync_reminders(
/// after a newer write put the reminder back as it was before the write.
pub static REMINDERS_PASS: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
+/// One calendar pass or write at a time. A refresh that read Apple before a save and stored
+/// after it pruned the new event, put an edited one back with its old etag — so the next
+/// edit failed as a conflict — and brought a just-deleted one back.
+pub static CALENDAR_PASS: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
+
async fn refresh_reminders(
http: &reqwest::Client,
root: &str,
@@ -352,6 +357,7 @@ async fn calendar_sync(
};
// Asked of Apple unlocked; the library is held only to store the answer.
+ let _one = CALENDAR_PASS.lock().await;
let fetched = quince_icloud::sync::fetch_calendar(&http, &root, params, &from, &to, &timezone)
.await
.map_err(|e| e.to_string())?;
@@ -453,6 +459,7 @@ async fn event_save(
auth: State<'_, Auth>,
data: State<'_, Data>,
) -> UiResult<String> {
+ let _one = CALENDAR_PASS.lock().await;
let title = draft.title.trim();
if title.is_empty() {
return Err("An event needs a title.".into());
@@ -512,6 +519,7 @@ async fn event_delete(
auth: State<'_, Auth>,
data: State<'_, Data>,
) -> UiResult<()> {
+ let _one = CALENDAR_PASS.lock().await;
let (http, root, params) = calendar_context(&auth).await?;
let event = {
let library = data.0.lock().await;
diff --git a/src-tauri/src/refresh.rs b/src-tauri/src/refresh.rs
index de33bf8..d30b75b 100644
--- a/src-tauri/src/refresh.rs
+++ b/src-tauri/src/refresh.rs
@@ -129,6 +129,8 @@ pub async fn all(client: &Arc<Mutex<Client>>, data: &Mutex<Library>) -> Refresh
reports.push(match ctx.calendar.as_deref() {
None => unavailable("calendar", "Calendar"),
Some(root) => {
+ // Fetch and store as one, never across a save: see `CALENDAR_PASS`.
+ let _one = crate::CALENDAR_PASS.lock().await;
let fetched = quince_icloud::sync::fetch_calendar(
&ctx.http,
root,