-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync_notes.py
More file actions
executable file
·871 lines (699 loc) · 27.3 KB
/
sync_notes.py
File metadata and controls
executable file
·871 lines (699 loc) · 27.3 KB
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
#!/usr/bin/env python3
"""
Sync Windows Sticky Notes to iOS Notes via Gmail IMAP.
Reads notes from the Microsoft Graph API (cloud) or local SQLite database,
and pushes them as IMAP messages to Gmail's "Notes" folder, which syncs
to the iOS Notes app when Gmail is configured with Notes enabled.
"""
import argparse
import glob
import imaplib
import json
import os
import re
import shutil
import sqlite3
import subprocess
import sys
import time
import urllib.request
from email.message import EmailMessage
from email.utils import formatdate
from html.parser import HTMLParser
from pathlib import Path
SCRIPT_DIR = Path(__file__).parent.resolve()
CONFIG_PATH = SCRIPT_DIR / "config.json"
SYNC_STATE_PATH = SCRIPT_DIR / "sync_state.json"
DELTA_LINK_PATH = SCRIPT_DIR / "delta_link.json"
MS_TOKEN_CACHE_PATH = SCRIPT_DIR / "ms_token_cache.json"
HEARTBEAT_PATH = SCRIPT_DIR / "heartbeat.json"
WATCH_LOG_PATH = SCRIPT_DIR / "watch.log"
NOTIFY_COOLDOWN_SEC = 3600
WATCH_LOG_MAX_BYTES = 1_000_000
WATCH_LOG_KEEP_LINES = 500
WATCH_LOG_ROTATE_EVERY = 200 # loop cycles
IMAP_TIMEOUT_SEC = 30
class AuthError(Exception):
"""Raised when authentication with a remote service fails in a way
that requires human action (e.g. expired MS refresh token, revoked
Gmail app password). Callers should treat as non-transient."""
GRAPH_SCOPES = ["Mail.Read"]
GRAPH_AUTHORITY = "https://login.microsoftonline.com/consumers"
GRAPH_NOTES_URL = "https://graph.microsoft.com/v1.0/me/mailfolders/notes/messages"
GRAPH_NOTES_DELTA_URL = "https://graph.microsoft.com/v1.0/me/mailfolders/notes/messages/delta"
STICKY_NOTES_GLOB = (
"/mnt/c/Users/*/AppData/Local/Packages/"
"Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe/LocalState/plum.sqlite"
)
# ---------------------------------------------------------------------------
# Config & state helpers
# ---------------------------------------------------------------------------
def load_config():
"""Load credentials from config.json."""
if not CONFIG_PATH.exists():
print(f"Error: Config file not found at {CONFIG_PATH}")
print()
print("Create config.json from config.example.json and fill in your values.")
print("See config.example.json for the required fields.")
sys.exit(1)
with open(CONFIG_PATH) as f:
config = json.load(f)
config.setdefault("imap_server", "imap.gmail.com")
config.setdefault("imap_port", 993)
return config
def require_config_keys(config, keys):
"""Check that required keys are present and non-placeholder in config."""
for key in keys:
val = config.get(key, "")
if not val or val.startswith("xxxx") or val.startswith("YOUR"):
print(f"Error: '{key}' in config.json is not set.")
sys.exit(1)
def load_sync_state():
"""Load sync state tracking which notes have been synced."""
if SYNC_STATE_PATH.exists():
with open(SYNC_STATE_PATH) as f:
return json.load(f)
return {}
def save_sync_state(state):
"""Save sync state to disk."""
with open(SYNC_STATE_PATH, "w") as f:
json.dump(state, f, indent=2)
# ---------------------------------------------------------------------------
# Microsoft Graph API (cloud source)
# ---------------------------------------------------------------------------
def get_msal_app(config):
"""Create an MSAL PublicClientApplication with token caching."""
import msal
require_config_keys(config, ["ms_client_id"])
cache = msal.SerializableTokenCache()
if MS_TOKEN_CACHE_PATH.exists():
cache.deserialize(MS_TOKEN_CACHE_PATH.read_text())
app = msal.PublicClientApplication(
config["ms_client_id"],
authority=GRAPH_AUTHORITY,
token_cache=cache,
)
return app, cache
def save_token_cache(cache):
"""Persist the MSAL token cache if it changed."""
if cache.has_state_changed:
MS_TOKEN_CACHE_PATH.write_text(cache.serialize())
def ms_authenticate(config, force_login=False, silent_only=False):
"""Authenticate with Microsoft and return an access token.
If silent_only is True, refuses to prompt for interactive login and
raises AuthError when the refresh token cannot be used silently —
appropriate for background daemons where no one is at a terminal.
"""
app, cache = get_msal_app(config)
result = None
if not force_login:
accounts = app.get_accounts()
if accounts:
result = app.acquire_token_silent(GRAPH_SCOPES, account=accounts[0])
if not result:
if silent_only:
raise AuthError(
"Microsoft refresh token is invalid or expired. "
"Run: python sync_notes.py login"
)
flow = app.initiate_device_flow(scopes=GRAPH_SCOPES)
if "user_code" not in flow:
raise AuthError(
f"Could not initiate MS device flow: "
f"{flow.get('error_description', flow)}"
)
print()
print(flow["message"])
print()
result = app.acquire_token_by_device_flow(flow)
save_token_cache(cache)
if "access_token" not in result:
raise AuthError(
f"Microsoft authentication failed: "
f"{result.get('error_description', result)}"
)
return result["access_token"]
def graph_api_get(url, access_token):
"""Make an authenticated GET request to the Microsoft Graph API."""
req = urllib.request.Request(url)
req.add_header("Authorization", f"Bearer {access_token}")
req.add_header("Accept", "application/json")
with urllib.request.urlopen(req) as resp:
return json.loads(resp.read().decode("utf-8"))
class _HTMLTextExtractor(HTMLParser):
"""Simple HTML to plain text converter."""
def __init__(self):
super().__init__()
self._pieces = []
self._skip = False
def handle_starttag(self, tag, attrs):
if tag in ("br",):
self._pieces.append("\n")
elif tag in ("p", "div", "li"):
if self._pieces and not self._pieces[-1].endswith("\n"):
self._pieces.append("\n")
elif tag in ("style", "script"):
self._skip = True
def handle_endtag(self, tag):
if tag in ("style", "script"):
self._skip = False
elif tag in ("p", "div"):
self._pieces.append("\n")
def handle_data(self, data):
if not self._skip:
self._pieces.append(data)
def get_text(self):
text = "".join(self._pieces)
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()
def html_to_text(html):
"""Convert HTML body content to plain text."""
parser = _HTMLTextExtractor()
parser.feed(html)
return parser.get_text()
def read_notes_from_graph(config, silent_only=False):
"""Fetch Sticky Notes from Microsoft Graph API."""
access_token = ms_authenticate(config, silent_only=silent_only)
print("Fetching notes from Microsoft Graph API...")
notes = []
url = GRAPH_NOTES_URL + "?$top=100&$select=id,subject,body,createdDateTime,lastModifiedDateTime"
while url:
data = graph_api_get(url, access_token)
for msg in data.get("value", []):
body_html = msg.get("body", {}).get("content", "")
text = html_to_text(body_html)
notes.append({
"id": msg["id"],
"text": text,
"created_at": msg.get("createdDateTime", ""),
"updated_at": msg.get("lastModifiedDateTime", ""),
})
url = data.get("@odata.nextLink")
return notes
def load_delta_link():
"""Load the saved delta link for incremental change detection."""
if DELTA_LINK_PATH.exists():
with open(DELTA_LINK_PATH) as f:
return json.load(f).get("delta_link")
return None
def save_delta_link(link):
"""Save the delta link for next incremental check."""
with open(DELTA_LINK_PATH, "w") as f:
json.dump({"delta_link": link}, f)
def graph_delta_check(config, silent_only=False):
"""Use Graph API delta queries to check for changes since last check.
Returns (has_changes, new_delta_link). On the first call, fetches all
notes and returns has_changes=True. On subsequent calls, only returns
True if something changed.
"""
access_token = ms_authenticate(config, silent_only=silent_only)
delta_link = load_delta_link()
url = delta_link if delta_link else (
GRAPH_NOTES_DELTA_URL + "?$select=id,subject,lastModifiedDateTime"
)
changes = []
new_delta_link = None
while url:
data = graph_api_get(url, access_token)
changes.extend(data.get("value", []))
# deltaLink means we've consumed all pages — save it for next time
if "@odata.deltaLink" in data:
new_delta_link = data["@odata.deltaLink"]
break
# nextLink means more pages of changes to fetch
url = data.get("@odata.nextLink")
if new_delta_link:
save_delta_link(new_delta_link)
# First run (no saved delta_link) always counts as "changed"
if not delta_link:
return True
return len(changes) > 0
def rotate_watch_log_if_needed():
"""Trim watch.log in place when it grows past WATCH_LOG_MAX_BYTES.
Keeps the last WATCH_LOG_KEEP_LINES lines. Best-effort; failures
never crash the daemon."""
try:
if not WATCH_LOG_PATH.exists():
return
if WATCH_LOG_PATH.stat().st_size < WATCH_LOG_MAX_BYTES:
return
with open(WATCH_LOG_PATH, "r", encoding="utf-8", errors="replace") as f:
lines = f.readlines()
keep = lines[-WATCH_LOG_KEEP_LINES:]
marker = f"--- log rotated at {time.strftime('%Y-%m-%d %H:%M:%S')}, kept last {len(keep)} lines ---\n"
with open(WATCH_LOG_PATH, "w", encoding="utf-8") as f:
f.write(marker)
f.writelines(keep)
except Exception:
pass
def load_heartbeat():
if HEARTBEAT_PATH.exists():
try:
return json.loads(HEARTBEAT_PATH.read_text())
except Exception:
return {}
return {}
def save_heartbeat(hb):
try:
HEARTBEAT_PATH.write_text(json.dumps(hb, indent=2))
except Exception:
pass
def notify_windows(title, message):
"""Fire a Windows 10/11 toast from WSL via powershell.exe. Best-effort."""
safe_title = title.replace('"', "'").replace("\n", " ")
safe_message = message.replace('"', "'").replace("\n", " ")
ps_script = (
'[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType=WindowsRuntime] | Out-Null;'
'[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType=WindowsRuntime] | Out-Null;'
'$tpl = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02);'
'$texts = $tpl.GetElementsByTagName("text");'
f'$texts.Item(0).AppendChild($tpl.CreateTextNode("{safe_title}")) | Out-Null;'
f'$texts.Item(1).AppendChild($tpl.CreateTextNode("{safe_message}")) | Out-Null;'
'$toast = [Windows.UI.Notifications.ToastNotification]::new($tpl);'
'[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("StickyNotesSync").Show($toast);'
)
try:
subprocess.run(
["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", ps_script],
timeout=15,
capture_output=True,
)
except Exception:
pass
def record_success():
"""Update heartbeat on a successful cycle; toast once if recovering."""
hb = load_heartbeat()
was_error = hb.get("error_state", False)
hb["last_success_ts"] = time.time()
hb["error_state"] = False
hb["last_error"] = None
save_heartbeat(hb)
if was_error:
notify_windows(
"Sticky Notes Sync recovered",
"Sync is working again.",
)
def record_error(error, toast_title=None, toast_message=None):
"""Update heartbeat on failure; toast once per NOTIFY_COOLDOWN_SEC."""
hb = load_heartbeat()
now = time.time()
was_error = hb.get("error_state", False)
last_toast_ts = hb.get("last_toast_ts", 0)
hb["last_error"] = str(error)
hb["last_error_ts"] = now
hb["error_state"] = True
should_toast = (not was_error) or (now - last_toast_ts > NOTIFY_COOLDOWN_SEC)
if should_toast and toast_title:
notify_windows(toast_title, toast_message or str(error))
hb["last_toast_ts"] = now
save_heartbeat(hb)
def cmd_watch(config, interval):
"""Run a polling daemon that syncs when changes are detected."""
rotate_watch_log_if_needed()
interactive = sys.stdout.isatty()
print(f"Watching for Sticky Notes changes (polling every {interval}s)...")
print("Press Ctrl+C to stop.\n")
# Initial full sync — silent_only so the daemon never tries device flow.
try:
notes = read_notes_from_graph(config, silent_only=True)
print(f"Found {len(notes)} active sticky note(s).")
sync_state = load_sync_state()
sync_state = sync_to_imap(config, notes, sync_state)
save_sync_state(sync_state)
graph_delta_check(config, silent_only=True)
record_success()
except AuthError as e:
print(f"Initial sync auth failed: {e}")
record_error(
e,
toast_title="Sticky Notes Sync: login needed",
toast_message=str(e),
)
except Exception as e:
print(f"Initial sync failed: {e}")
record_error(e)
cycle = 0
while True:
try:
time.sleep(interval)
cycle += 1
if cycle % WATCH_LOG_ROTATE_EVERY == 0:
rotate_watch_log_if_needed()
has_changes = graph_delta_check(config, silent_only=True)
if not has_changes:
if interactive:
ts = time.strftime("%H:%M:%S")
print(f"[{ts}] No changes detected.")
record_success()
continue
ts = time.strftime("%H:%M:%S")
print(f"[{ts}] Changes detected, syncing...")
notes = read_notes_from_graph(config, silent_only=True)
print(f"Found {len(notes)} active sticky note(s).")
sync_state = load_sync_state()
sync_state = sync_to_imap(config, notes, sync_state)
save_sync_state(sync_state)
record_success()
except KeyboardInterrupt:
print("\nStopping watch.")
break
except AuthError as e:
ts = time.strftime("%H:%M:%S")
print(f"[{ts}] Auth error: {e}")
record_error(
e,
toast_title="Sticky Notes Sync: login needed",
toast_message=str(e),
)
except Exception as e:
ts = time.strftime("%H:%M:%S")
print(f"[{ts}] Error: {e}")
record_error(e)
# Continue watching after transient errors
# ---------------------------------------------------------------------------
# Local SQLite source (fallback)
# ---------------------------------------------------------------------------
def find_sticky_notes_db():
"""Auto-detect the Sticky Notes plum.sqlite database via WSL mount."""
matches = glob.glob(STICKY_NOTES_GLOB)
if not matches:
return None
if len(matches) == 1:
return matches[0]
return max(matches, key=os.path.getmtime)
def strip_sticky_formatting(text):
"""Strip Sticky Notes formatting tags from note text."""
if not text:
return ""
lines = text.split("\n")
cleaned_lines = []
for line in lines:
line = re.sub(r"\\id=[a-zA-Z0-9-]+ ?", "", line)
line = re.sub(r"\\[a-z]+\d* ?", "", line)
line = re.sub(r"<[^>]+>", "", line)
cleaned_lines.append(line)
cleaned = "\n".join(cleaned_lines)
cleaned = cleaned.replace("\r\n", "\n").replace("\r", "\n")
cleaned = re.sub(r"\n{3,}", "\n\n", cleaned)
return cleaned.strip()
def read_notes_from_local(db_path):
"""Read all active notes from the Sticky Notes SQLite database."""
tmp_dir = str(SCRIPT_DIR / ".plum_copy")
os.makedirs(tmp_dir, exist_ok=True)
tmp_db = os.path.join(tmp_dir, "plum.sqlite")
try:
db_dir = os.path.dirname(db_path)
db_name = os.path.basename(db_path)
for suffix in ["", "-shm", "-wal"]:
src = os.path.join(db_dir, db_name + suffix)
if os.path.exists(src):
shutil.copy2(src, os.path.join(tmp_dir, db_name + suffix))
conn = sqlite3.connect(tmp_db)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
tables = {row["name"] for row in cursor.fetchall()}
notes = []
if "Note" in tables:
cursor.execute(
"SELECT * FROM Note WHERE DeletedAt IS NULL OR DeletedAt = ''"
)
for row in cursor.fetchall():
columns = row.keys()
note_id = row["Id"] if "Id" in columns else row["NoteId"]
text = row["Text"] if "Text" in columns else ""
updated = (
row["UpdatedAt"] if "UpdatedAt" in columns
else row["CreatedAt"] if "CreatedAt" in columns
else ""
)
created = row["CreatedAt"] if "CreatedAt" in columns else ""
notes.append({
"id": note_id,
"text": strip_sticky_formatting(text),
"created_at": created,
"updated_at": updated,
})
else:
print(f"Warning: No 'Note' table found. Available tables: {tables}")
conn.close()
return notes
finally:
if os.path.exists(tmp_dir):
shutil.rmtree(tmp_dir)
# ---------------------------------------------------------------------------
# IMAP push (Gmail → iOS Notes)
# ---------------------------------------------------------------------------
SAFE_NOTE_ID_RE = re.compile(r"^[A-Za-z0-9_\-=+/]{1,256}$")
def is_safe_note_id(nid):
"""Accept only IDs consisting of URL/base64-safe chars. Guards against
IMAP-search injection via a maliciously-formed note ID."""
return bool(nid) and bool(SAFE_NOTE_ID_RE.match(nid))
def make_note_subject(text):
"""Extract a subject line from the note text (first line, truncated)."""
if not text:
return "Sticky Note"
first_line = text.split("\n", 1)[0].strip()
if not first_line:
return "Sticky Note"
if len(first_line) > 78:
return first_line[:75] + "..."
return first_line
def build_note_email(note, gmail_address):
"""Build an RFC 2822 email message formatted as an iOS-compatible note."""
msg = EmailMessage()
subject = make_note_subject(note["text"])
body = note["text"] if note["text"] else "(empty note)"
msg["Subject"] = subject
msg["From"] = gmail_address
msg["To"] = gmail_address
msg["Date"] = formatdate(localtime=True)
msg["X-Uniform-Type-Identifier"] = "com.apple.mail-note"
msg["X-Sticky-Note-ID"] = note["id"]
msg.set_content(body)
return msg
def sync_to_imap(config, notes, sync_state, dry_run=False):
"""Push notes to Gmail IMAP Notes folder."""
if not notes and not sync_state:
print("No notes to sync.")
return sync_state
new_count = 0
updated_count = 0
skipped_count = 0
to_sync = []
for note in notes:
prev = sync_state.get(note["id"])
if prev and prev == note["updated_at"]:
skipped_count += 1
continue
is_update = prev is not None
to_sync.append((note, is_update))
if is_update:
updated_count += 1
else:
new_count += 1
current_ids = {note["id"] for note in notes}
deleted_ids = [nid for nid in sync_state if nid not in current_ids]
if not to_sync and not deleted_ids:
print(f"All {skipped_count} notes already synced. Nothing to do.")
return sync_state
print(
f"Found {new_count} new, {updated_count} modified, "
f"{skipped_count} unchanged, {len(deleted_ids)} deleted notes."
)
if dry_run:
print("\n[DRY RUN] Would sync these notes:")
for note, is_update in to_sync:
label = "UPDATE" if is_update else "NEW"
subject = make_note_subject(note["text"])
print(f" [{label}] {subject}")
for nid in deleted_ids:
print(f" [DELETE] {nid[:16]}...")
return sync_state
require_config_keys(config, ["gmail_address", "gmail_app_password"])
print(f"Connecting to {config['imap_server']}:{config['imap_port']}...")
imap = imaplib.IMAP4_SSL(
config["imap_server"],
config["imap_port"],
timeout=IMAP_TIMEOUT_SEC,
)
try:
try:
imap.login(config["gmail_address"], config["gmail_app_password"])
except imaplib.IMAP4.error as e:
raise AuthError(
f"Gmail IMAP login rejected: {e}. "
"App password may have been revoked — regenerate at "
"myaccount.google.com/apppasswords and update config.json."
)
status, folders = imap.list()
folder_names = []
if status == "OK":
for folder_line in folders:
if isinstance(folder_line, bytes):
folder_names.append(folder_line.decode("utf-8", errors="replace"))
notes_folder = "Notes"
has_notes_folder = any("Notes" in f for f in folder_names)
if not has_notes_folder:
print("Creating 'Notes' IMAP folder...")
imap.create(notes_folder)
imap.select(notes_folder)
for nid in deleted_ids:
if not is_safe_note_id(nid):
print(f" Skipping deletion for unsafe note ID: {nid!r}")
continue
status, data = imap.search(
None, f'HEADER X-Sticky-Note-ID "{nid}"'
)
if status == "OK" and data[0]:
for msg_num in data[0].split():
imap.store(msg_num, "+FLAGS", "\\Deleted")
imap.expunge()
print(f" Deleted: {nid[:16]}...")
sync_state.pop(nid, None)
for note, is_update in to_sync:
if is_update:
if not is_safe_note_id(note["id"]):
print(f" Skipping IMAP purge for unsafe note ID: {note['id']!r}")
continue
status, data = imap.search(
None, f'HEADER X-Sticky-Note-ID "{note["id"]}"'
)
if status == "OK" and data[0]:
for msg_num in data[0].split():
imap.store(msg_num, "+FLAGS", "\\Deleted")
imap.expunge()
for note, is_update in to_sync:
msg = build_note_email(note, config["gmail_address"])
msg_bytes = msg.as_bytes()
status, response = imap.append(
notes_folder, None, None, msg_bytes
)
if status == "OK":
label = "Updated" if is_update else "Synced"
subject = make_note_subject(note["text"])
print(f" {label}: {subject}")
sync_state[note["id"]] = note["updated_at"]
else:
subject = make_note_subject(note["text"])
print(f" FAILED: {subject} — {response}")
finally:
try:
imap.close()
except Exception:
pass
imap.logout()
return sync_state
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def cmd_login(config):
"""Handle the 'login' subcommand — authenticate with Microsoft."""
require_config_keys(config, ["ms_client_id"])
ms_authenticate(config, force_login=True)
print("Login successful! Token cached for future use.")
def cmd_list(notes):
"""Handle the --list flag — print notes and exit."""
for i, note in enumerate(notes, 1):
subject = make_note_subject(note["text"])
print(f"\n--- Note {i} (ID: {note['id'][:8]}...) ---")
print(f"Subject: {subject}")
print(f"Updated: {note['updated_at']}")
preview = note["text"][:200]
if len(note["text"]) > 200:
preview += "..."
print(preview)
def main():
parser = argparse.ArgumentParser(
description="Sync Windows Sticky Notes to iOS Notes via Gmail IMAP."
)
parser.add_argument(
"command",
nargs="?",
default="sync",
choices=["sync", "login", "watch"],
help="Command: 'sync' (default), 'login' (authenticate), or 'watch' (polling daemon)",
)
parser.add_argument(
"--source",
choices=["graph", "local"],
default="graph",
help="Note source: 'graph' (Microsoft cloud, default) or 'local' (SQLite DB)",
)
parser.add_argument(
"--db-path",
help="Path to plum.sqlite (for --source local, auto-detected if omitted)",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Show what would be synced without actually pushing to IMAP",
)
parser.add_argument(
"--force",
action="store_true",
help="Re-sync all notes, ignoring previous sync state",
)
parser.add_argument(
"--list",
action="store_true",
dest="list_notes",
help="List all Sticky Notes and exit (no IMAP connection needed)",
)
parser.add_argument(
"--interval",
type=int,
default=120,
help="Polling interval in seconds for 'watch' command (default: 120)",
)
args = parser.parse_args()
config = load_config()
# Login command
if args.command == "login":
cmd_login(config)
return
# Watch command
if args.command == "watch":
cmd_watch(config, args.interval)
return
# Read notes from chosen source
if args.source == "local":
db_path = args.db_path
if not db_path:
db_path = find_sticky_notes_db()
if not db_path:
print("Error: Could not find Sticky Notes database.")
print(f"Searched: {STICKY_NOTES_GLOB}")
print("Use --db-path to specify the location manually.")
sys.exit(1)
if not os.path.exists(db_path):
print(f"Error: Database not found at {db_path}")
sys.exit(1)
print(f"Using local database: {db_path}")
notes = read_notes_from_local(db_path)
else:
notes = read_notes_from_graph(config)
print(f"Found {len(notes)} active sticky note(s).")
if not notes:
return
# List mode
if args.list_notes:
cmd_list(notes)
return
# Sync to IMAP
sync_state = load_sync_state()
if args.force:
print("Force mode: ignoring previous sync state.")
sync_state = {}
sync_state = sync_to_imap(config, notes, sync_state, dry_run=args.dry_run)
if not args.dry_run:
save_sync_state(sync_state)
print("\nSync complete.")
else:
print("\n[DRY RUN] No changes made.")
if __name__ == "__main__":
try:
main()
except AuthError as e:
print(f"Authentication error: {e}", file=sys.stderr)
sys.exit(1)