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::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 = notes?.length || 0; const f = folders?.length || 0; return { ready: n > 0 || f > 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; } "# } async fn create_via_notes_app(page: &Page, title: &str, body: &str) -> Result { let full = format_note_text(title, body); let text_js = serde_json::to_string(&full)?; let helpers = note_list_helpers_js(); let expr = format!( r#"async () => {{ const text = {text_js}; {helpers} 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"); let note; if (typeof Note.createNoteWithTitleText === "function") {{ note = Note.createNoteWithTitleText(text, folder); }} else {{ note = Note.createEmptyNote(folder); note.userDidChangeTopoText?.(text); if (note.Title !== undefined) note.Title = text.split("\n")[0] || "Note"; }} if (typeof dataManager.userDidCreateNote === "function") {{ dataManager.userDidCreateNote(note); }} await note.save(true); return {{ title: String(note.Title || text.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 match_js = serde_json::to_string(match_title)?; let helpers = note_list_helpers_js(); let expr = format!( r#"async () => {{ const text = {text_js}; const matchTitle = {match_js}; {helpers} 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 note = findByTitle(noteList, matchTitle); if (!note) {{ throw new Error("No note titled " + JSON.stringify(matchTitle)); }} const Note = note.constructor; // Preferred path: replace TopoText via NotesApp helpers if (typeof Note.createInitialTopoTextString === "function" && dataManager.topoTextManager && typeof dataManager.topoTextManager.load === "function") {{ const replacement = Note.createInitialTopoTextString(text); dataManager.topoTextManager.load(note.id, replacement); if (typeof note.userDidChangeTopoText === "function") {{ note.userDidChangeTopoText(); }} }} else if (typeof note.userDidChangeTopoText === "function") {{ note.userDidChangeTopoText(text); }} else {{ throw new Error("No supported update path on Note model"); }} 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(()) }