-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeepsync_notes.py
More file actions
7233 lines (6221 loc) · 279 KB
/
Copy pathkeepsync_notes.py
File metadata and controls
7233 lines (6221 loc) · 279 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
"""
# ═══════════════════════════════════════════════════════════════════════════════
# Dependencies are managed by requirements.txt; the app never installs packages at runtime.
# ═══════════════════════════════════════════════════════════════════════════════
# ═══════════════════════════════════════════════════════════════════════════════
# 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
import shutil
import tempfile
import zipfile
import difflib
import traceback
import importlib.util
import xml.etree.ElementTree as ET
from html.parser import HTMLParser
from html import unescape
from datetime import datetime, timezone
from pathlib import Path
from typing import Optional, List, Dict, Any, Callable
import webbrowser
import uuid
from keepsync_models import (
Attachment,
ChecklistItem,
KEEP_COLOR_ALIASES,
KEEP_COLOR_PALETTE,
Label,
Note,
NoteType,
SyncStatus,
clamp_checklist_indent,
guess_attachment_mime,
keep_color_hex,
keep_color_name,
normalize_keep_color,
normalize_people,
sanitize_filename,
)
from keepsync_cloud_plan import (
build_cloud_sync_plan,
cloud_base_versions,
cloud_plan_counts,
note_data_hash,
save_cloud_conflict_copy,
)
from keepsync_import_safety import (
MAX_IMPORT_FOLDER_BYTES,
MAX_IMPORT_FOLDER_FILES,
MAX_IMPORT_TEXT_MEMBER_BYTES,
MAX_IMPORT_ZIP_MEMBERS,
MAX_IMPORT_ZIP_UNCOMPRESSED_BYTES,
ImportCancelled,
ImportSafetyError,
decode_zip_member,
extract_zip_member_safely,
guarded_import_files,
is_hidden_or_system_path,
safe_zip_member_parts,
validate_zip_members,
)
from keepsync_backups import LocalBackupManager
try:
import keyring
KEYRING_AVAILABLE = True
except ImportError:
keyring = None
KEYRING_AVAILABLE = False
# Optional: gkeepapi for Google Keep sync
try:
import gkeepapi
GKEEPAPI_AVAILABLE = True
except ImportError:
GKEEPAPI_AVAILABLE = False
try:
from plyer import notification as desktop_notification
DESKTOP_NOTIFICATIONS_AVAILABLE = True
except ImportError:
desktop_notification = None
DESKTOP_NOTIFICATIONS_AVAILABLE = False
# ═══════════════════════════════════════════════════════════════════════════════
# CONFIGURATION & CONSTANTS
# ═══════════════════════════════════════════════════════════════════════════════
APP_NAME = "KeepSync Notes"
APP_VERSION = "1.23.0"
DB_VERSION = 1
KEYRING_SERVICE = "KeepSyncNotes"
KEEP_MASTER_TOKEN_CREDENTIAL = "google_keep_master_token"
GDRIVE_OAUTH_TOKEN_CREDENTIAL = "google_drive_oauth_token"
GITHUB_PAT_CREDENTIAL = "github_personal_access_token"
# 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
}
def parse_reminder_datetime(value: str) -> Optional[datetime]:
text = (value or "").strip()
if not text:
return None
candidates = [text, text.replace("T", " ")]
for candidate in candidates:
try:
parsed = datetime.fromisoformat(candidate)
break
except ValueError:
parsed = None
else:
parsed = None
if parsed is None:
for fmt in ("%Y-%m-%d %H:%M", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d"):
try:
parsed = datetime.strptime(text, fmt)
break
except ValueError:
continue
if parsed is None:
raise ValueError("Use YYYY-MM-DD HH:MM for reminders.")
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=datetime.now().astimezone().tzinfo)
return parsed.astimezone(timezone.utc)
def format_reminder_datetime(value: Optional[datetime]) -> str:
if not value:
return ""
return value.astimezone().strftime("%Y-%m-%d %H:%M")
def is_markdown_label(value: Any) -> bool:
"""Return True when a note label enables markdown preview mode."""
return str(value or "").strip().lower() == ".md"
def note_uses_markdown(labels: List[str]) -> bool:
return any(is_markdown_label(label) for label in labels)
def split_inline_markdown(text: str) -> List[Dict[str, str]]:
"""Split a markdown line into display segments with lightweight styles."""
pattern = re.compile(r"(`([^`]+)`|\*\*([^*]+)\*\*|__([^_]+)__|\*([^*]+)\*|_([^_]+)_)")
segments = []
cursor = 0
for match in pattern.finditer(text or ""):
if match.start() > cursor:
segments.append({"text": text[cursor:match.start()], "style": "plain"})
if match.group(2) is not None:
segments.append({"text": match.group(2), "style": "inline_code"})
elif match.group(3) is not None or match.group(4) is not None:
segments.append({"text": match.group(3) or match.group(4), "style": "bold"})
else:
segments.append({"text": match.group(5) or match.group(6), "style": "italic"})
cursor = match.end()
if cursor < len(text or ""):
segments.append({"text": text[cursor:], "style": "plain"})
return segments
def markdown_preview_blocks(markdown_text: str) -> List[Dict[str, Any]]:
"""Convert a conservative markdown subset into styled preview blocks."""
blocks = []
in_code_block = False
for raw_line in (markdown_text or "").splitlines():
stripped = raw_line.strip()
if stripped.startswith("```"):
in_code_block = not in_code_block
continue
if in_code_block:
blocks.append({
"style": "code_block",
"segments": [{"text": raw_line, "style": "plain"}],
})
continue
if not stripped:
blocks.append({"style": "blank", "segments": []})
continue
heading = re.match(r"^(#{1,6})\s+(.+)$", stripped)
if heading:
level = min(len(heading.group(1)), 3)
blocks.append({
"style": f"heading_{level}",
"segments": split_inline_markdown(heading.group(2).strip()),
})
continue
task = re.match(r"^\s*[-*+]\s+\[([ xX])\]\s+(.+)$", raw_line)
if task:
mark = "[x]" if task.group(1).lower() == "x" else "[ ]"
blocks.append({
"style": "task",
"segments": split_inline_markdown(f"{mark} {task.group(2).strip()}"),
})
continue
bullet = re.match(r"^\s*[-*+]\s+(.+)$", raw_line)
if bullet:
blocks.append({
"style": "list_item",
"segments": split_inline_markdown(f"- {bullet.group(1).strip()}"),
})
continue
numbered = re.match(r"^\s*(\d+)[.)]\s+(.+)$", raw_line)
if numbered:
blocks.append({
"style": "list_item",
"segments": split_inline_markdown(f"{numbered.group(1)}. {numbered.group(2).strip()}"),
})
continue
if stripped.startswith(">"):
blocks.append({
"style": "quote",
"segments": split_inline_markdown(stripped.lstrip("> ").strip()),
})
continue
blocks.append({
"style": "paragraph",
"segments": split_inline_markdown(raw_line.strip()),
})
return blocks
def markdown_preview_text(markdown_text: str, limit: int = 150) -> str:
preview_parts = []
for block in markdown_preview_blocks(markdown_text):
text = "".join(segment["text"] for segment in block["segments"]).strip()
if text:
preview_parts.append(text)
preview = " ".join(preview_parts)
return preview[:limit] + ("..." if len(preview) > limit else "")
def extract_shared_with(data: dict) -> List[str]:
shared = []
for key in ("sharees", "collaborators", "contributors", "sharedWith", "sharingUserInfo"):
for person in normalize_people(data.get(key)):
if person not in shared:
shared.append(person)
if not shared and data.get("isShared"):
shared.append("Shared")
return shared
def first_present(data: dict, keys: List[str]) -> str:
for key in keys:
value = data.get(key)
if value:
return str(value)
return ""
def takeout_attachment_specs(data: dict) -> List[dict]:
specs = []
for key in ("attachments", "media", "files", "blobs"):
value = data.get(key)
if isinstance(value, dict):
specs.append(value)
elif isinstance(value, list):
specs.extend([item for item in value if isinstance(item, (dict, str))])
for key in ("drawingInfo", "audio", "image"):
value = data.get(key)
if isinstance(value, dict):
specs.append(value)
return specs
def resolve_takeout_attachment_path(source: str, base_path: Optional[Path]) -> Optional[Path]:
if not source or re.match(r"^[a-z]+://", source, re.IGNORECASE):
return None
source_path = Path(source)
candidates = [source_path]
if base_path:
candidates.extend([
base_path / source_path,
base_path / source_path.name,
base_path.parent / source_path,
])
for candidate in candidates:
try:
if candidate.exists():
return candidate
except OSError:
continue
return None
def copy_attachment_to_store(source_path: Path, attachments_root: Path, note_id: str, filename: str) -> Path:
note_dir = attachments_root / note_id
note_dir.mkdir(parents=True, exist_ok=True)
safe_name = sanitize_filename(filename or source_path.name)
destination = note_dir / safe_name
stem = destination.stem
suffix = destination.suffix
counter = 1
while destination.exists():
destination = note_dir / f"{stem}-{counter}{suffix}"
counter += 1
shutil.copy2(source_path, destination)
return destination
class KeyringCredentialStore:
"""Small wrapper around the OS credential store used for sync secrets."""
service_name = KEYRING_SERVICE
def __init__(self):
self.last_error = ""
def _available(self) -> bool:
if KEYRING_AVAILABLE and keyring is not None:
return True
self.last_error = "Python keyring package is not available."
return False
def get_secret(self, key: str) -> Optional[str]:
if not self._available():
return None
try:
return keyring.get_password(self.service_name, key)
except Exception as e:
self.last_error = str(e)
return None
def set_secret(self, key: str, value: str) -> bool:
if not value:
return self.delete_secret(key)
if not self._available():
return False
try:
keyring.set_password(self.service_name, key, value)
self.last_error = ""
return True
except Exception as e:
self.last_error = str(e)
return False
def delete_secret(self, key: str) -> bool:
if not self._available():
return False
try:
keyring.delete_password(self.service_name, key)
self.last_error = ""
return True
except Exception as e:
if "not found" not in str(e).lower():
self.last_error = str(e)
return False
SECURE_CREDENTIALS = KeyringCredentialStore()
def set_secure_credential_store(store: Any):
"""Swap the credential store for tests."""
global SECURE_CREDENTIALS
SECURE_CREDENTIALS = store
def migrate_setting_secret(db: Any, setting_key: str, credential_key: str) -> Optional[str]:
"""Move a legacy SQLite setting secret into the OS credential store."""
secret = SECURE_CREDENTIALS.get_secret(credential_key)
legacy_secret = db.get_setting(setting_key)
if not legacy_secret:
return secret
if SECURE_CREDENTIALS.set_secret(credential_key, str(legacy_secret)):
if hasattr(db, "delete_setting"):
db.delete_setting(setting_key)
else:
db.set_setting(setting_key, None)
return str(legacy_secret)
return secret or str(legacy_secret)
def migrate_file_secret(file_path: str, credential_key: str) -> Optional[str]:
"""Move a legacy token file into the OS credential store."""
path = Path(file_path)
secret = SECURE_CREDENTIALS.get_secret(credential_key)
legacy_secret = ""
if path.exists():
legacy_secret = path.read_text(encoding="utf-8").strip()
if legacy_secret and not secret:
if SECURE_CREDENTIALS.set_secret(credential_key, legacy_secret):
secret = legacy_secret
if secret and path.exists():
try:
path.unlink()
except OSError:
pass
return secret or legacy_secret or None
def store_file_secret(credential_key: str, value: str, legacy_file_path: Optional[str] = None) -> bool:
"""Persist a token in the OS credential store and remove any legacy file copy."""
if not SECURE_CREDENTIALS.set_secret(credential_key, value):
return False
if legacy_file_path:
try:
Path(legacy_file_path).unlink(missing_ok=True)
except OSError:
pass
return True
def import_takeout_attachments(data: dict, base_path: Optional[Path], attachments_root: Path, note_id: str) -> List["Attachment"]:
attachments = []
for raw in takeout_attachment_specs(data):
if isinstance(raw, str):
source = raw
filename = Path(raw).name
mime_type = guess_attachment_mime(filename)
else:
source = first_present(raw, [
"filePath", "path", "sourcePath", "url", "filename", "fileName",
"drawingFilePath", "snapshotFilePath", "audioFilePath"
])
filename = first_present(raw, ["filename", "fileName", "name", "title"]) or Path(source).name
mime_type = first_present(raw, ["mimeType", "mimetype", "contentType"])
if not source and not filename:
continue
resolved = resolve_takeout_attachment_path(source, base_path)
stored_path = source
if resolved:
stored_path = str(copy_attachment_to_store(resolved, attachments_root, note_id, filename))
attachments.append(Attachment(
filename=filename or Path(stored_path).name,
stored_path=stored_path,
source_path=str(resolved or source),
mime_type=guess_attachment_mime(stored_path or filename, mime_type),
))
return attachments
class HTMLTextExtractor(HTMLParser):
"""Small HTML-to-text extractor for imported note formats."""
BLOCK_TAGS = {
"address", "article", "aside", "blockquote", "br", "div", "dl", "dt", "dd",
"figcaption", "figure", "footer", "h1", "h2", "h3", "h4", "h5", "h6",
"header", "hr", "li", "main", "ol", "p", "pre", "section", "table", "tr",
"ul",
}
def __init__(self):
super().__init__(convert_charrefs=True)
self.parts: List[str] = []
def handle_starttag(self, tag, attrs):
tag = tag.lower()
if tag == "en-todo":
checked = any(name == "checked" and value == "true" for name, value in attrs)
self.parts.append("[x] " if checked else "[ ] ")
elif tag in self.BLOCK_TAGS:
self.parts.append("\n")
def handle_endtag(self, tag):
if tag.lower() in self.BLOCK_TAGS:
self.parts.append("\n")
def handle_data(self, data):
self.parts.append(data)
def text(self) -> str:
value = unescape("".join(self.parts))
value = re.sub(r"[ \t\r\f\v]+", " ", value)
value = re.sub(r" *\n *", "\n", value)
value = re.sub(r"\n{3,}", "\n\n", value)
return value.strip()
def html_to_text(value: str) -> str:
extractor = HTMLTextExtractor()
try:
extractor.feed(value or "")
return extractor.text()
except Exception:
return re.sub(r"<[^>]+>", "", value or "").strip()
def strip_enex_content(value: str) -> str:
content = value or ""
content = re.sub(r"<!DOCTYPE[^>]*>", "", content, flags=re.IGNORECASE)
content = re.sub(r"<\?xml[^>]*\?>", "", content, flags=re.IGNORECASE)
return html_to_text(content)
def normalize_import_labels(labels: List[str], source: str = "", markdown: bool = False) -> List[str]:
normalized = []
if source:
normalized.append(source)
if markdown:
normalized.append(".md")
for label in labels or []:
label_text = str(label or "").strip()
if label_text and label_text not in normalized:
normalized.append(label_text)
return normalized
def title_from_content(content: str, fallback: str) -> str:
for line in (content or "").splitlines():
cleaned = line.strip().strip("#").strip()
if cleaned:
return cleaned[:120]
return fallback[:120] or "Untitled"
def labels_from_hashtags(content: str) -> List[str]:
return sorted({match.group(1) for match in re.finditer(r"(?<!\w)#([A-Za-z0-9_-]+)", content or "")})
def parse_external_datetime(value: Any) -> Optional[datetime]:
if not value:
return None
text = str(value).strip()
candidates = [text, text.replace("Z", "+00:00")]
if re.fullmatch(r"\d{8}T\d{6}Z?", text):
candidates.append(f"{text[0:4]}-{text[4:6]}-{text[6:8]}T{text[9:11]}:{text[11:13]}:{text[13:15]}+00:00")
for candidate in candidates:
try:
parsed = datetime.fromisoformat(candidate)
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
return parsed.astimezone(timezone.utc)
except ValueError:
continue
return None
class DiagnosticsManager:
"""File-backed diagnostics and crash logging."""
DEPENDENCIES = {
"customtkinter": "customtkinter",
"Pillow": "PIL",
"requests": "requests",
"gkeepapi": "gkeepapi",
"gpsoauth": "gpsoauth",
"browser-cookie3": "browser_cookie3",
"plyer": "plyer",
"keyring": "keyring",
"PyGithub": "github",
"google-api-python-client": "googleapiclient",
"google-auth": "google.auth",
"google-auth-oauthlib": "google_auth_oauthlib",
}
def __init__(self, data_dir: Path):
self.data_dir = Path(data_dir)
self.log_dir = self.data_dir / "logs"
self.log_dir.mkdir(parents=True, exist_ok=True)
self.log_path = self.log_dir / "keepsync-diagnostics.log"
self.last_exception = ""
self._previous_sys_hook = None
self._previous_thread_hook = None
def install_hooks(self):
self._previous_sys_hook = sys.excepthook
sys.excepthook = self._handle_unhandled_exception
if hasattr(threading, "excepthook"):
self._previous_thread_hook = threading.excepthook
threading.excepthook = self._handle_thread_exception
def _write(self, level: str, message: str):
timestamp = datetime.now(timezone.utc).isoformat()
with open(self.log_path, "a", encoding="utf-8") as fh:
fh.write(f"[{timestamp}] {level.upper()} {message}\n")
def log_event(self, level: str, message: str):
self._write(level, message)
def log_exception(self, context: str, exc: BaseException):
detail = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__)).strip()
self.last_exception = f"{context}: {exc}"
self._write("error", f"{context}: {detail}")
def _handle_unhandled_exception(self, exc_type, exc, tb):
detail = "".join(traceback.format_exception(exc_type, exc, tb)).strip()
self.last_exception = f"unhandled: {exc}"
self._write("critical", f"Unhandled exception: {detail}")
if self._previous_sys_hook:
self._previous_sys_hook(exc_type, exc, tb)
def _handle_thread_exception(self, args):
detail = "".join(traceback.format_exception(args.exc_type, args.exc_value, args.exc_traceback)).strip()
self.last_exception = f"thread: {args.exc_value}"
self._write("critical", f"Thread exception: {detail}")
if self._previous_thread_hook:
self._previous_thread_hook(args)
def dependency_state(self) -> Dict[str, str]:
state = {}
for package, import_name in self.DEPENDENCIES.items():
state[package] = "available" if importlib.util.find_spec(import_name) else "missing"
return state
def recent_log(self, limit: int = 80) -> str:
if not self.log_path.exists():
return ""
lines = self.log_path.read_text(encoding="utf-8", errors="replace").splitlines()
return "\n".join(lines[-limit:])
def report(self, db_path: Path, attachments_path: Path) -> str:
dependencies = "\n".join(
f"- {package}: {state}"
for package, state in sorted(self.dependency_state().items())
)
return (
f"{APP_NAME} v{APP_VERSION}\n"
f"Database: {db_path}\n"
f"Attachments: {attachments_path}\n"
f"Diagnostics log: {self.log_path}\n"
f"Keyring available: {KEYRING_AVAILABLE}\n"
f"Google Keep API available: {GKEEPAPI_AVAILABLE}\n"
f"Desktop notifications available: {DESKTOP_NOTIFICATIONS_AVAILABLE}\n"
f"Last exception: {self.last_exception or 'None'}\n\n"
f"Dependencies:\n{dependencies}\n\n"
f"Recent log:\n{self.recent_log() or 'No log entries.'}"
)
DIAGNOSTICS: Optional[DiagnosticsManager] = None
def set_diagnostics_manager(manager: DiagnosticsManager):
global DIAGNOSTICS
DIAGNOSTICS = manager
def log_diagnostic_event(level: str, message: str):
if DIAGNOSTICS:
DIAGNOSTICS.log_event(level, message)
def log_diagnostic_exception(context: str, exc: BaseException):
if DIAGNOSTICS:
DIAGNOSTICS.log_exception(context, exc)
# ═══════════════════════════════════════════════════════════════════════════════
# DATA MODELS
# ═══════════════════════════════════════════════════════════════════════════════
def note_diff_body(note: Note) -> str:
if note.note_type == NoteType.CHECKLIST:
return "\n".join(
f"{' ' * item.indent}{'[x]' if item.checked else '[ ]'} {item.text}"
for item in note.checklist_items
)
return note.content or ""
def notes_equivalent(left: Note, right: Note) -> bool:
return (
(left.title or "").strip() == (right.title or "").strip()
and note_diff_body(left).strip() == note_diff_body(right).strip()
and sorted(left.labels) == sorted(right.labels)
and left.note_type == right.note_type
)
def note_conflict_diff(local_note: Note, imported_note: Note) -> str:
local_lines = [f"# {local_note.title or 'Untitled'}", *note_diff_body(local_note).splitlines()]
imported_lines = [f"# {imported_note.title or 'Untitled'}", *note_diff_body(imported_note).splitlines()]
return "\n".join(difflib.unified_diff(
local_lines,
imported_lines,
fromfile="local",
tofile="imported",
lineterm=""
))
def merge_note_conflict(local_note: Note, imported_note: Note) -> Note:
merged = Note.from_dict(local_note.to_dict())
merged.labels = normalize_import_labels(local_note.labels + imported_note.labels)
merged.attachments = local_note.attachments + [
attachment for attachment in imported_note.attachments
if attachment.filename not in {existing.filename for existing in local_note.attachments}
]
merged.updated_at = datetime.now(timezone.utc)
merged.local_modified = merged.updated_at
if local_note.note_type == NoteType.CHECKLIST or imported_note.note_type == NoteType.CHECKLIST:
merged.note_type = NoteType.NOTE
local_body = note_diff_body(local_note)
imported_body = note_diff_body(imported_note)
else:
local_body = local_note.content or ""
imported_body = imported_note.content or ""
if local_body.strip() == imported_body.strip():
merged.content = local_body
else:
merged.content = (
f"{local_body.strip()}\n\n"
"--- Imported version ---\n\n"
f"{imported_body.strip()}"
).strip()
merged.checklist_items = []
return merged
def default_advanced_filters() -> Dict[str, Any]:
return {
"mode": "AND",
"label": "",
"color": "",
"date_from": "",
"date_to": "",
"has_image": False,
"has_checklist": False,
"is_archived": False,
}
def advanced_filters_active(filters: Dict[str, Any]) -> bool:
defaults = default_advanced_filters()
return any(filters.get(key) != value for key, value in defaults.items() if key != "mode")
def parse_filter_date(value: str) -> Optional[datetime]:
text = (value or "").strip()
if not text:
return None
try:
return datetime.strptime(text, "%Y-%m-%d").replace(tzinfo=timezone.utc)
except ValueError:
return None
def note_matches_advanced_filters(note: Note, filters: Dict[str, Any]) -> bool:
checks = []
label = (filters.get("label") or "").strip()
if label:
checks.append(any(label.lower() == existing.lower() for existing in note.labels))
color = normalize_keep_color(filters.get("color", ""))
if color:
checks.append(normalize_keep_color(note.color) == color)
date_from = parse_filter_date(filters.get("date_from", ""))
if date_from:
checks.append(note.updated_at.astimezone(timezone.utc) >= date_from)
date_to = parse_filter_date(filters.get("date_to", ""))
if date_to:
end_of_day = date_to.replace(hour=23, minute=59, second=59)
checks.append(note.updated_at.astimezone(timezone.utc) <= end_of_day)
if filters.get("has_image"):
checks.append(any(attachment.is_image for attachment in note.attachments))
if filters.get("has_checklist"):
checks.append(note.note_type == NoteType.CHECKLIST or bool(note.checklist_items))
if filters.get("is_archived"):
checks.append(note.archived)
if not checks:
return True
if str(filters.get("mode", "AND")).upper() == "OR":
return any(checks)
return all(checks)
# ═══════════════════════════════════════════════════════════════════════════════
# 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 '',
reminder_at TEXT,
reminder_location TEXT DEFAULT '',
reminder_notified INTEGER DEFAULT 0,
shared_with TEXT DEFAULT '[]',
attachments 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
)
""")
self._ensure_column("notes", "reminder_at", "TEXT")
self._ensure_column("notes", "reminder_location", "TEXT DEFAULT ''")
self._ensure_column("notes", "reminder_notified", "INTEGER DEFAULT 0")
self._ensure_column("notes", "shared_with", "TEXT DEFAULT '[]'")
self._ensure_column("notes", "attachments", "TEXT DEFAULT '[]'")
# 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)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_notes_reminder_at ON notes(reminder_at)")
self.fts_available = self._init_fts(cursor)
if self.fts_available:
self._rebuild_fts(cursor)
self.conn.commit()
def _init_fts(self, cursor: sqlite3.Cursor) -> bool:
try:
cursor.execute("""
CREATE VIRTUAL TABLE IF NOT EXISTS notes_fts
USING fts5(note_id UNINDEXED, title, content, labels)
""")
return True
except sqlite3.OperationalError as e:
print(f"FTS5 unavailable: {e}")
return False
def _fts_text(self, note: Note) -> str:
if note.note_type == NoteType.CHECKLIST:
return "\n".join(item.text for item in note.checklist_items)
return note.content or ""
def _update_fts(self, cursor: sqlite3.Cursor, note: Note):
if not getattr(self, "fts_available", False):
return
cursor.execute("DELETE FROM notes_fts WHERE note_id = ?", (note.id,))
if note.trashed:
return
cursor.execute(
"INSERT INTO notes_fts (note_id, title, content, labels) VALUES (?, ?, ?, ?)",
(note.id, note.title, self._fts_text(note), " ".join(note.labels))
)
def _delete_fts(self, cursor: sqlite3.Cursor, note_id: str):
if getattr(self, "fts_available", False):
cursor.execute("DELETE FROM notes_fts WHERE note_id = ?", (note_id,))
def _rebuild_fts(self, cursor: sqlite3.Cursor):
cursor.execute("DELETE FROM notes_fts")
cursor.execute("SELECT * FROM notes WHERE trashed = 0")
for row in cursor.fetchall():
self._update_fts(cursor, self._row_to_note(row))
def _fts_query(self, query: str) -> str:
terms = re.findall(r"[A-Za-z0-9_]+", query or "")
return " ".join(f"{term}*" for term in terms)
def _ensure_column(self, table: str, column: str, definition: str):
cursor = self.conn.cursor()
cursor.execute(f"PRAGMA table_info({table})")
existing = {row["name"] for row in cursor.fetchall()}
if column not in existing:
cursor.execute(f"ALTER TABLE {table} ADD COLUMN {column} {definition}")
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, reminder_at, reminder_location, reminder_notified,
shared_with, attachments, 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.reminder_at.isoformat() if note.reminder_at else None,
note.reminder_location, int(note.reminder_notified),
json.dumps(note.shared_with),
json.dumps([a.to_dict() for a in note.attachments]),
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,