python-dbsync 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- dbsync/__init__.py +0 -0
- dbsync/__main__.py +5 -0
- dbsync/alerts.py +57 -0
- dbsync/api.py +254 -0
- dbsync/assets/dbsync-conflict.svg +1 -0
- dbsync/assets/dbsync-error.svg +1 -0
- dbsync/assets/dbsync-offline.svg +1 -0
- dbsync/assets/dbsync-paused.svg +1 -0
- dbsync/assets/dbsync-synced.svg +1 -0
- dbsync/assets/dbsync-syncing.svg +1 -0
- dbsync/auth.py +75 -0
- dbsync/cli.py +264 -0
- dbsync/config.py +135 -0
- dbsync/daemon.py +260 -0
- dbsync/gitops.py +170 -0
- dbsync/hashing.py +22 -0
- dbsync/ignore.py +50 -0
- dbsync/plat/__init__.py +41 -0
- dbsync/plat/linux_tray.py +123 -0
- dbsync/plat/posix.py +160 -0
- dbsync/plat/windows.py +254 -0
- dbsync/plat/windows_tray.py +143 -0
- dbsync/state.py +64 -0
- dbsync/status.py +42 -0
- dbsync/sync.py +627 -0
- python_dbsync-0.3.0.dist-info/METADATA +336 -0
- python_dbsync-0.3.0.dist-info/RECORD +31 -0
- python_dbsync-0.3.0.dist-info/WHEEL +5 -0
- python_dbsync-0.3.0.dist-info/entry_points.txt +2 -0
- python_dbsync-0.3.0.dist-info/licenses/LICENSE +48 -0
- python_dbsync-0.3.0.dist-info/top_level.txt +1 -0
dbsync/plat/windows.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""Windows implementation of the dbsync platform interface (see plat/__init__.py).
|
|
2
|
+
|
|
3
|
+
The Windows desktop version of dbsync.
|
|
4
|
+
Same names as posix.py:
|
|
5
|
+
|
|
6
|
+
CONFIG_DIR, DATA_DIR %APPDATA%\\dbsync and %LOCALAPPDATA%\\dbsync
|
|
7
|
+
file_lock(path, on_wait) msvcrt.locking on byte 0 of the lock file
|
|
8
|
+
single_instance(path) non-blocking msvcrt lock held for the process lifetime
|
|
9
|
+
control_address(data_dir) path of control.json (port + token of the channel)
|
|
10
|
+
ControlServer(addr, handler) 127.0.0.1 TCP, one JSON line in, one out, token-checked
|
|
11
|
+
send_command(addr, cmd) client side
|
|
12
|
+
open_path(path) os.startfile
|
|
13
|
+
notify(title, body, urgent) Windows toast through PowerShell (no extra package)
|
|
14
|
+
pid_alive(pid) OpenProcess + GetExitCodeProcess
|
|
15
|
+
service_hint() how to start the daemon here
|
|
16
|
+
|
|
17
|
+
The channel: AF_UNIX with mode 0600 is the posix guard. Here the daemon listens on
|
|
18
|
+
127.0.0.1 only, on a random port, and writes {"port", "token", "pid"} to control.json in
|
|
19
|
+
the user's own %LOCALAPPDATA%; a command must carry that token, so only someone who can
|
|
20
|
+
read the user's profile can drive the daemon.
|
|
21
|
+
"""
|
|
22
|
+
import ctypes
|
|
23
|
+
import hmac
|
|
24
|
+
import json
|
|
25
|
+
import logging
|
|
26
|
+
import msvcrt
|
|
27
|
+
import os
|
|
28
|
+
import secrets
|
|
29
|
+
import socket
|
|
30
|
+
import subprocess
|
|
31
|
+
import threading
|
|
32
|
+
import time
|
|
33
|
+
from contextlib import contextmanager
|
|
34
|
+
|
|
35
|
+
log = logging.getLogger("dbsync")
|
|
36
|
+
|
|
37
|
+
CONFIG_DIR = os.path.join(os.environ.get("APPDATA") or os.path.expanduser("~\\AppData\\Roaming"), "dbsync")
|
|
38
|
+
DATA_DIR_DEFAULT = os.path.join(os.environ.get("LOCALAPPDATA") or os.path.expanduser("~\\AppData\\Local"), "dbsync")
|
|
39
|
+
# DBSYNC_DATA_DIR gives one running copy its own data folder (see posix.py). Unset: exactly as before.
|
|
40
|
+
DATA_DIR = os.path.expanduser(os.environ.get("DBSYNC_DATA_DIR") or DATA_DIR_DEFAULT)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# --- locks -----------------------------------------------------------------------------
|
|
44
|
+
|
|
45
|
+
def _try_lock(fh):
|
|
46
|
+
fh.seek(0)
|
|
47
|
+
try:
|
|
48
|
+
msvcrt.locking(fh.fileno(), msvcrt.LK_NBLCK, 1)
|
|
49
|
+
return True
|
|
50
|
+
except OSError:
|
|
51
|
+
return False
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _unlock(fh):
|
|
55
|
+
fh.seek(0)
|
|
56
|
+
try:
|
|
57
|
+
msvcrt.locking(fh.fileno(), msvcrt.LK_UNLCK, 1)
|
|
58
|
+
except OSError:
|
|
59
|
+
pass
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@contextmanager
|
|
63
|
+
def file_lock(path, on_wait=None):
|
|
64
|
+
"""Exclusive inter-process lock; waits (calling on_wait once) until it is free."""
|
|
65
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
66
|
+
with open(path, "a+") as fh:
|
|
67
|
+
if not _try_lock(fh):
|
|
68
|
+
if on_wait:
|
|
69
|
+
on_wait()
|
|
70
|
+
while not _try_lock(fh):
|
|
71
|
+
time.sleep(0.2)
|
|
72
|
+
try:
|
|
73
|
+
yield
|
|
74
|
+
finally:
|
|
75
|
+
_unlock(fh)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def single_instance(path):
|
|
79
|
+
"""Non-blocking exclusive lock held for the process lifetime. Returns handle or None."""
|
|
80
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
81
|
+
fh = open(path, "a+")
|
|
82
|
+
if not _try_lock(fh):
|
|
83
|
+
fh.close()
|
|
84
|
+
return None
|
|
85
|
+
return fh
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
# --- control channel -------------------------------------------------------------------
|
|
89
|
+
|
|
90
|
+
def control_address(data_dir):
|
|
91
|
+
return os.path.join(data_dir, "control.json")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _read_address(addr):
|
|
95
|
+
try:
|
|
96
|
+
with open(addr, encoding="utf-8") as f:
|
|
97
|
+
d = json.load(f)
|
|
98
|
+
return int(d["port"]), str(d["token"])
|
|
99
|
+
except (OSError, ValueError, KeyError, TypeError) as e:
|
|
100
|
+
raise ConnectionRefusedError(f"no dbsync control channel at {addr}") from e
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _recv_line(conn, limit):
|
|
104
|
+
data = b""
|
|
105
|
+
while not data.endswith(b"\n") and len(data) < limit:
|
|
106
|
+
chunk = conn.recv(65536)
|
|
107
|
+
if not chunk:
|
|
108
|
+
break
|
|
109
|
+
data += chunk
|
|
110
|
+
return data
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class ControlServer:
|
|
114
|
+
"""One JSON line in ({"cmd": ..., "token": ...}), one JSON line out."""
|
|
115
|
+
|
|
116
|
+
def __init__(self, path, handler):
|
|
117
|
+
self.path = path
|
|
118
|
+
self.handler = handler
|
|
119
|
+
self._sock = None
|
|
120
|
+
self._token = secrets.token_hex(16)
|
|
121
|
+
|
|
122
|
+
def start(self):
|
|
123
|
+
if os.path.exists(self.path):
|
|
124
|
+
try: # another daemon alive?
|
|
125
|
+
send_command(self.path, "status", timeout=1)
|
|
126
|
+
raise RuntimeError(f"another dbsync daemon is listening ({self.path})")
|
|
127
|
+
except (ConnectionError, OSError):
|
|
128
|
+
try:
|
|
129
|
+
os.unlink(self.path)
|
|
130
|
+
except OSError:
|
|
131
|
+
pass
|
|
132
|
+
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
133
|
+
s.bind(("127.0.0.1", 0))
|
|
134
|
+
s.listen(4)
|
|
135
|
+
self._sock = s
|
|
136
|
+
os.makedirs(os.path.dirname(self.path), exist_ok=True)
|
|
137
|
+
tmp = self.path + ".tmp"
|
|
138
|
+
with open(tmp, "w", encoding="utf-8") as f:
|
|
139
|
+
json.dump({"port": s.getsockname()[1], "token": self._token, "pid": os.getpid()}, f)
|
|
140
|
+
for attempt in range(20): # a client reading it blocks the replace on Windows
|
|
141
|
+
try:
|
|
142
|
+
os.replace(tmp, self.path)
|
|
143
|
+
break
|
|
144
|
+
except PermissionError:
|
|
145
|
+
if attempt == 19:
|
|
146
|
+
raise
|
|
147
|
+
time.sleep(0.05)
|
|
148
|
+
threading.Thread(target=self._serve, name="control", daemon=True).start()
|
|
149
|
+
|
|
150
|
+
def _serve(self):
|
|
151
|
+
while True:
|
|
152
|
+
try:
|
|
153
|
+
conn, _ = self._sock.accept()
|
|
154
|
+
except OSError:
|
|
155
|
+
return
|
|
156
|
+
with conn:
|
|
157
|
+
try:
|
|
158
|
+
conn.settimeout(5)
|
|
159
|
+
msg = json.loads(_recv_line(conn, 4096).decode() or "{}")
|
|
160
|
+
if not hmac.compare_digest(str(msg.get("token", "")), self._token):
|
|
161
|
+
reply = {"ok": False, "error": "bad token"}
|
|
162
|
+
else:
|
|
163
|
+
reply = self.handler(msg.get("cmd", ""))
|
|
164
|
+
except Exception as e: # never kill the server thread
|
|
165
|
+
reply = {"ok": False, "error": type(e).__name__}
|
|
166
|
+
try:
|
|
167
|
+
conn.sendall((json.dumps(reply) + "\n").encode())
|
|
168
|
+
except OSError:
|
|
169
|
+
pass
|
|
170
|
+
|
|
171
|
+
def close(self):
|
|
172
|
+
if self._sock:
|
|
173
|
+
self._sock.close()
|
|
174
|
+
try:
|
|
175
|
+
with open(self.path, encoding="utf-8") as f:
|
|
176
|
+
mine = json.load(f).get("token") == self._token
|
|
177
|
+
except (OSError, ValueError):
|
|
178
|
+
mine = False
|
|
179
|
+
if mine: # never remove another daemon's address file
|
|
180
|
+
try:
|
|
181
|
+
os.unlink(self.path)
|
|
182
|
+
except OSError:
|
|
183
|
+
pass
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def send_command(path, cmd, timeout=5):
|
|
187
|
+
port, token = _read_address(path)
|
|
188
|
+
s = socket.create_connection(("127.0.0.1", port), timeout=timeout)
|
|
189
|
+
try:
|
|
190
|
+
s.sendall((json.dumps({"cmd": cmd, "token": token}) + "\n").encode())
|
|
191
|
+
return json.loads(_recv_line(s, 1 << 20).decode() or "{}")
|
|
192
|
+
finally:
|
|
193
|
+
s.close()
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
# --- desktop ---------------------------------------------------------------------------
|
|
197
|
+
|
|
198
|
+
def open_path(path):
|
|
199
|
+
os.startfile(path)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
# Toast through the WinRT API that Windows PowerShell 5.1 can reach without any module.
|
|
203
|
+
# Title and body travel in environment variables, never inside the script text.
|
|
204
|
+
_TOAST_PS = r"""
|
|
205
|
+
$null = [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime]
|
|
206
|
+
$null = [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime]
|
|
207
|
+
$x = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)
|
|
208
|
+
$t = $x.GetElementsByTagName('text')
|
|
209
|
+
$null = $t.Item(0).AppendChild($x.CreateTextNode($env:DBSYNC_TOAST_TITLE))
|
|
210
|
+
$null = $t.Item(1).AppendChild($x.CreateTextNode($env:DBSYNC_TOAST_BODY))
|
|
211
|
+
$app = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\WindowsPowerShell\v1.0\powershell.exe'
|
|
212
|
+
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($app).Show([Windows.UI.Notifications.ToastNotification]::new($x))
|
|
213
|
+
"""
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def notify(title, body, urgent=False):
|
|
217
|
+
env = dict(os.environ, DBSYNC_TOAST_TITLE=str(title)[:200], DBSYNC_TOAST_BODY=str(body)[:600])
|
|
218
|
+
try:
|
|
219
|
+
subprocess.Popen(["powershell.exe", "-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden",
|
|
220
|
+
"-Command", _TOAST_PS], env=env, stdout=subprocess.DEVNULL,
|
|
221
|
+
stderr=subprocess.DEVNULL, creationflags=subprocess.CREATE_NO_WINDOW)
|
|
222
|
+
except OSError:
|
|
223
|
+
log.info("notify (no toast): %s: %s", title, body)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
_PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
|
|
227
|
+
_STILL_ACTIVE = 259
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def pid_alive(pid):
|
|
231
|
+
try:
|
|
232
|
+
pid = int(pid)
|
|
233
|
+
except (ValueError, TypeError):
|
|
234
|
+
return False
|
|
235
|
+
if pid <= 0:
|
|
236
|
+
return False
|
|
237
|
+
k32 = ctypes.windll.kernel32
|
|
238
|
+
h = k32.OpenProcess(_PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
|
|
239
|
+
if not h:
|
|
240
|
+
return False # no such process (or no right to see it)
|
|
241
|
+
try:
|
|
242
|
+
code = ctypes.c_ulong()
|
|
243
|
+
if not k32.GetExitCodeProcess(h, ctypes.byref(code)):
|
|
244
|
+
return False
|
|
245
|
+
return code.value == _STILL_ACTIVE
|
|
246
|
+
finally:
|
|
247
|
+
k32.CloseHandle(h)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def service_hint(action="status"):
|
|
251
|
+
"""The "is it running?" text (posix: systemctl --user <action> dbsync)."""
|
|
252
|
+
if action == "start":
|
|
253
|
+
return "schtasks /Run /TN dbsync (or: dbsync daemon)"
|
|
254
|
+
return f"schtasks /Query /TN dbsync (action {action}: Task Scheduler, task 'dbsync')"
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Windows tray icon for dbsync (pystray + Pillow), same role and signature as linux_tray.py.
|
|
2
|
+
|
|
3
|
+
the Windows desktop version of dbsync. Talks to the daemon only through the
|
|
4
|
+
status file and the control channel, like the Linux tray. The icons are drawn here with
|
|
5
|
+
Pillow (it cannot read the SVGs in assets/): a coloured disc per state, with a mark.
|
|
6
|
+
"""
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
|
|
12
|
+
import pystray
|
|
13
|
+
from PIL import Image, ImageDraw
|
|
14
|
+
|
|
15
|
+
from ..status import PROBLEM_STATES, effective_state, read_status
|
|
16
|
+
from . import notify, open_path, pid_alive, send_command, service_hint
|
|
17
|
+
|
|
18
|
+
log = logging.getLogger("dbsync.tray")
|
|
19
|
+
|
|
20
|
+
LABEL = {"synced": "Synced", "syncing": "Syncing...", "paused": "Paused", "conflict": "Conflict",
|
|
21
|
+
"error": "Error", "offline": "Offline", "stopped": "Daemon not running"}
|
|
22
|
+
COLOUR = {"synced": (46, 160, 67), "syncing": (33, 118, 210), "paused": (128, 128, 128),
|
|
23
|
+
"conflict": (230, 145, 20), "error": (205, 40, 40), "offline": (110, 110, 110),
|
|
24
|
+
"stopped": (205, 40, 40)}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _icon(state, size=64):
|
|
28
|
+
img = Image.new("RGBA", (size, size), (0, 0, 0, 0))
|
|
29
|
+
d = ImageDraw.Draw(img)
|
|
30
|
+
d.ellipse((2, 2, size - 3, size - 3), fill=COLOUR.get(state, COLOUR["error"]) + (255,))
|
|
31
|
+
w, c = max(4, size // 10), size // 2
|
|
32
|
+
white = (255, 255, 255, 255)
|
|
33
|
+
if state == "synced": # tick
|
|
34
|
+
d.line((size * .28, c, size * .44, size * .68, size * .74, size * .32), fill=white, width=w)
|
|
35
|
+
elif state == "syncing": # two arrows, up and down
|
|
36
|
+
d.line((size * .38, size * .25, size * .38, size * .75), fill=white, width=w)
|
|
37
|
+
d.polygon(((size * .25, size * .38), (size * .38, size * .2), (size * .51, size * .38)), fill=white)
|
|
38
|
+
d.line((size * .62, size * .25, size * .62, size * .75), fill=white, width=w)
|
|
39
|
+
d.polygon(((size * .49, size * .62), (size * .62, size * .8), (size * .75, size * .62)), fill=white)
|
|
40
|
+
elif state == "paused": # two bars
|
|
41
|
+
d.rectangle((size * .33, size * .27, size * .44, size * .73), fill=white)
|
|
42
|
+
d.rectangle((size * .56, size * .27, size * .67, size * .73), fill=white)
|
|
43
|
+
elif state in ("conflict", "error", "stopped"): # exclamation mark
|
|
44
|
+
d.rectangle((c - w // 2, size * .22, c + w // 2, size * .6), fill=white)
|
|
45
|
+
d.ellipse((c - w // 2 - 1, size * .68, c + w // 2 + 1, size * .68 + w + 2), fill=white)
|
|
46
|
+
else: # offline: a dash
|
|
47
|
+
d.rectangle((size * .27, c - w // 2, size * .73, c + w // 2), fill=white)
|
|
48
|
+
return img
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Tray:
|
|
52
|
+
def __init__(self, status_path, control_addr, local_folder, log_path, poll=1):
|
|
53
|
+
self.status_path, self.control_addr = status_path, control_addr
|
|
54
|
+
self.local_folder, self.log_path = local_folder, log_path
|
|
55
|
+
self.poll = poll
|
|
56
|
+
self.notified = None # (state, message) last notified
|
|
57
|
+
self.state = None
|
|
58
|
+
self.line, self.detail = "dbsync: ...", ""
|
|
59
|
+
self._stop = threading.Event()
|
|
60
|
+
menu = pystray.Menu(
|
|
61
|
+
pystray.MenuItem(lambda _i: self.line, None, enabled=False),
|
|
62
|
+
pystray.MenuItem(lambda _i: self.detail, None, enabled=False,
|
|
63
|
+
visible=lambda _i: bool(self.detail)),
|
|
64
|
+
pystray.Menu.SEPARATOR,
|
|
65
|
+
pystray.MenuItem("Sync now", lambda *_: self._cmd("sync-now"),
|
|
66
|
+
enabled=lambda _i: self.state not in ("syncing", "stopped")),
|
|
67
|
+
pystray.MenuItem(lambda _i: "Resume" if self.state == "paused" else "Pause",
|
|
68
|
+
self._toggle_pause, enabled=lambda _i: self.state != "stopped"),
|
|
69
|
+
pystray.Menu.SEPARATOR,
|
|
70
|
+
pystray.MenuItem("Open folder", lambda *_: open_path(self.local_folder), default=True),
|
|
71
|
+
pystray.MenuItem("Open log", lambda *_: open_path(self.log_path)),
|
|
72
|
+
pystray.Menu.SEPARATOR,
|
|
73
|
+
pystray.MenuItem("Quit tray", self._quit),
|
|
74
|
+
)
|
|
75
|
+
self.icon = pystray.Icon("dbsync", _icon("syncing"), "dbsync", menu)
|
|
76
|
+
|
|
77
|
+
def _cmd(self, cmd):
|
|
78
|
+
def run():
|
|
79
|
+
try:
|
|
80
|
+
r = send_command(self.control_addr, cmd)
|
|
81
|
+
if not r.get("ok"):
|
|
82
|
+
log.warning("command %s failed: %s", cmd, r.get("error"))
|
|
83
|
+
except OSError as e:
|
|
84
|
+
log.warning("command %s: daemon unreachable (%s)", cmd, type(e).__name__)
|
|
85
|
+
notify("dbsync", f"Daemon is not running ({service_hint('start')})", True)
|
|
86
|
+
time.sleep(0.3)
|
|
87
|
+
self.refresh()
|
|
88
|
+
threading.Thread(target=run, daemon=True).start()
|
|
89
|
+
|
|
90
|
+
def _toggle_pause(self, *_):
|
|
91
|
+
self._cmd("resume" if self.state == "paused" else "pause")
|
|
92
|
+
|
|
93
|
+
def _quit(self, *_):
|
|
94
|
+
self._stop.set()
|
|
95
|
+
self.icon.stop()
|
|
96
|
+
|
|
97
|
+
def refresh(self):
|
|
98
|
+
st = read_status(self.status_path)
|
|
99
|
+
state = effective_state(st, pid_alive)
|
|
100
|
+
msg = (st or {}).get("message", "") if state != "stopped" else service_hint("start")
|
|
101
|
+
if state != self.state:
|
|
102
|
+
self.icon.icon = _icon(state)
|
|
103
|
+
self.state = state
|
|
104
|
+
last = (st or {}).get("last_sync")
|
|
105
|
+
line = f"dbsync: {LABEL.get(state, state)}"
|
|
106
|
+
if last and state in ("synced", "paused"):
|
|
107
|
+
line += f" - {last[11:16]}"
|
|
108
|
+
self.line, self.detail = line, (msg or "")[:70]
|
|
109
|
+
# Tooltip: folder, state, last sync, then the message.
|
|
110
|
+
name = os.path.basename(os.path.normpath(self.local_folder)) or self.local_folder
|
|
111
|
+
tip = f"dbsync - {name}\n{LABEL.get(state, state)}"
|
|
112
|
+
if last:
|
|
113
|
+
tip += f", last sync {last[11:16]}"
|
|
114
|
+
if self.detail and state != "synced":
|
|
115
|
+
tip += f"\n{self.detail}"
|
|
116
|
+
self.icon.title = tip[:127] # Windows cuts tooltips at 127 characters
|
|
117
|
+
self.icon.update_menu()
|
|
118
|
+
if state in PROBLEM_STATES:
|
|
119
|
+
key = (state, msg)
|
|
120
|
+
if key != self.notified:
|
|
121
|
+
self.notified = key
|
|
122
|
+
files = ", ".join((st or {}).get("conflicts", [])[:5])
|
|
123
|
+
notify(f"dbsync: {LABEL[state]}", (msg or "") + (f"\n{files}" if files else ""),
|
|
124
|
+
urgent=state == "error")
|
|
125
|
+
elif state == "synced":
|
|
126
|
+
self.notified = None
|
|
127
|
+
|
|
128
|
+
def _loop(self, icon):
|
|
129
|
+
icon.visible = True
|
|
130
|
+
while not self._stop.is_set():
|
|
131
|
+
try:
|
|
132
|
+
self.refresh()
|
|
133
|
+
except Exception: # the tray must not die on one bad read
|
|
134
|
+
log.exception("tray refresh failed")
|
|
135
|
+
self._stop.wait(self.poll)
|
|
136
|
+
|
|
137
|
+
def run(self):
|
|
138
|
+
self.icon.run(setup=self._loop)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def run_tray(status_path, control_addr, local_folder, log_path):
|
|
142
|
+
Tray(status_path, control_addr, local_folder, log_path).run()
|
|
143
|
+
return 0
|
dbsync/state.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Per-folder SQLite state: cursor, path -> (rev, content_hash, size, mtime), last sync."""
|
|
2
|
+
import os
|
|
3
|
+
import sqlite3
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
SCHEMA = """
|
|
7
|
+
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);
|
|
8
|
+
CREATE TABLE IF NOT EXISTS files (
|
|
9
|
+
rel TEXT PRIMARY KEY,
|
|
10
|
+
rel_lower TEXT NOT NULL,
|
|
11
|
+
rev TEXT, content_hash TEXT, size INTEGER, mtime REAL
|
|
12
|
+
);
|
|
13
|
+
CREATE INDEX IF NOT EXISTS files_lower ON files(rel_lower);
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class State:
|
|
18
|
+
def __init__(self, path):
|
|
19
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
20
|
+
self.path = path
|
|
21
|
+
self.db = sqlite3.connect(path)
|
|
22
|
+
self.db.row_factory = sqlite3.Row
|
|
23
|
+
self.db.executescript(SCHEMA)
|
|
24
|
+
self.db.commit()
|
|
25
|
+
|
|
26
|
+
def get_meta(self, key, default=None):
|
|
27
|
+
r = self.db.execute("SELECT value FROM meta WHERE key=?", (key,)).fetchone()
|
|
28
|
+
return r["value"] if r else default
|
|
29
|
+
|
|
30
|
+
def set_meta(self, key, value):
|
|
31
|
+
self.db.execute("INSERT OR REPLACE INTO meta(key, value) VALUES(?, ?)", (key, value))
|
|
32
|
+
self.db.commit()
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def cursor(self):
|
|
36
|
+
return self.get_meta("cursor")
|
|
37
|
+
|
|
38
|
+
def set_cursor(self, cursor):
|
|
39
|
+
self.set_meta("cursor", cursor)
|
|
40
|
+
|
|
41
|
+
def mark_synced(self):
|
|
42
|
+
self.set_meta("last_sync", time.strftime("%Y-%m-%d %H:%M:%S"))
|
|
43
|
+
|
|
44
|
+
def get(self, rel):
|
|
45
|
+
r = self.db.execute("SELECT * FROM files WHERE rel=?", (rel,)).fetchone()
|
|
46
|
+
if r is None:
|
|
47
|
+
r = self.db.execute("SELECT * FROM files WHERE rel_lower=?", (rel.lower(),)).fetchone()
|
|
48
|
+
return dict(r) if r else None
|
|
49
|
+
|
|
50
|
+
def put(self, rel, rev, content_hash, size, mtime):
|
|
51
|
+
self.db.execute("DELETE FROM files WHERE rel_lower=? AND rel<>?", (rel.lower(), rel))
|
|
52
|
+
self.db.execute("INSERT OR REPLACE INTO files(rel, rel_lower, rev, content_hash, size, mtime) "
|
|
53
|
+
"VALUES(?,?,?,?,?,?)", (rel, rel.lower(), rev, content_hash, size, mtime))
|
|
54
|
+
self.db.commit()
|
|
55
|
+
|
|
56
|
+
def delete(self, rel):
|
|
57
|
+
self.db.execute("DELETE FROM files WHERE rel=? OR rel_lower=?", (rel, rel.lower()))
|
|
58
|
+
self.db.commit()
|
|
59
|
+
|
|
60
|
+
def all(self):
|
|
61
|
+
return {r["rel"]: dict(r) for r in self.db.execute("SELECT * FROM files")}
|
|
62
|
+
|
|
63
|
+
def close(self):
|
|
64
|
+
self.db.close()
|
dbsync/status.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Daemon status file (JSON), shared by the daemon, the tray and `dbsync ctl status`."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import time
|
|
5
|
+
|
|
6
|
+
STATES = ("synced", "syncing", "paused", "conflict", "error", "offline")
|
|
7
|
+
STOPPED = "stopped" # written by the daemon on exit; also inferred if its pid is gone
|
|
8
|
+
PROBLEM_STATES = ("conflict", "error")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def write_status(path, data):
|
|
12
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
13
|
+
tmp = f"{path}.{os.getpid()}.tmp"
|
|
14
|
+
with open(tmp, "w") as f:
|
|
15
|
+
json.dump(data, f, indent=1, sort_keys=True)
|
|
16
|
+
# Windows refuses to replace a file another process has open (the tray reads this one
|
|
17
|
+
# every second): retry briefly instead of failing the sync.
|
|
18
|
+
for attempt in range(20):
|
|
19
|
+
try:
|
|
20
|
+
os.replace(tmp, path)
|
|
21
|
+
return
|
|
22
|
+
except PermissionError:
|
|
23
|
+
if attempt == 19:
|
|
24
|
+
raise
|
|
25
|
+
time.sleep(0.05)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def read_status(path):
|
|
29
|
+
try:
|
|
30
|
+
with open(path) as f:
|
|
31
|
+
return json.load(f)
|
|
32
|
+
except (OSError, ValueError):
|
|
33
|
+
return None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def effective_state(st, pid_alive):
|
|
37
|
+
"""State the UI should show: 'stopped' when there is no live daemon behind the file."""
|
|
38
|
+
if not st:
|
|
39
|
+
return STOPPED
|
|
40
|
+
if st.get("state") != STOPPED and not pid_alive(st.get("pid")):
|
|
41
|
+
return STOPPED
|
|
42
|
+
return st.get("state", STOPPED)
|