ovos-PHAL-plugin-sync 0.0.1a2__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.
- ovos_phal_plugin_sync/__init__.py +559 -0
- ovos_phal_plugin_sync/backends/__init__.py +63 -0
- ovos_phal_plugin_sync/backends/folder.py +41 -0
- ovos_phal_plugin_sync/backends/github.py +87 -0
- ovos_phal_plugin_sync/backends/webdav.py +72 -0
- ovos_phal_plugin_sync/controlpanel.json +315 -0
- ovos_phal_plugin_sync/controlpanel.svg +1 -0
- ovos_phal_plugin_sync/crypto.py +85 -0
- ovos_phal_plugin_sync/journal.py +166 -0
- ovos_phal_plugin_sync/local.py +143 -0
- ovos_phal_plugin_sync/locale/ca-ES/controlpanel.json +82 -0
- ovos_phal_plugin_sync/locale/da-DK/controlpanel.json +82 -0
- ovos_phal_plugin_sync/locale/de-DE/controlpanel.json +82 -0
- ovos_phal_plugin_sync/locale/en-US/controlpanel.json +82 -0
- ovos_phal_plugin_sync/locale/es-ES/controlpanel.json +82 -0
- ovos_phal_plugin_sync/locale/eu-ES/controlpanel.json +82 -0
- ovos_phal_plugin_sync/locale/fr-FR/controlpanel.json +82 -0
- ovos_phal_plugin_sync/locale/gl-ES/controlpanel.json +82 -0
- ovos_phal_plugin_sync/locale/it-IT/controlpanel.json +82 -0
- ovos_phal_plugin_sync/locale/nl-NL/controlpanel.json +82 -0
- ovos_phal_plugin_sync/locale/pt-BR/controlpanel.json +82 -0
- ovos_phal_plugin_sync/locale/pt-PT/controlpanel.json +82 -0
- ovos_phal_plugin_sync-0.0.1a2.dist-info/METADATA +184 -0
- ovos_phal_plugin_sync-0.0.1a2.dist-info/RECORD +28 -0
- ovos_phal_plugin_sync-0.0.1a2.dist-info/WHEEL +5 -0
- ovos_phal_plugin_sync-0.0.1a2.dist-info/entry_points.txt +2 -0
- ovos_phal_plugin_sync-0.0.1a2.dist-info/licenses/LICENSE +203 -0
- ovos_phal_plugin_sync-0.0.1a2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,559 @@
|
|
|
1
|
+
"""ovos-PHAL-plugin-sync: several OpenVoiceOS devices that are one assistant.
|
|
2
|
+
|
|
3
|
+
The assistant on the work PC, the one in the living room and the one in the
|
|
4
|
+
bedroom share what is yours - the skills' settings, your language and
|
|
5
|
+
location, and what skills want remembered across devices (three workouts in
|
|
6
|
+
the bedroom this morning, so the one at work is number four) - with no
|
|
7
|
+
server of anybody's in between. They are synced, not connected: each may be
|
|
8
|
+
a different kind of device (an old tablet, a strong PC), so skills are not
|
|
9
|
+
copied between them; the person's **library** of skills is shared, and a
|
|
10
|
+
skill goes on a device when it is ordered to (from my.emkay.ai, or "install
|
|
11
|
+
here" on the device's own page). The devices meet in a
|
|
12
|
+
storage **you** pick (a folder, WebDAV/Nextcloud, a private GitHub
|
|
13
|
+
repository), every device writing only its own file, sealed with a secret
|
|
14
|
+
only your devices know. Each device works on its own and catches up when it
|
|
15
|
+
can reach the storage; being offline is normal, not an error.
|
|
16
|
+
|
|
17
|
+
For skills, on the bus (answers are ``<type>.response``):
|
|
18
|
+
|
|
19
|
+
ovos.sync.event {"ns", "kind", "data"} -> {"id"} remember that it happened
|
|
20
|
+
ovos.sync.events {"ns", "kind"?, "since"?} -> {"events": [{"t", "kind", "data", "by", ...}]}
|
|
21
|
+
ovos.sync.set {"ns", "key", "value"} -> {} a shared value, newest wins
|
|
22
|
+
ovos.sync.get {"ns", "key"?} -> {"value"} or {"values"}
|
|
23
|
+
ovos.sync.changed {"ns": [...], "settings": [...], "config": [...]} (sent when others changed something)
|
|
24
|
+
|
|
25
|
+
``ns`` is the skill's own name (its skill id). Events are what to count with
|
|
26
|
+
- they are never lost or overwritten, whichever device was offline - and
|
|
27
|
+
values are for "the last thing I chose".
|
|
28
|
+
|
|
29
|
+
For the control panel and setting it up:
|
|
30
|
+
|
|
31
|
+
ovos.sync.status {} -> joined, state, storage, devices, what is shared
|
|
32
|
+
ovos.sync.setup {"type", ...storage, "name"} start a group on this device
|
|
33
|
+
ovos.sync.pair {} -> {"code"} the code another device joins with (a QR)
|
|
34
|
+
ovos.sync.code {} -> {"data"} the same code as a file
|
|
35
|
+
ovos.sync.join {"code", "name"}
|
|
36
|
+
ovos.sync.now {} -> sync now
|
|
37
|
+
ovos.sync.rename {"device", "name"}
|
|
38
|
+
ovos.sync.leave {} -> forget the group on this device
|
|
39
|
+
ovos.sync.install {"skill"} -> install a skill of the library here
|
|
40
|
+
ovos.sync.forget {"skill"} -> take a skill out of the library
|
|
41
|
+
|
|
42
|
+
Configuration, in mycroft.conf under PHAL.ovos-PHAL-plugin-sync (this
|
|
43
|
+
device's own, never shared):
|
|
44
|
+
|
|
45
|
+
interval 60 seconds between looks at the storage
|
|
46
|
+
share_settings true: the skills' settings
|
|
47
|
+
share_config true: the keys in config_keys
|
|
48
|
+
follow_orders true: install and uninstall skills when told to from my.emkay.ai
|
|
49
|
+
config_keys lang, location, units, time and date formats
|
|
50
|
+
local_settings "skill_id:key" or "*:key" lines kept to this device
|
|
51
|
+
keep_days 400: events older than this are let go
|
|
52
|
+
join_url "": the join code as it is; a distribution can make it a
|
|
53
|
+
link, e.g. "https://my.emkay.ai/#join=" - the code after
|
|
54
|
+
"#" never leaves the browser that opens it
|
|
55
|
+
"""
|
|
56
|
+
import base64
|
|
57
|
+
import json
|
|
58
|
+
import threading
|
|
59
|
+
import time
|
|
60
|
+
import uuid
|
|
61
|
+
from pathlib import Path
|
|
62
|
+
|
|
63
|
+
from ovos_bus_client.message import Message
|
|
64
|
+
from ovos_plugin_manager.templates.phal import PHALPlugin, PHALValidator
|
|
65
|
+
from ovos_utils.log import LOG
|
|
66
|
+
|
|
67
|
+
from ovos_phal_plugin_sync import crypto, journal, local
|
|
68
|
+
from ovos_phal_plugin_sync.backends import BackendError, make as make_backend, known as known_backends
|
|
69
|
+
|
|
70
|
+
NAME = "ovos-PHAL-plugin-sync"
|
|
71
|
+
NAME_MAX = 40
|
|
72
|
+
CODE_PREFIX = "OVOS-SYNC-1:"
|
|
73
|
+
#: after a change on this device, wait this long for more before writing (s)
|
|
74
|
+
SETTLE = 3.0
|
|
75
|
+
DEFAULTS = {"interval": 60, "share_settings": True, "share_config": True, "follow_orders": True,
|
|
76
|
+
"config_keys": list(local.CONFIG_KEYS), "local_settings": [], "keep_days": 400, "join_url": ""}
|
|
77
|
+
#: orders older than this are not carried out any more (a device that was
|
|
78
|
+
#: away for a month should not start installing what was asked back then)
|
|
79
|
+
ORDER_DAYS = 14
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def default_name() -> str:
|
|
83
|
+
import platform
|
|
84
|
+
node = (platform.node() or "").split(".")[0]
|
|
85
|
+
return node[:NAME_MAX] if node and node not in ("localhost", "emscripten") else "This device"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def state_dir() -> Path:
|
|
89
|
+
from ovos_utils.xdg_utils import xdg_state_home
|
|
90
|
+
return Path(xdg_state_home()) / "ovos-sync"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class SyncValidator(PHALValidator):
|
|
94
|
+
@staticmethod
|
|
95
|
+
def validate(config=None):
|
|
96
|
+
return (config or {}).get("enabled", True) is not False
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class SyncPlugin(PHALPlugin):
|
|
100
|
+
validator = SyncValidator
|
|
101
|
+
|
|
102
|
+
def __init__(self, bus=None, config=None, state=None, settings_dir=None, user_config=None, auto=True):
|
|
103
|
+
self._auto = auto # False in tests: no thread, sync() by hand
|
|
104
|
+
self.dir = Path(state) if state else state_dir()
|
|
105
|
+
self.lock = threading.RLock()
|
|
106
|
+
self.poke = threading.Event()
|
|
107
|
+
self.stopping = threading.Event()
|
|
108
|
+
self.last_sync = 0
|
|
109
|
+
self.problem = "" # a key of the page's words, or ""
|
|
110
|
+
self.problem_detail = ""
|
|
111
|
+
self._settings_dir = settings_dir
|
|
112
|
+
self._user_config = user_config
|
|
113
|
+
self.state = self._load("state.json") or {}
|
|
114
|
+
if not self.state.get("device"):
|
|
115
|
+
# a device is a group of one until it joins others: skills can use
|
|
116
|
+
# the events and values from the start, and keep them when it joins
|
|
117
|
+
self.state.update(device=uuid.uuid4().hex[:12], name=default_name())
|
|
118
|
+
self._save("state.json", self.state)
|
|
119
|
+
self.journal = journal.Journal(self._load("journal.json") or
|
|
120
|
+
journal.empty(self.state["device"], self.state["name"]))
|
|
121
|
+
# the others' files as last read (file name -> {"tag", "data"}), so
|
|
122
|
+
# what they said still counts while the storage cannot be reached
|
|
123
|
+
self.others = (self._load("others.json") or {}) if self.joined else {}
|
|
124
|
+
self._remerge()
|
|
125
|
+
if config is None:
|
|
126
|
+
from ovos_config import Configuration
|
|
127
|
+
config = Configuration().get("PHAL", {}).get(NAME, {})
|
|
128
|
+
# everything is in place before the template starts the thread (run)
|
|
129
|
+
super().__init__(bus=bus, name=NAME, config=dict(DEFAULTS, **config))
|
|
130
|
+
self.handlers = [("ovos.sync.status", self.handle_status), ("ovos.sync.setup", self.handle_setup),
|
|
131
|
+
("ovos.sync.pair", self.handle_pair), ("ovos.sync.code", self.handle_code),
|
|
132
|
+
("ovos.sync.join", self.handle_join), ("ovos.sync.now", self.handle_now),
|
|
133
|
+
("ovos.sync.rename", self.handle_rename), ("ovos.sync.leave", self.handle_leave),
|
|
134
|
+
("ovos.sync.reload", self.handle_reload), ("ovos.sync.form", self.handle_form),
|
|
135
|
+
("ovos.sync.event", self.handle_event), ("ovos.sync.events", self.handle_events),
|
|
136
|
+
("ovos.sync.set", self.handle_set), ("ovos.sync.get", self.handle_get),
|
|
137
|
+
("ovos.sync.install", self.handle_install), ("ovos.sync.forget", self.handle_forget)]
|
|
138
|
+
for topic, handler in self.handlers:
|
|
139
|
+
self.bus.on(topic, handler)
|
|
140
|
+
|
|
141
|
+
# -- files of this device -------------------------------------------------
|
|
142
|
+
|
|
143
|
+
def _load(self, name):
|
|
144
|
+
try:
|
|
145
|
+
return json.loads((self.dir / name).read_text(encoding="utf-8"))
|
|
146
|
+
except (OSError, ValueError):
|
|
147
|
+
return None
|
|
148
|
+
|
|
149
|
+
def _save(self, name, data):
|
|
150
|
+
self.dir.mkdir(parents=True, exist_ok=True)
|
|
151
|
+
tmp = self.dir / f".{name}.tmp"
|
|
152
|
+
tmp.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
|
153
|
+
tmp.replace(self.dir / name)
|
|
154
|
+
if name == "state.json":
|
|
155
|
+
try:
|
|
156
|
+
(self.dir / name).chmod(0o600) # it holds the secret
|
|
157
|
+
except OSError:
|
|
158
|
+
pass
|
|
159
|
+
|
|
160
|
+
@property
|
|
161
|
+
def joined(self) -> bool:
|
|
162
|
+
return bool(self.state.get("secret"))
|
|
163
|
+
|
|
164
|
+
@property
|
|
165
|
+
def me(self) -> str:
|
|
166
|
+
return self.state["device"]
|
|
167
|
+
|
|
168
|
+
def _own_file(self) -> str:
|
|
169
|
+
return f"{self.me}.sealed"
|
|
170
|
+
|
|
171
|
+
def _remerge(self):
|
|
172
|
+
self.view = journal.merge([self.journal.data] + [o["data"] for o in self.others.values()])
|
|
173
|
+
|
|
174
|
+
def _backend(self):
|
|
175
|
+
return make_backend(self.state["storage"], crypto.group_id(self.state["secret"]))
|
|
176
|
+
|
|
177
|
+
def _settings(self):
|
|
178
|
+
return local.Settings(self._settings_dir)
|
|
179
|
+
|
|
180
|
+
def _config(self):
|
|
181
|
+
return local.Config(self.config["config_keys"], path=self._user_config, bus=self.bus)
|
|
182
|
+
|
|
183
|
+
def _installed(self) -> dict:
|
|
184
|
+
return local.installed_skills()
|
|
185
|
+
|
|
186
|
+
def _kept_here(self, skill_id, key) -> bool:
|
|
187
|
+
lines = set(self.config.get("local_settings") or [])
|
|
188
|
+
return key.startswith("__") or f"{skill_id}:{key}" in lines or f"*:{key}" in lines
|
|
189
|
+
|
|
190
|
+
# -- the loop --------------------------------------------------------------
|
|
191
|
+
|
|
192
|
+
def run(self):
|
|
193
|
+
if not self._auto:
|
|
194
|
+
return
|
|
195
|
+
while not self.stopping.is_set():
|
|
196
|
+
if self.joined:
|
|
197
|
+
self.sync()
|
|
198
|
+
self.poke.wait(max(10, int(self.config.get("interval", 60))))
|
|
199
|
+
if self.poke.is_set():
|
|
200
|
+
self.poke.clear()
|
|
201
|
+
self.stopping.wait(SETTLE)
|
|
202
|
+
|
|
203
|
+
def shutdown(self):
|
|
204
|
+
self.stopping.set()
|
|
205
|
+
self.poke.set()
|
|
206
|
+
for topic, handler in self.handlers:
|
|
207
|
+
self.bus.remove(topic, handler)
|
|
208
|
+
super().shutdown()
|
|
209
|
+
|
|
210
|
+
def soon(self):
|
|
211
|
+
self.poke.set()
|
|
212
|
+
|
|
213
|
+
# -- this device's changes ------------------------------------------------
|
|
214
|
+
|
|
215
|
+
def _current(self, section, group, key):
|
|
216
|
+
"""What the group says now, or None."""
|
|
217
|
+
entries = self.view[section].get(group, {}) if section in ("values", "settings") else self.view[section]
|
|
218
|
+
entry = entries.get(key)
|
|
219
|
+
return entry if entry is None else entry.get("want" if section == "library" else "v")
|
|
220
|
+
|
|
221
|
+
def scan(self, record=True):
|
|
222
|
+
"""Note what changed here since the last look, as this device's own
|
|
223
|
+
changes. A change that only repeats what the group already says (a
|
|
224
|
+
setting another device made, written here) is not noted again."""
|
|
225
|
+
snap = self.state.setdefault("snap", {"settings": {}, "config": {}, "skills": {}})
|
|
226
|
+
if self.config.get("share_settings"):
|
|
227
|
+
for skill, values in self._settings().read().items():
|
|
228
|
+
old = snap["settings"].setdefault(skill, {})
|
|
229
|
+
for key, value in values.items():
|
|
230
|
+
if self._kept_here(skill, key) or old.get(key, object()) == value:
|
|
231
|
+
continue
|
|
232
|
+
old[key] = value
|
|
233
|
+
if record and self._current("settings", skill, key) != value:
|
|
234
|
+
self.journal.set("settings", skill, key, value)
|
|
235
|
+
if self.config.get("share_config"):
|
|
236
|
+
for key, value in self._config().read().items():
|
|
237
|
+
if snap["config"].get(key, object()) == value:
|
|
238
|
+
continue
|
|
239
|
+
snap["config"][key] = value
|
|
240
|
+
if record and self._current("config", "", key) != value:
|
|
241
|
+
self.journal.set_flat("config", key, {"v": value})
|
|
242
|
+
# what is installed here, for my.emkay.ai; a skill installed here
|
|
243
|
+
# after the device joined goes in the person's library too, so it
|
|
244
|
+
# can be put on the other devices (it is never put there by itself)
|
|
245
|
+
here, meta = self._installed()
|
|
246
|
+
self.journal.describe(here, meta)
|
|
247
|
+
for name in set(here) - set(snap["skills"]):
|
|
248
|
+
if record and self._current("library", "", name) is not True:
|
|
249
|
+
self.journal.set_flat("library", name, {"want": True})
|
|
250
|
+
snap["skills"] = {name: info.get("v") for name, info in here.items()}
|
|
251
|
+
self._save("state.json", self.state)
|
|
252
|
+
|
|
253
|
+
# -- the others' changes -------------------------------------------------
|
|
254
|
+
|
|
255
|
+
def apply(self):
|
|
256
|
+
"""Make this device what the group says, where another device said it
|
|
257
|
+
last. Returns what changed here, for ovos.sync.changed."""
|
|
258
|
+
snap = self.state["snap"]
|
|
259
|
+
changed = {"settings": [], "config": []}
|
|
260
|
+
if self.config.get("share_settings"):
|
|
261
|
+
here = self._settings().read()
|
|
262
|
+
for skill, entries in self.view["settings"].items():
|
|
263
|
+
todo = {}
|
|
264
|
+
for key, entry in entries.items():
|
|
265
|
+
if self.view["winners"][("settings", skill, key)] == self.me or self._kept_here(skill, key):
|
|
266
|
+
continue
|
|
267
|
+
if here.get(skill, {}).get(key, object()) != entry["v"]:
|
|
268
|
+
todo[key] = entry["v"]
|
|
269
|
+
if todo:
|
|
270
|
+
self._settings().write(skill, todo)
|
|
271
|
+
snap["settings"].setdefault(skill, {}).update(todo)
|
|
272
|
+
changed["settings"].append(skill)
|
|
273
|
+
if self.config.get("share_config"):
|
|
274
|
+
here = self._config().read()
|
|
275
|
+
for key, entry in self.view["config"].items():
|
|
276
|
+
if key not in self.config["config_keys"] or self.view["winners"][("config", "", key)] == self.me:
|
|
277
|
+
continue
|
|
278
|
+
if here.get(key, object()) != entry["v"]:
|
|
279
|
+
self._config().write(key, entry["v"])
|
|
280
|
+
snap["config"][key] = entry["v"]
|
|
281
|
+
changed["config"].append(key)
|
|
282
|
+
if self.config.get("follow_orders"):
|
|
283
|
+
self.carry_out_orders()
|
|
284
|
+
return changed
|
|
285
|
+
|
|
286
|
+
def carry_out_orders(self):
|
|
287
|
+
"""Install or uninstall what this device was told to, once each.
|
|
288
|
+
The order counts as carried out when it was sent on to OVOS' own
|
|
289
|
+
installer (ovos.pip.install); whether it worked shows in what the
|
|
290
|
+
device then has installed."""
|
|
291
|
+
here = self.journal.data["here"]
|
|
292
|
+
too_old = time.time() - ORDER_DAYS * 86400
|
|
293
|
+
for order in self.view["orders"]:
|
|
294
|
+
if order.get("to") != self.me or order["id"] in self.view["applied"]:
|
|
295
|
+
continue
|
|
296
|
+
skill = order.get("skill", "")
|
|
297
|
+
if order.get("t", 0) >= too_old and local.PIP_NAME.match(skill):
|
|
298
|
+
if order.get("do") == "install" and skill not in here:
|
|
299
|
+
self.bus.emit(Message("ovos.pip.install", {"packages": [skill]}))
|
|
300
|
+
elif order.get("do") == "uninstall" and skill in here:
|
|
301
|
+
self.bus.emit(Message("ovos.pip.uninstall", {"packages": [skill]}))
|
|
302
|
+
self.journal.applied(order["id"])
|
|
303
|
+
self.view["applied"].add(order["id"])
|
|
304
|
+
|
|
305
|
+
def sync(self):
|
|
306
|
+
"""Look at the storage once: read what is new from the others, take
|
|
307
|
+
it in, and write this device's own file if it has something new."""
|
|
308
|
+
if not self.joined:
|
|
309
|
+
return
|
|
310
|
+
with self.lock:
|
|
311
|
+
before_ids = {e["id"] for e in self.view["events"]}
|
|
312
|
+
before_values = json.dumps(self.view["values"], sort_keys=True, default=str)
|
|
313
|
+
self.scan()
|
|
314
|
+
keep = float(self.config.get("keep_days") or 400) * 86400
|
|
315
|
+
self.journal.forget_before(time.time() - keep)
|
|
316
|
+
try:
|
|
317
|
+
backend = self._backend()
|
|
318
|
+
files = backend.list()
|
|
319
|
+
for name, tag in files.items():
|
|
320
|
+
if name == self._own_file() or self.others.get(name, {}).get("tag") == tag:
|
|
321
|
+
continue
|
|
322
|
+
try:
|
|
323
|
+
data = json.loads(crypto.unseal(self.state["secret"], backend.read(name)))
|
|
324
|
+
except (crypto.SealError, ValueError) as e:
|
|
325
|
+
LOG.warning(f"{NAME}: {name} is not one of ours: {e}")
|
|
326
|
+
continue
|
|
327
|
+
if isinstance(data, dict) and data.get("device") and data.get("device") != self.me:
|
|
328
|
+
self.others[name] = {"tag": tag, "data": data}
|
|
329
|
+
self._save("others.json", self.others)
|
|
330
|
+
if self._own_file() not in files:
|
|
331
|
+
self.journal.dirty = True # new here, or the storage was emptied
|
|
332
|
+
self._remerge()
|
|
333
|
+
changed = self.apply()
|
|
334
|
+
if self.journal.dirty:
|
|
335
|
+
sealed = crypto.seal(self.state["secret"],
|
|
336
|
+
json.dumps(self.journal.stamped(), ensure_ascii=False).encode())
|
|
337
|
+
backend.write(self._own_file(), sealed)
|
|
338
|
+
self.journal.dirty = False
|
|
339
|
+
self.problem, self.problem_detail = "", ""
|
|
340
|
+
self.last_sync = time.time()
|
|
341
|
+
except BackendError as e:
|
|
342
|
+
self.problem, self.problem_detail = "storage", str(e)[:300]
|
|
343
|
+
LOG.info(f"{NAME}: the storage could not be reached: {e}")
|
|
344
|
+
self._remerge()
|
|
345
|
+
changed = {"settings": [], "config": []}
|
|
346
|
+
self._save("journal.json", self.journal.data)
|
|
347
|
+
self._remerge()
|
|
348
|
+
new_ns = sorted({e["ns"] for e in self.view["events"]
|
|
349
|
+
if e["id"] not in before_ids and e["device"] != self.me})
|
|
350
|
+
if json.dumps(self.view["values"], sort_keys=True, default=str) != before_values:
|
|
351
|
+
new_ns = sorted(set(new_ns) | {ns for ns, entries in self.view["values"].items()
|
|
352
|
+
if any(self.view["winners"][("values", ns, k)] != self.me
|
|
353
|
+
for k in entries)})
|
|
354
|
+
if new_ns or changed["settings"] or changed["config"]:
|
|
355
|
+
self.bus.emit(Message("ovos.sync.changed", {"ns": new_ns, **changed}))
|
|
356
|
+
|
|
357
|
+
# -- starting, joining, leaving -----------------------------------------
|
|
358
|
+
|
|
359
|
+
def _storage_from(self, data: dict) -> dict:
|
|
360
|
+
cls = known_backends().get(data.get("type", ""))
|
|
361
|
+
if cls is None:
|
|
362
|
+
raise BackendError("unknown storage")
|
|
363
|
+
return {"type": data["type"], **{k: str(data.get(k) or "").strip() for k in cls.FIELDS}}
|
|
364
|
+
|
|
365
|
+
def _start_group(self, secret, storage, name, own_settings):
|
|
366
|
+
"""Use this group from now on; check the storage answers first."""
|
|
367
|
+
make_backend(storage, crypto.group_id(secret)).list()
|
|
368
|
+
with self.lock:
|
|
369
|
+
name = (name or "").strip()[:NAME_MAX] or self.state.get("name") or default_name()
|
|
370
|
+
installed = {n: info.get("v") for n, info in self._installed()[0].items()}
|
|
371
|
+
self.state.update(secret=secret, storage=storage, name=name,
|
|
372
|
+
snap={"settings": {}, "config": {}, "skills": installed})
|
|
373
|
+
self.journal.data["name"] = name
|
|
374
|
+
self.journal.dirty = True
|
|
375
|
+
self.others = {}
|
|
376
|
+
# the one who starts the group brings its settings; one who joins
|
|
377
|
+
# takes the group's. What is installed is only described, never
|
|
378
|
+
# put in the library: only what is installed from now on is.
|
|
379
|
+
self.scan(record=own_settings)
|
|
380
|
+
self._save("journal.json", self.journal.data)
|
|
381
|
+
self._remerge()
|
|
382
|
+
|
|
383
|
+
def _answer(self, message, data):
|
|
384
|
+
self.bus.emit(message.response(data))
|
|
385
|
+
|
|
386
|
+
def handle_setup(self, message):
|
|
387
|
+
try:
|
|
388
|
+
storage = self._storage_from(message.data)
|
|
389
|
+
self._start_group(crypto.new_secret(), storage, message.data.get("name"), own_settings=True)
|
|
390
|
+
except BackendError as e:
|
|
391
|
+
return self._answer(message, {"error": "sync.err.storage", "detail": str(e)[:300]})
|
|
392
|
+
self._now()
|
|
393
|
+
self._answer(message, self.status())
|
|
394
|
+
|
|
395
|
+
def join_code(self) -> str:
|
|
396
|
+
raw = json.dumps({"s": self.state["secret"], "st": self.state["storage"]}, separators=(",", ":"))
|
|
397
|
+
return CODE_PREFIX + base64.urlsafe_b64encode(raw.encode()).decode().rstrip("=")
|
|
398
|
+
|
|
399
|
+
def handle_pair(self, message):
|
|
400
|
+
if not self.joined:
|
|
401
|
+
return self._answer(message, {"error": "sync.err.alone"})
|
|
402
|
+
self._answer(message, {"code": (self.config.get("join_url") or "") + self.join_code()})
|
|
403
|
+
|
|
404
|
+
def handle_code(self, message):
|
|
405
|
+
if not self.joined:
|
|
406
|
+
return self._answer(message, {"error": "sync.err.alone"})
|
|
407
|
+
text = self.join_code() + "\n"
|
|
408
|
+
self._answer(message, {"data": base64.b64encode(text.encode()).decode()})
|
|
409
|
+
|
|
410
|
+
def handle_join(self, message):
|
|
411
|
+
code = "".join((message.data.get("code") or "").split())
|
|
412
|
+
if "join=" in code: # the code as a link (join_url)
|
|
413
|
+
from urllib.parse import unquote
|
|
414
|
+
code = unquote(code.split("join=", 1)[1].split("&", 1)[0])
|
|
415
|
+
try:
|
|
416
|
+
if not code.startswith(CODE_PREFIX):
|
|
417
|
+
raise ValueError
|
|
418
|
+
body = code[len(CODE_PREFIX):]
|
|
419
|
+
raw = json.loads(base64.urlsafe_b64decode(body + "=" * (-len(body) % 4)))
|
|
420
|
+
secret, storage = raw["s"], raw["st"]
|
|
421
|
+
crypto.group_id(secret)
|
|
422
|
+
except (ValueError, KeyError, TypeError, crypto.SealError):
|
|
423
|
+
return self._answer(message, {"error": "sync.err.code"})
|
|
424
|
+
try:
|
|
425
|
+
self._start_group(secret, storage, message.data.get("name"), own_settings=False)
|
|
426
|
+
except BackendError as e:
|
|
427
|
+
return self._answer(message, {"error": "sync.err.storage", "detail": str(e)[:300]})
|
|
428
|
+
self._now()
|
|
429
|
+
self._answer(message, self.status())
|
|
430
|
+
|
|
431
|
+
def handle_leave(self, message):
|
|
432
|
+
with self.lock:
|
|
433
|
+
for key in ("secret", "storage", "snap"):
|
|
434
|
+
self.state.pop(key, None)
|
|
435
|
+
self.others = {}
|
|
436
|
+
self._save("state.json", self.state)
|
|
437
|
+
self._save("others.json", {})
|
|
438
|
+
self._remerge()
|
|
439
|
+
self._answer(message, self.status())
|
|
440
|
+
|
|
441
|
+
def handle_rename(self, message):
|
|
442
|
+
name = (message.data.get("name") or "").strip()[:NAME_MAX]
|
|
443
|
+
if not name or message.data.get("device", self.me) != self.me:
|
|
444
|
+
return self._answer(message, {"error": "sync.err.rename"})
|
|
445
|
+
with self.lock:
|
|
446
|
+
self.state["name"] = self.journal.data["name"] = name
|
|
447
|
+
self.journal.dirty = True
|
|
448
|
+
self._save("state.json", self.state)
|
|
449
|
+
self._save("journal.json", self.journal.data)
|
|
450
|
+
self._remerge()
|
|
451
|
+
self.soon()
|
|
452
|
+
self._answer(message, {})
|
|
453
|
+
|
|
454
|
+
def _now(self):
|
|
455
|
+
if self._auto:
|
|
456
|
+
self.soon()
|
|
457
|
+
else:
|
|
458
|
+
self.sync()
|
|
459
|
+
|
|
460
|
+
def handle_now(self, message):
|
|
461
|
+
"""Sync now, and answer when it is done (the voice says how it went)."""
|
|
462
|
+
def now():
|
|
463
|
+
self.sync()
|
|
464
|
+
self._answer(message, self.status())
|
|
465
|
+
if self._auto:
|
|
466
|
+
threading.Thread(target=now, daemon=True).start()
|
|
467
|
+
else:
|
|
468
|
+
now()
|
|
469
|
+
|
|
470
|
+
def handle_reload(self, message):
|
|
471
|
+
self.config = dict(DEFAULTS, **(message.data.get("config") or {}))
|
|
472
|
+
self.soon()
|
|
473
|
+
|
|
474
|
+
def status(self) -> dict:
|
|
475
|
+
state = "alone" if not self.joined else ("offline" if self.problem else ("ok" if self.last_sync else "waiting"))
|
|
476
|
+
storage = ""
|
|
477
|
+
if self.joined:
|
|
478
|
+
try:
|
|
479
|
+
storage = self._backend().describe()
|
|
480
|
+
except BackendError:
|
|
481
|
+
storage = self.state["storage"].get("type", "")
|
|
482
|
+
devices = [dict(d, me=d["device"] == self.me) for d in self.view["devices"]]
|
|
483
|
+
devices.sort(key=lambda d: (not d["me"], d["name"].lower()))
|
|
484
|
+
return {"joined": self.joined, "alone": not self.joined, "state": state, "name": self.state["name"],
|
|
485
|
+
"device": self.me, "storage": storage, "last": self.last_sync, "problem": self.problem,
|
|
486
|
+
"detail": self.problem_detail, "devices": devices, "others": len(devices) - 1,
|
|
487
|
+
"spaces": journal.namespaces(self.view), "library": self.library()}
|
|
488
|
+
|
|
489
|
+
def library(self) -> list:
|
|
490
|
+
"""The person's skills, and whether each is on this device."""
|
|
491
|
+
here = self.journal.data["here"]
|
|
492
|
+
return sorted(({"skill": name, "here": name in here} for name, entry in self.view["library"].items()
|
|
493
|
+
if entry.get("want")), key=lambda r: (r["here"], r["skill"]))
|
|
494
|
+
|
|
495
|
+
def handle_install(self, message):
|
|
496
|
+
"""Install a skill of the person's library on this device."""
|
|
497
|
+
skill = message.data.get("skill", "")
|
|
498
|
+
if skill not in self.view["library"] or not local.PIP_NAME.match(skill):
|
|
499
|
+
return self._answer(message, {"error": "sync.err.notInLibrary"})
|
|
500
|
+
self.bus.emit(Message("ovos.pip.install", {"packages": [skill]}))
|
|
501
|
+
self._answer(message, {})
|
|
502
|
+
|
|
503
|
+
def handle_forget(self, message):
|
|
504
|
+
"""Take a skill out of the library (it stays where it is installed)."""
|
|
505
|
+
skill = message.data.get("skill", "")
|
|
506
|
+
with self.lock:
|
|
507
|
+
self.journal.set_flat("library", skill, {"want": False})
|
|
508
|
+
self._save("journal.json", self.journal.data)
|
|
509
|
+
self._remerge()
|
|
510
|
+
self.soon()
|
|
511
|
+
self._answer(message, {})
|
|
512
|
+
|
|
513
|
+
def handle_status(self, message):
|
|
514
|
+
self._answer(message, self.status())
|
|
515
|
+
|
|
516
|
+
def handle_form(self, message):
|
|
517
|
+
"""What the start and join forms show: this device's name, and the
|
|
518
|
+
storage in use without its password or token."""
|
|
519
|
+
storage = dict(self.state.get("storage") or {"type": "github"})
|
|
520
|
+
cls = known_backends().get(storage.get("type"))
|
|
521
|
+
for key in getattr(cls, "SECRET", ()):
|
|
522
|
+
storage.pop(key, None)
|
|
523
|
+
self._answer(message, dict(storage, name=self.state["name"]))
|
|
524
|
+
|
|
525
|
+
# -- for skills --------------------------------------------------------
|
|
526
|
+
|
|
527
|
+
def handle_event(self, message):
|
|
528
|
+
ns, kind = message.data.get("ns"), message.data.get("kind")
|
|
529
|
+
if not ns or not kind:
|
|
530
|
+
return self._answer(message, {"error": "ns and kind are needed"})
|
|
531
|
+
with self.lock:
|
|
532
|
+
event = self.journal.add_event(str(ns), str(kind), message.data.get("data") or {})
|
|
533
|
+
self._save("journal.json", self.journal.data)
|
|
534
|
+
self._remerge()
|
|
535
|
+
self.soon()
|
|
536
|
+
self._answer(message, {"id": event["id"]})
|
|
537
|
+
|
|
538
|
+
def handle_events(self, message):
|
|
539
|
+
found = journal.events(self.view, message.data.get("ns"), message.data.get("kind"),
|
|
540
|
+
message.data.get("since"))
|
|
541
|
+
self._answer(message, {"events": [dict(e, here=e["device"] == self.me) for e in found]})
|
|
542
|
+
|
|
543
|
+
def handle_set(self, message):
|
|
544
|
+
ns, key = message.data.get("ns"), message.data.get("key")
|
|
545
|
+
if not ns or not key:
|
|
546
|
+
return self._answer(message, {"error": "ns and key are needed"})
|
|
547
|
+
with self.lock:
|
|
548
|
+
self.journal.set("values", str(ns), str(key), message.data.get("value"))
|
|
549
|
+
self._save("journal.json", self.journal.data)
|
|
550
|
+
self._remerge()
|
|
551
|
+
self.soon()
|
|
552
|
+
self._answer(message, {})
|
|
553
|
+
|
|
554
|
+
def handle_get(self, message):
|
|
555
|
+
entries = self.view["values"].get(message.data.get("ns"), {})
|
|
556
|
+
if message.data.get("key"):
|
|
557
|
+
entry = entries.get(message.data["key"])
|
|
558
|
+
return self._answer(message, {"value": entry["v"] if entry else None})
|
|
559
|
+
self._answer(message, {"values": {k: e["v"] for k, e in entries.items()}})
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Where the devices meet: a place that can list, read and write files.
|
|
2
|
+
|
|
3
|
+
A storage only ever sees sealed files named by device id in a folder named
|
|
4
|
+
by the group (crypto.group_id), so it learns how many devices there are and
|
|
5
|
+
when they write, and nothing else.
|
|
6
|
+
|
|
7
|
+
Built in: ``folder`` (a folder on the device: a mounted NAS, a Syncthing or
|
|
8
|
+
Nextcloud folder, Emkay Home's disk), ``webdav`` (Nextcloud, ownCloud, a NAS)
|
|
9
|
+
and ``github`` (a private repository; works from a browser too). Another
|
|
10
|
+
package can bring one with an entry point in the group ``ovos.sync.backend``
|
|
11
|
+
naming a class with the same methods.
|
|
12
|
+
"""
|
|
13
|
+
from importlib import metadata
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Backend:
|
|
17
|
+
"""Files in one folder of a storage."""
|
|
18
|
+
#: the settings it needs; the ones in SECRET are never shown again
|
|
19
|
+
FIELDS = ()
|
|
20
|
+
SECRET = ()
|
|
21
|
+
|
|
22
|
+
def __init__(self, config: dict, folder: str):
|
|
23
|
+
self.config = config
|
|
24
|
+
self.folder = folder
|
|
25
|
+
|
|
26
|
+
def list(self) -> dict:
|
|
27
|
+
"""{file name: something that changes when the file does}"""
|
|
28
|
+
raise NotImplementedError
|
|
29
|
+
|
|
30
|
+
def read(self, name: str) -> bytes:
|
|
31
|
+
raise NotImplementedError
|
|
32
|
+
|
|
33
|
+
def write(self, name: str, data: bytes):
|
|
34
|
+
raise NotImplementedError
|
|
35
|
+
|
|
36
|
+
def describe(self) -> str:
|
|
37
|
+
"""Where it is, for people (no passwords)."""
|
|
38
|
+
return self.__class__.__name__
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class BackendError(RuntimeError):
|
|
42
|
+
"""The storage could not be reached, or said no."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def known() -> dict:
|
|
46
|
+
from ovos_phal_plugin_sync.backends.folder import FolderBackend
|
|
47
|
+
from ovos_phal_plugin_sync.backends.github import GitHubBackend
|
|
48
|
+
from ovos_phal_plugin_sync.backends.webdav import WebDAVBackend
|
|
49
|
+
found = {"folder": FolderBackend, "webdav": WebDAVBackend, "github": GitHubBackend}
|
|
50
|
+
try:
|
|
51
|
+
for ep in metadata.entry_points(group="ovos.sync.backend"):
|
|
52
|
+
found.setdefault(ep.name, ep.load())
|
|
53
|
+
except Exception:
|
|
54
|
+
pass
|
|
55
|
+
return found
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def make(config: dict, folder: str) -> Backend:
|
|
59
|
+
kind = (config or {}).get("type", "")
|
|
60
|
+
cls = known().get(kind)
|
|
61
|
+
if cls is None:
|
|
62
|
+
raise BackendError(f"unknown storage: {kind!r}")
|
|
63
|
+
return cls(config, folder)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""A folder the device can write to: a mounted NAS share, a folder Syncthing
|
|
2
|
+
or the Nextcloud client keeps in step, or a disk on Emkay Home."""
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from ovos_phal_plugin_sync.backends import Backend, BackendError
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class FolderBackend(Backend):
|
|
10
|
+
FIELDS = ("path",)
|
|
11
|
+
|
|
12
|
+
def __init__(self, config, folder):
|
|
13
|
+
super().__init__(config, folder)
|
|
14
|
+
if not config.get("path"):
|
|
15
|
+
raise BackendError("a folder needs a path")
|
|
16
|
+
self.root = Path(os.path.expanduser(config["path"])) / folder
|
|
17
|
+
|
|
18
|
+
def list(self):
|
|
19
|
+
try:
|
|
20
|
+
self.root.mkdir(parents=True, exist_ok=True)
|
|
21
|
+
return {p.name: p.stat().st_mtime_ns for p in self.root.glob("*.sealed")}
|
|
22
|
+
except OSError as e:
|
|
23
|
+
raise BackendError(str(e)) from e
|
|
24
|
+
|
|
25
|
+
def read(self, name):
|
|
26
|
+
try:
|
|
27
|
+
return (self.root / name).read_bytes()
|
|
28
|
+
except OSError as e:
|
|
29
|
+
raise BackendError(str(e)) from e
|
|
30
|
+
|
|
31
|
+
def write(self, name, data):
|
|
32
|
+
try:
|
|
33
|
+
self.root.mkdir(parents=True, exist_ok=True)
|
|
34
|
+
tmp = self.root / f".{name}.tmp"
|
|
35
|
+
tmp.write_bytes(data)
|
|
36
|
+
os.replace(tmp, self.root / name)
|
|
37
|
+
except OSError as e:
|
|
38
|
+
raise BackendError(str(e)) from e
|
|
39
|
+
|
|
40
|
+
def describe(self):
|
|
41
|
+
return str(Path(self.config["path"]))
|