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
Notes: a tick or a style names the line it was meant for, and is refused if another device has put a different line there
Yashwanth Kamireddibabb078d18ff
diff --git a/crates/quince-icloud/src/ckdocument.rs b/crates/quince-icloud/src/ckdocument.rsindex d67c593..c2fa359 100644--- a/crates/quince-icloud/src/ckdocument.rs+++ b/crates/quince-icloud/src/ckdocument.rs@@ -672,7 +672,12 @@ fn bytes_field(message: &[u8], tag: u64) -> Option<Vec<u8>> {/// font, links and the rest of each run go back untouched. A checklist item keeps the id it/// had; one made a checklist here is given a fresh one, as a phone gives it.#[must_use]-pub fn set_paragraph(original: &[u8], start: u64, change: ParagraphChange) -> Option<Vec<u8>> {+pub fn set_paragraph(+ original: &[u8],+ start: u64,+ change: ParagraphChange,+ expect: Option<&str>,+) -> Option<Vec<u8>> {let plain = inflate(original)?;let text = std::str::from_utf8(field_at(&plain, TEXT_PATH)?).ok()?;let units: Vec<u16> = text.encode_utf16().collect();@@ -688,6 +693,16 @@ pub fn set_paragraph(original: &[u8], start: u64, change: ParagraphChange) -> Opif end == start {return None;}+ // The line asked about has to be the line there now. If another device edited above it,+ // the same offset is a different line, and a tick or a style would land on that one.+ if let Some(expected) = expect {+ let here =+ String::from_utf16(&units[usize::try_from(start).ok()?..usize::try_from(end).ok()?])+ .ok()?;+ if here.trim_end_matches('\n') != expected {+ return None;+ }+ }let note = field_at(&plain, &TEXT_PATH[..2])?;let runs = debug_attribute_runs(original);@@ -780,9 +795,10 @@ pub fn set_paragraph_in_base64(original: &str,start: u64,change: ParagraphChange,+ expect: Option<&str>,) -> Option<String> {let raw = B64.decode(original.trim()).ok()?;- Some(B64.encode(gzip(&set_paragraph(&raw, start, change)?)))+ Some(B64.encode(gzip(&set_paragraph(&raw, start, change, expect)?)))}/// Rewrite the text inside an existing document, leaving every other field exactly as it@@ -2178,8 +2194,13 @@ mod run_tests {let mut doc = Vec::new();len_field(2, &inner, &mut doc);- let out =- set_paragraph_in_base64(&B64.encode(&doc), 3, ParagraphChange::Style(103)).unwrap();+ let out = set_paragraph_in_base64(+ &B64.encode(&doc),+ 3,+ ParagraphChange::Style(103),+ Some("cd"),+ )+ .unwrap();let runs = runs_from_base64(&out);assert_eq!(runs.iter().map(|r| r.length).collect::<Vec<_>>(), [3, 3, 2]);assert_eq!(@@ -2239,8 +2260,13 @@ mod run_tests {assert!(runs[2].bold && runs[2].style.is_none());// Untick "egg" (the paragraph starting at 5): only its tick changes.- let unticked =- set_paragraph_in_base64(&B64.encode(&doc), 5, ParagraphChange::Checked(false)).unwrap();+ let unticked = set_paragraph_in_base64(+ &B64.encode(&doc),+ 5,+ ParagraphChange::Checked(false),+ Some("egg"),+ )+ .unwrap();let after = runs_from_base64(&unticked);assert_eq!(after[1].checked, Some(false));assert_eq!(after[0].style, Some(101), "the line above is untouched");@@ -2252,7 +2278,7 @@ mod run_tests {// Make "hi" — inside a run of its own, no newline — a heading: only it changes.let headed =- set_paragraph_in_base64(&B64.encode(&doc), 9, ParagraphChange::Style(1)).unwrap();+ set_paragraph_in_base64(&B64.encode(&doc), 9, ParagraphChange::Style(1), None).unwrap();let after = runs_from_base64(&headed);assert_eq!(after.last().unwrap().style, Some(1));assert!(after.last().unwrap().bold, "the run keeps its weight");diff --git a/crates/quince-icloud/src/notes.rs b/crates/quince-icloud/src/notes.rsindex fd81c75..3a796a5 100644--- a/crates/quince-icloud/src/notes.rs+++ b/crates/quince-icloud/src/notes.rs@@ -567,6 +567,7 @@ pub async fn set_paragraph_cloudkit(note: &Note,start: u64,change: crate::ckdocument::ParagraphChange,+ expect: Option<&str>,) -> Result<()> {let client = ZoneClient::new(http, ckdatabasews_root, CONTAINER, params);let current = client@@ -577,7 +578,7 @@ pub async fn set_paragraph_cloudkit(.pointer("/fields/TextDataEncrypted/value").and_then(Value::as_str).ok_or_else(|| Error::Refused("That note has no body Apple will let us read.".into()))?;- let rewritten = crate::ckdocument::set_paragraph_in_base64(encoded, start, change).ok_or_else(|| {+ let rewritten = crate::ckdocument::set_paragraph_in_base64(encoded, start, change, expect).ok_or_else(|| {Error::Refused("That line has changed since it was shown, so nothing was changed. Try again in a moment.".into())})?;fits_inline(&rewritten)?;diff --git a/probe/examples/notes_format_roundtrip.rs b/probe/examples/notes_format_roundtrip.rsindex 6f88acb..9751852 100644--- a/probe/examples/notes_format_roundtrip.rs+++ b/probe/examples/notes_format_roundtrip.rs@@ -62,6 +62,7 @@ async fn main() -> Result<()> {¬e,19,ParagraphChange::Style(103),+ Some("Buy milk"),).await?;println!(@@ -75,6 +76,7 @@ async fn main() -> Result<()> {¬e,19,ParagraphChange::Checked(true),+ Some("Buy milk"),).await?;println!(@@ -88,6 +90,7 @@ async fn main() -> Result<()> {¬e,28,ParagraphChange::Style(101),+ Some("Call the bank"),).await?;let last = zc.lookup_record("Notes", &guid).await?.unwrap();diff --git a/probe/examples/notes_merge_live.rs b/probe/examples/notes_merge_live.rsindex 5a8a4af..9d5ce32 100644--- a/probe/examples/notes_merge_live.rs+++ b/probe/examples/notes_merge_live.rs@@ -5,23 +5,78 @@ use anyhow::{anyhow, Result};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 root = client.session().service_url("ckdatabasews").ok_or_else(|| anyhow!("no ckdatabasews"))?;+ if !client.resume().await? {+ return Err(anyhow!("no session"));+ }+ let root = client+ .session()+ .service_url("ckdatabasews")+ .ok_or_else(|| anyhow!("no ckdatabasews"))?;let (http, p) = (client.http().clone(), client.service_params());let original = "Quince merge test\nmilk\neggs";- let guid = quince_icloud::notes::create_cloudkit(&http, &root, p.clone(), None, original, None).await?;- let note = quince_core::notes::Note { guid: guid.clone(), folder_guid: None, title: "Quince merge test".into(), snippet: None, body: None, locked: false, pinned: false, created_at: None, modified_at: None, editable: true, etag: None, runs: None };+ let guid = quince_icloud::notes::create_cloudkit(&http, &root, p.clone(), None, original, None)+ .await?;+ let note = quince_core::notes::Note {+ guid: guid.clone(),+ folder_guid: None,+ title: "Quince merge test".into(),+ snippet: None,+ body: None,+ locked: false,+ pinned: false,+ created_at: None,+ modified_at: None,+ editable: true,+ etag: None,+ runs: None,+ };// "The phone": changes the title.- quince_icloud::notes::edit_cloudkit(&http, &root, p.clone(), ¬e, "Quince merge test (phone)\nmilk\neggs").await?;+ quince_icloud::notes::edit_cloudkit(+ &http,+ &root,+ p.clone(),+ ¬e,+ "Quince merge test (phone)\nmilk\neggs",+ )+ .await?;// Quince, from the original: adds a line.- let saved = quince_icloud::notes::edit_cloudkit_from(&http, &root, p.clone(), ¬e, Some(original), "Quince merge test\nmilk\neggs\nbread").await?;+ let saved = quince_icloud::notes::edit_cloudkit_from(+ &http,+ &root,+ p.clone(),+ ¬e,+ Some(original),+ "Quince merge test\nmilk\neggs\nbread",+ )+ .await?;let zc = quince_icloud::cloudkit::ZoneClient::new(&http, &root, "com.apple.notes", p.clone());let rec = zc.lookup_record("Notes", &guid).await?.unwrap();println!("saved: {saved:?}");- println!("apple: {:?}", quince_icloud::ckdocument::text_from_base64(rec["fields"]["TextDataEncrypted"]["value"].as_str().unwrap_or("")));+ println!(+ "apple: {:?}",+ quince_icloud::ckdocument::text_from_base64(+ rec["fields"]["TextDataEncrypted"]["value"]+ .as_str()+ .unwrap_or("")+ )+ );// Same place, both sides: refused.- let refused = quince_icloud::notes::edit_cloudkit_from(&http, &root, p.clone(), ¬e, Some(original), "Quince merge test\nmilk\neggs and ham").await;- println!("same-place edit: {}", match refused { Ok(t) => format!("WROTE {t:?}"), Err(e) => format!("refused — {e}") });+ let refused = quince_icloud::notes::edit_cloudkit_from(+ &http,+ &root,+ p.clone(),+ ¬e,+ Some(original),+ "Quince merge test\nmilk\neggs and ham",+ )+ .await;+ println!(+ "same-place edit: {}",+ match refused {+ Ok(t) => format!("WROTE {t:?}"),+ Err(e) => format!("refused — {e}"),+ }+ );quince_icloud::notes::delete_cloudkit(&http, &root, p, ¬e).await?;println!("moved to Recently Deleted");Ok(())diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex 47e8ed4..94b702c 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -1013,6 +1013,8 @@ async fn note_paragraph(start: u64,style: Option<u64>,checked: Option<bool>,+ // The line's text as it was shown, so a tick cannot land on a line that moved there.+ expect: Option<String>,auth: State<'_, Auth>,data: State<'_, Data>,) -> UiResult<()> {@@ -1031,6 +1033,7 @@ async fn note_paragraph(¬e,start,change,+ expect.as_deref(),).await.map_err(|e| e.to_string())?;diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex 6c0977b..feb6345 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -120,7 +120,7 @@ export const api = {invoke<void>("reminder_delete", { guid, listGuid }),noteFolders: () => invoke<NoteFolder[]>("note_folders"),- noteParagraph: (guid: string, start: number, change: { style?: number; checked?: boolean }) =>+ noteParagraph: (guid: string, start: number, change: { style?: number; checked?: boolean; expect?: string }) =>invoke<void>("note_paragraph", { guid, start, ...change }),noteRuns: (guid: string) => invoke<import("../screens/notes/Formatted").Run[]>("note_runs", { guid }),noteFolderCreate: (title: string, parent: string | null) =>diff --git a/src/screens/NotesView.tsx b/src/screens/NotesView.tsxindex 439b3ee..505ae12 100644--- a/src/screens/NotesView.tsx+++ b/src/screens/NotesView.tsx@@ -214,7 +214,7 @@ export function NotesView() {});flip(checked);try {- await api.noteParagraph(guid, start, { checked });+ await api.noteParagraph(guid, start, { checked, expect: text.slice(start, nl < 0 ? text.length : nl) });} catch (e) {flip(!checked);setError(messageOf(e));