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 ADDED
File without changes
dbsync/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
dbsync/alerts.py ADDED
@@ -0,0 +1,57 @@
1
+ """Phone push alerts (ntfy via the owner's notify.sh) when the daemon enters conflict/error.
2
+
3
+ Rate limits: one push per state change into conflict/error; error pushes at most once per
4
+ 15 minutes (retries that flap error -> syncing -> error do not re-alert). The message holds
5
+ only the state, the daemon's message (paths / error type) and the folder, never secrets.
6
+ """
7
+ import logging
8
+ import os
9
+ import subprocess
10
+ import time
11
+
12
+ log = logging.getLogger("dbsync")
13
+
14
+ ERROR_MIN_INTERVAL = 15 * 60
15
+
16
+
17
+ class PhoneAlerter:
18
+ def __init__(self, script, enabled=True, min_interval=ERROR_MIN_INTERVAL, runner=None,
19
+ clock=time.time):
20
+ self.script = os.path.expanduser(script) if script else ""
21
+ self.enabled = enabled and bool(self.script)
22
+ self.min_interval = min_interval
23
+ self.runner = runner or self._run
24
+ self.clock = clock
25
+ self.last_state = None # last settled problem state we alerted for
26
+ self.last_error_push = -1e18
27
+
28
+ def observe(self, state, message, folder=""):
29
+ """Call for every settled state (not 'syncing'). Returns True if a push was sent."""
30
+ if state not in ("conflict", "error"):
31
+ if state in ("synced", "paused"):
32
+ self.last_state = None
33
+ return False
34
+ if not self.enabled or state == self.last_state:
35
+ return False
36
+ now = self.clock()
37
+ if state == "error" and now - self.last_error_push < self.min_interval:
38
+ self.last_state = state
39
+ return False
40
+ self.last_state = state
41
+ if state == "error":
42
+ self.last_error_push = now
43
+ body = f"{message}" + (f" [{folder}]" if folder else "")
44
+ self.runner([self.script, body[:300], f"dbsync: {state}", "4", "warning"])
45
+ log.info("phone alert sent: %s", state)
46
+ return True
47
+
48
+ @staticmethod
49
+ def _run(argv):
50
+ if not os.path.isfile(argv[0]):
51
+ log.warning("ntfy alert skipped: %s not found", argv[0])
52
+ return
53
+ try:
54
+ subprocess.Popen(argv, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
55
+ start_new_session=True)
56
+ except OSError as e:
57
+ log.warning("ntfy alert failed: %s", type(e).__name__)
dbsync/api.py ADDED
@@ -0,0 +1,254 @@
1
+ """Dropbox API layer. Every remote path is checked against the configured roots.
2
+
3
+ Deletes (files/delete_v2) always carry parent_rev, so Dropbox refuses them if the file
4
+ changed since our last known rev. Moves (files/move_v2) verify the source rev first.
5
+ """
6
+ import logging
7
+ import os
8
+ import posixpath
9
+ import time
10
+
11
+ log = logging.getLogger("dbsync")
12
+
13
+ CHUNK = 8 * 1024 * 1024
14
+ SIMPLE_UPLOAD_MAX = 140 * 1024 * 1024
15
+
16
+
17
+ class OutsideRootError(Exception):
18
+ pass
19
+
20
+
21
+ class CursorReset(Exception):
22
+ """Saved cursor is no longer valid; do a full listing."""
23
+
24
+
25
+ class RevConflict(Exception):
26
+ """Upload refused by Dropbox: remote changed since our last known rev (or exists)."""
27
+
28
+
29
+ class NotFound(Exception):
30
+ """Remote path does not exist (e.g. already deleted)."""
31
+
32
+
33
+ def is_network_error(e):
34
+ """True for connection problems (-> 'offline'), not for API errors."""
35
+ try:
36
+ import requests
37
+ if isinstance(e, (requests.exceptions.ConnectionError, requests.exceptions.Timeout)):
38
+ return True
39
+ except ImportError:
40
+ pass
41
+ return isinstance(e, (ConnectionError, TimeoutError)) or (
42
+ isinstance(e, OSError) and getattr(e, "errno", None) in (101, 110, 111, 113, -2, -3))
43
+
44
+
45
+ def normalize_remote(path: str) -> str:
46
+ if not path or not path.startswith("/"):
47
+ raise OutsideRootError(f"remote path must be absolute: {path!r}")
48
+ if "\\" in path or "\x00" in path:
49
+ raise OutsideRootError(f"bad remote path: {path!r}")
50
+ parts = path.split("/")
51
+ if any(p in ("..", ".") for p in parts):
52
+ raise OutsideRootError(f"relative segments not allowed: {path!r}")
53
+ norm = posixpath.normpath(path)
54
+ return norm.lower() # Dropbox paths are case-insensitive
55
+
56
+
57
+ def validate_root(root: str) -> str:
58
+ n = normalize_remote(root)
59
+ if n == "/" or len([p for p in n.split("/") if p]) < 2:
60
+ raise OutsideRootError(f"refusing too-broad sync root: {root!r}")
61
+ return n
62
+
63
+
64
+ def assert_within_configured_roots(path: str, roots) -> str:
65
+ """Raise OutsideRootError unless `path` is a configured root or below one."""
66
+ n = normalize_remote(path)
67
+ for r in roots:
68
+ rn = validate_root(r)
69
+ if n == rn or n.startswith(rn + "/"):
70
+ return path
71
+ raise OutsideRootError(f"REFUSED: {path!r} is outside configured roots")
72
+
73
+
74
+ def _entry(md):
75
+ import dropbox
76
+ if isinstance(md, dropbox.files.FileMetadata):
77
+ tag = "file"
78
+ elif isinstance(md, dropbox.files.FolderMetadata):
79
+ tag = "folder"
80
+ else:
81
+ tag = "deleted"
82
+ return {"tag": tag, "path": md.path_display, "path_lower": md.path_lower,
83
+ "rev": getattr(md, "rev", None), "content_hash": getattr(md, "content_hash", None),
84
+ "size": getattr(md, "size", None)}
85
+
86
+
87
+ class DropboxAPI:
88
+ def __init__(self, roots, secrets_file):
89
+ import dropbox
90
+ from dotenv import dotenv_values
91
+ self.roots = [validate_root(r) for r in roots]
92
+ cfg = dotenv_values(os.path.expanduser(secrets_file))
93
+ missing = [k for k in ("DROPBOX_APP_KEY", "DROPBOX_APP_SECRET", "DROPBOX_REFRESH_TOKEN")
94
+ if not cfg.get(k)]
95
+ if missing:
96
+ raise RuntimeError(f"missing credentials in {secrets_file}: {', '.join(missing)}")
97
+ self._dbx = dropbox.Dropbox(app_key=cfg["DROPBOX_APP_KEY"],
98
+ app_secret=cfg["DROPBOX_APP_SECRET"],
99
+ oauth2_refresh_token=cfg["DROPBOX_REFRESH_TOKEN"],
100
+ timeout=600)
101
+ self._dropbox = dropbox
102
+
103
+ def _check(self, path):
104
+ return assert_within_configured_roots(path, self.roots)
105
+
106
+ def longpoll_client(self):
107
+ """Separate client for the longpoll thread (HTTP sessions are not shared across threads)."""
108
+ c = object.__new__(DropboxAPI)
109
+ c.roots, c._dropbox = self.roots, self._dropbox
110
+ c._dbx = self._dbx.clone(session=self._dropbox.create_session())
111
+ return c
112
+
113
+ def _retry(self, fn, *a, **kw):
114
+ exc = self._dropbox.exceptions
115
+ for attempt in range(5):
116
+ try:
117
+ return fn(*a, **kw)
118
+ except exc.RateLimitError as e:
119
+ wait = (e.backoff or 5) + attempt
120
+ log.warning("rate limited; sleeping %ss", wait)
121
+ time.sleep(wait)
122
+ except exc.InternalServerError:
123
+ time.sleep(2 ** attempt)
124
+ return fn(*a, **kw)
125
+
126
+ def _filter(self, entries):
127
+ out = []
128
+ for md in entries:
129
+ e = _entry(md)
130
+ self._check(e["path_lower"]) # server should never return outside, but verify
131
+ out.append(e)
132
+ return out
133
+
134
+ def list_folder(self, root):
135
+ self._check(root)
136
+ r = self._retry(self._dbx.files_list_folder, root, recursive=True)
137
+ entries = self._filter(r.entries)
138
+ while r.has_more:
139
+ r = self._retry(self._dbx.files_list_folder_continue, r.cursor)
140
+ entries += self._filter(r.entries)
141
+ return entries, r.cursor
142
+
143
+ def list_continue(self, cursor):
144
+ entries = []
145
+ ApiError = self._dropbox.exceptions.ApiError
146
+ while True:
147
+ try:
148
+ r = self._retry(self._dbx.files_list_folder_continue, cursor)
149
+ except ApiError as e:
150
+ if hasattr(e.error, "is_reset") and e.error.is_reset():
151
+ raise CursorReset() from None
152
+ raise
153
+ entries += self._filter(r.entries)
154
+ cursor = r.cursor
155
+ if not r.has_more:
156
+ return entries, cursor
157
+
158
+ def get_latest_cursor(self, root):
159
+ self._check(root)
160
+ return self._retry(self._dbx.files_list_folder_get_latest_cursor, root, recursive=True).cursor
161
+
162
+ def longpoll(self, cursor, timeout):
163
+ """Returns (changes: bool, backoff: int|None). Cursor came from a checked root."""
164
+ r = self._dbx.files_list_folder_longpoll(cursor, timeout=timeout)
165
+ return r.changes, r.backoff
166
+
167
+ def download(self, path, dest):
168
+ self._check(path)
169
+ md = self._retry(self._dbx.files_download_to_file, dest, path)
170
+ return _entry(md)
171
+
172
+ def upload(self, path, local_file, rev=None):
173
+ """rev given -> mode update(rev); rev None -> mode add, autorename False."""
174
+ self._check(path)
175
+ WriteMode = self._dropbox.files.WriteMode
176
+ mode = WriteMode.update(rev) if rev else WriteMode.add
177
+ ApiError = self._dropbox.exceptions.ApiError
178
+ size = os.path.getsize(local_file)
179
+ try:
180
+ with open(local_file, "rb") as f:
181
+ if size <= SIMPLE_UPLOAD_MAX:
182
+ md = self._dbx.files_upload(f.read(), path, mode=mode, autorename=False,
183
+ strict_conflict=True)
184
+ else:
185
+ start = self._dbx.files_upload_session_start(f.read(CHUNK))
186
+ cur = self._dropbox.files.UploadSessionCursor(start.session_id, f.tell())
187
+ commit = self._dropbox.files.CommitInfo(path=path, mode=mode, autorename=False,
188
+ strict_conflict=True)
189
+ while True:
190
+ chunk = f.read(CHUNK)
191
+ if size - cur.offset <= CHUNK:
192
+ md = self._dbx.files_upload_session_finish(chunk, cur, commit)
193
+ break
194
+ self._dbx.files_upload_session_append_v2(chunk, cur)
195
+ cur.offset = f.tell()
196
+ except ApiError as e:
197
+ err = e.error
198
+ werr = None
199
+ if hasattr(err, "is_path") and err.is_path():
200
+ p = err.get_path()
201
+ werr = p.reason if hasattr(p, "reason") else p
202
+ if werr is not None and hasattr(werr, "is_conflict") and werr.is_conflict():
203
+ raise RevConflict(path) from None
204
+ raise
205
+ return _entry(md)
206
+
207
+ def get_metadata(self, path):
208
+ """-> entry dict, or None if the path does not exist."""
209
+ self._check(path)
210
+ ApiError = self._dropbox.exceptions.ApiError
211
+ try:
212
+ md = self._retry(self._dbx.files_get_metadata, path)
213
+ except ApiError as e:
214
+ err = e.error
215
+ if hasattr(err, "is_path") and err.is_path() and err.get_path().is_not_found():
216
+ return None
217
+ raise
218
+ return _entry(md)
219
+
220
+ def delete(self, path, parent_rev):
221
+ """Delete one FILE only if its current rev == parent_rev. Raises RevConflict / NotFound."""
222
+ self._check(path)
223
+ if not parent_rev:
224
+ raise ValueError(f"refusing delete without parent_rev: {path}")
225
+ ApiError = self._dropbox.exceptions.ApiError
226
+ try:
227
+ r = self._retry(self._dbx.files_delete_v2, path, parent_rev=parent_rev)
228
+ except ApiError as e:
229
+ cur = self.get_metadata(path)
230
+ if cur is None:
231
+ raise NotFound(path) from None
232
+ if cur["tag"] != "file" or cur["rev"] != parent_rev:
233
+ raise RevConflict(path) from None
234
+ log.warning("delete failed for %s: %s", path, type(e.error).__name__)
235
+ raise
236
+ log.info("DELETED remote %s parent_rev=%s", path, parent_rev)
237
+ return _entry(r.metadata)
238
+
239
+ def move(self, src, dst, expect_rev):
240
+ """Move one FILE src->dst after checking src's rev == expect_rev. Raises RevConflict."""
241
+ self._check(src)
242
+ self._check(dst)
243
+ cur = self.get_metadata(src)
244
+ if cur is None or cur["tag"] != "file" or cur["rev"] != expect_rev:
245
+ raise RevConflict(src)
246
+ ApiError = self._dropbox.exceptions.ApiError
247
+ try:
248
+ r = self._retry(self._dbx.files_move_v2, src, dst, autorename=False,
249
+ allow_ownership_transfer=False)
250
+ except ApiError as e:
251
+ log.warning("move %s -> %s refused: %s", src, dst, type(e.error).__name__)
252
+ raise RevConflict(src) from None
253
+ log.info("MOVED remote %s (rev=%s) -> %s", src, expect_rev, dst)
254
+ return _entry(r.metadata)
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><circle cx="12" cy="12" r="11" fill="#d97706"/><path d="M12 6.5v7" fill="none" stroke="#ffffff" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/><circle cx="12" cy="17.3" r="1.5" fill="#ffffff"/></svg>
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><circle cx="12" cy="12" r="11" fill="#c0392b"/><path d="M8 8l8 8M16 8l-8 8" fill="none" stroke="#ffffff" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><circle cx="12" cy="12" r="11" fill="#6b7280"/><path d="M7.5 15.5h9a3 3 0 0 0-.6-5.9 4.2 4.2 0 0 0-8.1.9A2.5 2.5 0 0 0 7.5 15.5z" fill="none" stroke="#ffffff" stroke-width="1.8"/><path d="M5.5 5.5l13 13" fill="none" stroke="#ffffff" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><circle cx="12" cy="12" r="11" fill="#6b7280"/><path d="M9.5 7.5v9M14.5 7.5v9" fill="none" stroke="#ffffff" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><circle cx="12" cy="12" r="11" fill="#1e7a46"/><path d="M6.5 12.5l3.5 3.5 7.5-8" fill="none" stroke="#ffffff" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
@@ -0,0 +1 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><circle cx="12" cy="12" r="11" fill="#1d5fbf"/><path d="M17.5 9.5A6 6 0 0 0 6.8 8.6M6.5 14.5a6 6 0 0 0 10.7.9" fill="none" stroke="#ffffff" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/><path d="M17.8 5.5v4h-4M6.2 18.5v-4h4" fill="none" stroke="#ffffff" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/></svg>
dbsync/auth.py ADDED
@@ -0,0 +1,75 @@
1
+ """`dbsync auth`: get a Dropbox refresh token and save it in the secrets file, without printing it.
2
+
3
+ the same steps as scripts/dropbox_reauth.py,
4
+ as a command, so someone who installed dbsync with pip can set up their own Dropbox app.
5
+ Run it in your own terminal: the code you paste is read hidden, and no token is ever printed.
6
+ """
7
+ import getpass
8
+ import os
9
+ import re
10
+ import shutil
11
+ import stat
12
+ import time
13
+ import urllib.parse
14
+ import webbrowser
15
+
16
+ from dotenv import dotenv_values
17
+
18
+ AUTH_URL = "https://www.dropbox.com/oauth2/authorize?"
19
+ TOKEN_URL = "https://api.dropboxapi.com/oauth2/token"
20
+
21
+
22
+ def _set(text, name, value):
23
+ line = f"{name}={value}"
24
+ if re.search(rf"^\s*{name}\s*=.*$", text, flags=re.M):
25
+ return re.sub(rf"^\s*{name}\s*=.*$", lambda m: line, text, count=1, flags=re.M)
26
+ return (text.rstrip("\n") + "\n" if text.strip() else "") + line + "\n"
27
+
28
+
29
+ def run(secrets_file, ask=input, ask_hidden=getpass.getpass, out=print, post=None, open_url=webbrowser.open):
30
+ path = os.path.expanduser(secrets_file)
31
+ old = dotenv_values(path) if os.path.isfile(path) else {}
32
+ key = old.get("DROPBOX_APP_KEY") or ask("Dropbox app key (App Console > your app > Settings): ").strip()
33
+ secret = old.get("DROPBOX_APP_SECRET") or ask_hidden("Dropbox app secret (input hidden): ").strip()
34
+ if not key or not secret:
35
+ raise SystemExit("an app key and an app secret are needed")
36
+ url = AUTH_URL + urllib.parse.urlencode(
37
+ {"client_id": key, "response_type": "code", "token_access_type": "offline"})
38
+ out("\n1) A Dropbox page opens. Sign in if asked and click 'Allow'.")
39
+ out(" If it does not open, copy this address into your browser:\n " + url)
40
+ open_url(url)
41
+ code = ask_hidden("\n2) Paste the code Dropbox shows you (input hidden), then Enter: ").strip()
42
+ if post is None:
43
+ import requests
44
+ post = requests.post
45
+ r = post(TOKEN_URL, data={"code": code, "grant_type": "authorization_code"},
46
+ auth=(key, secret), timeout=30)
47
+ if not r.ok:
48
+ raise SystemExit(f"token exchange failed ({r.status_code}): {r.text[:200]}")
49
+ j = r.json()
50
+ refresh = j.get("refresh_token")
51
+ if not refresh:
52
+ raise SystemExit("Dropbox returned no refresh token")
53
+ text = ""
54
+ if os.path.isfile(path):
55
+ bak = f"{path}.bak-{time.strftime('%Y%m%d-%H%M%S')}"
56
+ shutil.copy2(path, bak)
57
+ os.chmod(bak, stat.S_IRUSR | stat.S_IWUSR)
58
+ out(f" old file kept as {bak}")
59
+ with open(path) as fh:
60
+ text = fh.read()
61
+ else:
62
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
63
+ for name, value in (("DROPBOX_APP_KEY", key), ("DROPBOX_APP_SECRET", secret),
64
+ ("DROPBOX_REFRESH_TOKEN", refresh)):
65
+ text = _set(text, name, value)
66
+ with open(path, "w") as fh:
67
+ fh.write(text)
68
+ os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)
69
+ scopes = sorted((j.get("scope") or "").split())
70
+ out(f"\n3) Saved to {path} (mode 600). Scopes: {', '.join(scopes) if scopes else '(none listed)'}")
71
+ need = {"files.metadata.read", "files.content.read", "files.content.write"}
72
+ if scopes and not need <= set(scopes):
73
+ out(" Missing: " + ", ".join(sorted(need - set(scopes))) +
74
+ ". Enable them under Permissions in the App Console, then run `dbsync auth` again.")
75
+ return 0