summaryrefslogtreecommitdiff
path: root/scripts/icloud-note.mjs
blob: 13a6efd710da5a0905fca1761928ae1ffedadf81 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
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)));