diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/browser.rs | 302 | ||||
| -rw-r--r-- | src/config.rs | 51 | ||||
| -rw-r--r-- | src/helpers.rs | 142 | ||||
| -rw-r--r-- | src/lib.rs | 3 | ||||
| -rw-r--r-- | src/main.rs | 176 |
5 files changed, 674 insertions, 0 deletions
diff --git a/src/browser.rs b/src/browser.rs new file mode 100644 index 0000000..187b535 --- /dev/null +++ b/src/browser.rs @@ -0,0 +1,302 @@ +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<PathBuf> { + 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<bool> { + 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<bool> { + 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"); +} + +async fn create_via_notes_app(page: &Page, title: &str, body: &str) -> Result<CreatedNote> { + let full = format_note_text(title, body); + // Pass text via JSON.stringify embedded in JS to avoid injection issues + let text_js = serde_json::to_string(&full)?; + let expr = format!( + r#"async () => {{ + const text = {text_js}; + 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 || + (noteList?.objectAt ? noteList.objectAt(0) : 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 || + (folderList?.objectAt ? folderList.objectAt(0) : 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) +} + +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(()) +} + diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..dbd2136 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,51 @@ +use std::path::PathBuf; + +#[derive(Debug, Clone)] +pub struct Paths { + pub config_dir: PathBuf, + pub profile_dir: PathBuf, + pub marker_path: PathBuf, +} + +impl Paths { + pub fn resolve() -> Self { + let config_dir = std::env::var_os("ICLOUD_NOTES_CONFIG") + .map(PathBuf::from) + .unwrap_or_else(|| { + dirs::config_dir() + .unwrap_or_else(|| PathBuf::from(".").join(".config")) + .join("icloud-notes") + }); + Self { + profile_dir: config_dir.join("browser-profile"), + marker_path: config_dir.join("session.ok"), + config_dir, + } + } + + pub fn ensure(&self) -> std::io::Result<()> { + std::fs::create_dir_all(&self.config_dir)?; + std::fs::create_dir_all(&self.profile_dir)?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&self.config_dir, std::fs::Permissions::from_mode(0o700)); + let _ = std::fs::set_permissions(&self.profile_dir, std::fs::Permissions::from_mode(0o700)); + } + Ok(()) + } + + pub fn has_session(&self) -> bool { + self.marker_path.is_file() + || self.profile_dir.join("Default").is_dir() + || self.profile_dir.join("Cookies").is_file() + } +} + +pub fn dry_run() -> bool { + matches!(std::env::var("ICLOUD_NOTES_DRY_RUN").as_deref(), Ok("1")) +} + +pub fn notes_url() -> &'static str { + "https://www.icloud.com/notes/" +} diff --git a/src/helpers.rs b/src/helpers.rs new file mode 100644 index 0000000..c6a8163 --- /dev/null +++ b/src/helpers.rs @@ -0,0 +1,142 @@ +//! Pure helpers (no Chromium). + +/// Join title + body the way Apple Notes expects (first line = title). +pub fn format_note_text(title: &str, body: &str) -> String { + match (title.is_empty(), body.is_empty()) { + (true, true) => String::new(), + (false, true) => title.to_string(), + (true, false) => body.to_string(), + (false, false) => format!("{title}\n\n{body}"), + } +} + +pub fn is_apple_auth_url(url: &str) -> bool { + url.contains("idmsa.apple.com") || url.contains("appleid.apple.com") +} + +#[derive(Debug, Default, Clone)] +pub struct LoggedOutSignals { + pub url: String, + pub body_text: String, + pub has_password_field: bool, + pub has_sign_in_control: bool, + pub has_notes_app: bool, +} + +pub fn looks_logged_out(s: &LoggedOutSignals) -> bool { + if is_apple_auth_url(&s.url) { + return true; + } + let t = s.body_text.chars().take(4000).collect::<String>(); + if t.to_ascii_lowercase().contains("sign in to icloud") { + return true; + } + if s.has_password_field { + return true; + } + if s.has_sign_in_control && !s.has_notes_app { + return true; + } + false +} + +pub fn require_create_content(title: &str, body: &str) -> Result<(String, String), String> { + let title = title.to_string(); + let body = body.trim_end().to_string(); + if title.is_empty() && body.is_empty() { + return Err( + "Provide --title and/or --body / --body-file / stdin".to_string(), + ); + } + Ok((title, body)) +} + +/// Conventional Commits 1.0.0 subject line (no regex crate). +pub fn is_conventional_commit_subject(subject: &str) -> bool { + let line = subject.trim(); + let types = [ + "feat", "fix", "docs", "style", "refactor", "perf", "test", "build", "ci", "chore", + "revert", + ]; + let Some((ty, rest)) = line.split_once(':') else { + return false; + }; + if !rest.starts_with(' ') || rest.len() < 2 { + return false; + } + let ty = ty.trim_end_matches('!'); + if let Some((base, scope)) = ty.split_once('(') { + if !types.contains(&base) { + return false; + } + scope.ends_with(')') + && scope.len() > 1 + && scope[..scope.len() - 1] + .chars() + .all(|c| c.is_ascii_alphanumeric() || "/._-".contains(c)) + } else { + types.contains(&ty) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn format_joins_title_body() { + assert_eq!(format_note_text("Hi", "body"), "Hi\n\nbody"); + assert_eq!(format_note_text("Hi", ""), "Hi"); + assert_eq!(format_note_text("", "body"), "body"); + } + + #[test] + fn auth_urls() { + assert!(is_apple_auth_url("https://idmsa.apple.com/appleauth/auth")); + assert!(is_apple_auth_url("https://appleid.apple.com/")); + assert!(!is_apple_auth_url("https://www.icloud.com/notes/")); + } + + #[test] + fn logged_out_signals() { + assert!(looks_logged_out(&LoggedOutSignals { + body_text: "Sign in to iCloud to continue".into(), + ..Default::default() + })); + assert!(looks_logged_out(&LoggedOutSignals { + has_password_field: true, + ..Default::default() + })); + assert!(looks_logged_out(&LoggedOutSignals { + has_sign_in_control: true, + has_notes_app: false, + ..Default::default() + })); + assert!(!looks_logged_out(&LoggedOutSignals { + has_sign_in_control: true, + has_notes_app: true, + ..Default::default() + })); + } + + #[test] + fn create_content_required() { + assert!(require_create_content("", "").is_err()); + let (t, b) = require_create_content("T", "hi\n\n").unwrap(); + assert_eq!(t, "T"); + assert_eq!(b, "hi"); + } + + #[test] + fn conventional_subjects() { + assert!(is_conventional_commit_subject( + "feat: add icloud.com/notes helper and agent skill" + )); + assert!(is_conventional_commit_subject( + "fix: run create/status headless without a visible browser" + )); + assert!(is_conventional_commit_subject("feat(notes): add dry-run")); + assert!(!is_conventional_commit_subject("Added tests")); + assert!(!is_conventional_commit_subject("FIX: caps type")); + } +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..e6752a2 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,3 @@ +pub mod browser; +pub mod config; +pub mod helpers; diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..ccd21e2 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,176 @@ +use std::io::{self, Read}; +use std::path::PathBuf; +use std::process::ExitCode; + +use anyhow::{bail, Context, Result}; +use clap::{Parser, Subcommand}; + +use icloud_note::browser; +use icloud_note::config::{dry_run, Paths}; +use icloud_note::helpers::{format_note_text, require_create_content}; + +#[derive(Parser, Debug)] +#[command( + name = "icloud-note", + about = "Create Apple Notes from Linux via icloud.com/notes", + long_about = "create/status always run headless (no window).\n\ + login is the only command that opens a visible browser." +)] +struct Cli { + #[command(subcommand)] + cmd: Option<Command>, +} + +#[derive(Subcommand, Debug)] +enum Command { + /// Install Chromium deps + install this binary to ~/.local/bin + Setup, + /// Headless check that the saved session can open Notes + Status, + /// One-time Apple ID sign-in (visible browser) + Login, + /// Headless create a note + Create { + /// Note title (or positional) + #[arg(long)] + title: Option<String>, + /// Note body text + #[arg(long)] + body: Option<String>, + /// Read body from file (`-` = stdin) + #[arg(long = "body-file")] + body_file: Option<PathBuf>, + /// Positional title fallback + #[arg(value_name = "TITLE")] + positional_title: Option<String>, + }, +} + +#[tokio::main] +async fn main() -> ExitCode { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn")), + ) + .with_writer(std::io::stderr) + .init(); + + match run().await { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("{e:#}"); + ExitCode::FAILURE + } + } +} + +async fn run() -> Result<()> { + let cli = Cli::parse(); + let paths = Paths::resolve(); + + let Some(cmd) = cli.cmd else { + print_help(&paths); + return Ok(()); + }; + + match cmd { + Command::Setup => run_setup(), + Command::Status => { + if dry_run() { + if !paths.has_session() { + bail!("not ready: No saved session. Run: icloud-note login"); + } + println!("ok: dry-run status (would check Notes headless)"); + return Ok(()); + } + browser::cmd_status(&paths) + .await + .map_err(|e| anyhow::anyhow!("not ready: {e}")) + } + Command::Login => { + if dry_run() { + bail!("login dry-run: would open a visible browser (refusing)"); + } + browser::cmd_login(&paths).await + } + Command::Create { + title, + body, + body_file, + positional_title, + } => { + let title = title.or(positional_title).unwrap_or_default(); + let body_raw = read_body(body, body_file)?; + let (title, body) = require_create_content(&title, &body_raw) + .map_err(|e| anyhow::anyhow!(e))?; + if dry_run() { + let text = format_note_text(&title, &body); + println!( + "dry-run: would create note title={} chars={}", + serde_json::to_string(&title)?, + text.len() + ); + return Ok(()); + } + browser::cmd_create(&paths, &title, &body).await + } + } +} + +fn read_body(body: Option<String>, body_file: Option<PathBuf>) -> Result<String> { + if let Some(path) = body_file { + if path.as_os_str() == "-" { + let mut s = String::new(); + io::stdin().read_to_string(&mut s)?; + return Ok(s); + } + return Ok(std::fs::read_to_string(&path) + .with_context(|| format!("read body-file {}", path.display()))?); + } + if let Some(b) = body { + return Ok(b); + } + if !atty_stdin() { + let mut s = String::new(); + io::stdin().read_to_string(&mut s)?; + return Ok(s); + } + Ok(String::new()) +} + +fn atty_stdin() -> bool { + // avoid libc dep: treat non-tty as piped when `isatty` unavailable via std + std::io::IsTerminal::is_terminal(&io::stdin()) +} + +fn print_help(paths: &Paths) { + println!( + "Usage: + icloud-note setup + icloud-note status + icloud-note login # only command that opens a visible browser + icloud-note create --title TITLE [--body TEXT | --body-file PATH|-] + +Config: {} +Profile: {} +create/status always run headless (no window). +", + paths.config_dir.display(), + paths.profile_dir.display() + ); +} + +fn run_setup() -> Result<()> { + let script = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("scripts/setup.sh"); + if !script.is_file() { + bail!("setup.sh not found at {}", script.display()); + } + let status = std::process::Command::new(&script) + .status() + .with_context(|| format!("run {}", script.display()))?; + if !status.success() { + bail!("setup.sh failed with {status}"); + } + Ok(()) +} |
