-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeepsync_notes.py
More file actions
4684 lines (3987 loc) · 177 KB
/
keepsync_notes.py
File metadata and controls
4684 lines (3987 loc) · 177 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
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
KeepSync Notes - Professional Note Application with Google Keep Integration
A premium offline-first note manager with Google Keep synchronization.
Features:
- Full offline functionality with local SQLite database
- Google Keep sync via gkeepapi (unofficial API)
- Conflict resolution and sync status tracking
- Rich text editing with markdown support
- Labels/tags organization
- Search and filtering
- Import/Export capabilities
- Professional dark theme UI
"""
# ═══════════════════════════════════════════════════════════════════════════════
# AUTO-INSTALLER - Installs all required dependencies before running
# ═══════════════════════════════════════════════════════════════════════════════
def install_dependencies():
"""
Automatically install all required dependencies.
Runs once at startup before any imports.
"""
import subprocess
import sys
# Define all required packages
REQUIRED_PACKAGES = {
# Package name: (import name, description, required)
"customtkinter": ("customtkinter", "Modern UI framework", True),
"Pillow": ("PIL", "Image processing", True),
"requests": ("requests", "HTTP library", True),
"gkeepapi": ("gkeepapi", "Google Keep sync", False), # Optional
"gpsoauth": ("gpsoauth", "Google auth tokens", False), # Optional, for token generation
"browser-cookie3": ("browser_cookie3", "Browser cookie extraction", False), # Optional
"PyGithub": ("github", "GitHub API client", False), # Optional, for GitHub sync
"google-api-python-client": ("googleapiclient", "Google API client", False), # Optional, for Drive sync
"google-auth-oauthlib": ("google_auth_oauthlib", "Google OAuth", False), # Optional, for Drive sync
}
# Check for tkinter (system package, can't pip install)
try:
import tkinter
except ImportError:
print("=" * 60)
print("ERROR: tkinter is not installed!")
print("=" * 60)
print()
print("tkinter is a system package and must be installed via your")
print("system package manager, not pip.")
print()
print("Install tkinter:")
print(" Ubuntu/Debian: sudo apt install python3-tk")
print(" Fedora: sudo dnf install python3-tkinter")
print(" Arch: sudo pacman -S tk")
print(" macOS: brew install python-tk")
print(" Windows: Reinstall Python with 'tcl/tk' option checked")
print()
sys.exit(1)
missing_required = []
missing_optional = []
# Check which packages need installation
for package, (import_name, description, required) in REQUIRED_PACKAGES.items():
try:
__import__(import_name)
except ImportError:
if required:
missing_required.append((package, description))
else:
missing_optional.append((package, description))
# Install missing packages
if missing_required or missing_optional:
print("=" * 60)
print("KeepSync Notes - Dependency Installer")
print("=" * 60)
print()
all_missing = missing_required + missing_optional
if missing_required:
print(f"Required packages to install: {len(missing_required)}")
for pkg, desc in missing_required:
print(f" • {pkg} - {desc}")
if missing_optional:
print(f"Optional packages to install: {len(missing_optional)}")
for pkg, desc in missing_optional:
print(f" • {pkg} - {desc}")
print()
print("Installing packages...")
print()
for package, description in all_missing:
print(f"Installing {package}...", end=" ", flush=True)
try:
# Try standard install first
result = subprocess.run(
[sys.executable, "-m", "pip", "install", package, "-q"],
capture_output=True,
text=True
)
# If failed, try with --break-system-packages (for externally managed envs)
if result.returncode != 0:
result = subprocess.run(
[sys.executable, "-m", "pip", "install", package,
"--break-system-packages", "-q"],
capture_output=True,
text=True
)
if result.returncode == 0:
print("✓")
else:
print("✗")
if package in [p for p, _ in missing_required]:
print(f" Error: {result.stderr.strip()}")
except Exception as e:
print(f"✗ ({e})")
print()
print("=" * 60)
print("Installation complete! Starting application...")
print("=" * 60)
print()
# Run installer before any imports
install_dependencies()
# ═══════════════════════════════════════════════════════════════════════════════
# IMPORTS
# ═══════════════════════════════════════════════════════════════════════════════
import customtkinter as ctk
from tkinter import messagebox, filedialog
import tkinter as tk
from PIL import Image, ImageDraw, ImageFont
import sqlite3
import json
import hashlib
import threading
import queue
import time
import os
import sys
import re
from datetime import datetime, timezone
from pathlib import Path
from dataclasses import dataclass, field, asdict
from typing import Optional, List, Dict, Any, Callable
from enum import Enum
import webbrowser
import uuid
# Optional: gkeepapi for Google Keep sync
try:
import gkeepapi
GKEEPAPI_AVAILABLE = True
except ImportError:
GKEEPAPI_AVAILABLE = False
# ═══════════════════════════════════════════════════════════════════════════════
# CONFIGURATION & CONSTANTS
# ═══════════════════════════════════════════════════════════════════════════════
APP_NAME = "KeepSync Notes"
APP_VERSION = "1.0.0"
DB_VERSION = 1
# Theme Colors (User's preferred palette)
COLORS = {
"bg_darkest": "#020617", # Main background
"bg_dark": "#0f172a", # Secondary background
"bg_medium": "#1e293b", # Card/panel background
"bg_light": "#334155", # Elevated elements
"bg_hover": "#475569", # Hover states
"accent_green": "#22c55e", # Primary accent
"accent_green_hover": "#16a34a",
"accent_green_dim": "#166534",
"accent_blue": "#60a5fa", # Secondary accent
"accent_blue_hover": "#3b82f6",
"accent_blue_dim": "#1e40af",
"accent_yellow": "#fbbf24", # Warning/pinned
"accent_red": "#ef4444", # Error/delete
"accent_purple": "#a78bfa", # Labels
"accent_cyan": "#22d3ee", # Info
"text_primary": "#f8fafc", # Primary text
"text_secondary": "#94a3b8", # Secondary text
"text_muted": "#64748b", # Muted text
"text_disabled": "#475569", # Disabled text
"border": "#334155", # Borders
"border_light": "#475569", # Light borders
"divider": "#1e293b", # Dividers
"sync_synced": "#22c55e", # Synced status
"sync_pending": "#fbbf24", # Pending sync
"sync_error": "#ef4444", # Sync error
"sync_local": "#60a5fa", # Local only
}
# ═══════════════════════════════════════════════════════════════════════════════
# DATA MODELS
# ═══════════════════════════════════════════════════════════════════════════════
class SyncStatus(Enum):
LOCAL_ONLY = "local_only" # Never synced to Keep
SYNCED = "synced" # In sync with Keep
PENDING_PUSH = "pending_push" # Local changes need pushing
PENDING_PULL = "pending_pull" # Remote changes need pulling
CONFLICT = "conflict" # Conflicting changes
DELETED_REMOTE = "deleted_remote" # Deleted from Keep, kept locally
ERROR = "error" # Sync error
class NoteType(Enum):
NOTE = "note"
CHECKLIST = "checklist"
@dataclass
class ChecklistItem:
text: str
checked: bool = False
id: str = field(default_factory=lambda: str(uuid.uuid4()))
def to_dict(self) -> dict:
return {"id": self.id, "text": self.text, "checked": self.checked}
@classmethod
def from_dict(cls, data: dict) -> "ChecklistItem":
return cls(
id=data.get("id", str(uuid.uuid4())),
text=data.get("text", ""),
checked=data.get("checked", False)
)
@dataclass
class Note:
id: str
title: str
content: str
note_type: NoteType = NoteType.NOTE
checklist_items: List[ChecklistItem] = field(default_factory=list)
labels: List[str] = field(default_factory=list)
pinned: bool = False
archived: bool = False
trashed: bool = False
color: str = ""
# Sync metadata
keep_id: Optional[str] = None
sync_status: SyncStatus = SyncStatus.LOCAL_ONLY
local_modified: Optional[datetime] = None
remote_modified: Optional[datetime] = None
content_hash: str = ""
# Timestamps
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
updated_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
def __post_init__(self):
self.update_hash()
def update_hash(self):
"""Generate content hash for change detection"""
content = f"{self.title}|{self.content}|{json.dumps([i.to_dict() for i in self.checklist_items])}|{self.pinned}|{self.archived}"
self.content_hash = hashlib.md5(content.encode()).hexdigest()
def to_dict(self) -> dict:
return {
"id": self.id,
"title": self.title,
"content": self.content,
"note_type": self.note_type.value,
"checklist_items": [i.to_dict() for i in self.checklist_items],
"labels": self.labels,
"pinned": self.pinned,
"archived": self.archived,
"trashed": self.trashed,
"color": self.color,
"keep_id": self.keep_id,
"sync_status": self.sync_status.value,
"local_modified": self.local_modified.isoformat() if self.local_modified else None,
"remote_modified": self.remote_modified.isoformat() if self.remote_modified else None,
"content_hash": self.content_hash,
"created_at": self.created_at.isoformat(),
"updated_at": self.updated_at.isoformat(),
}
@classmethod
def from_dict(cls, data: dict) -> "Note":
return cls(
id=data["id"],
title=data.get("title", ""),
content=data.get("content", ""),
note_type=NoteType(data.get("note_type", "note")),
checklist_items=[ChecklistItem.from_dict(i) for i in data.get("checklist_items", [])],
labels=data.get("labels", []),
pinned=data.get("pinned", False),
archived=data.get("archived", False),
trashed=data.get("trashed", False),
color=data.get("color", ""),
keep_id=data.get("keep_id"),
sync_status=SyncStatus(data.get("sync_status", "local_only")),
local_modified=datetime.fromisoformat(data["local_modified"]) if data.get("local_modified") else None,
remote_modified=datetime.fromisoformat(data["remote_modified"]) if data.get("remote_modified") else None,
content_hash=data.get("content_hash", ""),
created_at=datetime.fromisoformat(data["created_at"]) if data.get("created_at") else datetime.now(timezone.utc),
updated_at=datetime.fromisoformat(data["updated_at"]) if data.get("updated_at") else datetime.now(timezone.utc),
)
@dataclass
class Label:
id: str
name: str
color: str = ""
keep_id: Optional[str] = None
def to_dict(self) -> dict:
return {"id": self.id, "name": self.name, "color": self.color, "keep_id": self.keep_id}
@classmethod
def from_dict(cls, data: dict) -> "Label":
return cls(
id=data["id"],
name=data["name"],
color=data.get("color", ""),
keep_id=data.get("keep_id")
)
# ═══════════════════════════════════════════════════════════════════════════════
# DATABASE MANAGER
# ═══════════════════════════════════════════════════════════════════════════════
class DatabaseManager:
"""SQLite database manager for local note storage"""
def __init__(self, db_path: str):
self.db_path = db_path
self.conn: Optional[sqlite3.Connection] = None
self._init_db()
def _init_db(self):
"""Initialize database schema"""
os.makedirs(os.path.dirname(self.db_path) or ".", exist_ok=True)
self.conn = sqlite3.connect(self.db_path, check_same_thread=False)
self.conn.row_factory = sqlite3.Row
cursor = self.conn.cursor()
# Notes table
cursor.execute("""
CREATE TABLE IF NOT EXISTS notes (
id TEXT PRIMARY KEY,
title TEXT DEFAULT '',
content TEXT DEFAULT '',
note_type TEXT DEFAULT 'note',
checklist_items TEXT DEFAULT '[]',
labels TEXT DEFAULT '[]',
pinned INTEGER DEFAULT 0,
archived INTEGER DEFAULT 0,
trashed INTEGER DEFAULT 0,
color TEXT DEFAULT '',
keep_id TEXT,
sync_status TEXT DEFAULT 'local_only',
local_modified TEXT,
remote_modified TEXT,
content_hash TEXT DEFAULT '',
created_at TEXT,
updated_at TEXT
)
""")
# Labels table
cursor.execute("""
CREATE TABLE IF NOT EXISTS labels (
id TEXT PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
color TEXT DEFAULT '',
keep_id TEXT
)
""")
# Settings table
cursor.execute("""
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT
)
""")
# Sync log table
cursor.execute("""
CREATE TABLE IF NOT EXISTS sync_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT,
action TEXT,
note_id TEXT,
status TEXT,
message TEXT
)
""")
# Create indexes
cursor.execute("CREATE INDEX IF NOT EXISTS idx_notes_keep_id ON notes(keep_id)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_notes_sync_status ON notes(sync_status)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_notes_pinned ON notes(pinned)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_notes_archived ON notes(archived)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_notes_trashed ON notes(trashed)")
self.conn.commit()
def save_note(self, note: Note) -> bool:
"""Save or update a note"""
try:
cursor = self.conn.cursor()
note.updated_at = datetime.now(timezone.utc)
note.update_hash()
cursor.execute("""
INSERT OR REPLACE INTO notes
(id, title, content, note_type, checklist_items, labels, pinned, archived,
trashed, color, keep_id, sync_status, local_modified, remote_modified,
content_hash, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
note.id, note.title, note.content, note.note_type.value,
json.dumps([i.to_dict() for i in note.checklist_items]),
json.dumps(note.labels), int(note.pinned), int(note.archived),
int(note.trashed), note.color, note.keep_id, note.sync_status.value,
note.local_modified.isoformat() if note.local_modified else None,
note.remote_modified.isoformat() if note.remote_modified else None,
note.content_hash, note.created_at.isoformat(), note.updated_at.isoformat()
))
self.conn.commit()
return True
except Exception as e:
print(f"Error saving note: {e}")
return False
def get_note(self, note_id: str) -> Optional[Note]:
"""Get a note by ID"""
cursor = self.conn.cursor()
cursor.execute("SELECT * FROM notes WHERE id = ?", (note_id,))
row = cursor.fetchone()
if row:
return self._row_to_note(row)
return None
def get_all_notes(self, include_trashed: bool = False, include_archived: bool = False) -> List[Note]:
"""Get all notes with optional filters"""
cursor = self.conn.cursor()
query = "SELECT * FROM notes WHERE 1=1"
if not include_trashed:
query += " AND trashed = 0"
if not include_archived:
query += " AND archived = 0"
query += " ORDER BY pinned DESC, updated_at DESC"
cursor.execute(query)
return [self._row_to_note(row) for row in cursor.fetchall()]
def get_notes_by_label(self, label: str) -> List[Note]:
"""Get notes with a specific label"""
cursor = self.conn.cursor()
cursor.execute(
"SELECT * FROM notes WHERE labels LIKE ? AND trashed = 0 ORDER BY pinned DESC, updated_at DESC",
(f'%"{label}"%',)
)
return [self._row_to_note(row) for row in cursor.fetchall()]
def search_notes(self, query: str) -> List[Note]:
"""Search notes by title or content"""
cursor = self.conn.cursor()
search_term = f"%{query}%"
cursor.execute(
"""SELECT * FROM notes WHERE (title LIKE ? OR content LIKE ?)
AND trashed = 0 ORDER BY pinned DESC, updated_at DESC""",
(search_term, search_term)
)
return [self._row_to_note(row) for row in cursor.fetchall()]
def delete_note(self, note_id: str, permanent: bool = False) -> bool:
"""Delete a note (move to trash or permanent delete)"""
try:
cursor = self.conn.cursor()
if permanent:
cursor.execute("DELETE FROM notes WHERE id = ?", (note_id,))
else:
cursor.execute(
"UPDATE notes SET trashed = 1, updated_at = ? WHERE id = ?",
(datetime.now(timezone.utc).isoformat(), note_id)
)
self.conn.commit()
return True
except Exception as e:
print(f"Error deleting note: {e}")
return False
def restore_note(self, note_id: str) -> bool:
"""Restore a note from trash"""
try:
cursor = self.conn.cursor()
cursor.execute(
"UPDATE notes SET trashed = 0, updated_at = ? WHERE id = ?",
(datetime.now(timezone.utc).isoformat(), note_id)
)
self.conn.commit()
return True
except Exception as e:
print(f"Error restoring note: {e}")
return False
def _row_to_note(self, row: sqlite3.Row) -> Note:
"""Convert database row to Note object"""
return Note(
id=row["id"],
title=row["title"] or "",
content=row["content"] or "",
note_type=NoteType(row["note_type"]) if row["note_type"] else NoteType.NOTE,
checklist_items=[ChecklistItem.from_dict(i) for i in json.loads(row["checklist_items"] or "[]")],
labels=json.loads(row["labels"] or "[]"),
pinned=bool(row["pinned"]),
archived=bool(row["archived"]),
trashed=bool(row["trashed"]),
color=row["color"] or "",
keep_id=row["keep_id"],
sync_status=SyncStatus(row["sync_status"]) if row["sync_status"] else SyncStatus.LOCAL_ONLY,
local_modified=datetime.fromisoformat(row["local_modified"]) if row["local_modified"] else None,
remote_modified=datetime.fromisoformat(row["remote_modified"]) if row["remote_modified"] else None,
content_hash=row["content_hash"] or "",
created_at=datetime.fromisoformat(row["created_at"]) if row["created_at"] else datetime.now(timezone.utc),
updated_at=datetime.fromisoformat(row["updated_at"]) if row["updated_at"] else datetime.now(timezone.utc),
)
# Label operations
def save_label(self, label: Label) -> bool:
try:
cursor = self.conn.cursor()
cursor.execute(
"INSERT OR REPLACE INTO labels (id, name, color, keep_id) VALUES (?, ?, ?, ?)",
(label.id, label.name, label.color, label.keep_id)
)
self.conn.commit()
return True
except Exception as e:
print(f"Error saving label: {e}")
return False
def get_all_labels(self) -> List[Label]:
cursor = self.conn.cursor()
cursor.execute("SELECT * FROM labels ORDER BY name")
return [Label(id=row["id"], name=row["name"], color=row["color"], keep_id=row["keep_id"])
for row in cursor.fetchall()]
def delete_label(self, label_id: str) -> bool:
try:
cursor = self.conn.cursor()
cursor.execute("DELETE FROM labels WHERE id = ?", (label_id,))
self.conn.commit()
return True
except Exception as e:
print(f"Error deleting label: {e}")
return False
# Settings operations
def get_setting(self, key: str, default: Any = None) -> Any:
cursor = self.conn.cursor()
cursor.execute("SELECT value FROM settings WHERE key = ?", (key,))
row = cursor.fetchone()
if row:
try:
return json.loads(row["value"])
except:
return row["value"]
return default
def set_setting(self, key: str, value: Any) -> bool:
try:
cursor = self.conn.cursor()
cursor.execute(
"INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)",
(key, json.dumps(value) if not isinstance(value, str) else value)
)
self.conn.commit()
return True
except Exception as e:
print(f"Error saving setting: {e}")
return False
def log_sync(self, action: str, note_id: str, status: str, message: str):
"""Log sync activity"""
try:
cursor = self.conn.cursor()
cursor.execute(
"INSERT INTO sync_log (timestamp, action, note_id, status, message) VALUES (?, ?, ?, ?, ?)",
(datetime.now(timezone.utc).isoformat(), action, note_id, status, message)
)
self.conn.commit()
except Exception as e:
print(f"Error logging sync: {e}")
def close(self):
if self.conn:
self.conn.close()
# ═══════════════════════════════════════════════════════════════════════════════
# GOOGLE KEEP SYNC ENGINE
# ═══════════════════════════════════════════════════════════════════════════════
class KeepSyncEngine:
"""Google Keep synchronization engine using gkeepapi"""
def __init__(self, db: DatabaseManager):
self.db = db
self.keep: Optional[gkeepapi.Keep] = None if not GKEEPAPI_AVAILABLE else gkeepapi.Keep()
self.is_authenticated = False
self.sync_in_progress = False
self.last_sync: Optional[datetime] = None
self.sync_callbacks: List[Callable] = []
self._sync_thread: Optional[threading.Thread] = None
self._stop_sync = threading.Event()
def add_sync_callback(self, callback: Callable):
"""Add callback for sync status updates"""
self.sync_callbacks.append(callback)
def _notify_callbacks(self, status: str, message: str):
"""Notify all callbacks of sync status change"""
for callback in self.sync_callbacks:
try:
callback(status, message)
except:
pass
def login(self, email: str, master_token: str = None, password: str = None) -> tuple[bool, str]:
"""Authenticate with Google Keep using the new API"""
if not GKEEPAPI_AVAILABLE:
return False, "gkeepapi not installed. Install with: pip install gkeepapi"
try:
# Use the new authenticate() method
if master_token:
# Master token authentication (preferred)
self.keep.authenticate(email, master_token)
elif password:
# Try password auth (may not work with Google's security)
# This typically requires a master token now
try:
self.keep.authenticate(email, password)
except Exception:
return False, (
"Password authentication failed. Google requires a Master Token.\n\n"
"To get your master token:\n"
"1. Click 'Get Master Token' button below\n"
"2. Or run: python keep_sync_notes.py --get-token"
)
else:
return False, "Either master_token or password required"
self.is_authenticated = True
# Save token for future sessions
self.db.set_setting("keep_email", email)
try:
self.db.set_setting("keep_master_token", self.keep.getMasterToken())
except:
pass # Token retrieval may fail on some auth methods
self._notify_callbacks("connected", "Connected to Google Keep")
return True, "Successfully connected to Google Keep"
except Exception as e:
self.is_authenticated = False
error_msg = str(e)
if "BadAuthentication" in error_msg:
return False, (
"Authentication failed. Google requires a Master Token.\n\n"
"App Passwords no longer work with gkeepapi.\n"
"Use the 'Get Master Token' button or run:\n"
" python keep_sync_notes.py --get-token"
)
return False, f"Authentication failed: {error_msg}"
def try_auto_login(self) -> bool:
"""Attempt to login using saved credentials"""
if not GKEEPAPI_AVAILABLE:
return False
email = self.db.get_setting("keep_email")
token = self.db.get_setting("keep_master_token")
if email and token:
try:
self.keep.authenticate(email, token)
self.is_authenticated = True
self._notify_callbacks("connected", "Connected to Google Keep")
return True
except Exception as e:
print(f"Auto-login failed: {e}")
return False
return False
def logout(self):
"""Disconnect from Google Keep"""
self.is_authenticated = False
self.keep = gkeepapi.Keep() if GKEEPAPI_AVAILABLE else None
self.db.set_setting("keep_email", None)
self.db.set_setting("keep_master_token", None)
self._notify_callbacks("disconnected", "Disconnected from Google Keep")
def sync(self, full_sync: bool = False) -> tuple[bool, str, dict]:
"""
Perform synchronization with Google Keep
Returns: (success, message, stats)
"""
if not self.is_authenticated:
return False, "Not authenticated with Google Keep", {}
if self.sync_in_progress:
return False, "Sync already in progress", {}
self.sync_in_progress = True
self._notify_callbacks("syncing", "Synchronizing...")
stats = {"pulled": 0, "pushed": 0, "conflicts": 0, "errors": 0}
try:
# Sync with Google Keep servers
self.keep.sync()
# Pull remote notes
pull_stats = self._pull_from_keep()
stats["pulled"] = pull_stats.get("new", 0) + pull_stats.get("updated", 0)
# Push local changes
push_stats = self._push_to_keep()
stats["pushed"] = push_stats.get("created", 0) + push_stats.get("updated", 0)
# Final sync to commit changes
self.keep.sync()
self.last_sync = datetime.now(timezone.utc)
self.db.set_setting("last_sync", self.last_sync.isoformat())
self._notify_callbacks("synced", f"Synced: ↓{stats['pulled']} ↑{stats['pushed']}")
return True, "Sync completed successfully", stats
except Exception as e:
stats["errors"] += 1
self.db.log_sync("sync", "", "error", str(e))
self._notify_callbacks("error", f"Sync error: {str(e)}")
return False, f"Sync error: {str(e)}", stats
finally:
self.sync_in_progress = False
def _pull_from_keep(self) -> dict:
"""Pull notes from Google Keep to local database"""
stats = {"new": 0, "updated": 0, "skipped": 0}
for keep_note in self.keep.all():
try:
# Find existing local note
cursor = self.db.conn.cursor()
cursor.execute("SELECT * FROM notes WHERE keep_id = ?", (keep_note.id,))
row = cursor.fetchone()
if row:
local_note = self.db._row_to_note(row)
# Check if remote is newer
if keep_note.timestamps.updated > (local_note.remote_modified or datetime.min.replace(tzinfo=timezone.utc)):
# Update local note from remote
local_note = self._keep_note_to_local(keep_note, local_note)
local_note.sync_status = SyncStatus.SYNCED
self.db.save_note(local_note)
stats["updated"] += 1
else:
stats["skipped"] += 1
else:
# Create new local note from Keep
local_note = self._keep_note_to_local(keep_note)
local_note.sync_status = SyncStatus.SYNCED
self.db.save_note(local_note)
stats["new"] += 1
except Exception as e:
self.db.log_sync("pull", keep_note.id, "error", str(e))
return stats
def _push_to_keep(self) -> dict:
"""Push local changes to Google Keep"""
stats = {"created": 0, "updated": 0, "deleted": 0, "errors": 0}
# Get notes that need pushing
cursor = self.db.conn.cursor()
cursor.execute(
"SELECT * FROM notes WHERE sync_status IN (?, ?) AND trashed = 0",
(SyncStatus.PENDING_PUSH.value, SyncStatus.LOCAL_ONLY.value)
)
for row in cursor.fetchall():
local_note = self.db._row_to_note(row)
try:
if local_note.keep_id:
# Update existing Keep note
keep_note = self.keep.get(local_note.keep_id)
if keep_note:
self._update_keep_note(keep_note, local_note)
stats["updated"] += 1
else:
# Create new Keep note
keep_note = self._create_keep_note(local_note)
local_note.keep_id = keep_note.id
stats["created"] += 1
local_note.sync_status = SyncStatus.SYNCED
local_note.remote_modified = datetime.now(timezone.utc)
self.db.save_note(local_note)
except Exception as e:
stats["errors"] += 1
self.db.log_sync("push", local_note.id, "error", str(e))
return stats
def _keep_note_to_local(self, keep_note, existing: Note = None) -> Note:
"""Convert gkeepapi note to local Note object"""
note_id = existing.id if existing else str(uuid.uuid4())
# Determine note type and content
if hasattr(keep_note, 'items') and keep_note.items:
note_type = NoteType.CHECKLIST
checklist_items = [
ChecklistItem(text=item.text, checked=item.checked)
for item in keep_note.items
]
content = ""
else:
note_type = NoteType.NOTE
checklist_items = []
content = keep_note.text or ""
# Get labels
labels = [label.name for label in keep_note.labels.all()]
return Note(
id=note_id,
title=keep_note.title or "",
content=content,
note_type=note_type,
checklist_items=checklist_items,
labels=labels,
pinned=keep_note.pinned,
archived=keep_note.archived,
trashed=keep_note.trashed,
color=str(keep_note.color.value) if keep_note.color else "",
keep_id=keep_note.id,
remote_modified=keep_note.timestamps.updated,
created_at=existing.created_at if existing else (keep_note.timestamps.created or datetime.now(timezone.utc)),
updated_at=datetime.now(timezone.utc),
)
def _create_keep_note(self, local_note: Note):
"""Create a new note in Google Keep"""
if local_note.note_type == NoteType.CHECKLIST:
keep_note = self.keep.createList(
local_note.title,
[(item.text, item.checked) for item in local_note.checklist_items]
)
else:
keep_note = self.keep.createNote(local_note.title, local_note.content)
keep_note.pinned = local_note.pinned
keep_note.archived = local_note.archived
# Add labels
for label_name in local_note.labels:
label = self.keep.findLabel(label_name)
if not label:
label = self.keep.createLabel(label_name)
keep_note.labels.add(label)
return keep_note
def _update_keep_note(self, keep_note, local_note: Note):
"""Update an existing Google Keep note"""
keep_note.title = local_note.title
if local_note.note_type == NoteType.CHECKLIST:
# Update checklist items (simplified - full implementation would be more complex)
keep_note.text = ""
# Note: Updating list items requires more complex handling
else:
keep_note.text = local_note.content
keep_note.pinned = local_note.pinned
keep_note.archived = local_note.archived
def unlink_note(self, note_id: str, delete_from_keep: bool = True) -> bool:
"""
Unlink a note from Google Keep (keep locally, optionally delete from Keep)
"""
note = self.db.get_note(note_id)
if not note:
return False
if delete_from_keep and note.keep_id and self.is_authenticated:
try:
keep_note = self.keep.get(note.keep_id)
if keep_note:
keep_note.delete()
self.keep.sync()
except Exception as e:
self.db.log_sync("unlink", note_id, "error", str(e))
note.keep_id = None
note.sync_status = SyncStatus.LOCAL_ONLY
self.db.save_note(note)
return True
def start_auto_sync(self, interval_minutes: int = 5):
"""Start automatic background sync"""
self._stop_sync.clear()
def sync_loop():
while not self._stop_sync.is_set():
if self.is_authenticated and not self.sync_in_progress:
self.sync()
self._stop_sync.wait(interval_minutes * 60)
self._sync_thread = threading.Thread(target=sync_loop, daemon=True)
self._sync_thread.start()
def stop_auto_sync(self):
"""Stop automatic background sync"""
self._stop_sync.set()
if self._sync_thread:
self._sync_thread.join(timeout=1)
# ═══════════════════════════════════════════════════════════════════════════════
# MASTER TOKEN GENERATOR
# ═══════════════════════════════════════════════════════════════════════════════
def get_master_token_cli():
"""
Command-line utility to get a Google Master Token for gkeepapi.
This is required because Google no longer allows simple password auth.
"""
print("=" * 60)
print("Google Keep Master Token Generator")
print("=" * 60)
print()
print("This will generate a master token for Google Keep sync.")
print("You'll need your Google email and password.")
print()
print("NOTE: If you have 2FA enabled, you need an App Password:")
print(" 1. Go to: https://myaccount.google.com/apppasswords")
print(" 2. Generate a new app password")
print(" 3. Use that password below (not your regular password)")
print()
try:
import gpsoauth
except ImportError:
print("Installing gpsoauth...")
import subprocess
import sys
result = subprocess.run(
[sys.executable, "-m", "pip", "install", "gpsoauth", "--break-system-packages", "-q"],
capture_output=True
)
if result.returncode != 0:
subprocess.run([sys.executable, "-m", "pip", "install", "gpsoauth", "-q"])
import gpsoauth
email = input("Enter your Google email: ").strip()
import getpass
password = getpass.getpass("Enter your password (or App Password if 2FA enabled): ")
# Android device ID (can be any hex string)
android_id = "0123456789abcdef"
print()
print("Authenticating with Google...")
try:
# Perform master login