diff options
Diffstat (limited to 'scripts')
| -rwxr-xr-x | scripts/icloud-note.mjs | 334 | ||||
| -rwxr-xr-x | scripts/setup.sh | 36 |
2 files changed, 370 insertions, 0 deletions
diff --git a/scripts/icloud-note.mjs b/scripts/icloud-note.mjs new file mode 100755 index 0000000..13a6efd --- /dev/null +++ b/scripts/icloud-note.mjs @@ -0,0 +1,334 @@ +#!/usr/bin/env node +/** + * Create Apple Notes via https://www.icloud.com/notes using a persistent + * Playwright Chromium profile under ~/.config/icloud-notes/ + */ +import { createRequire } from "node:module"; +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { parseArgs } from "node:util"; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const CONFIG_DIR = + process.env.ICLOUD_NOTES_CONFIG || + path.join(os.homedir(), ".config", "icloud-notes"); +const PROFILE_DIR = path.join(CONFIG_DIR, "browser-profile"); +const NOTES_URL = "https://www.icloud.com/notes/"; + +function die(msg, code = 1) { + console.error(msg); + process.exit(code); +} + +function ensureConfigDir() { + fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 }); + fs.mkdirSync(PROFILE_DIR, { recursive: true, mode: 0o700 }); +} + +function loadPlaywright() { + const require = createRequire(path.join(CONFIG_DIR, "package.json")); + try { + return require("playwright"); + } catch { + die( + `Playwright not installed. Run:\n ${path.join(__dirname, "setup.sh")}`, + ); + } +} + +async function withNotesContext({ headed, fn }) { + ensureConfigDir(); + const { chromium } = loadPlaywright(); + const context = await chromium.launchPersistentContext(PROFILE_DIR, { + headless: !headed, + viewport: { width: 1280, height: 900 }, + args: ["--disable-blink-features=AutomationControlled"], + }); + try { + const page = + context.pages()[0] || (await context.newPage()); + return await fn(page, context); + } finally { + await context.close(); + } +} + +async function pageLooksLoggedOut(page) { + const url = page.url(); + if (/idmsa\.apple\.com|appleid\.apple\.com/i.test(url)) return true; + return page.evaluate(() => { + const t = (document.body?.innerText || "").slice(0, 4000); + if (/Sign in to iCloud/i.test(t)) return true; + if ( + document.querySelector( + 'input[type="password"], #password_text_field, #account_name_text_field', + ) + ) { + return true; + } + // Prominent Sign In control without Notes app loaded + const signIn = [...document.querySelectorAll("a,button,div[role='button']")].some( + (el) => /^sign in$/i.test((el.textContent || "").trim()), + ); + const hasNotes = Boolean( + document.querySelector("iframe")?.contentWindow?.NotesApp?.dataManager, + ); + return signIn && !hasNotes; + }).catch(() => false); +} + +async function waitForNotesApp(page, { timeoutMs = 120_000, allowLoginWait = false } = {}) { + await page.goto(NOTES_URL, { waitUntil: "domcontentloaded", timeout: 60_000 }); + const deadline = Date.now() + timeoutMs; + let sawLogin = false; + while (Date.now() < deadline) { + const ready = await page.evaluate(() => { + const iframe = document.querySelector("iframe"); + const w = iframe?.contentWindow; + return Boolean(w?.NotesApp?.dataManager); + }).catch(() => false); + if (ready) return; + + if (await pageLooksLoggedOut(page)) { + sawLogin = true; + if (!allowLoginWait) { + throw new Error("Not signed in. Run: icloud-note login"); + } + } + await page.waitForTimeout(1000); + } + throw new Error( + sawLogin + ? "Login did not finish. Complete Apple ID sign-in in the browser window." + : "NotesApp did not become ready. Run: icloud-note login", + ); +} + +async function createViaNotesApp(page, title, body) { + const fullText = [title, body].filter((s) => s != null && String(s).length) + .join("\n\n"); + + return page.evaluate(async (text) => { + 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; + let Note = mv?.selectedNote?.constructor; + if (!Note && dataManager.allNotes?.length) { + Note = dataManager.allNotes[0].constructor; + } + if (!Note?.createNoteWithTitleText) { + throw new Error( + "Could not find Note.createNoteWithTitleText — UI may have changed", + ); + } + + const folder = + mv?.selectedFolder || + dataManager.defaultFolder || + dataManager.inboxFolder || + (Array.isArray(dataManager.folders) ? dataManager.folders[0] : null) || + (dataManager.allFolders && dataManager.allFolders[0]) || + null; + + if (!folder) { + throw new Error("Could not resolve a Notes folder"); + } + + const note = Note.createNoteWithTitleText(text, folder); + dataManager.userDidCreateNote(note); + await note.save(true); + return { + title: String(note.Title || text.split("\n")[0] || "(untitled)"), + recordName: String(note.recordName || note.id || ""), + }; + }, fullText); +} + +async function createViaUiFallback(page, title, body) { + // Last resort: keyboard into the Notes UI + const candidates = [ + 'button[aria-label*="New Note" i]', + 'button[title*="New Note" i]', + 'button[aria-label*="Create" i]', + '[data-testid="new-note"]', + ]; + let clicked = false; + for (const sel of candidates) { + const btn = page.frameLocator("iframe").locator(sel).first(); + if ((await btn.count().catch(() => 0)) > 0) { + await btn.click({ timeout: 5000 }); + clicked = true; + break; + } + } + if (!clicked) { + // try top-level too + for (const sel of candidates) { + const btn = page.locator(sel).first(); + if ((await btn.count().catch(() => 0)) > 0) { + await btn.click({ timeout: 5000 }); + clicked = true; + break; + } + } + } + if (!clicked) { + throw new Error("UI fallback: could not find New Note control"); + } + + const text = [title, body].filter(Boolean).join("\n\n"); + const editable = page + .frameLocator("iframe") + .locator('[contenteditable="true"], [role="textbox"]') + .first(); + await editable.click({ timeout: 10_000 }); + await editable.fill(text); + await page.waitForTimeout(1500); + return { title: title || text.split("\n")[0] || "(untitled)", recordName: "" }; +} + +async function cmdStatus() { + try { + await withNotesContext({ + headed: false, + fn: async (page) => { + await waitForNotesApp(page, { timeoutMs: 20_000 }); + console.log("ok: logged in to icloud.com/notes"); + }, + }); + } catch (err) { + die(`not ready: ${err.message}`); + } +} + +async function cmdLogin() { + if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) { + die("login needs a graphical session (DISPLAY or WAYLAND_DISPLAY)."); + } + console.error("Opening Chromium for Apple ID sign-in…"); + console.error("Sign in, complete 2FA, wait until Notes loads, then return here."); + await withNotesContext({ + headed: true, + fn: async (page) => { + await page.goto(NOTES_URL, { waitUntil: "domcontentloaded" }); + try { + await waitForNotesApp(page, { + timeoutMs: 10 * 60_000, + allowLoginWait: true, + }); + console.log("ok: session saved — you can close the window next time"); + } catch (err) { + die(`login incomplete: ${err.message}`); + } + }, + }); +} + +function readBody(opts) { + if (opts.values["body-file"]) { + const f = opts.values["body-file"]; + if (f === "-") { + return fs.readFileSync(0, "utf8"); + } + return fs.readFileSync(f, "utf8"); + } + if (opts.values.body != null) return String(opts.values.body); + if (!process.stdin.isTTY) { + return fs.readFileSync(0, "utf8"); + } + return ""; +} + +async function cmdCreate(opts) { + const title = opts.values.title || ""; + const body = readBody(opts).replace(/\s+$/, ""); + if (!title && !body) { + die("Provide --title and/or --body / --body-file / stdin"); + } + + const headed = Boolean(opts.values.headed); + await withNotesContext({ + headed, + fn: async (page) => { + await waitForNotesApp(page, { timeoutMs: 90_000 }); + let result; + try { + result = await createViaNotesApp(page, title, body); + } catch (err) { + console.error(`NotesApp path failed (${err.message}); trying UI…`); + result = await createViaUiFallback(page, title, body); + } + // Give CloudKit a moment to flush + await page.waitForTimeout(2000); + console.log( + `created: ${result.title}${result.recordName ? ` (${result.recordName})` : ""}`, + ); + }, + }); +} + +function printHelp() { + console.log(`Usage: + icloud-note setup + icloud-note status + icloud-note login + icloud-note create --title TITLE [--body TEXT | --body-file PATH|-] [--headed] + +Config: ${CONFIG_DIR} +`); +} + +async function main() { + const argv = process.argv.slice(2); + const cmd = argv[0] || "help"; + + if (cmd === "help" || cmd === "-h" || cmd === "--help") { + printHelp(); + return; + } + + if (cmd === "setup") { + const setup = path.join(__dirname, "setup.sh"); + const r = spawnSync(setup, { stdio: "inherit" }); + process.exit(r.status ?? 1); + } + + if (cmd === "status") { + await cmdStatus(); + return; + } + if (cmd === "login") { + await cmdLogin(); + return; + } + if (cmd === "create") { + const opts = parseArgs({ + args: argv.slice(1), + options: { + title: { type: "string" }, + body: { type: "string" }, + "body-file": { type: "string" }, + headed: { type: "boolean", default: false }, + }, + allowPositionals: true, + }); + if (!opts.values.title && opts.positionals[0]) { + opts.values.title = opts.positionals[0]; + } + await cmdCreate(opts); + return; + } + + die(`Unknown command: ${cmd}\nRun: icloud-note help`); +} + +main().catch((err) => die(err.stack || String(err))); diff --git a/scripts/setup.sh b/scripts/setup.sh new file mode 100755 index 0000000..a4a03fa --- /dev/null +++ b/scripts/setup.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Install Playwright + Chromium for icloud-note under ~/.config/icloud-notes +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +CONFIG_DIR="${ICLOUD_NOTES_CONFIG:-$HOME/.config/icloud-notes}" +SKILL_SCRIPT="$REPO_ROOT/scripts/icloud-note.mjs" +BIN="$HOME/.local/bin/icloud-note" +AGENTS_SKILL="$HOME/.agents/skills/iphone-icloud-notes" +CURSOR_SKILL="$HOME/.cursor/skills/iphone-icloud-notes" + +mkdir -p "$CONFIG_DIR" "$HOME/.local/bin" "$HOME/.agents/skills" "$HOME/.cursor/skills" +chmod 700 "$CONFIG_DIR" + +cd "$CONFIG_DIR" +if [[ ! -f package.json ]]; then + npm init -y >/dev/null +fi + +npm install playwright@latest +npx playwright install chromium + +cat > "$BIN" <<EOF +#!/usr/bin/env bash +exec node "$SKILL_SCRIPT" "\$@" +EOF +chmod 755 "$BIN" "$SKILL_SCRIPT" "$REPO_ROOT/scripts/setup.sh" + +# Point agent skill dirs at this repo (source of truth) +ln -sfn "$REPO_ROOT" "$AGENTS_SKILL" +ln -sfn "$REPO_ROOT" "$CURSOR_SKILL" + +echo "ok: playwright installed in $CONFIG_DIR" +echo "ok: wrapper $BIN" +echo "ok: skill linked -> $REPO_ROOT" +echo "Next: icloud-note login" |
