-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProSyncStart_V3.1.py
More file actions
3987 lines (3383 loc) · 149 KB
/
Copy pathProSyncStart_V3.1.py
File metadata and controls
3987 lines (3383 loc) · 149 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
import sys
import os
import argparse
import ntpath
import json
import uuid
import hashlib
import shutil
import threading
import sqlite3
import time
import subprocess
import re
import posixpath
import stat
from datetime import datetime, timezone
from fnmatch import fnmatch
from pathlib import Path
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QListWidget, QListWidgetItem,
QToolBar, QMenu, QHBoxLayout, QPushButton, QProgressBar, QLabel,
QDialog, QFormLayout, QLineEdit, QComboBox, QCheckBox, QDialogButtonBox,
QFileDialog, QMessageBox, QSystemTrayIcon, QStyle, QSizePolicy, QSplitter,
QAbstractItemView,
QTextEdit
)
from PySide6.QtCore import Qt, QThread, Signal, QObject, QTimer, QLockFile, QDir, QCoreApplication
from PySide6.QtGui import QAction, QActionGroup, QIcon
# ProSync Logger
from logger import log_debug, log_info, log_warning, log_error
def _configure_windows_utf8_streams() -> None:
"""Use UTF-8 console streams on Windows without replacing capture objects."""
if sys.platform != 'win32':
return
for stream_name in ("stdout", "stderr"):
stream = getattr(sys, stream_name, None)
reconfigure = getattr(stream, "reconfigure", None)
if reconfigure is None:
continue
try:
reconfigure(encoding="utf-8")
except (AttributeError, OSError, ValueError):
# Test runners and embedded hosts may expose non-standard streams.
# Keeping the existing object intact is safer than replacing it.
pass
# Windows UTF-8 Fix
_configure_windows_utf8_streams()
def app_base_dir() -> str:
"""Return the runtime directory for local and frozen builds."""
if getattr(sys, "frozen", False):
return os.path.dirname(sys.executable)
return os.path.dirname(os.path.abspath(__file__))
WINDOWS_ENV_VAR_PATTERN = re.compile(r"%([^%]+)%")
def normalize_configured_tool_path(base_dir, configured_path):
"""Expand a configured tool path and anchor relative paths at the app root."""
raw_path = str(configured_path).strip()
if not raw_path:
return None
expanded_raw_path = WINDOWS_ENV_VAR_PATTERN.sub(
lambda match: os.environ.get(match.group(1), match.group(0)),
raw_path,
)
expanded_path = Path(os.path.expandvars(expanded_raw_path)).expanduser()
if not expanded_path.is_absolute():
expanded_path = Path(base_dir).expanduser() / expanded_path
return expanded_path
def resolve_profiler_launch_path(base_dir, configured_path=""):
"""Resolve the best available ProFiler entrypoint."""
base_dir = Path(base_dir).expanduser()
sibling_root = base_dir.parent / "REL-PUB_ProFiler"
candidates = []
if configured_path:
configured = normalize_configured_tool_path(base_dir, configured_path)
if configured.is_dir():
candidates.extend([
configured / "Profiler_Suite_V15.py",
configured / "ProFiler.exe",
configured / "dist" / "ProFiler" / "ProFiler.exe",
configured / "START.bat",
])
else:
candidates.append(configured)
candidates.extend([
base_dir / "Profiler_Suite_V15.py",
base_dir / "ProFiler.exe",
base_dir / "START.bat",
sibling_root / "Profiler_Suite_V15.py",
sibling_root / "ProFiler.exe",
sibling_root / "START.bat",
sibling_root / "dist" / "ProFiler" / "ProFiler.exe",
])
seen = set()
for candidate in candidates:
candidate = Path(candidate).expanduser()
resolved = str(candidate)
if resolved in seen:
continue
seen.add(resolved)
if candidate.exists():
return candidate
return None
def configure_compact_button_accessibility(button, *, name: str, tooltip: str, description: str | None = None) -> None:
"""Keep compact symbol buttons screenreader-friendly without adding permanent labels."""
button.setToolTip(tooltip)
button.setStatusTip(tooltip)
button.setAccessibleName(name)
button.setAccessibleDescription(description or tooltip)
# Windows Registry Support (Optional)
try:
import winreg
HAS_WINREG = True
except ImportError:
HAS_WINREG = False
# ---------------- CONSTANTS ----------------
DB_CONNECTION_TIMEOUT = 5.0 # Seconds for SQLite database connection timeout
SEARCH_RESULT_LIMIT = 500 # Maximum number of search results
DEFAULT_AUTOSYNC_INTERVAL = 15
PORTABLE_PROFILE_SCHEMA = "prosync-profile-v1"
PORTABLE_PROFILE_APP_VERSION = "3.2"
# FileSyncWorker Progress Percentages
PROGRESS_CHECKPOINT = 10 # WAL checkpoint phase
PROGRESS_PREPARE = 30 # Target directory creation
PROGRESS_COPY = 50 # File copy phase
PROGRESS_VERIFY = 90 # Verification phase
PROGRESS_DONE = 100 # Completion
# Dialog Dimensions
DIALOG_WIDTH = 500 # Default width for ConnectionDialog
DIALOG_HEIGHT = 600 # Default height for ConnectionDialog (increased for safety info)
def default_config_data():
"""Return a fresh default structure for the local configuration file."""
return {"app": {}, "connections": []}
def portable_path_label(raw_path, fallback):
"""Derive a non-sensitive display label from a local path."""
value = str(raw_path or "").strip().rstrip("\\/")
if not value:
return fallback
name = ntpath.basename(value) or os.path.basename(value)
if name:
return name
drive, _tail = ntpath.splitdrive(value)
if drive:
return f"{drive}\\"
return fallback
def sync_report_log_path():
"""Return the local report log path used by ProSync."""
appdata = str(os.environ.get("APPDATA", "") or "").strip()
base_dir = Path(appdata) if appdata else Path.home()
if not base_dir.is_absolute():
base_dir = Path.home()
reports_dir = base_dir / "ProSync" / "reports"
return reports_dir / "sync_log.json"
def save_sync_report(report):
"""Persist a sync-run report as JSON and keep the last 100 entries."""
try:
reports_dir = sync_report_log_path().parent
reports_dir.mkdir(parents=True, exist_ok=True)
log_file = sync_report_log_path()
if log_file.exists():
try:
with open(log_file, "r", encoding="utf-8") as fh:
all_reports = json.load(fh)
if not isinstance(all_reports, list):
all_reports = []
except (json.JSONDecodeError, UnicodeDecodeError, OSError):
all_reports = []
else:
all_reports = []
all_reports.append(report)
all_reports = all_reports[-100:]
tmp_path = str(log_file) + ".tmp"
with open(tmp_path, "w", encoding="utf-8") as fh:
json.dump(all_reports, fh, ensure_ascii=False, indent=2)
os.replace(tmp_path, log_file)
log_info(
f"Sync-Report gespeichert: {report['files_copied']} kopiert, "
f"{report['files_deleted']} gelöscht, "
f"{report['bytes_copied']:,} Bytes, "
f"{report['duration_seconds']}s"
)
except Exception as exc:
log_warning(f"Konnte Sync-Report nicht speichern: {exc}")
# ---------------- DATABASE SAFETY MANAGER ----------------
class DatabaseSafetyManager:
"""
V3.1 IMPROVED: Option D - Separate handling for folder vs. file connections.
For FOLDER connections:
- Critical DBs are auto-excluded
- User gets warning
- Suggestion to create FILE connection for DB
For FILE connections:
- Enforce one-way for critical DBs
- Auto-enable WAL checkpoint
- Prevent two-way sync
"""
# Database file extensions
DB_EXTENSIONS = {
".sqlite", ".sqlite3", ".db", ".db3",
".mdb", ".accdb" # MS Access
}
# MS Access lock files
ACCESS_LOCK_EXTENSIONS = {
".ldb", ".laccdb"
}
@classmethod
def is_database_file(cls, filepath: str) -> bool:
"""
Prüft ob eine Datei eine Datenbank ist (anhand der Dateiendung).
Args:
filepath: Pfad zur zu prüfenden Datei
Returns:
True wenn die Datei eine bekannte Datenbank-Endung hat
"""
ext = Path(filepath).suffix.lower()
return ext in cls.DB_EXTENSIONS
@classmethod
def is_access_lock_file(cls, filepath: str) -> bool:
"""
Prüft ob eine Datei eine MS Access Lock-Datei ist.
MS Access erstellt .ldb (Access 2003) oder .laccdb (Access 2007+) Lock-Dateien
wenn eine Datenbank geöffnet ist. Diese sollten nie kopiert werden.
Args:
filepath: Pfad zur zu prüfenden Datei
Returns:
True wenn die Datei eine MS Access Lock-Datei ist (.ldb, .laccdb)
"""
ext = Path(filepath).suffix.lower()
return ext in cls.ACCESS_LOCK_EXTENSIONS
@classmethod
def is_sqlite_database(cls, filepath: str) -> bool:
"""
Prüft ob eine Datei eine SQLite-Datenbank ist (durch Lesen des Headers).
Liest die ersten 16 Bytes der Datei und prüft auf die SQLite-Magic-Number
"SQLite format 3". Dies ist zuverlässiger als nur die Dateiendung zu prüfen.
Args:
filepath: Pfad zur zu prüfenden Datei
Returns:
True wenn die Datei eine gültige SQLite 3 Datenbank ist
"""
if not os.path.exists(filepath):
return False
try:
with open(filepath, 'rb') as f:
header = f.read(16)
return header.startswith(b'SQLite format 3')
except (OSError, IOError):
return False
@classmethod
def check_wal_mode(cls, db_path: str) -> bool:
"""
Prüft ob eine SQLite-Datenbank im WAL-Modus läuft.
Args:
db_path: Pfad zur SQLite-Datenbankdatei
Returns:
True wenn die Datenbank im WAL-Modus ist, sonst False
"""
if not os.path.exists(db_path):
return False
# Bugsweep 26 BUG-A1: conn in finally schliessen — bei Exception (z.B. fetchone()[0] auf None)
# blieb die Connection sonst offen (Handle-Leak auf Nutzer-DB, blockiert spaeteres Kopieren).
conn = None
try:
conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True, timeout=DB_CONNECTION_TIMEOUT)
cur = conn.cursor()
cur.execute("PRAGMA journal_mode;")
row = cur.fetchone()
return bool(row) and row[0].upper() == "WAL"
except (sqlite3.Error, OSError):
return False
finally:
if conn is not None:
conn.close()
@classmethod
def scan_directory_for_databases(cls, directory: str) -> list:
"""
Scannt ein Verzeichnis nach Datenbankdateien und analysiert sie.
Args:
directory: Pfad zum zu scannenden Verzeichnis
Returns:
Liste von Dicts mit Datenbank-Metadaten (type, wal_mode, size_mb, etc.)
"""
databases = []
if not os.path.exists(directory):
return databases
try:
for root, dirs, files in os.walk(directory):
# Skip hidden and cache directories
dirs[:] = [d for d in dirs if not d.startswith('.') and d != '__pycache__']
for file in files:
filepath = os.path.join(root, file)
if cls.is_database_file(filepath):
db_info = cls._analyze_database_file(filepath, directory)
databases.append(db_info)
except Exception as e:
log_error(f"Error scanning directory: {e}")
return databases
@classmethod
def _analyze_database_file(cls, filepath: str, base_directory: str) -> dict:
"""Analysiert eine einzelne Datenbankdatei und gibt Metadaten zurück."""
db_info = {
"path": filepath,
"name": os.path.basename(filepath),
"relative_path": os.path.relpath(filepath, base_directory),
"type": "unknown",
"wal_mode": False,
"has_wal_files": False,
"size_mb": 0,
"is_critical": False
}
# Analyze SQLite databases
if cls.is_sqlite_database(filepath):
db_info["type"] = "sqlite"
db_info["wal_mode"] = cls.check_wal_mode(filepath)
db_info["has_wal_files"] = (
os.path.exists(filepath + "-wal") or
os.path.exists(filepath + "-shm")
)
db_info["is_critical"] = db_info["wal_mode"] or db_info["has_wal_files"]
# Analyze MS Access databases
elif filepath.endswith(('.mdb', '.accdb')):
db_info["type"] = "ms_access"
# Get file size
try:
db_info["size_mb"] = os.path.getsize(filepath) / (1024 * 1024)
except OSError:
pass
return db_info
@classmethod
def apply_safe_settings_folder(cls, conn_config: dict, databases: list) -> tuple:
"""
V3.1 NEW: Apply safe settings for FOLDER connections.
Strategy:
- Exclude critical databases from folder sync
- Keep two-way for all other files
- Suggest creating FILE connections for excluded DBs
Returns: (modified_config, warnings_list, excluded_dbs_list, was_changed)
"""
warnings = []
excluded_dbs = []
was_changed = False
# Filtere kritische Datenbanken (WAL-Modus oder WAL-Dateien vorhanden)
critical_dbs = [db for db in databases if db.get("is_critical")]
if critical_dbs:
# Initialisiere exclude_patterns falls noch nicht vorhanden
if "exclude_patterns" not in conn_config:
conn_config["exclude_patterns"] = []
# Verwende Set für schnellere Duplikatsprüfung
current_excludes = set(conn_config["exclude_patterns"])
for db in critical_dbs:
db_name = db["name"]
# Schließe die Datenbankdatei selbst aus
if db_name not in current_excludes:
conn_config["exclude_patterns"].append(db_name)
current_excludes.add(db_name)
was_changed = True
# Schließe zugehörige WAL-Dateien aus (SQLite Write-Ahead Log)
# -wal: Write-Ahead Log Datei
# -shm: Shared Memory Datei
# -journal: Rollback Journal (für Non-WAL Mode)
wal_patterns = [
db_name + "-wal",
db_name + "-shm",
db_name + "-journal"
]
for pattern in wal_patterns:
if pattern not in current_excludes:
conn_config["exclude_patterns"].append(pattern)
current_excludes.add(pattern)
was_changed = True
excluded_dbs.append(db)
# Add general unsafe patterns
for pattern in ["*.lock", "*.lck", "*.tmp", ".DS_Store", "Thumbs.db",
"__pycache__", "*.pyc"]:
if pattern not in current_excludes:
conn_config["exclude_patterns"].append(pattern)
current_excludes.add(pattern)
was_changed = True
if excluded_dbs:
warnings.append(f"⚠ {len(excluded_dbs)} kritische Datenbank(en) ausgeschlossen")
warnings.append("💡 Erstelle Datei-Verbindungen für einzelne DB-Sync")
# Speichere Metadaten über ausgeschlossene DBs für spätere Referenz
# (z.B. um dem User zu zeigen welche DBs ausgeschlossen wurden)
conn_config["_auto_excluded_dbs"] = [
{
"name": db["name"],
"size_mb": db["size_mb"],
"type": db["type"],
"wal_mode": db.get("wal_mode", False),
"relative_path": db.get("relative_path", db["name"])
}
for db in excluded_dbs
]
# MS Access lock files
access_dbs = [db for db in databases if db.get("type") == "ms_access"]
if access_dbs:
lock_patterns = ["*.ldb", "*.laccdb"]
current_excludes = set(conn_config.get("exclude_patterns", []))
for pattern in lock_patterns:
if pattern not in current_excludes:
if "exclude_patterns" not in conn_config:
conn_config["exclude_patterns"] = []
conn_config["exclude_patterns"].append(pattern)
was_changed = True
if was_changed:
warnings.append("✓ MS Access Lock-Dateien ausgeschlossen (.ldb, .laccdb)")
# Add safety metadata
if databases:
conn_config["_safety_analysis"] = {
"databases_found": len(databases),
"critical_databases": len(critical_dbs),
"excluded_databases": len(excluded_dbs),
"total_db_size_mb": sum(db.get("size_mb", 0) for db in databases),
"last_check": datetime.now(timezone.utc).isoformat(),
"auto_configured": True,
"version": "3.1",
"connection_type": "folder"
}
return (conn_config, warnings, excluded_dbs, was_changed)
@classmethod
def apply_safe_settings_file(cls, conn_config: dict) -> tuple:
"""
V3.1 NEW: Apply safe settings for FILE connections.
Strategy:
- Enforce one-way for critical database files
- Enable WAL checkpoint for SQLite WAL databases
- Disable auto-sync by default
Returns: (modified_config, warnings_list, was_changed)
"""
warnings = []
was_changed = False
source_file = conn_config.get("source_file", "")
if not source_file or not os.path.exists(source_file):
return (conn_config, warnings, was_changed)
filename = os.path.basename(source_file)
# Check if database file
if cls.is_database_file(source_file):
db_info = {
"name": filename,
"type": "unknown",
"wal_mode": False,
"size_mb": 0,
"is_critical": False
}
# Analyze SQLite
if cls.is_sqlite_database(source_file):
db_info["type"] = "sqlite"
db_info["wal_mode"] = cls.check_wal_mode(source_file)
db_info["is_critical"] = db_info["wal_mode"]
# Enable checkpoint for WAL databases
if db_info["wal_mode"]:
if not conn_config.get("checkpoint_before_sync"):
conn_config["checkpoint_before_sync"] = True
warnings.append("✓ WAL-Checkpoint vor Sync aktiviert")
was_changed = True
elif source_file.endswith(('.mdb', '.accdb')):
db_info["type"] = "ms_access"
# Get size
try:
db_info["size_mb"] = os.path.getsize(source_file) / (1024 * 1024)
except OSError:
pass
# Enforce one-way for critical databases
if db_info["is_critical"] or db_info["type"] in ["sqlite", "ms_access"]:
if conn_config.get("mode") != "one_way":
conn_config["mode"] = "one_way"
warnings.append("⚠ Modus auf one_way gesetzt (kritische Datenbank)")
was_changed = True
# Disable auto-sync
if conn_config.get("autosync", {}).get("enabled", False):
conn_config["autosync"]["enabled"] = False
conn_config["autosync"]["_reason"] = "Manuelle Sync empfohlen für Datenbanken"
warnings.append("⚠ Auto-sync deaktiviert (manueller Sync empfohlen)")
was_changed = True
# Add metadata
conn_config["_file_analysis"] = {
"filename": filename,
"type": db_info["type"],
"size_mb": db_info["size_mb"],
"wal_mode": db_info.get("wal_mode", False),
"is_critical": db_info["is_critical"],
"checkpoint_enabled": conn_config.get("checkpoint_before_sync", False),
"last_check": datetime.now(timezone.utc).isoformat(),
"version": "3.1",
"connection_type": "file"
}
return (conn_config, warnings, was_changed)
@classmethod
def checkpoint_sqlite_database(cls, db_path: str) -> bool:
"""
Führt einen WAL-Checkpoint auf einer SQLite-Datenbank aus.
WAL (Write-Ahead Logging) speichert Änderungen zunächst in einer separaten
-wal Datei. Ein Checkpoint merged diese Änderungen zurück in die Hauptdatei.
Dies ist wichtig vor dem Kopieren, um einen konsistenten Zustand zu garantieren.
Args:
db_path: Pfad zur SQLite-Datenbankdatei
Returns:
True wenn erfolgreich, False bei Fehler
"""
if not os.path.exists(db_path):
return False
# Bugsweep 26 BUG-A2: conn in finally schliessen — bei Checkpoint-Fehler (DB gelockt/Rechte)
# blieb sie sonst offen und das Handle blockierte das anschliessende Kopieren der DB.
conn = None
try:
# Verbinde zur DB mit 30s Timeout (falls gerade gelockt)
conn = sqlite3.connect(db_path, timeout=30.0)
conn.execute("PRAGMA wal_checkpoint(FULL);")
conn.commit()
log_info(f"✓ WAL checkpoint successful: {os.path.basename(db_path)}")
return True
except Exception as e:
log_warning(f"⚠ WAL checkpoint failed: {e}")
return False
finally:
if conn is not None:
conn.close()
# ---------------- CONNECTION TYPES (V3.1 NEW) ----------------
class ConnectionType:
"""V3.1 NEW: Connection type constants."""
FOLDER = "folder" # Sync entire folder
FILE = "file" # Sync single file only
SFTP = "sftp" # Sync local folder to SSH/SFTP target
REMOTE_UNSAFE_DATABASE_WARNING = (
"SFTP-Ziele sind nicht datenbanksicher: WAL-/Lock-Dateien und Remote-"
"Atomizität können nicht wie bei lokalen Datei-Verbindungen garantiert "
"werden. Nutze für SQLite/Access lieber eine lokale Datei-Verbindung."
)
def normalize_remote_path(path):
"""Normalize a configured SFTP path without applying local filesystem rules."""
raw = str(path or "").strip().replace("\\", "/")
if not raw:
return ""
normalized = posixpath.normpath(raw)
if raw.startswith("/") and not normalized.startswith("/"):
normalized = "/" + normalized
return normalized.rstrip("/") or "/"
def join_remote_path(root, rel_path=""):
"""Join remote POSIX path fragments for SFTP operations."""
root = normalize_remote_path(root)
rel = str(rel_path or "").replace("\\", "/").strip("/")
if not rel:
return root
return posixpath.join(root, rel)
def sftp_connection_display(conn):
"""Return a secret-free SFTP endpoint label."""
user = str(conn.get("remote_username", "") or "").strip()
host = str(conn.get("remote_host", "") or "").strip()
try:
port = int(conn.get("remote_port") or 22)
except (TypeError, ValueError):
port = 22
remote = normalize_remote_path(conn.get("target", ""))
user_prefix = f"{user}@" if user else ""
port_suffix = f":{port}" if port != 22 else ""
if not host:
return remote or "?"
return f"{user_prefix}{host}{port_suffix}:{remote}"
def validate_sftp_connection(conn):
"""Validate SFTP target configuration and reject unsafe sync modes."""
source = str(conn.get("source", "") or "").strip()
target = normalize_remote_path(conn.get("target", ""))
host = str(conn.get("remote_host", "") or "").strip()
if not source:
raise ValueError("SFTP-Quelle fehlt")
if not os.path.isdir(source):
raise ValueError(f"SFTP-Quelle ist kein Ordner: {source}")
if not host:
raise ValueError("SFTP-Host fehlt")
if not target:
raise ValueError("SFTP-Zielpfad fehlt")
mode = conn.get("mode", "update")
if mode not in ("mirror", "update", "one_way"):
raise ValueError("SFTP unterstützt nur mirror, update oder one_way")
if conn.get("checkpoint_before_sync"):
raise ValueError(REMOTE_UNSAFE_DATABASE_WARNING)
return True
# ---------------- AUTOSTART MANAGER ----------------
class AutostartManager:
"""
Verwaltet den Windows-Autostart für ProSync über die Registry.
Nutzt den Run-Schlüssel in HKEY_CURRENT_USER um die Anwendung
beim Windows-Start automatisch zu starten. Windows-spezifisch (winreg).
"""
APP_NAME = "ProSync"
@staticmethod
def set_autostart(enable=True):
"""
Aktiviert oder deaktiviert den Windows-Autostart für ProSync.
Args:
enable: True = Autostart aktivieren, False = deaktivieren
Returns:
True bei Erfolg, False bei Fehler oder fehlender winreg-Unterstützung
"""
if not HAS_WINREG: return False
try:
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Run",
0, winreg.KEY_SET_VALUE)
if enable:
if getattr(sys, 'frozen', False):
exe_path = f'"{sys.executable}"'
else:
script_path = os.path.abspath(__file__)
exe_path = f'"{sys.executable}" "{script_path}"'
winreg.SetValueEx(key, AutostartManager.APP_NAME, 0, winreg.REG_SZ, exe_path)
else:
try:
winreg.DeleteValue(key, AutostartManager.APP_NAME)
except FileNotFoundError: pass
winreg.CloseKey(key)
return True
except Exception as e:
log_error(f"Registry Fehler: {e}")
return False
@staticmethod
def is_autostart_enabled():
"""
Prüft ob ProSync im Windows-Autostart eingetragen ist.
Returns:
True wenn Autostart aktiv, False sonst
"""
if not HAS_WINREG: return False
try:
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Run",
0, winreg.KEY_READ)
winreg.QueryValueEx(key, AutostartManager.APP_NAME)
winreg.CloseKey(key)
return True
except (FileNotFoundError, OSError):
return False
# ---------------- CONFIG ----------------
class ConfigManager:
"""
Verwaltet die ProSync-Konfigurationsdatei (JSON).
Die Konfiguration enthält App-Einstellungen und alle Sync-Verbindungen.
Automatisches Laden/Speichern bei Änderungen.
"""
def __init__(self, path):
"""
Initialisiert den ConfigManager und lädt die Konfiguration.
Args:
path: Pfad zur Konfigurationsdatei (ProSync_config.json)
"""
self.path = path
self.data = default_config_data()
self.load()
def load(self):
"""
Lädt die Konfiguration aus der JSON-Datei.
Bei Fehler oder fehlender Datei wird eine neue Config erstellt.
"""
if os.path.exists(self.path):
try:
with open(self.path, "r", encoding="utf-8") as f:
loaded = json.load(f)
if not isinstance(loaded, dict):
log_error(
"Config load error: expected JSON object root, "
f"got {type(loaded).__name__}"
)
self.data = default_config_data()
self.save()
return
self.data = loaded
if not isinstance(self.data.get("app"), dict):
self.data["app"] = {}
if not isinstance(self.data.get("connections"), list):
self.data["connections"] = []
except (json.JSONDecodeError, OSError, UnicodeDecodeError) as e:
log_error(f"Config load error: {e}")
self.data = default_config_data()
self.save()
else:
self.save()
def save(self):
"""
Speichert die Konfiguration in die JSON-Datei.
Erstellt das Verzeichnis falls es nicht existiert.
"""
os.makedirs(os.path.dirname(self.path) or ".", exist_ok=True)
# Bugsweep 26 BUG-A3: atomar schreiben (tmp + os.replace), sonst korrupte config.json bei
# Absturz/OneDrive-Lock mitten im json.dump.
tmp = f"{self.path}.tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(self.data, f, indent=2, ensure_ascii=False)
os.replace(tmp, self.path)
def list_connections(self):
"""
Gibt alle gespeicherten Sync-Verbindungen zurück.
Returns:
Liste von Connection-Dicts
"""
return self.data.get("connections", [])
def add_or_update_connection(self, conn):
"""
Fügt eine neue Verbindung hinzu oder aktualisiert eine bestehende.
Die Verbindung wird anhand der ID identifiziert. Speichert automatisch.
Args:
conn: Connection-Dict mit mindestens {"id": "..."}
"""
conns = self.data.get("connections", [])
found = False
for i, c in enumerate(conns):
if c.get("id") == conn.get("id"):
conns[i] = conn
found = True
break
if not found:
conns.append(conn)
self.data["connections"] = conns
self.save()
def remove_connection(self, conn_id):
"""
Entfernt eine Verbindung anhand der ID.
Args:
conn_id: ID der zu entfernenden Verbindung
"""
self.data["connections"] = [c for c in self.data.get("connections", [])
if c.get("id") != conn_id]
self.save()
@staticmethod
def _portable_path_hints(conn):
"""Build redacted path hints for a portable profile export."""
conn_type = conn.get("type", ConnectionType.FOLDER)
if conn_type == ConnectionType.FILE:
return {
"source_label": portable_path_label(conn.get("source_file", ""), "Quelldatei"),
"target_label": portable_path_label(conn.get("target_file", ""), "Zieldatei"),
}
if conn_type == ConnectionType.SFTP:
return {
"source_label": portable_path_label(conn.get("source", ""), "Quellordner"),
"target_label": portable_path_label(conn.get("target", ""), "SFTP-Ziel"),
}
hints = {
"source_label": portable_path_label(conn.get("source", ""), "Quellordner"),
"target_label": portable_path_label(conn.get("target", ""), "Zielordner"),
}
if conn.get("indexing"):
hints["db_label"] = portable_path_label(conn.get("db_path", ""), "Indexdatenbank")
return hints
@staticmethod
def _portable_safety_summary(conn):
"""Reduce local safety metadata to a redacted summary."""
if "_safety_analysis" in conn and isinstance(conn["_safety_analysis"], dict):
safety = conn["_safety_analysis"]
return {
"kind": "folder",
"databases_found": int(safety.get("databases_found", 0)),
"critical_databases": int(safety.get("critical_databases", 0)),
"excluded_databases": int(safety.get("excluded_databases", 0)),
"total_db_size_mb": round(float(safety.get("total_db_size_mb", 0)), 2),
}
if "_file_analysis" in conn and isinstance(conn["_file_analysis"], dict):
analysis = conn["_file_analysis"]
return {
"kind": "file",
"type": analysis.get("type", "unknown"),
"wal_mode": bool(analysis.get("wal_mode", False)),
"is_critical": bool(analysis.get("is_critical", False)),
"size_mb": round(float(analysis.get("size_mb", 0)), 2),
}
return None
@staticmethod
def _portable_report_snapshot():
"""Read the local sync-report log and expose only report-safe metadata."""
log_file = sync_report_log_path()
if not log_file.exists():
return {"count": 0, "latest": None}
try:
with open(log_file, "r", encoding="utf-8") as fh:
reports = json.load(fh)
except (OSError, json.JSONDecodeError, UnicodeDecodeError):
return {"count": 0, "latest": None}
if not isinstance(reports, list):
return {"count": 0, "latest": None}
latest = reports[-1] if reports else None
if not isinstance(latest, dict):
latest = None
latest_summary = None
if latest:
latest_summary = {
"connection": latest.get("connection", ""),
"connection_id": latest.get("connection_id", ""),
"mode": latest.get("mode", ""),
"started_at": latest.get("started_at", ""),
"duration_seconds": latest.get("duration_seconds", 0),
"files_copied": latest.get("files_copied", 0),
"files_deleted": latest.get("files_deleted", 0),
"files_skipped": latest.get("files_skipped", 0),
"bytes_copied": latest.get("bytes_copied", 0),
"total_actions": latest.get("total_actions", 0),
}
return {"count": len(reports), "latest": latest_summary}
@staticmethod
def _portable_autosync(conn):
"""Normalize autosync settings for export without leaking local runtime state."""
autosync = conn.get("autosync", {})
interval = autosync.get("interval_minutes", DEFAULT_AUTOSYNC_INTERVAL)
try:
interval = int(interval)
except (TypeError, ValueError):
interval = DEFAULT_AUTOSYNC_INTERVAL
return {
"enabled": bool(autosync.get("enabled", False)),
"interval_minutes": max(1, interval),
}
@staticmethod
def _portable_patterns(conn):
"""Normalize exclude patterns for export to avoid character-wise string splitting."""
raw_patterns = conn.get("exclude_patterns", [])
if isinstance(raw_patterns, (str, bytes)):
raw_patterns = [raw_patterns]
elif not isinstance(raw_patterns, (list, tuple)):
raw_patterns = []
return [str(pattern) for pattern in raw_patterns if str(pattern).strip()]
def _build_portable_connection(self, conn):
"""Create one redacted portable connection entry."""
conn_type = conn.get("type", ConnectionType.FOLDER)
default_mode = "one_way" if conn_type == ConnectionType.FILE else "mirror"
if conn_type == ConnectionType.SFTP:
default_mode = "update"
portable = {
"id": conn.get("id", ""),
"name": conn.get("name", ""),
"type": conn_type,
"mode": conn.get("mode", default_mode),
"exclude_patterns": self._portable_patterns(conn),
"autosync": self._portable_autosync(conn),
"path_hints": self._portable_path_hints(conn),
}
if conn_type == ConnectionType.FILE:
portable["checkpoint_before_sync"] = bool(conn.get("checkpoint_before_sync", False))
elif conn_type == ConnectionType.SFTP:
portable["conflict_policy"] = "source"
portable["indexing"] = False
portable["remote_warning"] = REMOTE_UNSAFE_DATABASE_WARNING
else:
portable["conflict_policy"] = conn.get("conflict_policy", "source")
portable["indexing"] = bool(conn.get("indexing", True))
safety_summary = self._portable_safety_summary(conn)
if safety_summary: