itcpr 2.1.10__tar.gz → 3.0.0__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.
Files changed (42) hide show
  1. itcpr-3.0.0/.gitignore +6 -0
  2. itcpr-3.0.0/PKG-INFO +87 -0
  3. itcpr-3.0.0/README.md +68 -0
  4. itcpr-3.0.0/install/install.ps1 +26 -0
  5. itcpr-3.0.0/install/install.sh +28 -0
  6. itcpr-3.0.0/pyproject.toml +43 -0
  7. itcpr-3.0.0/src/itcpr_sync/__init__.py +3 -0
  8. itcpr-3.0.0/src/itcpr_sync/__main__.py +3 -0
  9. itcpr-3.0.0/src/itcpr_sync/auth.py +245 -0
  10. itcpr-3.0.0/src/itcpr_sync/autostart.py +88 -0
  11. itcpr-3.0.0/src/itcpr_sync/brand.py +20 -0
  12. itcpr-3.0.0/src/itcpr_sync/cli.py +123 -0
  13. itcpr-3.0.0/src/itcpr_sync/engine.py +492 -0
  14. itcpr-3.0.0/src/itcpr_sync/index.py +95 -0
  15. itcpr-3.0.0/src/itcpr_sync/remote.py +98 -0
  16. itcpr-3.0.0/src/itcpr_sync/service.py +130 -0
  17. itcpr-3.0.0/src/itcpr_sync/settings.py +77 -0
  18. itcpr-3.0.0/src/itcpr_sync/theme.py +189 -0
  19. itcpr-3.0.0/src/itcpr_sync/tray.py +669 -0
  20. itcpr-2.1.10/LICENSE +0 -22
  21. itcpr-2.1.10/MANIFEST.in +0 -4
  22. itcpr-2.1.10/PKG-INFO +0 -645
  23. itcpr-2.1.10/README.md +0 -612
  24. itcpr-2.1.10/itcpr/__init__.py +0 -4
  25. itcpr-2.1.10/itcpr/api.py +0 -176
  26. itcpr-2.1.10/itcpr/auth.py +0 -289
  27. itcpr-2.1.10/itcpr/cli.py +0 -892
  28. itcpr-2.1.10/itcpr/config.py +0 -98
  29. itcpr-2.1.10/itcpr/gitops.py +0 -328
  30. itcpr-2.1.10/itcpr/service.py +0 -327
  31. itcpr-2.1.10/itcpr/storage.py +0 -155
  32. itcpr-2.1.10/itcpr/sync.py +0 -253
  33. itcpr-2.1.10/itcpr/utils.py +0 -40
  34. itcpr-2.1.10/itcpr.egg-info/PKG-INFO +0 -645
  35. itcpr-2.1.10/itcpr.egg-info/SOURCES.txt +0 -21
  36. itcpr-2.1.10/itcpr.egg-info/dependency_links.txt +0 -1
  37. itcpr-2.1.10/itcpr.egg-info/entry_points.txt +0 -2
  38. itcpr-2.1.10/itcpr.egg-info/requires.txt +0 -10
  39. itcpr-2.1.10/itcpr.egg-info/top_level.txt +0 -1
  40. itcpr-2.1.10/pyproject.toml +0 -41
  41. itcpr-2.1.10/setup.cfg +0 -4
  42. itcpr-2.1.10/setup.py +0 -47
itcpr-3.0.0/.gitignore ADDED
@@ -0,0 +1,6 @@
1
+ .venv/
2
+ dist/
3
+ build/
4
+ __pycache__/
5
+ dev-home/
6
+ .env
itcpr-3.0.0/PKG-INFO ADDED
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.5
2
+ Name: itcpr
3
+ Version: 3.0.0
4
+ Summary: ITCPR Sync: keeps your ITCPR research folder on Alpha in sync with this computer.
5
+ Project-URL: Homepage, https://itcpr.org
6
+ Author: ITCPR
7
+ License-Expression: MIT
8
+ Classifier: Environment :: X11 Applications :: Qt
9
+ Classifier: Operating System :: MacOS
10
+ Classifier: Operating System :: Microsoft :: Windows
11
+ Classifier: Operating System :: POSIX :: Linux
12
+ Classifier: Programming Language :: Python :: 3
13
+ Requires-Python: >=3.10
14
+ Requires-Dist: httpx<1,>=0.27
15
+ Requires-Dist: keyring>=24
16
+ Requires-Dist: pyside6-essentials>=6.6
17
+ Requires-Dist: watchdog>=4
18
+ Description-Content-Type: text/markdown
19
+
20
+ # ITCPR Sync
21
+
22
+ Keeps your ITCPR research folder on Alpha in sync with your computer. Windows, macOS and Linux.
23
+
24
+ ## Install
25
+
26
+ You need an approved device for Alpha with Cloudflare One connected, as for SSH.
27
+
28
+ **Windows** (PowerShell):
29
+
30
+ ```
31
+ irm https://itcpr.org/sync/install.ps1 | iex
32
+ ```
33
+
34
+ **macOS and Linux** (Terminal):
35
+
36
+ ```
37
+ curl -fsSL https://itcpr.org/sync/install.sh | sh
38
+ ```
39
+
40
+ Then click the ITCPR Sync icon in the tray or menu bar and sign in. Run the same line again to update.
41
+
42
+ On Linux, GNOME shows tray icons only with the AppIndicator extension. Qt also needs `libxcb-cursor0` (Debian and Ubuntu: `sudo apt install libxcb-cursor0`).
43
+
44
+ ## Using it
45
+
46
+ Your folder appears at `~/ITCPR Sync`. In the window:
47
+
48
+ - **Folders:** untick folders you don't want on this computer. They stay on Alpha.
49
+ - **Activity:** what came and went, conflicts, and files that couldn't sync.
50
+ - **Restore:** files that were replaced or deleted in the last 30 days (7 days for files over 1 GB).
51
+ - **Settings:** move the folder, start at login, pause, sign out.
52
+
53
+ When a file changes in two places before they sync, both copies are kept. Yours is renamed `name (conflict <device> <date>)`.
54
+
55
+ Some names can't sync, because Windows doesn't allow them: `< > : " \ | ? *`, names ending in a space or dot, and `CON`, `NUL` and the like. Two names that differ only in case can't sync either. Activity lists these files.
56
+
57
+ ## Command line
58
+
59
+ ```
60
+ itcpr status
61
+ itcpr login | logout
62
+ itcpr pause | resume
63
+ itcpr exclude Data/raw # --keep to leave the copies here
64
+ itcpr include Data/raw
65
+ itcpr folder [new place]
66
+ itcpr autostart on|off
67
+ itcpr run # without the tray, for a machine with no desktop
68
+ ```
69
+
70
+ ## How it works
71
+
72
+ See the module docstrings: `engine.py` (the sync rules), `auth.py` (sign-in), `remote.py` (Alpha). On Alpha, the service is `alpha-agent/agent/alpha_sync.py`. On the API, it's `api-itcpr/itcpr_api/routes/sync.py`.
73
+
74
+ ## Development
75
+
76
+ ```
77
+ uv venv && uv pip install -e .
78
+ ITCPR_SYNC_API=http://localhost:8795 ITCPR_SYNC_PORTAL=http://localhost:5173 ITCPR_SYNC_HOME=./dev-home .venv/bin/itcpr tray
79
+ ```
80
+
81
+ ## Publishing
82
+
83
+ Put a PyPI API token for the `itcpr` project in `.env` as `PYPI_TOKEN=pypi-...`, then:
84
+
85
+ ```
86
+ .\publish.ps1 3.0.1 # sets the version, builds, checks and uploads; -DryRun to stop before uploading
87
+ ```
itcpr-3.0.0/README.md ADDED
@@ -0,0 +1,68 @@
1
+ # ITCPR Sync
2
+
3
+ Keeps your ITCPR research folder on Alpha in sync with your computer. Windows, macOS and Linux.
4
+
5
+ ## Install
6
+
7
+ You need an approved device for Alpha with Cloudflare One connected, as for SSH.
8
+
9
+ **Windows** (PowerShell):
10
+
11
+ ```
12
+ irm https://itcpr.org/sync/install.ps1 | iex
13
+ ```
14
+
15
+ **macOS and Linux** (Terminal):
16
+
17
+ ```
18
+ curl -fsSL https://itcpr.org/sync/install.sh | sh
19
+ ```
20
+
21
+ Then click the ITCPR Sync icon in the tray or menu bar and sign in. Run the same line again to update.
22
+
23
+ On Linux, GNOME shows tray icons only with the AppIndicator extension. Qt also needs `libxcb-cursor0` (Debian and Ubuntu: `sudo apt install libxcb-cursor0`).
24
+
25
+ ## Using it
26
+
27
+ Your folder appears at `~/ITCPR Sync`. In the window:
28
+
29
+ - **Folders:** untick folders you don't want on this computer. They stay on Alpha.
30
+ - **Activity:** what came and went, conflicts, and files that couldn't sync.
31
+ - **Restore:** files that were replaced or deleted in the last 30 days (7 days for files over 1 GB).
32
+ - **Settings:** move the folder, start at login, pause, sign out.
33
+
34
+ When a file changes in two places before they sync, both copies are kept. Yours is renamed `name (conflict <device> <date>)`.
35
+
36
+ Some names can't sync, because Windows doesn't allow them: `< > : " \ | ? *`, names ending in a space or dot, and `CON`, `NUL` and the like. Two names that differ only in case can't sync either. Activity lists these files.
37
+
38
+ ## Command line
39
+
40
+ ```
41
+ itcpr status
42
+ itcpr login | logout
43
+ itcpr pause | resume
44
+ itcpr exclude Data/raw # --keep to leave the copies here
45
+ itcpr include Data/raw
46
+ itcpr folder [new place]
47
+ itcpr autostart on|off
48
+ itcpr run # without the tray, for a machine with no desktop
49
+ ```
50
+
51
+ ## How it works
52
+
53
+ See the module docstrings: `engine.py` (the sync rules), `auth.py` (sign-in), `remote.py` (Alpha). On Alpha, the service is `alpha-agent/agent/alpha_sync.py`. On the API, it's `api-itcpr/itcpr_api/routes/sync.py`.
54
+
55
+ ## Development
56
+
57
+ ```
58
+ uv venv && uv pip install -e .
59
+ ITCPR_SYNC_API=http://localhost:8795 ITCPR_SYNC_PORTAL=http://localhost:5173 ITCPR_SYNC_HOME=./dev-home .venv/bin/itcpr tray
60
+ ```
61
+
62
+ ## Publishing
63
+
64
+ Put a PyPI API token for the `itcpr` project in `.env` as `PYPI_TOKEN=pypi-...`, then:
65
+
66
+ ```
67
+ .\publish.ps1 3.0.1 # sets the version, builds, checks and uploads; -DryRun to stop before uploading
68
+ ```
@@ -0,0 +1,26 @@
1
+ # ITCPR Sync for Windows. Run in PowerShell:
2
+ # irm https://itcpr.org/sync/install.ps1 | iex
3
+ # Installs uv (Astral's Python tool installer) if it is missing, then ITCPR Sync from PyPI, for this user only.
4
+ # Nothing needs administrator rights. Run it again to update.
5
+ $ErrorActionPreference = 'Stop'
6
+
7
+ $bin = Join-Path $env:USERPROFILE '.local\bin'
8
+ $uv = Join-Path $bin 'uv.exe'
9
+ if (-not (Test-Path $uv)) {
10
+ $found = Get-Command uv -ErrorAction SilentlyContinue
11
+ if ($found) { $uv = $found.Source }
12
+ else {
13
+ Write-Host 'Installing uv...'
14
+ powershell -ExecutionPolicy ByPass -NoProfile -Command "irm https://astral.sh/uv/install.ps1 | iex"
15
+ }
16
+ }
17
+
18
+ # A running copy is stopped first: Windows can't replace a program that is running.
19
+ Get-Process -Name 'itcpr-sync-tray' -ErrorAction SilentlyContinue | Stop-Process -Force
20
+
21
+ Write-Host 'Installing ITCPR Sync...'
22
+ & $uv tool install --upgrade itcpr
23
+ & $uv tool update-shell 2>$null | Out-Null
24
+
25
+ Start-Process (Join-Path $bin 'itcpr-sync-tray.exe')
26
+ Write-Host 'ITCPR Sync is running. Click its icon in the tray to sign in.'
@@ -0,0 +1,28 @@
1
+ #!/bin/sh
2
+ # ITCPR Sync for macOS and Linux. Run in a terminal:
3
+ # curl -fsSL https://itcpr.org/sync/install.sh | sh
4
+ # Installs uv (Astral's Python tool installer) if it is missing, then ITCPR Sync from PyPI, for this user only.
5
+ # Nothing needs sudo. Run it again to update.
6
+ set -eu
7
+
8
+ BIN="$HOME/.local/bin"
9
+ UV="$BIN/uv"
10
+ if [ ! -x "$UV" ]; then
11
+ if command -v uv >/dev/null 2>&1; then
12
+ UV="$(command -v uv)"
13
+ else
14
+ echo "Installing uv..."
15
+ curl -LsSf https://astral.sh/uv/install.sh | sh
16
+ fi
17
+ fi
18
+
19
+ echo "Installing ITCPR Sync..."
20
+ "$UV" tool install --upgrade itcpr
21
+ "$UV" tool update-shell >/dev/null 2>&1 || true
22
+
23
+ pkill -f itcpr-sync-tray >/dev/null 2>&1 || true
24
+ nohup "$BIN/itcpr-sync-tray" >/dev/null 2>&1 &
25
+ echo "ITCPR Sync is running. Click its icon in the menu bar or tray to sign in."
26
+ if [ "$(uname)" = "Linux" ]; then
27
+ echo "No icon? GNOME needs the AppIndicator extension. Or run: itcpr tray"
28
+ fi
@@ -0,0 +1,43 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.24"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "itcpr"
7
+ version = "3.0.0"
8
+ description = "ITCPR Sync: keeps your ITCPR research folder on Alpha in sync with this computer."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ authors = [{ name = "ITCPR" }]
13
+ classifiers = [
14
+ "Programming Language :: Python :: 3",
15
+ "Operating System :: Microsoft :: Windows",
16
+ "Operating System :: MacOS",
17
+ "Operating System :: POSIX :: Linux",
18
+ "Environment :: X11 Applications :: Qt",
19
+ ]
20
+ dependencies = [
21
+ "httpx>=0.27,<1",
22
+ "watchdog>=4",
23
+ "keyring>=24",
24
+ "PySide6-Essentials>=6.6",
25
+ ]
26
+
27
+ [project.urls]
28
+ Homepage = "https://itcpr.org"
29
+
30
+ [project.scripts]
31
+ itcpr = "itcpr_sync.cli:main"
32
+ itcpr-sync = "itcpr_sync.cli:main" # the same command under its first name
33
+
34
+ # Windowless on Windows, for the tray and for starting at login.
35
+ [project.gui-scripts]
36
+ itcpr-sync-tray = "itcpr_sync.tray:main"
37
+
38
+ [tool.hatch.build.targets.wheel]
39
+ packages = ["src/itcpr_sync"]
40
+
41
+ # Only these go into the source package on PyPI.
42
+ [tool.hatch.build.targets.sdist]
43
+ include = ["src/itcpr_sync", "install", "README.md", "pyproject.toml"]
@@ -0,0 +1,3 @@
1
+ """ITCPR Sync: keeps a member's research folder on Alpha in sync with their own computer."""
2
+ __version__ = '3.0.0'
3
+ APP_NAME = 'ITCPR Sync'
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
@@ -0,0 +1,245 @@
1
+ """
2
+ Signing in, and the tickets that open Alpha.
3
+
4
+ The browser does the sign-in: the app opens the portal's ITCPR Sync page, the member allows it there,
5
+ and the portal sends the browser back to a one-time listener on 127.0.0.1 with a code. The app trades
6
+ the code for a device token, kept in the OS keychain (Credential Manager, Keychain, Secret Service),
7
+ or in a private file where there is none. The token is never shown, and the password never reaches the app.
8
+ """
9
+ import json
10
+ import os
11
+ import secrets
12
+ import socket
13
+ import stat
14
+ import threading
15
+ import time
16
+ import webbrowser
17
+ from http.server import BaseHTTPRequestHandler, HTTPServer
18
+ from urllib.parse import parse_qs, quote, urlencode, urlsplit
19
+
20
+ import httpx
21
+
22
+ from . import __version__
23
+ from .brand import HERO, MARK
24
+ from .settings import API_URL, PORTAL_URL, app_dir, platform_name
25
+
26
+ SERVICE = 'ITCPR Sync'
27
+ ACCOUNT = 'device'
28
+ USER_AGENT = f'itcpr-sync/{__version__}'
29
+
30
+
31
+ class SignedOut(Exception):
32
+ pass
33
+
34
+
35
+ class ApiProblem(Exception):
36
+ pass
37
+
38
+
39
+ # ---------- The device token ----------
40
+
41
+ def _file():
42
+ return app_dir() / 'device-token'
43
+
44
+
45
+ def save_token(token: str) -> None:
46
+ try:
47
+ import keyring
48
+ keyring.set_password(SERVICE, ACCOUNT, token)
49
+ _file().unlink(missing_ok=True)
50
+ return
51
+ except Exception:
52
+ pass
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
59
+
60
+
61
+ def load_token() -> str | None:
62
+ try:
63
+ import keyring
64
+ token = keyring.get_password(SERVICE, ACCOUNT)
65
+ if token:
66
+ return token
67
+ except Exception:
68
+ pass
69
+ try:
70
+ return _file().read_text(encoding='utf-8').strip() or None
71
+ except OSError:
72
+ return None
73
+
74
+
75
+ def forget_token() -> None:
76
+ try:
77
+ import keyring
78
+ keyring.delete_password(SERVICE, ACCOUNT)
79
+ except Exception:
80
+ pass
81
+ _file().unlink(missing_ok=True)
82
+
83
+
84
+ def _account_path():
85
+ return app_dir() / 'account.json'
86
+
87
+
88
+ def account() -> dict:
89
+ try:
90
+ return json.loads(_account_path().read_text(encoding='utf-8'))
91
+ except (OSError, ValueError):
92
+ return {}
93
+
94
+
95
+ # ---------- Signing in ----------
96
+
97
+ _ICONS = {
98
+ 'good': '<path d="M6 12.5l4 4 8-9" pathLength="1"/>',
99
+ 'danger': '<path d="M7.5 7.5l9 9M16.5 7.5l-9 9" pathLength="1"/>',
100
+ }
101
+
102
+
103
+ def _page(ok: bool) -> bytes:
104
+ """What the browser shows after the portal sends it back: the app's dark band, the mark and the outcome."""
105
+ tone = 'good' if ok else 'danger'
106
+ title, note = ('Signed in', 'You can close this tab.') if ok else ("Sign-in didn't finish", 'Try again from ITCPR Sync.')
107
+ mark = f'<svg viewBox="2 2 96 96" aria-hidden="true"><path fill="currentColor" d="{MARK}"/></svg>'
108
+ favicon = quote(f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="2 2 96 96"><path fill="{HERO["bg"]}" d="{MARK}"/></svg>')
109
+ return f'''<!doctype html>
110
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
111
+ <title>{title} · ITCPR Sync</title><link rel="icon" href="data:image/svg+xml,{favicon}">
112
+ <style>
113
+ *{{box-sizing:border-box;margin:0}}
114
+ html,body{{height:100%}}
115
+ body{{display:grid;place-items:center;padding:24px;overflow:hidden;color:{HERO["ink"]};
116
+ font:15px/1.5 Geist,"Segoe UI Variable Text","Segoe UI",system-ui,-apple-system,sans-serif;-webkit-font-smoothing:antialiased;
117
+ background:radial-gradient(90vmax 90vmax at 85% 0%,{HERO["glow"]}96,transparent 70%),
118
+ radial-gradient(80vmax 80vmax at 0% 100%,{HERO["spark"]}46,transparent 70%),{HERO["bg"]}}}
119
+ .watermark{{position:fixed;right:-12vmin;bottom:-14vmin;width:62vmin;opacity:.06;pointer-events:none}}
120
+ main{{position:relative;display:flex;flex-direction:column;align-items:center;text-align:center;animation:rise .5s cubic-bezier(.2,.8,.2,1) both}}
121
+ .mark{{width:56px;height:56px}}
122
+ h1{{margin-top:16px;font:600 30px/1.1 "Source Serif 4","Source Serif Pro",Georgia,serif;letter-spacing:-.01em}}
123
+ h1 i{{font-weight:500}}
124
+ .status{{display:inline-flex;align-items:center;gap:10px;margin-top:28px;padding:10px 18px 10px 12px;border-radius:999px;
125
+ background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.14);font-weight:600;
126
+ -webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px)}}
127
+ .icon{{display:grid;place-items:center;width:26px;height:26px;border-radius:50%;background:var(--tone);color:{HERO["bg"]}}}
128
+ .icon svg{{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:2.4;stroke-linecap:round;stroke-linejoin:round}}
129
+ .icon path{{stroke-dasharray:1;stroke-dashoffset:1;animation:draw .45s .35s ease-out forwards}}
130
+ p{{margin-top:12px;color:{HERO["muted"]};font-size:14px}}
131
+ @keyframes rise{{from{{opacity:0;transform:translateY(8px)}}}}
132
+ @keyframes draw{{to{{stroke-dashoffset:0}}}}
133
+ </style></head>
134
+ <body style="--tone:{HERO[tone]}">
135
+ <div class="watermark">{mark}</div>
136
+ <main>
137
+ <div class="mark">{mark}</div>
138
+ <h1>ITCPR <i>Sync</i></h1>
139
+ <div class="status" role="status"><span class="icon"><svg viewBox="0 0 24 24" aria-hidden="true">{_ICONS[tone]}</svg></span>{title}</div>
140
+ <p>{note}</p>
141
+ </main>
142
+ </body></html>'''.encode()
143
+
144
+
145
+ class _Callback(BaseHTTPRequestHandler):
146
+ result: dict
147
+ state: str
148
+
149
+ def log_message(self, *args):
150
+ pass
151
+
152
+ def do_GET(self):
153
+ url = urlsplit(self.path)
154
+ if url.path != '/callback':
155
+ self.send_response(404)
156
+ self.end_headers()
157
+ return
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))
161
+ self.send_response(200)
162
+ self.send_header('Content-Type', 'text/html; charset=utf-8')
163
+ self.send_header('Content-Length', str(len(page)))
164
+ self.send_header('Cache-Control', 'no-store')
165
+ self.send_header('Referrer-Policy', 'no-referrer')
166
+ self.send_header('X-Content-Type-Options', 'nosniff')
167
+ self.send_header('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; img-src data:; frame-ancestors 'none'")
168
+ self.end_headers()
169
+ self.wfile.write(page)
170
+
171
+
172
+ def sign_in(open_browser=webbrowser.open, timeout: float = 300) -> dict:
173
+ """The whole sign-in. Returns the member's name and this device's name."""
174
+ state = secrets.token_urlsafe(32)
175
+ result: dict = {}
176
+ handler = type('Callback', (_Callback,), {'result': result, 'state': state})
177
+ server = HTTPServer(('127.0.0.1', 0), handler)
178
+ server.timeout = 1
179
+ port = server.server_address[1]
180
+ name = socket.gethostname()[:80] or 'Computer'
181
+ url = f'{PORTAL_URL}/server/sync/connect?' + urlencode({'state': state, 'port': port, 'name': name, 'platform': platform_name()})
182
+ open_browser(url)
183
+ deadline = time.monotonic() + timeout
184
+ try:
185
+ while 'code' not in result and time.monotonic() < deadline:
186
+ server.handle_request()
187
+ finally:
188
+ server.server_close()
189
+ if 'code' not in result:
190
+ raise ApiProblem('Sign-in timed out.')
191
+ if not secrets.compare_digest(result.get('state', ''), state):
192
+ raise ApiProblem('Sign-in failed. Try again.')
193
+ response = httpx.post(f'{API_URL}/v1/sync/token', json={'code': result['code'], 'state': state},
194
+ headers={'User-Agent': USER_AGENT}, timeout=30)
195
+ data = _json(response)
196
+ save_token(data['device_token'])
197
+ info = {'member': data.get('member'), 'device': data.get('name'), 'device_id': data.get('device_id')}
198
+ _account_path().write_text(json.dumps(info), encoding='utf-8')
199
+ return info
200
+
201
+
202
+ def sign_out() -> None:
203
+ token = load_token()
204
+ if token:
205
+ try:
206
+ httpx.post(f'{API_URL}/v1/sync/logout', headers={'Authorization': f'Bearer {token}', 'User-Agent': USER_AGENT}, timeout=15)
207
+ except httpx.HTTPError:
208
+ pass
209
+ forget_token()
210
+ _account_path().unlink(missing_ok=True)
211
+
212
+
213
+ def _json(response: httpx.Response) -> dict:
214
+ try:
215
+ data = response.json()
216
+ except ValueError:
217
+ data = {}
218
+ if response.status_code == 401:
219
+ raise SignedOut(data.get('error') or 'Signed out.')
220
+ if response.status_code >= 400:
221
+ raise ApiProblem(data.get('error') or f'ITCPR answered {response.status_code}.')
222
+ return data
223
+
224
+
225
+ # ---------- Tickets ----------
226
+
227
+ class Tickets:
228
+ """Keeps a current ticket, asking the API for a new one shortly before it runs out."""
229
+
230
+ def __init__(self):
231
+ self.current: dict | None = None
232
+ self.lock = threading.Lock()
233
+
234
+ def get(self, fresh: bool = False) -> dict:
235
+ with self.lock:
236
+ if fresh or not self.current or self.current['expires_at'] - time.time() < 90:
237
+ token = load_token()
238
+ if not token:
239
+ raise SignedOut('Not signed in.')
240
+ try:
241
+ response = httpx.post(f'{API_URL}/v1/sync/ticket', headers={'Authorization': f'Bearer {token}', 'User-Agent': USER_AGENT}, timeout=30)
242
+ except httpx.HTTPError:
243
+ raise ApiProblem("Can't reach ITCPR.")
244
+ self.current = _json(response)
245
+ return self.current
@@ -0,0 +1,88 @@
1
+ """Starting the tray at login, on each OS, for this user only."""
2
+ import shutil
3
+ import subprocess
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ NAME = 'ITCPR Sync'
8
+
9
+
10
+ def _command() -> list[str]:
11
+ tray = shutil.which('itcpr-sync-tray')
12
+ if tray:
13
+ return [tray]
14
+ python = Path(sys.executable)
15
+ if sys.platform == 'win32' and python.with_name('pythonw.exe').exists():
16
+ python = python.with_name('pythonw.exe')
17
+ return [str(python), '-m', 'itcpr_sync.tray']
18
+
19
+
20
+ def _mac_plist() -> Path:
21
+ return Path.home() / 'Library' / 'LaunchAgents' / 'org.itcpr.sync.plist'
22
+
23
+
24
+ def _desktop_exec(command: list[str]) -> str:
25
+ """An Exec line as the desktop entry spec reads it: double quotes, not a shell's single quotes."""
26
+ reserved = set(' \t\n"\'\\><~|&;$*?#()`')
27
+
28
+ def quote(arg: str) -> str:
29
+ if reserved & set(arg):
30
+ arg = '"' + ''.join('\\' + c if c in '"`$\\' else c for c in arg) + '"'
31
+ # The file format itself escapes backslashes once more, and % starts a field code.
32
+ return arg.replace('\\', '\\\\').replace('%', '%%')
33
+ return ' '.join(quote(a) for a in command)
34
+
35
+
36
+ def _linux_desktop() -> Path:
37
+ return Path.home() / '.config' / 'autostart' / 'itcpr-sync.desktop'
38
+
39
+
40
+ def enable() -> None:
41
+ command = _command()
42
+ if sys.platform == 'win32':
43
+ import winreg
44
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Run', 0, winreg.KEY_SET_VALUE) as key:
45
+ winreg.SetValueEx(key, NAME, 0, winreg.REG_SZ, subprocess.list2cmdline(command))
46
+ elif sys.platform == 'darwin':
47
+ from xml.sax.saxutils import escape
48
+ args = ''.join(f'<string>{escape(c)}</string>' for c in command)
49
+ _mac_plist().parent.mkdir(parents=True, exist_ok=True)
50
+ _mac_plist().write_text(f'''<?xml version="1.0" encoding="UTF-8"?>
51
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
52
+ <plist version="1.0"><dict>
53
+ <key>Label</key><string>org.itcpr.sync</string>
54
+ <key>ProgramArguments</key><array>{args}</array>
55
+ <key>RunAtLoad</key><true/>
56
+ <key>ProcessType</key><string>Interactive</string>
57
+ </dict></plist>
58
+ ''', encoding='utf-8')
59
+ else:
60
+ _linux_desktop().parent.mkdir(parents=True, exist_ok=True)
61
+ _linux_desktop().write_text(f'''[Desktop Entry]
62
+ Type=Application
63
+ Name={NAME}
64
+ Exec={_desktop_exec(command)}
65
+ X-GNOME-Autostart-enabled=true
66
+ NoDisplay=false
67
+ ''', encoding='utf-8')
68
+
69
+
70
+ def disable() -> None:
71
+ if sys.platform == 'win32':
72
+ import winreg
73
+ try:
74
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Run', 0, winreg.KEY_SET_VALUE) as key:
75
+ winreg.DeleteValue(key, NAME)
76
+ except OSError:
77
+ pass
78
+ elif sys.platform == 'darwin':
79
+ _mac_plist().unlink(missing_ok=True)
80
+ else:
81
+ _linux_desktop().unlink(missing_ok=True)
82
+
83
+
84
+ def apply(on: bool) -> None:
85
+ try:
86
+ enable() if on else disable()
87
+ except OSError:
88
+ pass
@@ -0,0 +1,20 @@
1
+ """
2
+ ITCPR's mark and the dark band's colours, without Qt, so the tray and the sign-in page in the browser
3
+ can share them.
4
+ """
5
+
6
+ # The dark hero band, the same in light and dark mode, as on the site.
7
+ HERO = {'bg': '#14142b', 'glow': '#4b4b8f', 'spark': '#c4552a', 'ink': '#ffffff', 'muted': '#b9b9d9', 'bar': '#b5b5e8',
8
+ 'good': '#4cc38a', 'danger': '#f08080'}
9
+
10
+ # The ITCPR mark (portal-itcpr/public/assets/brand/itcpr-mark.svg), drawn in viewBox "2 2 96 96".
11
+ MARK = ('M2.01 50.95C5.5 51.04 8.82 52.21 12.13 53.75C15.43 55.29 18.75 57.27 21.96 59.18C25.18 61.09 28.29 62.92 30.97 64.2'
12
+ 'C33.65 65.47 35.88 66.1 37.21 66.16C38.54 66.22 38.92 66.05 39.68 65.34C40.44 64.62 41.48 62.95 42.36 60.38'
13
+ 'C43.25 57.8 44.01 54.42 44.74 50.82C45.46 47.22 46.17 43.4 47.13 39.83C48.09 36.25 49.27 32.89 51.23 30.02'
14
+ 'C53.19 27.15 56.26 24.81 59.75 24.1C63.24 23.4 66.71 24.13 70.04 25.37C73.36 26.61 76.67 28.43 79.94 30.33'
15
+ 'C83.21 32.24 86.43 34.23 89.34 35.79C92.25 37.36 94.86 38.46 96.69 38.85A48 48 0 0 0 2.01 50.95Z'
16
+ 'M3.31 61.15C5.14 61.54 7.75 62.64 10.66 64.21C13.57 65.77 16.79 67.76 20.06 69.67C23.33 71.57 26.64 73.39 29.96 74.63'
17
+ 'C33.29 75.87 36.76 76.6 40.25 75.9C43.74 75.19 46.81 72.85 48.77 69.98C50.73 67.11 51.91 63.75 52.87 60.17'
18
+ 'C53.83 56.6 54.54 52.78 55.26 49.18C55.99 45.58 56.75 42.2 57.64 39.62C58.52 37.05 59.56 35.38 60.32 34.66'
19
+ 'C61.08 33.95 61.46 33.78 62.79 33.84C64.12 33.9 66.35 34.53 69.03 35.8C71.71 37.08 74.82 38.91 78.04 40.82'
20
+ 'C81.25 42.73 84.57 44.71 87.87 46.25C91.18 47.79 94.5 48.96 97.99 49.05A48 48 0 0 1 3.31 61.15Z')