cueward-adapter-macos 0.3.0

macOS adapter for Cueward with Safari, Notes, Messages, Reminders, Calendar, Screenshot, Clipboard, and OCR integrations.
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
use std::collections::HashMap;

use chrono::{DateTime, Utc};
use urlencoding::decode;

use crate::MacosError;
use crate::notes::{MapAttachment, MapNote, WebPreviewAttachment, WebPreviewNote};

use super::{apple_to_unix_timestamp, normalize_media_title, open_notes_db, since_apple_epoch};

pub(crate) fn load_web_preview_notes(since: DateTime<Utc>) -> Result<Vec<WebPreviewNote>, MacosError> {
    let conn = open_notes_db()?;

    let mut stmt = conn
        .prepare(
            r#"
        SELECT
            COALESCE(
                note.ZMODIFICATIONDATE,
                note.ZMODIFICATIONDATE1,
                attachment.ZMODIFICATIONDATE,
                attachment.ZMODIFICATIONDATE1
            ),
            COALESCE(note.ZTITLE, note.ZTITLE1),
            attachment.ZTITLE,
            attachment.ZURLSTRING
        FROM ZICCLOUDSYNCINGOBJECT AS attachment
        JOIN ZICCLOUDSYNCINGOBJECT AS note
            ON attachment.ZNOTE = note.Z_PK
        WHERE attachment.ZTYPEUTI = 'public.url'
          AND attachment.ZURLSTRING IS NOT NULL
          AND attachment.ZURLSTRING != ''
          AND COALESCE(
                note.ZMODIFICATIONDATE,
                note.ZMODIFICATIONDATE1,
                attachment.ZMODIFICATIONDATE,
                attachment.ZMODIFICATIONDATE1
              ) > ?
        "#,
        )
        .map_err(|err| MacosError::Other(format!("failed to prepare web preview query: {err}")))?;

    let mut rows = stmt
        .query([since_apple_epoch(since)])
        .map_err(|err| MacosError::Other(format!("failed to query web previews: {err}")))?;

    let mut grouped: HashMap<(i64, Option<String>), Vec<WebPreviewAttachment>> = HashMap::new();
    while let Some(row) = rows
        .next()
        .map_err(|err| MacosError::Other(format!("failed to read web preview row: {err}")))?
    {
        let modification_date: f64 = row.get(0).map_err(|err| {
            MacosError::Other(format!("failed to decode web preview modification date: {err}"))
        })?;
        let note_title: Option<String> = row
            .get(1)
            .map_err(|err| MacosError::Other(format!("failed to decode note title: {err}")))?;
        let attachment_title: Option<String> = row.get(2).map_err(|err| {
            MacosError::Other(format!("failed to decode web preview title: {err}"))
        })?;
        let url: String = row.get(3).map_err(|err| {
            MacosError::Other(format!("failed to decode web preview url: {err}"))
        })?;

        let normalized_note_title = normalize_media_title(note_title);
        if is_apple_maps_url(&url)
            && map_attachment_from_row(attachment_title.clone(), normalized_note_title.as_deref(), url.clone())
                .is_some()
        {
            continue;
        }

        let Some(attachment) =
            web_preview_attachment_from_row(attachment_title, normalized_note_title.as_deref(), url)
        else {
            continue;
        };

        let timestamp = apple_to_unix_timestamp(modification_date);
        grouped
            .entry((timestamp, normalized_note_title))
            .or_default()
            .push(attachment);
    }

    Ok(grouped
        .into_iter()
        .map(|((timestamp, title), attachments)| WebPreviewNote {
            timestamp,
            title,
            attachments,
        })
        .collect())
}

pub(crate) fn load_map_notes(since: DateTime<Utc>) -> Result<Vec<MapNote>, MacosError> {
    let conn = open_notes_db()?;

    let mut stmt = conn
        .prepare(
            r#"
        SELECT
            COALESCE(
                note.ZMODIFICATIONDATE,
                note.ZMODIFICATIONDATE1,
                attachment.ZMODIFICATIONDATE,
                attachment.ZMODIFICATIONDATE1
            ),
            COALESCE(note.ZTITLE, note.ZTITLE1),
            attachment.ZTITLE,
            attachment.ZURLSTRING
        FROM ZICCLOUDSYNCINGOBJECT AS attachment
        JOIN ZICCLOUDSYNCINGOBJECT AS note
            ON attachment.ZNOTE = note.Z_PK
        WHERE attachment.ZTYPEUTI = 'public.url'
          AND attachment.ZURLSTRING LIKE '%maps.apple.com/%'
          AND COALESCE(
                note.ZMODIFICATIONDATE,
                note.ZMODIFICATIONDATE1,
                attachment.ZMODIFICATIONDATE,
                attachment.ZMODIFICATIONDATE1
              ) > ?
        "#,
        )
        .map_err(|err| MacosError::Other(format!("failed to prepare map query: {err}")))?;

    let mut rows = stmt
        .query([since_apple_epoch(since)])
        .map_err(|err| MacosError::Other(format!("failed to query maps: {err}")))?;

    let mut grouped: HashMap<(i64, Option<String>), Vec<MapAttachment>> = HashMap::new();
    while let Some(row) = rows
        .next()
        .map_err(|err| MacosError::Other(format!("failed to read map row: {err}")))?
    {
        let modification_date: f64 = row
            .get(0)
            .map_err(|err| MacosError::Other(format!("failed to decode map modification date: {err}")))?;
        let note_title: Option<String> = row
            .get(1)
            .map_err(|err| MacosError::Other(format!("failed to decode map note title: {err}")))?;
        let attachment_title: Option<String> = row
            .get(2)
            .map_err(|err| MacosError::Other(format!("failed to decode map title: {err}")))?;
        let url: String = row
            .get(3)
            .map_err(|err| MacosError::Other(format!("failed to decode map url: {err}")))?;

        let normalized_note_title = normalize_media_title(note_title);
        let Some(attachment) =
            map_attachment_from_row(attachment_title, normalized_note_title.as_deref(), url)
        else {
            continue;
        };

        let timestamp = apple_to_unix_timestamp(modification_date);
        grouped
            .entry((timestamp, normalized_note_title))
            .or_default()
            .push(attachment);
    }

    Ok(grouped
        .into_iter()
        .map(|((timestamp, title), attachments)| MapNote {
            timestamp,
            title,
            attachments,
        })
        .collect())
}

fn preferred_web_preview_title(
    attachment_title: Option<String>,
    note_title: Option<&str>,
    url: &str,
) -> Option<String> {
    normalize_media_title(attachment_title)
        .or_else(|| normalize_media_title(note_title.map(str::to_string)))
        .or_else(|| {
            let trimmed = url.trim();
            if trimmed.is_empty() {
                None
            } else {
                Some(trimmed.to_string())
            }
        })
}

fn web_preview_attachment_from_row(
    attachment_title: Option<String>,
    note_title: Option<&str>,
    url: String,
) -> Option<WebPreviewAttachment> {
    let url = url.trim().to_string();
    if url.is_empty() {
        return None;
    }

    Some(WebPreviewAttachment {
        title: preferred_web_preview_title(attachment_title, note_title, &url),
        url,
    })
}

fn preferred_map_title(
    attachment_title: Option<String>,
    note_title: Option<&str>,
    url_name: Option<&str>,
) -> Option<String> {
    normalize_media_title(attachment_title)
        .or_else(|| normalize_media_title(url_name.map(str::to_string)))
        .or_else(|| normalize_media_title(note_title.map(str::to_string)))
}

fn is_apple_maps_url(url: &str) -> bool {
    url.contains("maps.apple.com/")
}

fn parse_map_coordinate(url: &str) -> Option<(f64, f64)> {
    let query = url.split('#').next()?.split('?').nth(1)?;
    let coordinate = query
        .split('&')
        .find_map(|pair| pair.strip_prefix("coordinate="))?;
    let mut parts = coordinate.split(',');
    let latitude = parts.next()?.parse::<f64>().ok()?;
    let longitude = parts.next()?.parse::<f64>().ok()?;

    if !(-90.0..=90.0).contains(&latitude) || !(-180.0..=180.0).contains(&longitude) {
        return None;
    }

    Some((latitude, longitude))
}

fn parse_map_name(url: &str) -> Option<String> {
    let query = url.split('#').next()?.split('?').nth(1)?;
    let encoded = query
        .split('&')
        .find_map(|pair| pair.strip_prefix("name="))?;
    let decoded = decode(encoded).ok()?;
    let trimmed = decoded.trim();
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_string())
    }
}

fn map_attachment_from_row(
    attachment_title: Option<String>,
    note_title: Option<&str>,
    url: String,
) -> Option<MapAttachment> {
    if !is_apple_maps_url(&url) {
        return None;
    }

    let (latitude, longitude) = parse_map_coordinate(&url)?;
    let title = preferred_map_title(attachment_title, note_title, parse_map_name(&url).as_deref());

    Some(MapAttachment {
        title,
        url: Some(url),
        latitude,
        longitude,
    })
}

#[cfg(test)]
mod tests {
    use chrono::{TimeZone, Utc};
    use rusqlite::Connection;

    use crate::notes::db::test_support::with_temp_home;

    use super::{
        load_map_notes, load_web_preview_notes, map_attachment_from_row, preferred_map_title,
        preferred_web_preview_title, web_preview_attachment_from_row,
    };

    fn seed_note_store(
        home: &std::path::Path,
        note_title: &str,
        attachment_title: &str,
        url: &str,
    ) {
        let notes_dir = home.join("Library/Group Containers/group.com.apple.notes");
        std::fs::create_dir_all(&notes_dir).expect("create notes dir");
        let db_path = notes_dir.join("NoteStore.sqlite");
        let conn = Connection::open(db_path).expect("open sqlite");
        conn.execute_batch(
            &format!(
                r#"
                CREATE TABLE ZICCLOUDSYNCINGOBJECT (
                    Z_PK INTEGER PRIMARY KEY,
                    ZMODIFICATIONDATE REAL,
                    ZMODIFICATIONDATE1 REAL,
                    ZTITLE TEXT,
                    ZTITLE1 TEXT,
                    ZNOTE INTEGER,
                    ZTYPEUTI TEXT,
                    ZURLSTRING TEXT
                );

                INSERT INTO ZICCLOUDSYNCINGOBJECT (Z_PK, ZTITLE, ZMODIFICATIONDATE1)
                VALUES (1, '{note_title}', 1000.0);

                INSERT INTO ZICCLOUDSYNCINGOBJECT (
                    Z_PK, ZNOTE, ZTYPEUTI, ZTITLE, ZURLSTRING, ZMODIFICATIONDATE
                )
                VALUES (
                    2, 1, 'public.url', '{attachment_title}', '{url}', 999.0
                );
                "#
            ),
        )
        .expect("seed sqlite");
    }

    #[test]
    fn preferred_web_preview_title_prefers_attachment_then_note_then_url() {
        assert_eq!(
            preferred_web_preview_title(
                Some("Cursor Docs".into()),
                Some("Working with Context"),
                "https://docs.cursor.com/guides/working-with-context",
            ),
            Some("Cursor Docs".into())
        );
        assert_eq!(
            preferred_web_preview_title(
                None,
                Some("Working with Context"),
                "https://docs.cursor.com/guides/working-with-context",
            ),
            Some("Working with Context".into())
        );
        assert_eq!(
            preferred_web_preview_title(
                None,
                None,
                "https://docs.cursor.com/guides/working-with-context",
            ),
            Some("https://docs.cursor.com/guides/working-with-context".into())
        );
    }

    #[test]
    fn web_preview_attachment_from_row_ignores_empty_url() {
        assert_eq!(
            web_preview_attachment_from_row(
                Some("Cursor Docs".into()),
                Some("Working with Context"),
                "   ".into(),
            ),
            None
        );
    }

    #[test]
    fn web_preview_attachment_from_row_builds_structured_attachment() {
        let attachment = web_preview_attachment_from_row(
            Some("Cursor Docs".into()),
            Some("Working with Context"),
            "https://docs.cursor.com/guides/working-with-context".into(),
        )
        .expect("attachment");

        assert_eq!(attachment.title.as_deref(), Some("Cursor Docs"));
        assert_eq!(
            attachment.url,
            "https://docs.cursor.com/guides/working-with-context"
        );
    }

    #[test]
    fn preferred_map_title_prefers_attachment_then_url_name_then_note() {
        assert_eq!(
            preferred_map_title(
                Some("屏東縣立棒球場".into()),
                Some("備忘錄標題"),
                Some("地圖上的名稱")
            ),
            Some("屏東縣立棒球場".into())
        );
        assert_eq!(
            preferred_map_title(None, Some("備忘錄標題"), Some("地圖上的名稱")),
            Some("地圖上的名稱".into())
        );
        assert_eq!(
            preferred_map_title(None, Some("備忘錄標題"), None),
            Some("備忘錄標題".into())
        );
    }

    #[test]
    fn map_attachment_from_row_parses_coordinate_and_name() {
        let attachment = map_attachment_from_row(
            Some("屏東縣立棒球場".into()),
            Some("新增備忘錄"),
            "https://maps.apple.com/place?address=900044%E5%8F%B0%E7%81%A3%E5%B1%8F%E6%9D%B1%E7%B8%A3%E5%B1%8F%E6%9D%B1%E5%B8%82%E6%A3%92%E7%90%83%E8%B7%AF1%E8%99%9F&coordinate=22.657349,120.485956&name=%E5%B1%8F%E6%9D%B1%E7%B8%A3%E7%AB%8B%E6%A3%92%E7%90%83%E5%A0%B4&place-id=I3A6B061B285192F6".into(),
        )
        .expect("map attachment");

        assert_eq!(attachment.title.as_deref(), Some("屏東縣立棒球場"));
        assert_eq!(attachment.url.as_deref(), Some("https://maps.apple.com/place?address=900044%E5%8F%B0%E7%81%A3%E5%B1%8F%E6%9D%B1%E7%B8%A3%E5%B1%8F%E6%9D%B1%E5%B8%82%E6%A3%92%E7%90%83%E8%B7%AF1%E8%99%9F&coordinate=22.657349,120.485956&name=%E5%B1%8F%E6%9D%B1%E7%B8%A3%E7%AB%8B%E6%A3%92%E7%90%83%E5%A0%B4&place-id=I3A6B061B285192F6"));
        assert_eq!(attachment.latitude, 22.657349);
        assert_eq!(attachment.longitude, 120.485956);
    }

    #[test]
    fn map_attachment_from_row_ignores_non_map_urls() {
        assert_eq!(
            map_attachment_from_row(
                Some("Cursor Docs".into()),
                Some("Working with Context"),
                "https://docs.cursor.com/guides/working-with-context".into(),
            ),
            None
        );
    }

    #[test]
    fn map_attachment_from_row_rejects_out_of_range_coordinates() {
        assert_eq!(
            map_attachment_from_row(
                Some("Bad Place".into()),
                Some("新增備忘錄"),
                "https://maps.apple.com/place?coordinate=123.0,456.0&name=Bad".into(),
            ),
            None
        );
    }

    #[test]
    fn map_attachment_from_row_handles_url_fragment() {
        let attachment = map_attachment_from_row(
            Some("屏東縣立棒球場".into()),
            Some("新增備忘錄"),
            "https://maps.apple.com/place?coordinate=22.657349,120.485956&name=%E5%B1%8F%E6%9D%B1%E7%B8%A3%E7%AB%8B%E6%A3%92%E7%90%83%E5%A0%B4#label".into(),
        )
        .expect("map attachment with fragment");

        assert_eq!(attachment.latitude, 22.657349);
        assert_eq!(attachment.longitude, 120.485956);
        assert_eq!(attachment.title.as_deref(), Some("屏東縣立棒球場"));
    }

    #[test]
    fn load_web_preview_notes_uses_note_ztitle_when_ztitle1_missing() {
        with_temp_home(|home| {
            seed_note_store(
                home,
                "note title from ztitle",
                "Cursor Docs",
                "https://docs.cursor.com/guides/working-with-context",
            );
            let since = Utc
                .timestamp_opt(978_307_200 + 900, 0)
                .single()
                .expect("since");

            let notes = load_web_preview_notes(since).expect("load web previews");

            assert_eq!(notes.len(), 1);
            assert_eq!(notes[0].title.as_deref(), Some("note title from ztitle"));
        });
    }

    #[test]
    fn load_map_notes_uses_note_ztitle_when_ztitle1_missing() {
        with_temp_home(|home| {
            seed_note_store(
                home,
                "map note title from ztitle",
                "屏東縣立棒球場",
                "https://maps.apple.com/place?coordinate=22.657349,120.485956&name=%E5%B1%8F%E6%9D%B1%E7%B8%A3%E7%AB%8B%E6%A3%92%E7%90%83%E5%A0%B4",
            );
            let since = Utc
                .timestamp_opt(978_307_200 + 900, 0)
                .single()
                .expect("since");

            let notes = load_map_notes(since).expect("load maps");

            assert_eq!(notes.len(), 1);
            assert_eq!(notes[0].title.as_deref(), Some("map note title from ztitle"));
        });
    }
}