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.

Downloads keep iCloud's dates; resume by version; second copies are 'name 2' everywhere

Yashwanth Kamireddiac9caa2d93a0
diff --git a/crates/quince-icloud/src/drive.rs b/crates/quince-icloud/src/drive.rs
index 15fdad3..3237ab7 100644
--- a/crates/quince-icloud/src/drive.rs
+++ b/crates/quince-icloud/src/drive.rs
@@ -299,6 +299,14 @@ impl Drop for Partial {
}
}
+/// When `item` was last changed in iCloud, as the time a file on disk carries; `None` when
+/// Apple didn't say (or said before 1970).
+#[must_use]
+pub fn changed_at(item: &DriveItem) -> Option<std::time::SystemTime> {
+ let seconds = u64::try_from(item.modified_at?).ok()?;
+ std::time::UNIX_EPOCH.checked_add(std::time::Duration::from_secs(seconds))
+}
+
/// [`download_to`], telling `progress` how many bytes have arrived, of how many (the size
/// Apple sends with the bytes, else the item's own; 0 when neither is known), and placed as
/// `placing` says. The file is only ever moved into place whole: every byte Apple said it would
@@ -397,6 +405,14 @@ pub async fn download_with_progress(
}
}
file.flush().await?;
+ // The file keeps the date it was last changed in iCloud, as a copy from any other disk
+ // does: sorted by date it sits where it belongs, and a resumed folder download tells by
+ // it which version it already has. Best effort — a disk that won't take a date keeps today's.
+ if let Some(when) = changed_at(item) {
+ let std_file = file.into_std().await;
+ let _ = std_file.set_modified(when);
+ file = tokio::fs::File::from_std(std_file);
+ }
file.sync_all().await?;
drop(file);
// Fewer bytes than were promised is a connection that ended early, whatever it said: never
diff --git a/src-tauri/src/folder_download.rs b/src-tauri/src/folder_download.rs
index f4dbd5b..3e44a27 100644
--- a/src-tauri/src/folder_download.rs
+++ b/src-tauri/src/folder_download.rs
@@ -1071,11 +1071,27 @@ impl Run<'_> {
}
}
-/// Whether the file at `path` is `item` whole: a plain file, at the size iCloud has it.
+/// Whether the file at `path` is `item` whole and current: a plain file, at the size iCloud has
+/// it, carrying the date it was last changed there (every download gives a file that date). By
+/// size alone, a file edited in iCloud since — a fixed typo, the same length — was kept stale.
+/// Dates are compared to within two seconds: FAT and exFAT keep no finer.
fn whole_here(path: &Path, item: &DriveItem) -> bool {
- size_of(item).is_some_and(|size| {
- std::fs::symlink_metadata(path).is_ok_and(|m| m.is_file() && m.len() == size)
- })
+ let Ok(meta) = std::fs::symlink_metadata(path) else {
+ return false;
+ };
+ let same_size = size_of(item).is_some_and(|size| meta.is_file() && meta.len() == size);
+ let same_version = match (quince_icloud::drive::changed_at(item), meta.modified()) {
+ (Some(changed), Ok(on_disk)) => {
+ let apart = changed
+ .duration_since(on_disk)
+ .unwrap_or_else(|e| e.duration());
+ apart <= std::time::Duration::from_secs(2)
+ }
+ // Apple gave no date: the size is all there is to go by.
+ (None, _) => true,
+ (Some(_), Err(_)) => false,
+ };
+ same_size && same_version
}
fn now_seconds() -> i64 {
diff --git a/src-tauri/src/folder_download/tests.rs b/src-tauri/src/folder_download/tests.rs
index d3a9576..2aae086 100644
--- a/src-tauri/src/folder_download/tests.rs
+++ b/src-tauri/src/folder_download/tests.rs
@@ -259,6 +259,8 @@ struct Node {
folder: bool,
bytes: Vec<u8>,
children: Vec<Node>,
+ /// When iCloud says it was last changed, in seconds.
+ changed: Option<i64>,
}
fn file(id: &str, name: &str, ext: Option<&str>, bytes: &[u8]) -> Node {
@@ -269,6 +271,7 @@ fn file(id: &str, name: &str, ext: Option<&str>, bytes: &[u8]) -> Node {
folder: false,
bytes: bytes.to_vec(),
children: vec![],
+ changed: None,
}
}
@@ -280,6 +283,7 @@ fn folder(id: &str, name: &str, children: Vec<Node>) -> Node {
folder: true,
bytes: vec![],
children,
+ changed: None,
}
}
@@ -296,6 +300,7 @@ fn as_json(n: &Node, parent: &str) -> Value {
"drivewsid": wsid(n), "docwsid": n.id, "parentId": parent, "name": n.name,
"extension": n.ext, "type": if n.folder { "FOLDER" } else { "FILE" },
"size": if n.folder { -1 } else { n.bytes.len() as i64 }, "etag": "1",
+ "dateModified": n.changed.map(|s| s * 1000),
})
}
@@ -309,7 +314,7 @@ fn item(n: &Node) -> DriveItem {
size: (!n.folder).then_some(n.bytes.len() as i64),
child_count: None,
created_at: None,
- modified_at: None,
+ modified_at: n.changed,
etag: None,
}
}
@@ -883,6 +888,71 @@ async fn resumed_a_wrong_sized_copy_is_replaced_and_leftovers_cleared() {
assert_eq!(hits.lock().unwrap().get("b"), None);
}
+/// A file changed in iCloud since the first run — the same size, a typo fixed — is fetched
+/// again on resume; one that is the version iCloud has is left alone. Every downloaded file
+/// carries the date it was last changed in iCloud, which is how the two are told apart.
+#[tokio::test]
+async fn resumed_a_file_changed_in_icloud_since_is_fetched_again() {
+ const MONDAY: i64 = 1_793_000_000;
+ const TUESDAY: i64 = MONDAY + 86_400;
+ let mut edited = file("a", "a", Some("txt"), b"fixed");
+ edited.changed = Some(TUESDAY);
+ let mut same = file("b", "b", Some("txt"), b"as it was");
+ same.changed = Some(MONDAY);
+ let tree = folder("r", "R", vec![edited, same]);
+ let downloads = tempfile::tempdir().unwrap();
+ let state = tempfile::tempdir().unwrap();
+ let journal = Journal::new(state.path().to_path_buf());
+ let top = downloads.path().join("R");
+ std::fs::create_dir(&top).unwrap();
+ let at = |secs: i64| std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs as u64);
+ for (name, bytes) in [("a.txt", &b"fixd!"[..]), ("b.txt", &b"as it was"[..])] {
+ std::fs::write(top.join(name), bytes).unwrap();
+ let f = std::fs::File::options()
+ .write(true)
+ .open(top.join(name))
+ .unwrap();
+ f.set_modified(at(MONDAY)).unwrap();
+ }
+ journal
+ .save(&Record {
+ key: Journal::key(&[item(&tree)]),
+ title: "R".into(),
+ items: vec![item(&tree)],
+ placed: vec![Placed {
+ drivewsid: wsid(&tree),
+ path: top.clone(),
+ folder: true,
+ }],
+ started_at: 1,
+ })
+ .unwrap();
+ let (_server, drive, hits) = drive_of(std::slice::from_ref(&tree), Setup::default()).await;
+ let (_heard, emit) = hearing();
+ let report = download(
+ &drive,
+ &[&tree],
+ downloads.path(),
+ Some(&journal),
+ emit,
+ &Stop::default(),
+ )
+ .await
+ .unwrap();
+ assert!(report.failed.is_empty(), "{report:?}");
+ assert_eq!(std::fs::read(top.join("a.txt")).unwrap(), b"fixed");
+ assert_eq!(
+ hits.lock().unwrap().get("b"),
+ None,
+ "the current one is kept"
+ );
+ let changed = std::fs::metadata(top.join("a.txt"))
+ .unwrap()
+ .modified()
+ .unwrap();
+ assert_eq!(changed, at(TUESDAY), "a download carries iCloud's date");
+}
+
/// A journal edited to point outside Downloads is not followed: the download starts afresh.
#[tokio::test]
async fn a_journal_pointing_outside_downloads_is_not_followed() {
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 110a97a..bf8c0c0 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -4201,7 +4201,9 @@ async fn contact_delete(guid: String, data: State<'_, Data>) -> UiResult<()> {
fn free_path(dir: &std::path::Path, name: &str) -> std::path::PathBuf {
let (stem, ext) = name_parts(name);
let mut path = dir.join(name);
- let mut suffix = 1;
+ // "Report 2.pdf" for the second copy, as Finder and a folder download (folder_download's
+ // `Taken`) number it, so every save names a second copy the same way.
+ let mut suffix = 2;
// Anything at all under the name counts as taken — a link too, even one that leads
// nowhere: written through, it would put the file wherever the link points.
while path.symlink_metadata().is_ok() {
@@ -7498,7 +7500,7 @@ mod tests {
}
/// The number a second copy takes goes before the whole extension, as a browser puts it:
- /// "archive.tar.gz" was saved as "archive.tar 1.gz", and "v1.2 notes" as "v1 1.2 notes".
+ /// "archive.tar.gz" was saved as "archive.tar 2.gz", and "v1.2 notes" as "v1 2.2 notes".
#[test]
fn a_second_copy_is_numbered_before_its_extension() {
let dir = tempfile::tempdir().unwrap();
@@ -7512,10 +7514,10 @@ mod tests {
.to_string_lossy()
.into_owned()
};
- assert_eq!(next("archive.tar.gz"), "archive 1.tar.gz");
- assert_eq!(next("v1.2 notes"), "v1.2 notes 1");
- assert_eq!(next("Report.pdf"), "Report 1.pdf");
- assert_eq!(next("Makefile"), "Makefile 1");
+ assert_eq!(next("archive.tar.gz"), "archive 2.tar.gz");
+ assert_eq!(next("v1.2 notes"), "v1.2 notes 2");
+ assert_eq!(next("Report.pdf"), "Report 2.pdf");
+ assert_eq!(next("Makefile"), "Makefile 2");
assert_eq!(next("new.txt"), "new.txt");
}
diff --git a/src-tauri/src/saving.rs b/src-tauri/src/saving.rs
index cbc1da2..b68db35 100644
--- a/src-tauri/src/saving.rs
+++ b/src-tauri/src/saving.rs
@@ -117,7 +117,7 @@ mod tests {
std::fs::create_dir_all(&dir).unwrap();
std::os::unix::fs::symlink("/nonexistent/target", dir.join("a.pdf")).unwrap();
let at = save_path(&dir, "a.pdf", "Download").unwrap();
- assert_eq!(at, dir.join("a 1.pdf"));
+ assert_eq!(at, dir.join("a 2.pdf"));
std::fs::remove_dir_all(&dir).ok();
}