itcpr 3.0.0__tar.gz → 3.0.2__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: itcpr
3
- Version: 3.0.0
3
+ Version: 3.0.2
4
4
  Summary: ITCPR Sync: keeps your ITCPR research folder on Alpha in sync with this computer.
5
5
  Project-URL: Homepage, https://itcpr.org
6
6
  Author: ITCPR
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "itcpr"
7
- version = "3.0.0"
7
+ version = "3.0.2"
8
8
  description = "ITCPR Sync: keeps your ITCPR research folder on Alpha in sync with this computer."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -1,3 +1,3 @@
1
1
  """ITCPR Sync: keeps a member's research folder on Alpha in sync with their own computer."""
2
- __version__ = '3.0.0'
2
+ __version__ = '3.0.2'
3
3
  APP_NAME = 'ITCPR Sync'
@@ -51,11 +51,11 @@ def save_token(token: str) -> None:
51
51
  except Exception:
52
52
  pass
53
53
  path = _file()
54
- path.write_text(token, encoding='utf-8')
55
- try:
56
- os.chmod(path, stat.S_IRUSR | stat.S_IWUSR)
57
- except OSError:
58
- pass
54
+ path.unlink(missing_ok=True)
55
+ # Made private from the start (owner read and write only), not made private after it was written.
56
+ handle = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, 'O_BINARY', 0), stat.S_IRUSR | stat.S_IWUSR)
57
+ with os.fdopen(handle, 'w', encoding='utf-8') as out:
58
+ out.write(token)
59
59
 
60
60
 
61
61
  def load_token() -> str | None:
@@ -156,8 +156,10 @@ class _Callback(BaseHTTPRequestHandler):
156
156
  self.end_headers()
157
157
  return
158
158
  query = {k: v[0] for k, v in parse_qs(url.query).items()}
159
- self.result.update(query)
160
- page = _page(bool(query.get('code')) and secrets.compare_digest(query.get('state', ''), self.state))
159
+ ok = bool(query.get('code')) and secrets.compare_digest(query.get('state', ''), self.state)
160
+ if ok: # anything else (another page or program poking this port) is ignored, and sign-in keeps waiting
161
+ self.result.update(query)
162
+ page = _page(ok)
161
163
  self.send_response(200)
162
164
  self.send_header('Content-Type', 'text/html; charset=utf-8')
163
165
  self.send_header('Content-Length', str(len(page)))
@@ -1,123 +1,148 @@
1
- """The `itcpr` command (also installed as `itcpr-sync`). Everything here is also in the tray."""
2
- import argparse
3
- import json
4
- import os
5
- import subprocess
6
- import sys
7
- from pathlib import Path
8
-
9
- from . import __version__, auth, autostart
10
- from .settings import Settings, app_dir
11
-
12
-
13
- def size(n) -> str:
14
- if n is None:
15
- return '?'
16
- for unit in ('B', 'KB', 'MB', 'GB', 'TB'):
17
- if n < 1024 or unit == 'TB':
18
- return f'{n:.0f} {unit}' if unit == 'B' else f'{n:.1f} {unit}'
19
- n /= 1024
20
-
21
-
22
- def open_folder(path: str) -> None:
23
- if sys.platform == 'win32':
24
- os.startfile(path) # noqa: S606
25
- elif sys.platform == 'darwin':
26
- subprocess.Popen(['open', path])
27
- else:
28
- subprocess.Popen(['xdg-open', path])
29
-
30
-
31
- def main() -> None:
32
- parser = argparse.ArgumentParser(prog='itcpr', description='ITCPR Sync: your ITCPR research folder on Alpha, on this computer.')
33
- parser.add_argument('--version', action='version', version=f'itcpr {__version__}')
34
- commands = parser.add_subparsers(dest='command')
35
- commands.add_parser('tray', help='start the tray icon (the usual way to run it)')
36
- commands.add_parser('run', help='sync without the tray, for a machine with no desktop')
37
- commands.add_parser('login', help='sign in through the browser')
38
- commands.add_parser('logout', help='sign this computer out')
39
- commands.add_parser('status', help='what ITCPR Sync is doing')
40
- commands.add_parser('open', help='open the synced folder')
41
- commands.add_parser('pause', help='pause syncing')
42
- commands.add_parser('resume', help='resume syncing')
43
- exclude = commands.add_parser('exclude', help="stop syncing a folder to this computer (it stays on Alpha)")
44
- exclude.add_argument('folder', help='a folder path on Alpha, like Data/raw')
45
- exclude.add_argument('--keep', action='store_true', help='keep the copies already here')
46
- include = commands.add_parser('include', help='sync a folder to this computer again')
47
- include.add_argument('folder')
48
- where = commands.add_parser('folder', help='show or set where the synced folder is on this computer')
49
- where.add_argument('path', nargs='?')
50
- start = commands.add_parser('autostart', help='start ITCPR Sync at login')
51
- start.add_argument('state', choices=['on', 'off'])
52
- args = parser.parse_args()
53
-
54
- if args.command in (None, 'tray'):
55
- from .tray import main as tray
56
- tray()
57
- elif args.command == 'run':
58
- from .service import run_headless
59
- run_headless()
60
- elif args.command == 'login':
61
- print('Opening the browser to sign in...')
62
- info = auth.sign_in(open_browser=lambda url: (print(url), __import__('webbrowser').open(url)))
63
- print(f"Signed in as {info['member']} on {info['device']}.")
64
- elif args.command == 'logout':
65
- auth.sign_out()
66
- print('Signed out.')
67
- elif args.command == 'status':
68
- from .service import running
69
- try:
70
- status = json.loads((app_dir() / 'status.json').read_text(encoding='utf-8'))
71
- except (OSError, ValueError):
72
- status = {}
73
- settings = Settings.load()
74
- account = auth.account()
75
- print(f"Account: {account.get('member') or 'signed out'}{' on ' + account['device'] if account.get('device') else ''}")
76
- print(f"Folder: {settings.root}")
77
- print(f"Running: {'yes' if running() else 'no'}")
78
- if status:
79
- print(f"State: {status.get('state')} ({status.get('message')})")
80
- print(f"Space: {size(status.get('used'))} of {size(status.get('quota'))}")
81
- for problem in status.get('problems') or []:
82
- print(f" Not synced: {problem}")
83
- if settings.excludes:
84
- print('Not on this computer: ' + ', '.join(settings.excludes))
85
- elif args.command == 'open':
86
- open_folder(Settings.load().root)
87
- elif args.command in ('pause', 'resume'):
88
- settings = Settings.load()
89
- settings.paused = args.command == 'pause'
90
- settings.save()
91
- print('Paused.' if settings.paused else 'Resumed.')
92
- elif args.command == 'exclude':
93
- from .engine import Engine
94
- Engine().exclude(args.folder.strip('/'), remove_here=not args.keep)
95
- print(f'{args.folder} is no longer synced to this computer.')
96
- elif args.command == 'include':
97
- settings = Settings.load()
98
- settings.excludes = [e for e in settings.excludes if e != args.folder.strip('/') and not e.startswith(args.folder.strip('/') + '/')]
99
- settings.save()
100
- print(f'{args.folder} syncs to this computer again.')
101
- elif args.command == 'folder':
102
- settings = Settings.load()
103
- if not args.path:
104
- print(settings.root)
105
- return
106
- from .service import running
107
- if running():
108
- print('Quit ITCPR Sync first, then run this again.')
109
- sys.exit(1)
110
- new = Path(args.path).expanduser().resolve()
111
- old = Path(settings.root)
112
- if old.exists() and not new.exists():
113
- import shutil
114
- shutil.move(str(old), str(new))
115
- settings.root = str(new)
116
- settings.save()
117
- print(f'The synced folder is now {new}')
118
- elif args.command == 'autostart':
119
- settings = Settings.load()
120
- settings.autostart = args.state == 'on'
121
- settings.save()
122
- autostart.apply(settings.autostart)
123
- print('ITCPR Sync starts at login.' if settings.autostart else "ITCPR Sync doesn't start at login.")
1
+ """The `itcpr` command (also installed as `itcpr-sync`). Everything here is also in the tray."""
2
+ import argparse
3
+ import json
4
+ import os
5
+ import subprocess
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from . import __version__, auth, autostart
10
+ from .settings import Settings, app_dir
11
+
12
+
13
+ def size(n) -> str:
14
+ if n is None:
15
+ return '?'
16
+ for unit in ('B', 'KB', 'MB', 'GB', 'TB'):
17
+ if n < 1024 or unit == 'TB':
18
+ return f'{n:.0f} {unit}' if unit == 'B' else f'{n:.1f} {unit}'
19
+ n /= 1024
20
+
21
+
22
+ def open_folder(path: str) -> None:
23
+ if sys.platform == 'win32':
24
+ os.startfile(path) # noqa: S606
25
+ elif sys.platform == 'darwin':
26
+ subprocess.Popen(['open', path])
27
+ else:
28
+ subprocess.Popen(['xdg-open', path])
29
+
30
+
31
+ def main() -> None:
32
+ parser = argparse.ArgumentParser(prog='itcpr', description='ITCPR Sync: your ITCPR research folder on Alpha, on this computer.')
33
+ parser.add_argument('--version', action='version', version=f'itcpr {__version__}')
34
+ commands = parser.add_subparsers(dest='command')
35
+ commands.add_parser('tray', help='start the tray icon (the usual way to run it)')
36
+ commands.add_parser('run', help='sync without the tray, for a machine with no desktop')
37
+ commands.add_parser('login', help='sign in through the browser')
38
+ commands.add_parser('logout', help='sign this computer out')
39
+ commands.add_parser('status', help='what ITCPR Sync is doing')
40
+ commands.add_parser('open', help='open the synced folder')
41
+ commands.add_parser('start', help='start syncing, after choosing folders (exclude) and the place (folder)')
42
+ commands.add_parser('update', help='install the newest version from PyPI')
43
+ commands.add_parser('pause', help='pause syncing')
44
+ commands.add_parser('resume', help='resume syncing')
45
+ exclude = commands.add_parser('exclude', help="stop syncing a folder to this computer (it stays on Alpha)")
46
+ exclude.add_argument('folder', help='a folder path on Alpha, like Data/raw')
47
+ exclude.add_argument('--keep', action='store_true', help='keep the copies already here')
48
+ include = commands.add_parser('include', help='sync a folder to this computer again')
49
+ include.add_argument('folder')
50
+ where = commands.add_parser('folder', help='show or set where the synced folder is on this computer')
51
+ where.add_argument('path', nargs='?')
52
+ start = commands.add_parser('autostart', help='start ITCPR Sync at login')
53
+ start.add_argument('state', choices=['on', 'off'])
54
+ args = parser.parse_args()
55
+
56
+ if args.command in (None, 'tray'):
57
+ from .tray import main as tray
58
+ tray()
59
+ elif args.command == 'run':
60
+ from .service import run_headless
61
+ run_headless()
62
+ elif args.command == 'login':
63
+ print('Opening the browser to sign in...')
64
+ info = auth.sign_in(open_browser=lambda url: (print(url), __import__('webbrowser').open(url)))
65
+ print(f"Signed in as {info['member']} on {info['device']}.")
66
+ elif args.command == 'logout':
67
+ auth.sign_out()
68
+ print('Signed out.')
69
+ elif args.command == 'status':
70
+ from .service import running
71
+ try:
72
+ status = json.loads((app_dir() / 'status.json').read_text(encoding='utf-8'))
73
+ except (OSError, ValueError):
74
+ status = {}
75
+ settings = Settings.load()
76
+ account = auth.account()
77
+ print(f"Account: {account.get('member') or 'signed out'}{' on ' + account['device'] if account.get('device') else ''}")
78
+ print(f"Folder: {settings.root}")
79
+ print(f"Running: {'yes' if running() else 'no'}")
80
+ if status:
81
+ print(f"State: {status.get('state')} ({status.get('message')})")
82
+ print(f"Space: {size(status.get('used'))} of {size(status.get('quota'))}")
83
+ for problem in status.get('problems') or []:
84
+ print(f" Not synced: {problem}")
85
+ if settings.excludes:
86
+ print('Not on this computer: ' + ', '.join(settings.excludes))
87
+ if not settings.started:
88
+ print('Not started. Choose folders (itcpr exclude) and the place (itcpr folder), then: itcpr start')
89
+ elif args.command == 'open':
90
+ open_folder(Settings.load().root)
91
+ elif args.command == 'start':
92
+ settings = Settings.load()
93
+ settings.started = True
94
+ settings.save()
95
+ print(f'Syncing to {settings.root}.')
96
+ elif args.command == 'update':
97
+ from . import updates
98
+ from .service import running
99
+ how = updates.plan()
100
+ if how is None:
101
+ print('This is a development copy: update it with git.')
102
+ return
103
+ newest = updates.latest()
104
+ if not updates.newer(newest):
105
+ print(f'ITCPR Sync {__version__} is up to date.')
106
+ return
107
+ if running():
108
+ print(f'Version {newest} is available. Quit ITCPR Sync first, or use Update in its Settings.')
109
+ sys.exit(1)
110
+ print(f'Updating to {newest}...')
111
+ sys.exit(subprocess.run(how['upgrade']).returncode)
112
+ elif args.command in ('pause', 'resume'):
113
+ settings = Settings.load()
114
+ settings.paused = args.command == 'pause'
115
+ settings.save()
116
+ print('Paused.' if settings.paused else 'Resumed.')
117
+ elif args.command == 'exclude':
118
+ from .engine import Engine
119
+ Engine().exclude(args.folder.strip('/'), remove_here=not args.keep)
120
+ print(f'{args.folder} is no longer synced to this computer.')
121
+ elif args.command == 'include':
122
+ settings = Settings.load()
123
+ settings.excludes = [e for e in settings.excludes if e != args.folder.strip('/') and not e.startswith(args.folder.strip('/') + '/')]
124
+ settings.save()
125
+ print(f'{args.folder} syncs to this computer again.')
126
+ elif args.command == 'folder':
127
+ settings = Settings.load()
128
+ if not args.path:
129
+ print(settings.root)
130
+ return
131
+ from .service import running
132
+ if running():
133
+ print('Quit ITCPR Sync first, then run this again.')
134
+ sys.exit(1)
135
+ new = Path(args.path).expanduser().resolve()
136
+ old = Path(settings.root)
137
+ if old.exists() and not new.exists():
138
+ import shutil
139
+ shutil.move(str(old), str(new))
140
+ settings.root = str(new)
141
+ settings.save()
142
+ print(f'The synced folder is now {new}')
143
+ elif args.command == 'autostart':
144
+ settings = Settings.load()
145
+ settings.autostart = args.state == 'on'
146
+ settings.save()
147
+ autostart.apply(settings.autostart)
148
+ print('ITCPR Sync starts at login.' if settings.autostart else "ITCPR Sync doesn't start at login.")
@@ -60,6 +60,30 @@ def name_problem(name: str) -> str | None:
60
60
  return None
61
61
 
62
62
 
63
+ def safe_path(path) -> bool:
64
+ """A path from Alpha that stays inside the synced folder: relative, no '..', no drive letters or streams,
65
+ nothing Windows refuses. Alpha checks the same; this is so a broken or hostile server can't write elsewhere."""
66
+ if not isinstance(path, str) or not path or len(path) > 1000:
67
+ return False
68
+ return all(part not in ('', '.', '..') and name_problem(part) is None for part in path.split('/'))
69
+
70
+
71
+ def inside(root: Path, rel: str) -> Path:
72
+ """Where a synced path lives on this computer. Refuses a path that would leave the folder or go through a link."""
73
+ if not safe_path(rel):
74
+ raise OSError(f'Refused a path that is not allowed: {rel!r}')
75
+ target = root.joinpath(*rel.split('/'))
76
+ probe = root
77
+ for part in rel.split('/')[:-1]:
78
+ probe = probe / part
79
+ if is_link(probe):
80
+ raise OSError('That folder is a link here, which ITCPR Sync does not follow.')
81
+ real_root = os.path.realpath(root)
82
+ if os.path.commonpath([os.path.realpath(target.parent), real_root]) != real_root:
83
+ raise OSError('That path is outside the ITCPR Sync folder.')
84
+ return target
85
+
86
+
63
87
  def hash_file(path: Path):
64
88
  before = os.stat(path)
65
89
  whole, chunks = hashlib.sha256(), []
@@ -86,6 +110,10 @@ class Held(Exception):
86
110
  """Syncing stopped until the member decides something."""
87
111
 
88
112
 
113
+ class Paused(Exception):
114
+ """The member paused syncing in the middle of a round."""
115
+
116
+
89
117
  class Engine:
90
118
  def __init__(self, on_change=None):
91
119
  self.tickets = Tickets()
@@ -102,6 +130,7 @@ class Engine:
102
130
  self.activity: deque = deque(maxlen=100)
103
131
  self.conflicts: deque = deque(maxlen=50)
104
132
  self.problems: dict[str, str] = {}
133
+ self._paused, self._paused_read = False, 0.0
105
134
 
106
135
  # ---------- Status ----------
107
136
 
@@ -135,6 +164,9 @@ class Engine:
135
164
  except Held as held:
136
165
  self.set(state='held', held=str(held), message=str(held), busy=None)
137
166
  delay = 3600
167
+ except Paused:
168
+ self.set(state='paused', message='Paused', busy=None)
169
+ delay = 300
138
170
  except Exception as failure: # anything unexpected: say so, and try again soon
139
171
  log.exception('Sync round failed')
140
172
  self.set(state='error', message=str(failure) or 'Something went wrong.', busy=None)
@@ -143,7 +175,7 @@ class Engine:
143
175
  def _watch_alpha(self) -> None:
144
176
  """Waits on Alpha for changes (a long request), and starts a round when there are some."""
145
177
  while not self.stop.is_set():
146
- if Settings.load().paused or self.status['state'] in ('signed-out', 'held'):
178
+ if self.paused() or self.status['state'] in ('signed-out', 'held'):
147
179
  time.sleep(10)
148
180
  continue
149
181
  try:
@@ -157,15 +189,47 @@ class Engine:
157
189
  def nudge(self) -> None:
158
190
  self.wake.set()
159
191
 
192
+ def _remote(self, entry: dict) -> dict:
193
+ """An entry Alpha sent back, checked before it goes into the index."""
194
+ if not isinstance(entry, dict) or not safe_path(entry.get('path')):
195
+ raise RemoteError(502, 'Alpha sent a path that is not allowed.', {})
196
+ return entry
197
+
198
+ def paused(self) -> bool:
199
+ """The tray and the command line both change it, so it's read from the settings, at most once a second."""
200
+ if time.monotonic() - self._paused_read > 1:
201
+ self._paused, self._paused_read = Settings.load().paused, time.monotonic()
202
+ return self._paused
203
+
204
+ def pause(self, on: bool) -> None:
205
+ """Pausing takes effect now: a round under way stops at its next file or chunk."""
206
+ self._paused, self._paused_read = on, time.monotonic()
207
+ if on:
208
+ self.set(state='paused', message='Paused', busy=None)
209
+ self.nudge()
210
+
211
+ def check(self) -> None:
212
+ if self.paused():
213
+ raise Paused()
214
+
160
215
  def run_once(self) -> None:
161
216
  with self.round_lock:
162
217
  settings = Settings.load()
163
- if settings.paused:
218
+ self._paused, self._paused_read = settings.paused, time.monotonic()
219
+ if settings.paused and settings.started:
164
220
  self.set(state='paused', message='Paused', busy=None)
165
221
  return
166
222
  ticket = self.tickets.get()
167
223
  self.status.update(folder=ticket['folder'], member=ticket.get('member'), quota=ticket.get('quota_bytes'))
168
224
  root = Path(settings.root)
225
+ if not settings.started:
226
+ # Before the first sync: only Alpha's list, so the member can choose folders. Nothing moves yet.
227
+ self.index.for_folder(ticket['folder'], str(root.resolve()))
228
+ self.set(state='setup', message='Choose what to sync', busy='Reading your folder on Alpha', held=None)
229
+ self.pull()
230
+ info = self.alpha.info()
231
+ self.set(state='setup', message='Choose what to sync', used=info['used'], quota=info['quota'], busy=None)
232
+ return
169
233
  if not root.exists():
170
234
  if settings.root_made:
171
235
  raise Held(f'Your ITCPR Sync folder is missing: {root}')
@@ -194,6 +258,9 @@ class Engine:
194
258
  since = 0
195
259
  continue
196
260
  for entry in answer['entries']:
261
+ if not isinstance(entry, dict) or not safe_path(entry.get('path')):
262
+ log.warning('Alpha sent a path that is not allowed; skipped: %r', entry.get('path') if isinstance(entry, dict) else entry)
263
+ continue
197
264
  entry['path'] = unicodedata.normalize('NFC', entry['path'])
198
265
  self.index.put_remote(entry)
199
266
  since = answer['seq']
@@ -255,6 +322,7 @@ class Engine:
255
322
  for k in sorted(keys, key=lambda k: (k.count('/'), k)):
256
323
  if self.stop.is_set():
257
324
  return
325
+ self.check()
258
326
  r, b, l = remote.get(k), base.get(k), local.get(k)
259
327
  path = (r or b or l)['path']
260
328
  if settings.excluded(path):
@@ -277,7 +345,7 @@ class Engine:
277
345
  self.remove_local_dir(root, path)
278
346
  for path in sorted(later_remote_rmdirs, key=lambda p: -p.count('/')):
279
347
  try:
280
- self.index.put_remote(self.alpha.delete(path, None)['entry'])
348
+ self.index.put_remote(self._remote(self.alpha.delete(path, None)['entry']))
281
349
  self.index.drop_base(path)
282
350
  except RemoteError:
283
351
  pass
@@ -338,13 +406,13 @@ class Engine:
338
406
  self.index.drop_base(path)
339
407
  return
340
408
  if r['kind'] == 'dir':
341
- (root / (l['disk'] if l else r['path'])).mkdir(parents=True, exist_ok=True)
409
+ inside(root, l['disk'] if l else r['path']).mkdir(parents=True, exist_ok=True)
342
410
  self.index.put_base(r['path'], 'dir')
343
411
  return
344
412
  self.download(root, r, l)
345
413
 
346
414
  def download(self, root: Path, r, l) -> None:
347
- target = root / (l['disk'] if l else r['path'])
415
+ target = inside(root, l['disk'] if l else r['path'])
348
416
  target.parent.mkdir(parents=True, exist_ok=True)
349
417
  temp = target.parent / f'{TEMP_PREFIX}{secrets.token_hex(6)}.tmp'
350
418
  self.set(busy=f"Downloading {r['path']}")
@@ -352,6 +420,7 @@ class Engine:
352
420
  whole = hashlib.sha256()
353
421
  with open(temp, 'wb') as out:
354
422
  for i in range(-(-r['size'] // CHUNK)):
423
+ self.check()
355
424
  data = self.alpha.chunk(r['path'], r['hash'], i)
356
425
  whole.update(data)
357
426
  out.write(data)
@@ -377,12 +446,12 @@ class Engine:
377
446
  if b and b['kind'] == 'dir':
378
447
  remote_rmdirs.append(r['path'] if r else b['path'])
379
448
  elif r:
380
- self.index.put_remote(self.alpha.delete(r['path'], r['hash'])['entry'])
449
+ self.index.put_remote(self._remote(self.alpha.delete(r['path'], r['hash'])['entry']))
381
450
  self.index.drop_base(path)
382
451
  self.note('deleted on Alpha', path)
383
452
  return
384
453
  if l['kind'] == 'dir':
385
- entry = self.alpha.mkdir(l['path'])['entry']
454
+ entry = self._remote(self.alpha.mkdir(l['path'])['entry'])
386
455
  self.index.put_remote(entry)
387
456
  self.index.put_base(entry['path'], 'dir')
388
457
  return
@@ -403,13 +472,14 @@ class Engine:
403
472
  else:
404
473
  with open(source, 'rb') as handle:
405
474
  for i in started['missing']:
475
+ self.check()
406
476
  handle.seek(i * CHUNK)
407
477
  data = handle.read(CHUNK)
408
478
  if hashlib.sha256(data).hexdigest() != chunks[i]:
409
479
  return # changed while sending: next round
410
480
  self.alpha.put_chunk(started['id'], i, data)
411
481
  entry = self.alpha.commit(started['id'])['entry']
412
- self.index.put_remote(entry)
482
+ self.index.put_remote(self._remote(entry))
413
483
  self.index.put_base(entry['path'], 'file', digest, size, mtime)
414
484
  self.note('uploaded', l['path'])
415
485
 
@@ -84,6 +84,10 @@ class Index:
84
84
  def remote_dirs(self) -> list[str]:
85
85
  return [r['path'] for r in self.db.execute("SELECT path FROM remote WHERE kind = 'dir' AND deleted = 0 ORDER BY path COLLATE NOCASE")]
86
86
 
87
+ def remote_total(self) -> int:
88
+ """Bytes of every file on Alpha in this folder."""
89
+ return self.db.execute("SELECT COALESCE(SUM(size), 0) FROM remote WHERE kind = 'file' AND deleted = 0").fetchone()[0]
90
+
87
91
  def remote_sizes(self) -> dict:
88
92
  """Bytes under each folder on Alpha, for the folder picker."""
89
93
  sizes: dict[str, int] = {}