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 shows #tags in their line; live check for contact photo changes
Yashwanth Kamireddia3b959b20a66
diff --git a/.uiverify/notes-tags.mjs b/.uiverify/notes-tags.mjsnew file mode 100644index 0000000..388f8e5--- /dev/null+++ b/.uiverify/notes-tags.mjs@@ -0,0 +1,38 @@+// A #tag made on a phone sits in its line as its words, in the Notes accent — never a file+// card, never a gap — in the reader and the editor alike, and opening the note leaves it alone.+import { engine } from "./engine.mjs";+import { SERVICES, installStub, openScreen } from "./stub.mjs";++const b = await engine.launch();+let failures = 0;+const ok = (p, m) => { console.log(`${p ? "PASS" : "FAIL"} ${m}`); if (!p) failures++; };+for (const theme of ["light", "dark"]) {+ const ctx = await b.newContext({ viewport: { width: 1280, height: 800 }, colorScheme: theme });+ await ctx.addInitScript(() => { window.__tagNote = true; });+ await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, notesFixture: true });+ const page = await ctx.newPage();+ await page.goto(process.env.BASE ?? "http://localhost:4173", { waitUntil: "networkidle" });+ await openScreen(page, "Notes");+ await page.waitForTimeout(400);+ await page.locator(".note-row", { hasText: "Pasta" }).first().click();+ const tag = page.locator(".nf-attachment.is-inline .nf-inline");+ await tag.first().waitFor({ timeout: 5000 }).catch(() => {});+ ok((await tag.count()) === 1 && (await tag.first().textContent()) === "#Recipes", `${theme}: the tag shows its words`);+ ok((await page.locator(".note-rich .nf-file").count()) === 0, `${theme}: and is not drawn as a file`);+ const look = await tag.first().evaluate((el) => {+ const host = el.parentElement.getBoundingClientRect(), line = el.closest("p, div")?.getBoundingClientRect();+ const cs = getComputedStyle(el), hs = getComputedStyle(el.parentElement);+ return { color: cs.color, bg: hs.backgroundColor, fontSize: cs.fontSize, lineSize: getComputedStyle(el.closest("p, div")).fontSize,+ inLine: line ? host.top >= line.top - 1 && host.bottom <= line.bottom + 1 : false };+ });+ ok(look.bg === "rgba(0, 0, 0, 0)" && look.fontSize === look.lineSize && look.inLine, `${theme}: set in its line at the text's size ${JSON.stringify(look)}`);+ const text = await page.locator(".note-rich").first().innerText();+ ok(/Dinner for #Recipes tonight/.test(text.replace(/\s+/g, " ")), `${theme}: the line reads through the tag ${JSON.stringify(text.slice(0, 60))}`);+ const wanted = theme === "light" ? "rgb(138, 104, 0)" : "rgb(255, 214, 0)";+ ok(look.color === wanted, `${theme}: in the Notes accent ${look.color}`);+ await page.waitForTimeout(300);+ ok((await page.evaluate(() => (window.__noteSaves ?? []).length)) === 0, `${theme}: opening it saves nothing`);+ await ctx.close();+}+await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjsindex a8d197d..1c5107a 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -372,6 +372,11 @@ export function installStub({ screen, services, twoFactor, calendarFixture, noteconst plain = (length) => ({ length, style: null, indent: 0, checked: null, bold: false, italic: false, underline: false, strike: false, link: null });return [plain(5), { ...plain(1), attachment: "M1" }, plain(1), { ...plain(1), attachment: "M2" }, plain(4)];}+ if (args.guid === "nG") {+ // "Pasta\n", "Dinner for ", a #tag, " tonight": the tag one inline attachment in its line.+ const plain = (length) => ({ length, style: null, indent: 0, checked: null, bold: false, italic: false, underline: false, strike: false, link: null });+ return [{ ...plain(6), style: 0 }, plain(11), { ...plain(1), attachment: "T1" }, plain(8)];+ }if (args.guid === "nD") {const plain = (length) => ({ length, style: null, indent: 0, checked: null, bold: false, italic: false, underline: false, strike: false, link: null });// "Sketch\n", "See " then "The plan" linked to that note (lower-cased, as a phone links), "\n", the drawing, "\nend".@@ -508,6 +513,10 @@ export function installStub({ screen, services, twoFactor, calendarFixture, noteif (window.__attachNote && !noteList.some((n) => n.guid === "nA"))noteList.unshift({ guid: "nA", folderGuid: "f1", title: "Attachments", snippet: "", body: `Attachments\n${"\uFFFC\n".repeat(8)}A few words to try it out \n\uFFFC`,locked: false, editable: true, pinned: false, createdAt: null, modifiedAt: 1789500000, etag: null });+ // Opt-in: a note with a #tag in its line, as a phone sets one.+ if (window.__tagNote && !noteList.some((n) => n.guid === "nG"))+ noteList.unshift({ guid: "nG", folderGuid: "f1", title: "Pasta", snippet: "", body: "Pasta\nDinner for \uFFFC tonight",+ locked: false, editable: true, pinned: false, createdAt: null, modifiedAt: 1789600000, etag: null });if (window.__tableNote && !noteList.some((n) => n.guid === "nT"))noteList.unshift({ guid: "nT", folderGuid: "f1", title: "Groceries", snippet: "", body: "Groceries\n\uFFFC\nend",locked: false, editable: true, pinned: false, createdAt: null, modifiedAt: 1789000000, etag: null });@@ -535,6 +544,7 @@ export function installStub({ screen, services, twoFactor, calendarFixture, noteconst info = { id: args.id, title: null, width: null, height: null, size: null, hasPreview: false, filename: null, ...A };return window.__slowInfo ? new Promise((r) => setTimeout(() => r(info), window.__slowInfo)) : info;}+ if (args.id === "T1") return { id: "T1", uti: "com.apple.notes.inlinetextattachment.hashtag", kind: "inline", filename: null, title: "#Recipes", width: null, height: null, size: null, hasPreview: false };if (args.id === "D1") return { id: "D1", uti: "com.apple.paper", kind: "drawing", filename: null, title: null, width: 768, height: 621, size: null, hasPreview: true };if (args.id === "U1") return { id: "U1", uti: "com.apple.notes.table", kind: "table", filename: null, title: null, width: null, height: null, size: 1116, hasPreview: false };// Any other id a table is drawn for (note_table answers it): a table, as the backenddiff --git a/crates/quince-icloud/src/note_media.rs b/crates/quince-icloud/src/note_media.rsindex 5297f8a..9facd7e 100644--- a/crates/quince-icloud/src/note_media.rs+++ b/crates/quince-icloud/src/note_media.rs@@ -25,7 +25,8 @@ const ZONE: &str = "Notes";pub struct AttachmentInfo {pub id: String,pub uti: String,- /// `image`, `drawing`, `table`, `document` (PDF, scan), `audio`, `video`, or `file`.+ /// `image`, `drawing`, `table`, `document` (PDF, scan), `audio`, `video`, `inline` (a+ /// tag or a mention, drawn as its text), or `file`.pub kind: &'static str,pub filename: Option<String>,pub title: Option<String>,@@ -48,6 +49,11 @@ pub fn kind_of(uti: &str) -> &'static str {) {return "drawing";}+ // Text set inside a line — a #tag (`…inlinetextattachment.hashtag`) or an @mention: drawn+ // as the words it shows, never as a file.+ if u.starts_with("com.apple.notes.inlinetextattachment") {+ return "inline";+ }// A table: drawn as its grid, never offered as a file to open.if u == crate::table::UTI {return "table";@@ -113,6 +119,9 @@ pub async fn info(.map(str::to_string)}).unwrap_or_default();+ if kind_of(&uti) == "inline" {+ return Ok(inline_info(id, uti, &record));+ }let media = match record.pointer("/fields/Media/value/recordName").and_then(Value::as_str)@@ -162,6 +171,42 @@ pub async fn info(})}+/// A tag or mention, with the words it shows as its title. Notes keeps those words as the+/// attachment's alt text, cased as typed, and a tag's normalised name as its token (upper+/// case, no `#`); either is read, plain or in its `…Encrypted` form.+fn inline_info(id: &str, uti: String, record: &Value) -> AttachmentInfo {+ let field = |name: &str| {+ decoded(record, &format!("{name}Encrypted")).or_else(|| {+ record+ .pointer(&format!("/fields/{name}/value"))+ .and_then(Value::as_str)+ .map(|s| s.trim().to_string())+ .filter(|s| !s.is_empty())+ })+ };+ let hashtag = uti.to_ascii_lowercase().ends_with(".hashtag");+ let title = field("AltText").or_else(|| {+ field("TokenContentIdentifier").map(|t| {+ if hashtag && !t.starts_with('#') {+ format!("#{t}")+ } else {+ t+ }+ })+ });+ AttachmentInfo {+ id: id.to_string(),+ kind: "inline",+ filename: None,+ title,+ width: None,+ height: None,+ size: None,+ has_preview: false,+ uti,+ }+}+/// Which bytes of an attachment to fetch.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Part {@@ -287,4 +332,35 @@ mod tests {"file");}++ /// A tag shows the words it was typed as; with only its token, the token behind a `#`.+ #[test]+ fn a_tag_is_drawn_as_its_words() {+ use base64::Engine;+ let b64 = |s: &str| base64::engine::general_purpose::STANDARD.encode(s);+ let uti = "com.apple.notes.inlinetextattachment.hashtag";+ assert_eq!(kind_of(uti), "inline");+ assert_eq!(+ kind_of("com.apple.notes.inlinetextattachment.mention"),+ "inline"+ );+ let typed = serde_json::json!({ "fields": {+ "AltTextEncrypted": { "value": b64("#Recipes") },+ "TokenContentIdentifierEncrypted": { "value": b64("RECIPES") },+ }});+ let info = inline_info("A", uti.into(), &typed);+ assert_eq!(+ (info.kind, info.title.as_deref()),+ ("inline", Some("#Recipes"))+ );+ let token = serde_json::json!({ "fields": {+ "TokenContentIdentifier": { "value": "RECIPES" },+ }});+ assert_eq!(+ inline_info("A", uti.into(), &token).title.as_deref(),+ Some("#RECIPES")+ );+ let bare = serde_json::json!({ "fields": {} });+ assert_eq!(inline_info("A", uti.into(), &bare).title, None);+ }}diff --git a/probe/examples/contact_photo_live.rs b/probe/examples/contact_photo_live.rsnew file mode 100644index 0000000..f108341--- /dev/null+++ b/probe/examples/contact_photo_live.rs@@ -0,0 +1,162 @@+//! Live, on a throwaway card only: a picture added, its square moved, and the picture taken+//! away, each read back from Apple; the card is deleted at the end. `contact_photo_live <jpeg>`.+//! Prints PASS/FAIL lines only.+use anyhow::{anyhow, Result};+use base64::Engine;+use quince_core::contacts::Contact;+use quince_icloud::contacts as c;++#[tokio::main]+async fn main() -> Result<()> {+ let jpeg = std::fs::read(std::env::args().nth(1).ok_or_else(|| anyhow!("a jpeg"))?)?;+ 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("contacts")+ .ok_or_else(|| anyhow!("no contacts"))?;+ let (http, p) = (client.http().clone(), client.service_params());++ let read = |guid: String| {+ let (http, root, p) = (http.clone(), root.clone(), p.clone());+ async move {+ let card = c::card(&http, &root, p, &guid).await?;+ let contact = card.as_ref().and_then(|v| {+ c::parse_cards(&serde_json::json!({ "contacts": [v] }))+ .pop()+ .map(|c| c.contact)+ });+ Ok::<_, anyhow::Error>((card, contact))+ }+ };+ let say = |ok: bool, what: &str| println!("{} {what}", if ok { "PASS" } else { "FAIL" });++ let throwaway = Contact {+ guid: String::new(),+ first_name: Some("Alex".into()),+ middle_name: None,+ last_name: Some(format!("Rivera Photo {}", std::process::id())),+ company: None,+ is_company: false,+ birthday: None,+ notes: None,+ photo_url: None,+ photo_signature: None,+ photo_crop: None,+ etag: None,+ methods: vec![],+ };+ let (_, tokens) = c::fetch_with_tokens(&http, &root, p.clone()).await?;+ let guid = c::create(&http, &root, p.clone(), &tokens, &throwaway).await?;+ let result = async {+ // A picture added, as the form sends one: the JPEG as a data: URL with its square.+ let (card, base) = read(guid.clone()).await?;+ let base = base.ok_or_else(|| anyhow!("the new card is not at Apple"))?;+ let mut with = base.clone();+ with.photo_url = Some(format!(+ "data:image/jpeg;base64,{}",+ base64::engine::general_purpose::STANDARD.encode(&jpeg)+ ));+ with.photo_crop = Some("0,0,600,600".into());+ let (_, tokens) = c::fetch_with_tokens(&http, &root, p.clone()).await?;+ c::update_from(+ &http,+ &root,+ p.clone(),+ &tokens,+ &with,+ card.as_ref(),+ Some(&base),+ )+ .await?;+ let (card, now) = read(guid.clone()).await?;+ let now = now.ok_or_else(|| anyhow!("card gone after the photo"))?;+ let url = now.photo_url.clone().unwrap_or_default();+ say(+ url.starts_with("https://"),+ "photo added: Apple holds it at its own URL",+ );+ say(+ now.photo_crop.as_deref() == Some("0,0,600,600"),+ "photo added: square kept",+ );+ let r = http.get(&url).query(&p).send().await?;+ let ok = r.status().is_success();+ let bytes = r.bytes().await?;+ let drawn = quince_media::avatar(+ &bytes,+ now.photo_crop+ .as_deref()+ .and_then(quince_media::Crop::parse),+ 128,+ );+ say(+ ok && drawn.is_ok(),+ &format!("photo added: fetched {} bytes and drawn", bytes.len()),+ );++ // The square moved on the same picture: the rest of Apple's entry stays.+ let mut moved = now.clone();+ moved.photo_crop = Some("100,100,400,400".into());+ let (_, tokens) = c::fetch_with_tokens(&http, &root, p.clone()).await?;+ c::update_from(+ &http,+ &root,+ p.clone(),+ &tokens,+ &moved,+ card.as_ref(),+ Some(&now),+ )+ .await?;+ let (card, after) = read(guid.clone()).await?;+ let after = after.ok_or_else(|| anyhow!("card gone after the crop"))?;+ say(+ after.photo_crop.as_deref() == Some("100,100,400,400"),+ "square moved",+ );+ say(+ after.photo_url.is_some(),+ "square moved: picture still there",+ );++ // The picture taken away.+ let mut none = after.clone();+ none.photo_url = None;+ none.photo_crop = None;+ none.photo_signature = None;+ let (_, tokens) = c::fetch_with_tokens(&http, &root, p.clone()).await?;+ c::update_from(+ &http,+ &root,+ p.clone(),+ &tokens,+ &none,+ card.as_ref(),+ Some(&after),+ )+ .await?;+ let (_, gone) = read(guid.clone()).await?;+ let gone = gone.ok_or_else(|| anyhow!("card gone after removing the photo"))?;+ say(gone.photo_url.is_none(), "photo removed");+ say(+ gone.first_name.as_deref() == Some("Alex"),+ "name untouched throughout",+ );+ Ok::<_, anyhow::Error>(gone)+ }+ .await;++ // The throwaway goes whatever happened above.+ let (_, last) = read(guid.clone()).await?;+ if let Some(last) = last {+ let (_, tokens) = c::fetch_with_tokens(&http, &root, p.clone()).await?;+ c::delete(&http, &root, p.clone(), &tokens, &last).await?;+ }+ let (card, _) = read(guid).await?;+ say(card.is_none(), "throwaway deleted");+ result.map(|_| ())+}diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex 5af2312..4d56b1a 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -679,7 +679,7 @@ export type AccountInfo = {export type NoteAttachment = {id: string;uti: string;- kind: "image" | "drawing" | "table" | "document" | "audio" | "video" | "file";+ kind: "image" | "drawing" | "table" | "document" | "audio" | "video" | "inline" | "file";filename: string | null;title: string | null;width: number | null;diff --git a/src/screens/notes/NoteEditor.tsx b/src/screens/notes/NoteEditor.tsxindex de2e7b0..f7db9ed 100644--- a/src/screens/notes/NoteEditor.tsx+++ b/src/screens/notes/NoteEditor.tsx@@ -186,6 +186,16 @@ export function drawMedia(dom: HTMLElement, info: NoteAttachment) {});return img;};+ // A #tag or @mention sits in its line as the words it shows, as Notes sets it — not a file.+ if (info.kind === "inline") {+ const words = document.createElement("span");+ words.className = "nf-inline";+ words.textContent = info.title ?? "";+ dom.className = "nf-attachment is-inline";+ dom.title = "";+ dom.replaceChildren(words);+ return;+ }dom.title = `Open ${name}`;if (info.kind === "image") {const img = picture("file", "nf-image");diff --git a/src/styles/notes.css b/src/styles/notes.cssindex b2b89fb..00740a8 100644--- a/src/styles/notes.css+++ b/src/styles/notes.css@@ -473,6 +473,10 @@ textarea.note-title::placeholder { color: var(--text-3); }display: block; padding: 10px 12px; border: 1px dashed var(--separator); border-radius: 8px;color: var(--text-3); font-size: var(--t-13, 13px);}+.note-rich .nf-attachment.is-inline, .nf-attachment.is-inline {+ display: inline; padding: 0; margin: 0; background: none; color: inherit; font-size: inherit;+}+.nf-inline { color: var(--accent-strong); font-weight: 500; }.notes-folder-rename { width: 100%; }/* An attachment not yet known: a quiet frame holding its place, no words, no motion — never