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
|
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(())
}
|