use std::path::PathBuf; use std::time::{Duration, Instant}; use anyhow::{anyhow, bail, Context, Result}; use chromiumoxide::browser::{Browser, BrowserConfig}; use chromiumoxide::page::Page; use futures::StreamExt; use serde::Deserialize; use tokio::time::sleep; use crate::config::{notes_url, Paths}; use crate::format::{build_paragraphs, ParagraphStyle}; use crate::helpers::{format_note_text, looks_logged_out, LoggedOutSignals}; #[derive(Debug, Deserialize)] struct ReadyFlag { ready: bool, } #[derive(Debug, Deserialize)] struct SignalsJson { body_text: String, has_password_field: bool, has_sign_in_control: bool, has_notes_app: bool, } #[derive(Debug, Deserialize)] struct CreatedNote { title: String, #[serde(default)] record_name: String, } fn find_chrome() -> Result { if let Ok(p) = std::env::var("ICLOUD_NOTES_CHROME") { let pb = PathBuf::from(&p); if pb.is_file() { return Ok(pb); } bail!("ICLOUD_NOTES_CHROME not a file: {p}"); } let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("/tmp")); let candidates = [ home.join(".cache/ms-playwright/chromium-1248/chrome-linux64/chrome"), PathBuf::from("/usr/bin/chromium"), PathBuf::from("/usr/bin/chromium-browser"), PathBuf::from("/usr/bin/google-chrome"), PathBuf::from("/usr/bin/google-chrome-stable"), ]; for c in candidates { if c.is_file() { return Ok(c); } } // glob playwright chromium let pw = home.join(".cache/ms-playwright"); if pw.is_dir() { if let Ok(entries) = std::fs::read_dir(&pw) { for ent in entries.flatten() { let name = ent.file_name().to_string_lossy().to_string(); if name.starts_with("chromium-") { let chrome = ent.path().join("chrome-linux64/chrome"); if chrome.is_file() { return Ok(chrome); } } } } } bail!( "No Chrome/Chromium found. Set ICLOUD_NOTES_CHROME or install Chromium. \ Tip: run scripts/setup.sh (uses Playwright Chromium under ~/.cache/ms-playwright)." ) } async fn launch(paths: &Paths, headed: bool) -> Result<(Browser, tokio::task::JoinHandle<()>)> { paths.ensure()?; let chrome = find_chrome()?; let mut builder = BrowserConfig::builder() .chrome_executable(chrome) .user_data_dir(&paths.profile_dir) .arg("--disable-blink-features=AutomationControlled") .arg("--no-first-run") .arg("--no-default-browser-check"); builder = if headed { builder.with_head() } else { builder .new_headless_mode() .arg("--ozone-platform=headless") }; let cfg = builder.build().map_err(|e| anyhow!(e))?; let (browser, mut handler) = Browser::launch(cfg).await.context("launch Chrome")?; let handle = tokio::spawn(async move { while let Some(h) = handler.next().await { if h.is_err() { break; } } }); Ok((browser, handle)) } async fn page_looks_logged_out(page: &Page) -> Result { let url = page.url().await?.unwrap_or_default(); let signals: SignalsJson = page .evaluate( r#"() => { const t = (document.body?.innerText || "").slice(0, 4000); const hasPasswordField = Boolean( document.querySelector( 'input[type="password"], #password_text_field, #account_name_text_field' ) ); const hasSignInControl = [...document.querySelectorAll("a,button,div[role='button']")] .some((el) => /^sign in$/i.test((el.textContent || "").trim())); const hasNotesApp = Boolean( document.querySelector("iframe")?.contentWindow?.NotesApp?.dataManager ); return { body_text: t, has_password_field: hasPasswordField, has_sign_in_control: hasSignInControl, has_notes_app: hasNotesApp }; }"#, ) .await? .into_value() .unwrap_or(SignalsJson { body_text: String::new(), has_password_field: false, has_sign_in_control: false, has_notes_app: false, }); Ok(looks_logged_out(&LoggedOutSignals { url, body_text: signals.body_text, has_password_field: signals.has_password_field, has_sign_in_control: signals.has_sign_in_control, has_notes_app: signals.has_notes_app, })) } async fn notes_ready(page: &Page) -> Result { let flag: ReadyFlag = page .evaluate( r#"() => { const iframe = document.querySelector("iframe"); const w = iframe?.contentWindow; const dm = w?.NotesApp?.dataManager; if (!dm) return { ready: false }; const notes = dm.allNotes || dm.__CW__allNotes; const folders = dm.allFolders || dm.__CW__allFolders || dm.folders; const n = (typeof notes?.get === "function" && typeof notes.get("length") === "number") ? notes.get("length") : (notes?.length || 0); // Need at least one note so Note.create* is reachable via sample.constructor return { ready: n > 0 }; }"#, ) .await? .into_value() .unwrap_or(ReadyFlag { ready: false }); Ok(flag.ready) } async fn wait_for_notes_app(page: &Page, timeout: Duration, allow_login_wait: bool) -> Result<()> { page.goto(notes_url()).await.context("goto Notes")?; let deadline = Instant::now() + timeout; let mut saw_login = false; while Instant::now() < deadline { if notes_ready(page).await? { return Ok(()); } if page_looks_logged_out(page).await? { saw_login = true; if !allow_login_wait { bail!("Not signed in. Run: icloud-note login"); } } sleep(Duration::from_secs(1)).await; } if saw_login { bail!("Login did not finish. Complete Apple ID sign-in in the browser window."); } bail!("NotesApp did not become ready. Run: icloud-note login"); } fn note_list_helpers_js() -> &'static str { r#" function noteLen(list) { if (!list) return 0; if (typeof list.get === "function" && typeof list.get("length") === "number") return list.get("length"); return list.length || 0; } function noteAt(list, i) { if (!list) return null; if (typeof list.objectAt === "function") return list.objectAt(i); if (typeof list.get === "function") return list.objectAt?.(i) ?? list[i]; return list[i]; } function findByTitle(list, want) { const norm = (s) => String(s || "").trim().toLowerCase(); const target = norm(want); let best = null; let bestMod = -1; const n = noteLen(list); for (let i = 0; i < n; i++) { const note = noteAt(list, i); if (!note) continue; const title = note.Title ?? note.title ?? ""; if (norm(title) !== target) continue; const mod = Number(note.ModificationDate || note.modificationDate || 0); if (!best || mod >= bestMod) { best = note; bestMod = mod; } } return best; } "# } fn paragraphs_json(title: &str, body: &str) -> Result { let paras = build_paragraphs(title, body); let wire: Vec = paras .iter() .map(|p| { serde_json::json!({ "style": match p.style { ParagraphStyle::Title => "title", ParagraphStyle::Heading => "heading", ParagraphStyle::Subheading => "subheading", ParagraphStyle::Body => "body", ParagraphStyle::Bullet => "bullet", ParagraphStyle::Dashed => "dashed", ParagraphStyle::Numbered => "numbered", ParagraphStyle::Checklist => "checklist", ParagraphStyle::Monospace => "mono", ParagraphStyle::Divider => "divider", ParagraphStyle::BlockQuote => "quote", }, "text": p.text, "checked": p.checked, }) }) .collect(); Ok(serde_json::to_string(&wire)?) } fn style_helpers_js() -> &'static str { // Apple Notes attributed strings use paragraphStyle.style: // 0=Title, 1=Heading, 2=Body (confirmed against icloud.com/notes). // Plain createNoteWithTitleText / createInitialTopoTextString leave Body // lines as Title (style 0) when the account default is "start with Title". r#" function styleIdFor(name) { switch (String(name || "")) { case "title": return 0; case "heading": return 1; case "subheading": return 1; default: return 2; // body, lists, checklist, mono, quote, divider } } function applyParagraphStyle(topo, startIdx, endIdx, basePs, styleName, checked) { if (!basePs || typeof topo.addAttributeToRange !== "function") return; let ps = basePs.setStyle(styleIdFor(styleName)); if (styleName === "checklist" && typeof ps.setToDo === "function") { try { const maybe = ps.setToDo(!!checked); if (maybe && typeof maybe.style === "number") ps = maybe; } catch (_) {} } const a = topo.iteratorAt(startIdx); const b = topo.iteratorAt(endIdx); topo.addAttributeToRange(a, b, "paragraphStyle", ps); } /** Build a note with real Title/Heading/Body paragraph styles from paras[]. */ function createStyledNote(Note, folder, paras) { const list = Array.isArray(paras) ? paras : []; const titlePara = list.find((p) => p && p.style === "title") || list[0]; const title = String((titlePara && titlePara.text) || "Note"); const note = Note.createNoteWithTitleText(title + "\n", folder); const topo = note.TopoTextString; if (!topo) return note; let basePs = null; try { topo.forEachWithAttributesInRange( topo.atStart(), topo.iteratorAt(Math.min(1, topo.length)), (cp, attrs) => { if (!basePs && attrs && attrs.paragraphStyle) basePs = attrs.paragraphStyle; } ); } catch (_) {} let skippedTitle = false; for (const p of list) { if (!p) continue; if (!skippedTitle && p.style === "title") { skippedTitle = true; continue; } skippedTitle = true; const chunk = String(p.text || "") + "\n"; const startIdx = topo.length; try { topo.atEnd().insert(chunk); } catch (_) { // Fallback: some builds expose insert on the string itself try { topo.insert?.(chunk); } catch (_) { continue; } } const endIdx = topo.length; applyParagraphStyle(topo, startIdx, endIdx, basePs, p.style, p.checked); } if (typeof note.userDidChangeTopoText === "function") note.userDidChangeTopoText(); return note; } function writeNoteText(Note, dataManager, note, text, folder, paras) { const canLoad = dataManager.topoTextManager && typeof dataManager.topoTextManager.load === "function"; if (typeof Note.createNoteWithTitleText === "function" && folder && canLoad) { const scratch = Array.isArray(paras) && paras.length ? createStyledNote(Note, folder, paras) : Note.createNoteWithTitleText(text, folder); try { const topo = scratch.TopoTextString; if (topo) { dataManager.topoTextManager.load(note.id, topo); if (typeof note.userDidChangeTopoText === "function") { note.userDidChangeTopoText(); } return; } } finally { try { if (scratch && scratch !== note) { if (typeof dataManager.removeUnsavedItem === "function") { dataManager.removeUnsavedItem(scratch); } else if (typeof dataManager.didDeleteNote === "function") { dataManager.didDeleteNote(scratch); } } } catch (_) {} } } if (typeof Note.createInitialTopoTextString === "function" && canLoad) { const replacement = Note.createInitialTopoTextString(text); dataManager.topoTextManager.load(note.id, replacement); if (typeof note.userDidChangeTopoText === "function") note.userDidChangeTopoText(); return; } if (typeof note.userDidChangeTopoText === "function") { note.userDidChangeTopoText(text); } } "# } async fn create_via_notes_app(page: &Page, title: &str, body: &str) -> Result { // Prefer Rust-formatted plain text (Apple Notes spacing/lists); pass paras for future rich path let full = format_note_text(title, body); let text_js = serde_json::to_string(&full)?; let paras_js = paragraphs_json(title, body)?; let helpers = note_list_helpers_js(); let styles = style_helpers_js(); // Use `async function ()` (not `async () =>`) so chromiumoxide detects a JS // function. Arrow form is misclassified as an expression and never invoked. let expr = format!( r#"async function () {{ const text = {text_js}; const paras = {paras_js}; {helpers} {styles} const iframe = document.querySelector("iframe"); const w = iframe?.contentWindow; const app = w?.NotesApp; if (!app?.dataManager) throw new Error("NotesApp unavailable"); const dataManager = app.dataManager; const mv = app.mainViewModel; const noteList = dataManager.allNotes || dataManager.__CW__allNotes; const sample = mv?.selectedNote || noteAt(noteList, 0) || null; const Note = sample?.constructor; if (!Note?.createNoteWithTitleText && !Note?.createEmptyNote) {{ throw new Error("Could not find Note.createNoteWithTitleText — UI may have changed"); }} const folderList = dataManager.allFolders || dataManager.__CW__allFolders || dataManager.folders; const folder = mv?.selectedFolder || dataManager.defaultFolder || dataManager.inboxFolder || noteAt(folderList, 0) || null; if (!folder) throw new Error("Could not resolve a Notes folder"); const payload = text; let note; if (typeof Note.createNoteWithTitleText === "function" && Array.isArray(paras) && paras.length) {{ note = createStyledNote(Note, folder, paras); }} else if (typeof Note.createNoteWithTitleText === "function") {{ note = Note.createNoteWithTitleText(payload, folder); }} else {{ note = Note.createEmptyNote(folder); writeNoteText(Note, dataManager, note, payload, folder, paras); if (note.Title !== undefined) note.Title = payload.split("\n")[0] || "Note"; }} if (typeof dataManager.userDidCreateNote === "function") {{ dataManager.userDidCreateNote(note); }} await note.save(true); return {{ title: String(note.Title || payload.split("\n")[0] || "(untitled)"), record_name: String(note.recordName || note.id || "") }}; }}"# ); let note: CreatedNote = page.evaluate(expr).await?.into_value()?; Ok(note) } /// Find an existing note by title and replace its content (does not create). async fn update_via_notes_app(page: &Page, match_title: &str, title: &str, body: &str) -> Result { let full = format_note_text(title, body); let text_js = serde_json::to_string(&full)?; let paras_js = paragraphs_json(title, body)?; let match_js = serde_json::to_string(match_title)?; let helpers = note_list_helpers_js(); let styles = style_helpers_js(); // Use `async function ()` (not `async () =>`) — see create_via_notes_app. let expr = format!( r#"async function () {{ const text = {text_js}; const paras = {paras_js}; const matchTitle = {match_js}; {helpers} {styles} const iframe = document.querySelector("iframe"); const w = iframe?.contentWindow; const app = w?.NotesApp; if (!app?.dataManager) throw new Error("NotesApp unavailable"); const dataManager = app.dataManager; const noteList = dataManager.allNotes || dataManager.__CW__allNotes; const note = findByTitle(noteList, matchTitle); if (!note) {{ throw new Error("No note titled " + JSON.stringify(matchTitle)); }} const Note = note.constructor; const mv = app.mainViewModel; const folderList = dataManager.allFolders || dataManager.__CW__allFolders || dataManager.folders; const folder = note.Folder || note.folder || mv?.selectedFolder || dataManager.defaultFolder || dataManager.inboxFolder || noteAt(folderList, 0) || null; writeNoteText(Note, dataManager, note, text, folder, paras); if (note.Title !== undefined) {{ note.Title = text.split("\n")[0] || matchTitle; }} await note.save(true); return {{ title: String(note.Title || text.split("\n")[0] || matchTitle), record_name: String(note.recordName || note.id || "") }}; }}"# ); let note: CreatedNote = page.evaluate(expr).await?.into_value()?; Ok(note) } fn mark_session(paths: &Paths) -> Result<()> { std::fs::write(&paths.marker_path, b"ok\n")?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let _ = std::fs::set_permissions(&paths.marker_path, std::fs::Permissions::from_mode(0o600)); } Ok(()) } pub async fn cmd_login(paths: &Paths) -> Result<()> { if std::env::var_os("DISPLAY").is_none() && std::env::var_os("WAYLAND_DISPLAY").is_none() { bail!("login needs a graphical session (DISPLAY or WAYLAND_DISPLAY)."); } eprintln!("Opening Chromium for Apple ID sign-in (one-time)…"); eprintln!("Sign in, complete 2FA, wait until Notes loads."); let (mut browser, handle) = launch(paths, true).await?; let page = browser.new_page(notes_url()).await?; wait_for_notes_app(&page, Duration::from_secs(600), true).await?; mark_session(paths)?; println!("ok: session saved under {}", paths.profile_dir.display()); println!("ok: create/status will run headless (no window)"); browser.close().await?; let _ = handle.await; Ok(()) } pub async fn cmd_status(paths: &Paths) -> Result<()> { if !paths.has_session() { bail!("No saved session. Run: icloud-note login"); } let (mut browser, handle) = launch(paths, false).await?; let page = browser.new_page("about:blank").await?; wait_for_notes_app(&page, Duration::from_secs(20), false).await?; println!("ok: logged in to icloud.com/notes (headless)"); browser.close().await?; let _ = handle.await; Ok(()) } pub async fn cmd_create(paths: &Paths, title: &str, body: &str) -> Result<()> { if !paths.has_session() { bail!("No saved session. Run: icloud-note login"); } let (mut browser, handle) = launch(paths, false).await?; let page = browser.new_page("about:blank").await?; wait_for_notes_app(&page, Duration::from_secs(90), false).await?; let note = create_via_notes_app(&page, title, body) .await .context("create note via NotesApp")?; sleep(Duration::from_secs(2)).await; mark_session(paths)?; if note.record_name.is_empty() { println!("created: {}", note.title); } else { println!("created: {} ({})", note.title, note.record_name); } browser.close().await?; let _ = handle.await; Ok(()) } /// Update an existing note matched by title. Never creates a new note. pub async fn cmd_update( paths: &Paths, match_title: &str, title: &str, body: &str, ) -> Result<()> { if !paths.has_session() { bail!("No saved session. Run: icloud-note login"); } let (mut browser, handle) = launch(paths, false).await?; let page = browser.new_page("about:blank").await?; wait_for_notes_app(&page, Duration::from_secs(90), false).await?; let note = update_via_notes_app(&page, match_title, title, body) .await .context("update note via NotesApp")?; sleep(Duration::from_secs(2)).await; mark_session(paths)?; if note.record_name.is_empty() { println!("updated: {}", note.title); } else { println!("updated: {} ({})", note.title, note.record_name); } browser.close().await?; let _ = handle.await; Ok(()) } #[cfg(test)] mod tests { use super::style_helpers_js; #[test] fn update_write_prefers_styled_create_scratch() { let js = style_helpers_js(); assert!( js.contains("createNoteWithTitleText"), "updates must build TopoText via createNoteWithTitleText" ); assert!( js.contains("removeUnsavedItem"), "scratch note from create path must be discarded" ); let scratch = js.find("createNoteWithTitleText").expect("scratch"); let fallback = js.find("createInitialTopoTextString").expect("fallback"); assert!( scratch < fallback, "styled scratch path must run before Title-everywhere fallback" ); } }