prim-ctrl 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.
prim_ctrl/__init__.py ADDED
File without changes
prim_ctrl/__main__.py ADDED
@@ -0,0 +1,870 @@
1
+
2
+ import argparse
3
+ import asyncio
4
+ import logging
5
+ import os
6
+ import platform
7
+ import socket
8
+ import subprocess
9
+ import sys
10
+ import time
11
+ from abc import abstractmethod
12
+ from contextlib import nullcontext, suppress
13
+ from datetime import datetime, timezone
14
+ from pathlib import Path
15
+ from typing import Dict
16
+
17
+ import aiohttp
18
+ from aiohttp import ClientTimeout, web
19
+ from platformdirs import user_cache_dir
20
+ from zeroconf import Zeroconf, ServiceInfo, ServiceListener as ZeroconfServiceListener
21
+ from zeroconf.asyncio import AsyncZeroconf
22
+
23
+ ########
24
+
25
+ class LevelFormatter(logging.Formatter):
26
+ logging.Formatter.default_msec_format = logging.Formatter.default_msec_format.replace(',', '.') if logging.Formatter.default_msec_format else None
27
+
28
+ def __init__(self, fmts: Dict[int, str], fmt: str, **kwargs):
29
+ super().__init__()
30
+ self.formatters = dict({level: logging.Formatter(fmt, **kwargs) for level, fmt in fmts.items()})
31
+ self.default_formatter = logging.Formatter(fmt, **kwargs)
32
+
33
+ def format(self, record: logging.LogRecord) -> str:
34
+ return self.formatters.get(record.levelno, self.default_formatter).format(record)
35
+
36
+ class Logger(logging.Logger):
37
+ def __init__(self, name, level=logging.NOTSET):
38
+ super().__init__(name, level)
39
+ self.exitcode = 0
40
+
41
+ def prepare(self, timestamp: bool, silent: bool):
42
+ handler = logging.StreamHandler(sys.stderr)
43
+ handler.setFormatter(
44
+ LevelFormatter(
45
+ {
46
+ logging.WARNING: '%(asctime)s %(message)s',
47
+ logging.INFO: '%(asctime)s %(message)s',
48
+ logging.DEBUG: '%(asctime)s %(levelname)s %(message)s',
49
+ },
50
+ '%(asctime)s %(name)s: %(levelname)s: %(message)s')
51
+ if timestamp else
52
+ LevelFormatter(
53
+ {
54
+ logging.WARNING: '%(message)s',
55
+ logging.INFO: '%(message)s',
56
+ logging.DEBUG: '%(levelname)s %(message)s',
57
+ },
58
+ '%(name)s: %(levelname)s: %(message)s')
59
+ )
60
+ self.addHandler(handler)
61
+ if self.level == logging.NOTSET:
62
+ self.setLevel(logging.WARNING if silent else logging.INFO)
63
+
64
+ def error(self, msg, *args, **kwargs):
65
+ self.exitcode = 1
66
+ super().error(msg, *args, **kwargs)
67
+
68
+ def critical(self, msg, *args, **kwargs):
69
+ self.exitcode = 1
70
+ super().critical(msg, *args, **kwargs)
71
+
72
+ def log(self, level, msg, *args, **kwargs):
73
+ if level >= logging.ERROR:
74
+ self.exitcode = 1
75
+ super().log(level, msg, *args, **kwargs)
76
+
77
+ class LazyStr:
78
+ def __init__(self, func, *args, **kwargs):
79
+ self.func = func
80
+ self.args = args
81
+ self.kwargs = kwargs
82
+ self.result = None
83
+ def __str__(self):
84
+ if self.result is None:
85
+ self.result = str(self.func(*self.args, **self.kwargs))
86
+ return self.result
87
+
88
+ logger = Logger(Path(sys.argv[0]).name)
89
+
90
+ ########
91
+
92
+ # based on https://stackoverflow.com/a/55656177/2755656
93
+ def sync_ping(host, packets: int = 1, timeout: float = 1):
94
+ if platform.system().lower() == 'windows':
95
+ command = ['ping', '-n', str(packets), '-w', str(int(timeout*1000)), host]
96
+ # don't use text=True, the async version will raise ValueError("text must be False"), who knows why
97
+ result = subprocess.run(command, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, creationflags=subprocess.CREATE_NO_WINDOW)
98
+ return result.returncode == 0 and b'TTL=' in result.stdout
99
+ else:
100
+ command = ['ping', '-c', str(packets), '-W', str(int(timeout)), host]
101
+ result = subprocess.run(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
102
+ return result.returncode == 0
103
+
104
+ async def async_ping(host, packets: int = 1, timeout: float = 1):
105
+ if platform.system().lower() == 'windows':
106
+ command = ['ping', '-n', str(packets), '-w', str(int(timeout*1000)), host]
107
+ # don't use text=True, the async version will raise ValueError("text must be False"), who knows why
108
+ proc = await asyncio.create_subprocess_exec(*command, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, creationflags=subprocess.CREATE_NO_WINDOW)
109
+ stdout, _stderr = await proc.communicate()
110
+ return proc.returncode == 0 and b'TTL=' in stdout
111
+ else:
112
+ command = ['ping', '-c', str(packets), '-W', str(int(timeout)), host]
113
+ proc = await asyncio.create_subprocess_exec(*command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
114
+ _stdout, _stderr = await proc.communicate()
115
+ return proc.returncode == 0
116
+
117
+ ########
118
+
119
+ class Secrets:
120
+ DIR_NAME = '.secrets'
121
+
122
+ def __init__(self):
123
+ self.secrets_path = Path.home() / Secrets.DIR_NAME
124
+
125
+ def get(self, tokenfile: str):
126
+ with open(str(self.secrets_path / tokenfile), 'rt') as file:
127
+ return file.readline().rstrip()
128
+
129
+ def set(self, tokenfile: str, token: str):
130
+ self.secrets_path.mkdir(parents=True, exist_ok=True)
131
+ with open(str(self.secrets_path / tokenfile), 'wt') as file:
132
+ file.write(token)
133
+
134
+ def get_age(self, tokenfile: str):
135
+ return (datetime.now(timezone.utc) - datetime.fromtimestamp(os.stat(str(self.secrets_path / tokenfile)).st_mtime, timezone.utc)).total_seconds()
136
+
137
+ class Pingable:
138
+ @abstractmethod
139
+ async def ping(self, availability_hint: bool | None = None) -> bool:
140
+ pass
141
+
142
+ def get_class_name(self):
143
+ return self.__qualname__ if hasattr(self, '__qualname__') else self.__class__.__qualname__.rsplit('.', maxsplit=1)[0]
144
+
145
+ @staticmethod
146
+ def get_state_name(available: bool):
147
+ return 'up' if available else 'down'
148
+
149
+ async def wait_for(self, available: bool, timeout: float):
150
+ logger.debug("Waiting for %s to be %s (timeout is %ds)", LazyStr(self.get_class_name), LazyStr(Pingable.get_state_name, available), int(timeout))
151
+ async with asyncio.timeout(timeout):
152
+ while await self.ping(available) != available:
153
+ if not available:
154
+ await asyncio.sleep(1)
155
+
156
+ class Manager:
157
+ @abstractmethod
158
+ async def start(self):
159
+ pass
160
+
161
+ @abstractmethod
162
+ async def stop(self):
163
+ pass
164
+
165
+ class Manageable(Pingable):
166
+ def __init__(self, manager: Manager):
167
+ super().__init__()
168
+ self.manager = manager
169
+
170
+ async def _set_state(self, available: bool, repeat: float, timeout: float):
171
+ action_name = LazyStr(lambda: 'Starting' if available else 'Stopping')
172
+ class_name = LazyStr(self.get_class_name)
173
+ available_name = LazyStr(Pingable.get_state_name, available)
174
+ logger.info("%s %s...", action_name, class_name)
175
+ logger.debug("%s %s (repeat after %ds, timeout is %ds)", action_name, class_name, int(repeat), int(timeout))
176
+ try:
177
+ async with asyncio.timeout(timeout):
178
+ while True:
179
+ try:
180
+ if available:
181
+ await self.manager.start()
182
+ else:
183
+ await self.manager.stop()
184
+ await self.wait_for(available, min(repeat, timeout))
185
+ break
186
+ except TimeoutError:
187
+ pass
188
+ except TimeoutError as e:
189
+ e.add_note(f"Can't get {class_name} {available_name} for {timeout} seconds")
190
+ raise
191
+ logger.info(" %s is %s", class_name, available_name)
192
+ return available
193
+
194
+ async def test(self):
195
+ available = await self.ping()
196
+ logger.info("%s is %s", LazyStr(self.get_class_name), LazyStr(Pingable.get_state_name, available))
197
+ return available
198
+
199
+ async def start(self, repeat: float, timeout: float):
200
+ return await self._set_state(True, repeat, timeout)
201
+
202
+ async def stop(self, repeat: float, timeout: float):
203
+ return await self._set_state(False, repeat, timeout)
204
+
205
+ class Service(Manageable):
206
+ def __init__(self, host: str, port: int, manager: Manager):
207
+ super().__init__(manager)
208
+ self.host = host
209
+ self.port = port
210
+
211
+ async def ping(self, _availability_hint: bool | None = None):
212
+ async def _connect(connect_timeout: float):
213
+ logger.debug(" Connecting to %s on port %d (timeout is %ds)", self.host, self.port, connect_timeout)
214
+ async with asyncio.timeout(connect_timeout):
215
+ return await asyncio.open_connection(self.host, self.port)
216
+ logger.debug("Pinging %s (%s:%d)", LazyStr(self.get_class_name), self.host, self.port)
217
+ try:
218
+ _reader, writer = await _connect(2)
219
+ writer.close()
220
+ await writer.wait_closed()
221
+ return True
222
+ except (TimeoutError, socket.gaierror, ConnectionRefusedError):
223
+ return False
224
+ except Exception as e:
225
+ logger.debug(" Unexpected ping exception: %s", e.__str__())
226
+ raise
227
+
228
+ class Device(Manageable):
229
+ def __init__(self, host: str, manager: Manager):
230
+ super().__init__(manager)
231
+ self.host = host
232
+
233
+ async def ping(self, availability_hint: bool | None = None):
234
+ logger.debug("Pinging %s (%s)", LazyStr(self.get_class_name), self.host)
235
+ return await async_ping(self.host, timeout=2)
236
+
237
+ class StateSerializer:
238
+ BOOL = {False: Pingable.get_state_name(False), True: Pingable.get_state_name(True)}
239
+ INV_BOOL = {v: k for k, v in BOOL.items()}
240
+
241
+ @staticmethod
242
+ def dump_value(v):
243
+ return v if not isinstance(v, bool) else StateSerializer.BOOL[v]
244
+
245
+ @staticmethod
246
+ def load_value(v):
247
+ return v if v not in StateSerializer.INV_BOOL else StateSerializer.INV_BOOL[v]
248
+
249
+ @staticmethod
250
+ def dumps(d: dict):
251
+ return ','.join(f"{k}={StateSerializer.dump_value(v)}" for k, v in d.items())
252
+
253
+ @staticmethod
254
+ def loads(s: str):
255
+ try:
256
+ return dict({k: StateSerializer.load_value(v) for k, v in [s.split('=') for s in s.split(',')]})
257
+ except ValueError as e:
258
+ e.add_note("Missing '=' in state")
259
+ raise
260
+
261
+ class State:
262
+ WIFI = 'wifi'
263
+ PFTPD = 'pftpd'
264
+ NAMES = { WIFI: "Wi-Fi", PFTPD: "pFTPd"}
265
+
266
+ @abstractmethod
267
+ async def get(self, repeat: float, timeout: float) -> dict:
268
+ pass
269
+
270
+ ########
271
+
272
+ class Webhooks:
273
+ PING_PATH = 'ping'
274
+ VARIABLE_PATH = 'variable'
275
+
276
+ def __init__(self, host: str, port: int):
277
+ self.host = host
278
+ self.port = port
279
+ self.variables = dict[str, asyncio.Queue[str]]()
280
+
281
+ @staticmethod
282
+ def get_ping_path():
283
+ return f'/{Webhooks.PING_PATH}'
284
+
285
+ @staticmethod
286
+ def get_variable_path(variable: str):
287
+ return f'/{Webhooks.VARIABLE_PATH}/{variable}'
288
+
289
+ async def _start(self):
290
+ async def _ping(request: web.Request):
291
+ return web.Response(text='pong')
292
+ async def _receive_variable(request: web.Request):
293
+ queue = self.variables.get(request.match_info['name'])
294
+ if queue:
295
+ with suppress(asyncio.QueueFull):
296
+ queue.put_nowait(await request.text())
297
+ return web.Response(text='OK')
298
+ app = web.Application()
299
+ app.add_routes([
300
+ web.get(f'/{Webhooks.PING_PATH}', _ping),
301
+ web.post(f'/{Webhooks.VARIABLE_PATH}' + r'/{name}', _receive_variable)])
302
+ self.runner = web.AppRunner(app)
303
+ await self.runner.setup()
304
+ self.site = web.TCPSite(self.runner, host=self.host, port=self.port)
305
+ await self.site.start()
306
+
307
+ async def _stop(self):
308
+ await self.runner.cleanup()
309
+
310
+ def subscribe_variable(self, variable: str):
311
+ if variable not in self.variables:
312
+ self.variables[variable] = asyncio.Queue[str](maxsize=16)
313
+
314
+ def unsubscribe_variable(self, variable: str):
315
+ self.variables.pop(variable)
316
+
317
+ async def get_variable(self, variable: str, timeout: float):
318
+ queue = self.variables.get(variable)
319
+ if not queue:
320
+ raise ValueError(f"The {variable} is unknown")
321
+ try:
322
+ async with asyncio.timeout(timeout):
323
+ return await queue.get()
324
+ except TimeoutError as e:
325
+ e.add_note(f"Can't get value of {variable} for {timeout} seconds")
326
+ raise
327
+
328
+ def __enter__(self):
329
+ raise TypeError("Use async with instead")
330
+ def __exit__(self, exc_type, exc_value, exc_tb):
331
+ pass
332
+ async def __aenter__(self):
333
+ await self._start()
334
+ return self
335
+ async def __aexit__(self, exc_type, exc_value, exc_tb):
336
+ await self._stop()
337
+
338
+ class Automate:
339
+ def __init__(self, secrets: Secrets, session: aiohttp.ClientSession, account: str, device: str, tokenfile: str):
340
+ self.session = session
341
+ self.account = account
342
+ self.device = device
343
+ self.secret = secrets.get(tokenfile)
344
+
345
+ async def send_message(self, message: str):
346
+ data = {
347
+ "secret": self.secret,
348
+ "to": self.account,
349
+ "device": self.device,
350
+ "priority": "high",
351
+ "payload": f"prim-ctrl;{time.time()};" + message
352
+ }
353
+ logger.debug("Messaging Automate with: %s", message)
354
+ async with self.session.post(f'https://llamalab.com/automate/cloud/message', json=data) as response:
355
+ await response.text()
356
+
357
+ class AutomatepFTPdManager(Manager):
358
+ def __init__(self, automate: Automate):
359
+ self.automate = automate
360
+
361
+ async def start(self):
362
+ await self.automate.send_message('start-pftpd')
363
+
364
+ async def stop(self):
365
+ await self.automate.send_message('stop-pftpd')
366
+
367
+ class AutomateTailscaleManager(Manager):
368
+ def __init__(self, automate: Automate):
369
+ self.automate = automate
370
+
371
+ async def start(self):
372
+ await self.automate.send_message('start-tailscale')
373
+
374
+ async def stop(self):
375
+ await self.automate.send_message('stop-tailscale')
376
+
377
+ class AutomateState(State):
378
+ VARIABLE_STATE = 'state'
379
+
380
+ def __init__(self, session: aiohttp.ClientSession, webhooks: Webhooks, automate: Automate, external_url: str):
381
+ self.session = session
382
+ self.webhooks = webhooks
383
+ self.automate = automate
384
+ self.external_url = external_url
385
+
386
+ async def get(self, repeat: float, timeout: float):
387
+ logger.info("Getting state...")
388
+ # first test funnel + webhooks availability, to not wait for a reply if local tailscale or funnel is down
389
+ # though it will be routed locally, it will not go out to Tailscale's TCP forwarder servers, so the route is different from what Automate will see
390
+ logger.debug("Testing funnel with pinging local webhook (timeout is %ds)", int(timeout))
391
+ try:
392
+ async with self.session.get(f'{self.external_url}{Webhooks.get_ping_path()}', timeout=ClientTimeout(total=timeout)) as response:
393
+ if await response.text() != 'pong':
394
+ raise Exception()
395
+ except:
396
+ raise RuntimeError(f"Local Tailscale is down or local Funnel is not configured properly for {self.external_url}")
397
+ # get state
398
+ logger.debug("Getting state (repeat after %ds, timeout is %ds)", int(repeat), int(timeout))
399
+ self.webhooks.subscribe_variable(AutomateState.VARIABLE_STATE)
400
+ try:
401
+ async with asyncio.timeout(timeout):
402
+ while True:
403
+ try:
404
+ await self.automate.send_message(f'get-state;{self.external_url}{Webhooks.get_variable_path(AutomateState.VARIABLE_STATE)}')
405
+ state = await self.webhooks.get_variable(AutomateState.VARIABLE_STATE, min(repeat, timeout))
406
+ break
407
+ except TimeoutError:
408
+ pass
409
+ except TimeoutError as e:
410
+ e.add_note(f"Can't get value of {AutomateState.VARIABLE_STATE} for {timeout} seconds")
411
+ raise
412
+ finally:
413
+ self.webhooks.unsubscribe_variable(AutomateState.VARIABLE_STATE)
414
+ logger.info(" state is %s", state)
415
+ return StateSerializer.loads(state)
416
+
417
+ ########
418
+
419
+ class Cache:
420
+ PRIM_SYNC_APP_NAME = 'prim-sync'
421
+
422
+ def __init__(self):
423
+ self.cache_path = Path(user_cache_dir(Cache.PRIM_SYNC_APP_NAME, False))
424
+
425
+ def set(self, key: str, value: str):
426
+ self.cache_path.mkdir(parents=True, exist_ok=True)
427
+ cache_filename = str(self.cache_path / key)
428
+ with open(cache_filename, 'wt') as file:
429
+ file.write(value)
430
+
431
+ def get(self, key: str):
432
+ self.cache_path.mkdir(parents=True, exist_ok=True)
433
+ cache_filename = str(self.cache_path / key)
434
+ if os.path.exists(cache_filename) and os.path.isfile(cache_filename):
435
+ with open(cache_filename, 'rt') as file:
436
+ return file.readline().rstrip()
437
+ else:
438
+ return None
439
+
440
+ class ServiceCache:
441
+ def __init__(self, cache: Cache):
442
+ self.cache = cache
443
+
444
+ def set(self, service_name: str, host: str, port: int):
445
+ self.cache.set(service_name, '|'.join([host, str(port)]))
446
+
447
+ def get(self, service_name: str):
448
+ if cached_value := self.cache.get(service_name):
449
+ cached_value = cached_value.split('|')
450
+ return (cached_value[0], int(cached_value[1]))
451
+ else:
452
+ return (None, None)
453
+
454
+ class ServiceResolver:
455
+ def __init__(self, zeroconf: AsyncZeroconf, service_type: str):
456
+ self.zeroconf = zeroconf
457
+ self.service_type = service_type
458
+
459
+ async def get(self, service_name: str, timeout: float = 3):
460
+ service_info = await self.zeroconf.async_get_service_info(self.service_type, f"{service_name}.{self.service_type}", timeout=int(timeout*1000))
461
+ if not service_info or not service_info.port:
462
+ raise TimeoutError("Unable to resolve zeroconf (DNS-SD) service information")
463
+ return (service_info.parsed_addresses()[0], int(service_info.port))
464
+
465
+ class ServiceListener:
466
+ @abstractmethod
467
+ def set_service(self, service_name: str, service_info: ServiceInfo):
468
+ pass
469
+
470
+ @abstractmethod
471
+ def del_service(self, service_name: str):
472
+ pass
473
+
474
+ class ServiceBrowser:
475
+ def __init__(self, zeroconf: AsyncZeroconf, service_type: str):
476
+ self.zeroconf = zeroconf
477
+ self.service_type = service_type
478
+
479
+ class ServiceListenerWrapper(ZeroconfServiceListener):
480
+ def __init__(self, listener: ServiceListener):
481
+ self.listener = listener
482
+
483
+ @staticmethod
484
+ def get_service_name(name: str):
485
+ return name.split('.', maxsplit=1)[0]
486
+
487
+ def set_service(self, zc: Zeroconf, type_: str, name: str):
488
+ service_info = ServiceInfo(type_, name)
489
+ if service_info.load_from_cache(zc):
490
+ self.listener.set_service(ServiceBrowser.ServiceListenerWrapper.get_service_name(name), service_info)
491
+
492
+ def del_service(self, zc: Zeroconf, type_: str, name: str):
493
+ self.listener.del_service(ServiceBrowser.ServiceListenerWrapper.get_service_name(name))
494
+
495
+ def add_service(self, zc: Zeroconf, type_: str, name: str):
496
+ self.set_service(zc, type_, name)
497
+
498
+ def remove_service(self, zc: Zeroconf, type_: str, name: str):
499
+ self.del_service(zc, type_, name)
500
+
501
+ def update_service(self, zc: Zeroconf, type_: str, name: str):
502
+ self.set_service(zc, type_, name)
503
+
504
+ async def add_service_listener(self, listener: ServiceListener):
505
+ await self.zeroconf.async_add_service_listener(self.service_type, ServiceBrowser.ServiceListenerWrapper(listener))
506
+
507
+ SFTP_SERVICE_TYPE = '_sftp-ssh._tcp.local.'
508
+
509
+ class SftpServiceResolver(ServiceResolver):
510
+ def __init__(self, zeroconf: AsyncZeroconf):
511
+ super().__init__(zeroconf, SFTP_SERVICE_TYPE)
512
+
513
+ class SftpServiceBrowser(ServiceBrowser):
514
+ def __init__(self, zeroconf: AsyncZeroconf):
515
+ super().__init__(zeroconf, SFTP_SERVICE_TYPE)
516
+
517
+ class ZeroconfService(Manageable):
518
+ def __init__(self, service_name: str, service_cache: ServiceCache, service_resolver: ServiceResolver, manager: Manager):
519
+ super().__init__(manager)
520
+ self.service_name = service_name
521
+ self.host = None
522
+ self.port = None
523
+ self.service_cache = service_cache
524
+ self.service_resolver = service_resolver
525
+
526
+ async def ping(self, availability_hint: bool | None = None):
527
+ async def _connect(connect_timeout: float, resolve_timeout: float):
528
+ async def asyncio_open_connection(host: str, port: int, timeout: float):
529
+ logger.debug(" Connecting to %s on port %d (timeout is %ds)", host, port, timeout)
530
+ async with asyncio.timeout(timeout):
531
+ return await asyncio.open_connection(host, port)
532
+ async def service_resolver_get(service_name: str, timeout: float):
533
+ logger.debug(" Resolving %s (timeout is %ds)", service_name, timeout)
534
+ return await self.service_resolver.get(service_name, timeout)
535
+ if self.host and self.port:
536
+ return await asyncio_open_connection(self.host, self.port, connect_timeout)
537
+ host, port = self.service_cache.get(self.service_name)
538
+ if host and port:
539
+ try:
540
+ reader_writer = await asyncio_open_connection(host, port, connect_timeout)
541
+ self.host = host
542
+ self.port = port
543
+ return reader_writer
544
+ except (TimeoutError, socket.gaierror, ConnectionRefusedError):
545
+ if availability_hint is None or availability_hint:
546
+ pass
547
+ else:
548
+ raise
549
+ host, port = await service_resolver_get(self.service_name, resolve_timeout)
550
+ reader_writer = await asyncio_open_connection(host, port, connect_timeout)
551
+ self.service_cache.set(self.service_name, host, port)
552
+ self.host = host
553
+ self.port = port
554
+ return reader_writer
555
+ logger.debug("Pinging %s (%s - %s:%s)", LazyStr(self.get_class_name), self.service_name, str(self.host), str(self.port))
556
+ try:
557
+ _reader, writer = await _connect(2, 6)
558
+ writer.close()
559
+ await writer.wait_closed()
560
+ return True
561
+ except (TimeoutError, socket.gaierror, ConnectionRefusedError):
562
+ return False
563
+ except Exception as e:
564
+ logger.debug(" Unexpected ping exception: %s", e.__str__())
565
+ raise
566
+
567
+ ########
568
+
569
+ class Phone:
570
+ def __init__(self, local_sftp: ZeroconfService, vpn: Device | None, remote_sftp: Service | None, state: State | None):
571
+ self.local_sftp = local_sftp
572
+ self.vpn = vpn
573
+ self.remote_sftp = remote_sftp
574
+ self.state = state
575
+
576
+ class pFTPdServiceListener(ServiceListener):
577
+ def __init__(self, server_name: str, cache: ServiceCache):
578
+ self.server_name = server_name
579
+ self.cache = cache
580
+
581
+ def set_service(self, service_name: str, service_info: ServiceInfo):
582
+ if service_name == self.server_name and service_info.port:
583
+ host = service_info.parsed_addresses()[0]
584
+ port = int(service_info.port)
585
+ self.cache.set(service_name, host, port)
586
+ logger.debug(" (ServiceListener) Resolved %s to %s:%d", service_name, host, port)
587
+
588
+ def del_service(self, service_name: str):
589
+ pass
590
+
591
+ class pFTPd(Service):
592
+ pass
593
+
594
+ class pFTPdZeroconf(ZeroconfService):
595
+ def __init__(self, *args, **kwargs):
596
+ super().__init__(*args, **kwargs)
597
+ self.__qualname__ = pFTPd.__qualname__
598
+
599
+ class Tailscale(Device):
600
+ def __init__(self, tailnet: str, machine_name: str, manager: Manager):
601
+ super().__init__(f'{machine_name}.{tailnet}', manager)
602
+ self.tailnet = tailnet
603
+
604
+ class Funnel:
605
+ LOCAL_HOST = '127.0.0.1'
606
+
607
+ def __init__(self, tailscale: Tailscale, machine_name: str, local_port: int, local_path: str, external_port: int):
608
+ self.local_port = local_port
609
+ self.external_url = f'https://{machine_name}.{tailscale.tailnet}:{external_port}{local_path}'
610
+
611
+ ########
612
+
613
+ class WideHelpFormatter(argparse.RawTextHelpFormatter):
614
+ def __init__(self, prog: str, indent_increment: int = 2, max_help_position: int = 35, width: int | None = None) -> None:
615
+ super().__init__(prog, indent_increment, max_help_position, width)
616
+
617
+ async def gather_with_taskgroup(*coros):
618
+ try:
619
+ async with asyncio.TaskGroup() as tg:
620
+ tasks = [tg.create_task(coro) for coro in coros]
621
+ return tuple([task.result() for task in tasks])
622
+ except ExceptionGroup as eg:
623
+ raise eg.exceptions[0] from (None if len(eg.exceptions) == 1 else eg)
624
+
625
+ class Control:
626
+ WIFI = 'wifi'
627
+ VPN = 'vpn'
628
+ SFTP = 'sftp'
629
+ CONNECTED = 'connected'
630
+ LOCAL = 'local'
631
+ REMOTE = 'remote'
632
+
633
+ @staticmethod
634
+ def setup_parser_arguments(parser):
635
+ parser.add_argument('server_name', metavar='server-name', help="the Servername configuration option from Primitive FTPd app")
636
+ parser.add_argument('-i', '--intent', choices=["test", "start", "stop"], help="what to do with the apps, default: test", default="test")
637
+
638
+ @staticmethod
639
+ def setup_parser_options(parser):
640
+ pass
641
+
642
+ @staticmethod
643
+ def setup_parser_groups(parser):
644
+ logging_group = parser.add_argument_group('logging')
645
+ logging_group.add_argument('-t', '--timestamp', help="prefix each message with an UTC timestamp", default=False, action='store_true')
646
+ logging_group.add_argument('-s', '--silent', help="only errors printed", default=False, action='store_true')
647
+ logging_group.add_argument('--debug', help="use debug level logging and add stack trace for exceptions, disables the --silent and enables the --timestamp options", default=False, action='store_true')
648
+
649
+ @staticmethod
650
+ def setup_parser_vpngroup(vpn_group):
651
+ vpn_group.add_argument('-ac', '--accept-cellular', help="in case of start, if WiFi is not connected, don't return error, but start VPN up", default=False, action='store_true')
652
+ vpn_group.add_argument('-b', '--backup-state', help="in case of start, backup current state to stdout as single string (in case of an error, it will try to restore the original state but will not write it to stdout)", default=False, action='store_true')
653
+ vpn_group.add_argument('-r', '--restore-state', metavar="STATE", help="in case of stop, restore previous state from STATE (use -b to get a valid STATE string)", action='store')
654
+
655
+ @abstractmethod
656
+ async def run(self, args):
657
+ pass
658
+
659
+ def prepare(self, args):
660
+ if args.debug:
661
+ logger.setLevel(logging.DEBUG)
662
+ logger.prepare(args.timestamp or args.debug, args.silent)
663
+
664
+ if args.accept_cellular and args.intent != 'start':
665
+ raise ValueError("The --accept-cellular options can be enabled only for the start intent")
666
+ if args.backup_state and args.intent != 'start':
667
+ raise ValueError("The --backup-state option can be enabled only for the start intent")
668
+ if args.restore_state and args.intent != 'stop':
669
+ raise ValueError("The --restore-state option can be enabled only for the stop intent")
670
+
671
+ async def execute(self, args, phone: Phone):
672
+ async def _stop(restore_state: dict | None):
673
+ if phone.vpn and phone.remote_sftp and await phone.vpn.test():
674
+ if (restore_state is None or not restore_state.get(Control.SFTP, False)) and await phone.remote_sftp.test():
675
+ await phone.remote_sftp.stop(10, 30)
676
+ if restore_state is None or not restore_state.get(Control.VPN, False):
677
+ await phone.vpn.stop(10, 60)
678
+ else:
679
+ if (restore_state is None or not restore_state.get(Control.SFTP, False)):
680
+ await phone.local_sftp.stop(10, 30)
681
+ match args.intent:
682
+ case 'test':
683
+ if phone.vpn and phone.remote_sftp and phone.state:
684
+ phone_state, _vpn_state = await gather_with_taskgroup(phone.state.get(10, 30), phone.vpn.test())
685
+ for k, v in phone_state.items():
686
+ logger.info("%s is %s", LazyStr(lambda: State.NAMES[k]), LazyStr(StateSerializer.dump_value, v))
687
+ elif phone.vpn and phone.remote_sftp and await phone.vpn.test():
688
+ await phone.remote_sftp.test()
689
+ else:
690
+ await phone.local_sftp.test()
691
+ case 'start':
692
+ if phone.vpn and phone.remote_sftp:
693
+ state = dict()
694
+ local_accessible = False
695
+ remote_accessible = False
696
+ # gather state info
697
+ if phone.state:
698
+ phone_state, vpn_state = await gather_with_taskgroup(phone.state.get(10, 30), phone.vpn.test())
699
+ state[Control.WIFI] = phone_state[State.WIFI]
700
+ state[Control.VPN] = vpn_state
701
+ state[Control.SFTP] = phone_state[State.PFTPD]
702
+ if not state[Control.WIFI] and not args.accept_cellular:
703
+ raise RuntimeError(f"Phone is not on Wi-Fi network")
704
+ else:
705
+ state[Control.VPN] = await phone.vpn.test()
706
+ if state[Control.VPN]:
707
+ state[Control.SFTP] = remote_accessible = await phone.remote_sftp.test()
708
+ # start changing state
709
+ try:
710
+ if phone.state:
711
+ if not state[Control.SFTP]:
712
+ if not state[Control.VPN]:
713
+ if state[Control.WIFI]:
714
+ try:
715
+ local_accessible = await phone.local_sftp.start(10, 30)
716
+ except TimeoutError:
717
+ await phone.vpn.start(10, 60)
718
+ remote_accessible = await phone.remote_sftp.test()
719
+ else:
720
+ await phone.vpn.start(10, 60)
721
+ remote_accessible = await phone.remote_sftp.start(10, 30)
722
+ else:
723
+ remote_accessible = await phone.remote_sftp.start(10, 30)
724
+ if state[Control.WIFI]:
725
+ local_accessible = await phone.local_sftp.test()
726
+ else:
727
+ if not state[Control.VPN]:
728
+ if not state[Control.WIFI] or not (local_accessible := await phone.local_sftp.test()):
729
+ await phone.vpn.start(10, 60)
730
+ remote_accessible = await phone.remote_sftp.test()
731
+ else:
732
+ local_accessible, remote_accessible = await gather_with_taskgroup(phone.local_sftp.test(), phone.remote_sftp.test())
733
+ else:
734
+ if not state[Control.VPN]:
735
+ if not (local_accessible := await phone.local_sftp.test()):
736
+ try:
737
+ local_accessible = await phone.local_sftp.start(10, 30)
738
+ except TimeoutError:
739
+ await phone.vpn.start(10, 60)
740
+ remote_accessible = await phone.remote_sftp.test()
741
+ else:
742
+ if not state[Control.SFTP]:
743
+ remote_accessible = await phone.remote_sftp.start(10, 30)
744
+ local_accessible = await phone.local_sftp.test()
745
+ if not local_accessible and not remote_accessible:
746
+ raise RuntimeError(f"Even when {phone.vpn.get_class_name()} and {phone.remote_sftp.get_class_name()} is started, {phone.remote_sftp.get_class_name()} is still not accessible")
747
+ except:
748
+ await _stop(state)
749
+ raise
750
+ if not args.backup_state:
751
+ state = dict()
752
+ state[Control.CONNECTED] = Control.LOCAL if local_accessible else Control.REMOTE
753
+ print(StateSerializer.dumps(state))
754
+ else:
755
+ if not await phone.local_sftp.test():
756
+ try:
757
+ await phone.local_sftp.start(10, 30)
758
+ except:
759
+ await _stop(None)
760
+ raise
761
+ case 'stop':
762
+ await _stop(StateSerializer.loads(args.restore_state) if args.restore_state else None)
763
+
764
+ class AutomateControl(Control):
765
+ @staticmethod
766
+ def setup_subparser(subparsers):
767
+ parser = subparsers.add_parser('Automate', aliases=['a'],
768
+ description="Remote control of your phone's Primitive FTPd and optionally Tailscale app statuses via the Automate app, for more details see https://github.com/lmagyar/prim-ctrl\n\n"
769
+ "Note: you must install Automate app on your phone, download prim-ctrl flow into it, and configure your Google account in the flow to receive messages (see the project's GitHub page for more details)\n"
770
+ "Note: optionally if your phone is not accessible on local network but your laptop is part of the Tailscale VPN then Tailscale VPN can be started on the phone\n"
771
+ "Note: optionally if your laptop is accessible through Tailscale Funnel then VPN on cellular can be refused and app statuses on the phone can be backed up and restored\n\n"
772
+ "Output: even when -b option is not used, the script will output 'connected=(local|remote)', what you can use to determine whether to use -a option for the prim-sync script",
773
+ formatter_class=WideHelpFormatter)
774
+
775
+ parser.add_argument('automate_account', metavar='automate-account', help="your Google account email you set up in the Automate flow's first Set variable block's Value field")
776
+ parser.add_argument('automate_device', metavar='automate-device', help="the device name you can see at the Automate flow's Cloud receive block's This device field")
777
+ parser.add_argument('automate_tokenfile', metavar='automate-tokenfile', help="filename containing Automates's Secret that located under your .secrets folder\n"
778
+ "(generated on https://llamalab.com/automate/cloud, use the same Google account you set up on the Cloud receive block)")
779
+
780
+ Control.setup_parser_arguments(parser)
781
+
782
+ Control.setup_parser_options(parser)
783
+
784
+ Control.setup_parser_groups(parser)
785
+
786
+ vpn_group = parser.add_argument_group('VPN',
787
+ description="To use --tailscale option you must install Tailscale and configure Tailscale VPN on your phone and your laptop\n"
788
+ "To use --funnel option you must configure Tailscale Funnel on your laptop for prim-ctrl's local webhook to accept responses from the Automate app\n"
789
+ " (eg.: tailscale funnel --bg --https=8443 --set-path=/prim-ctrl \"http://127.0.0.1:12345\")\n"
790
+ "Note: --funnel, --backup-state and --restore-state options can be used only when --tailscale is used\n"
791
+ "Note: --backup-state is accurate only, when --funnel is used\n"
792
+ "Note: --accept-cellular option can be used only when --funnel is used")
793
+ vpn_group.add_argument('--tailscale', nargs=3, metavar=('tailnet', 'remote-machine-name', 'sftp-port'), help=
794
+ "tailnet: your Tailscale tailnet name (eg. tailxxxx.ts.net)\n"
795
+ "remote-machine-name: your phone's name within your tailnet (just the name, without the tailnet)\n"
796
+ "sftp-port: Primitive FTPd's sftp port")
797
+ vpn_group.add_argument('--funnel', nargs=4, metavar=('local-machine-name', 'local-port', 'local-path', 'external-port'), help=
798
+ "local-machine-name: your laptop's name within your tailnet (just the name, without the tailnet)\n"
799
+ "local-port: 12345 - if you used the example tailscale funnel command above (the local webhook will be started on this port)\n"
800
+ "local-path: /prim-ctrl - if you used the example tailscale funnel command above\n"
801
+ "external-port: 8443 - if you used the example tailscale funnel command above")
802
+ Control.setup_parser_vpngroup(vpn_group)
803
+
804
+ parser.set_defaults(ctor=AutomateControl)
805
+
806
+ def prepare(self, args):
807
+ super().prepare(args)
808
+ if args.funnel and not args.tailscale:
809
+ raise ValueError("--funnel option can be used only when --tailscale is used")
810
+ if args.backup_state and not args.tailscale:
811
+ raise ValueError("--backup-state option can be used only when --tailscale is used")
812
+ if args.restore_state and not args.tailscale:
813
+ raise ValueError("--restore-state option can be used only when --tailscale is used")
814
+ if args.accept_cellular and not args.funnel:
815
+ raise ValueError("--accept-cellular option can be used only when --funnel is used")
816
+
817
+ async def run(self, args):
818
+ self.prepare(args)
819
+
820
+ async with (
821
+ aiohttp.ClientSession(
822
+ # Automate messaging server prefers closing connections
823
+ connector=aiohttp.TCPConnector(force_close=True)) as session,
824
+ AsyncZeroconf() as zeroconf
825
+ ):
826
+ service_cache = ServiceCache(Cache())
827
+ service_resolver = SftpServiceResolver(zeroconf)
828
+ service_listener = pFTPdServiceListener(args.server_name, service_cache)
829
+ service_browser = SftpServiceBrowser(zeroconf)
830
+ await service_browser.add_service_listener(service_listener)
831
+
832
+ automate = Automate(Secrets(), session, args.automate_account, args.automate_device, args.automate_tokenfile)
833
+ local_pftpd = pFTPdZeroconf(args.server_name, service_cache, service_resolver, AutomatepFTPdManager(automate))
834
+ tailscale = Tailscale(args.tailscale[0], args.tailscale[1], AutomateTailscaleManager(automate)) if args.tailscale else None
835
+ remote_pftpd = pFTPd(tailscale.host, int(args.tailscale[2]), local_pftpd.manager) if tailscale else None
836
+ funnel = Funnel(tailscale, args.funnel[0], int(args.funnel[1]), args.funnel[2], int(args.funnel[3])) if tailscale and args.funnel else None
837
+
838
+ async with Webhooks(Funnel.LOCAL_HOST, funnel.local_port) if funnel else nullcontext() as webhooks:
839
+ state = AutomateState(session, webhooks, automate, funnel.external_url) if funnel and webhooks else None
840
+ phone = Phone(local_pftpd, tailscale, remote_pftpd, state)
841
+ await self.execute(args, phone)
842
+
843
+ async def main():
844
+ args = None
845
+ try:
846
+ parser = argparse.ArgumentParser(
847
+ description="Remote control of your phone's Primitive FTPd and optionally Tailscale app statuses via the Automate app, for more details see https://github.com/lmagyar/prim-ctrl",
848
+ formatter_class=WideHelpFormatter)
849
+ subparsers = parser.add_subparsers(required=True,
850
+ title="Phone app to use for control")
851
+
852
+ AutomateControl.setup_subparser(subparsers)
853
+
854
+ args = parser.parse_args()
855
+ await args.ctor().run(args)
856
+
857
+ except Exception as e:
858
+ if not args or args.debug:
859
+ logger.exception(e)
860
+ else:
861
+ if hasattr(e, '__notes__'):
862
+ logger.error("%s: %s", LazyStr(repr, e), LazyStr(", ".join, e.__notes__))
863
+ else:
864
+ logger.error(LazyStr(repr, e))
865
+
866
+ return logger.exitcode
867
+
868
+ def run():
869
+ with suppress(KeyboardInterrupt):
870
+ exit(asyncio.run(main()))
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,215 @@
1
+ Metadata-Version: 2.1
2
+ Name: prim-ctrl
3
+ Version: 0.3.0
4
+ Summary: Primitive Ctrl - Remote control of your phone's Primitive FTPd Android SFTP server and optionally Tailscale VPN.
5
+ Home-page: https://github.com/lmagyar/prim-ctrl
6
+ License: Apache-2.0
7
+ Author: Laszlo Magyar
8
+ Author-email: lmagyar1973@gmail.com
9
+ Requires-Python: >=3.12,<4.0
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Requires-Dist: aiohttp (==3.10.5)
17
+ Requires-Dist: platformdirs (==4.3.2)
18
+ Requires-Dist: zeroconf (==0.134.0)
19
+ Project-URL: Change Log, https://github.com/lmagyar/prim-ctrl/blob/main/CHANGELOG.md
20
+ Project-URL: Repository, https://github.com/lmagyar/prim-ctrl
21
+ Description-Content-Type: text/markdown
22
+
23
+
24
+ > [!WARNING]
25
+ > ***This repository works with both the original and the forked version of the Primitive FTPd Android SFTP server!***
26
+ > - ***install my fork from https://github.com/lmagyar/prim-ftpd - and use the prim-ctrl-lmagyar Automate flow below***
27
+ > - ***install the original version from https://github.com/wolpi/prim-ftpd - and use the prim-ctrl Automate flow below***
28
+
29
+ # Primitive Ctrl
30
+
31
+ Remote control of your phone's [Primitive FTPd Android SFTP server](https://github.com/wolpi/prim-ftpd) and optionally [Tailscale VPN](https://tailscale.com/).
32
+
33
+ Though Primitive FTPd consumes minimal power when it is not used, remote start/stop can be usefull for zeroconf (DNS-SD). Android doesn't reply DSN-SD queries when the screen is off, but Android announces the new service when the Primitive FTPd server starts up. So SFTP clients can/should capture and cache the announcement at Primitive FTPd server startup to connect to a phone through zeroconf even when the screen is off.
34
+
35
+ But in case of Tailscale, it is a real battery and mobile network data drain when not used, remote start/stop is de facto very useful.
36
+
37
+ With the help of this script you can sync your phone with eg. your home NAS server whereever your phone is on a WiFi network - or even on cellular. Your phone doesn't have to be on the same LAN to make zeroconf working when you have alternative access through VPN.
38
+
39
+ See my other project, https://github.com/lmagyar/prim-sync, for bidirectional and unidirectional sync over SFTP (multiplatform Python script optimized for the Primitive FTPd SFTP server).
40
+
41
+ See my other project, https://github.com/lmagyar/prim-batch, for batch execution of prim-ctrl and prim-sync commands.
42
+
43
+ **Note:** These are my first ever Python projects, any comments on how to make them better are appreciated.
44
+
45
+ ## Features
46
+
47
+ - Remote start/stop of Primitive FTPd Android SFTP server and optionally Tailscale VPN
48
+ - Using VPN on cellular can be refused
49
+ - Backup states before starting them, restore when stopping (ie. they won't be stopped if they were running before the script were asked to start them)
50
+
51
+ ## Installation
52
+
53
+ You need to install:
54
+ - Automate on your phone - see: https://llamalab.com/automate/
55
+
56
+ - Python 3.12+, pip and venv on your laptop - see: https://www.python.org/downloads/ or
57
+ <details><summary>Unix</summary>
58
+
59
+ ```
60
+ sudo apt update
61
+ sudo apt upgrade
62
+ sudo apt install python3 python3-pip python3-venv
63
+ ```
64
+ </details>
65
+ <details><summary>Windows</summary>
66
+
67
+ - Install from Microsoft Store the latest [Python 3](https://apps.microsoft.com/search?query=python+3&department=Apps) (search), [Python 3.12](https://www.microsoft.com/store/productId/9NCVDN91XZQP) (App)
68
+ - Install from Chocolatey: `choco install python3 -y`
69
+ </details>
70
+
71
+ - pipx - see: https://pipx.pypa.io/stable/installation/#installing-pipx or
72
+ <details><summary>Unix</summary>
73
+
74
+ ```
75
+ sudo apt install pipx
76
+ pipx ensurepath
77
+ ```
78
+ </details>
79
+ <details><summary>Windows</summary>
80
+
81
+ ```
82
+ py -m pip install --user pipx
83
+ py -m pipx ensurepath
84
+ ```
85
+ </details>
86
+
87
+ - This repo
88
+ ```
89
+ pipx install prim-ctrl
90
+ ```
91
+
92
+ Optionally you can install:
93
+ - Tailscale on your phone and laptop - see: https://tailscale.com/download
94
+
95
+ Optionally, if you want to edit or even contribute to the source, you also need to install:
96
+ - poetry - see: https://python-poetry.org/
97
+ ```
98
+ pipx install poetry
99
+ ```
100
+
101
+ ## Configuration
102
+
103
+ ### Automate
104
+
105
+ - Depending on whether you installed the [forked](https://github.com/lmagyar/prim-ftpd) or the [original](https://github.com/wolpi/prim-ftpd) version of Primitive FTPd, download the appropriate Automate flow to your phone:
106
+ - Flow for the **forked** Primitive FTPd: https://raw.githubusercontent.com/lmagyar/prim-ctrl/main/res/prim-ctrl-lmagyar.flo (see [image](https://raw.githubusercontent.com/lmagyar/prim-ctrl/main/res/prim-ctrl-lmagyar.png) of the flow)
107
+ - Flow for the **original** Primitive FTPd: https://raw.githubusercontent.com/lmagyar/prim-ctrl/main/res/prim-ctrl.flo (see [image](https://raw.githubusercontent.com/lmagyar/prim-ctrl/main/res/prim-ctrl.png) of the flow)
108
+ - Import it with the ... menu / Import command
109
+ - Enable all privileges
110
+ - Click on the flow, edit the 2. block ("Set variable google_account to...), enter your Google account and press Save
111
+ - Start the flow
112
+ - Settings
113
+ - Run on system startup: enable
114
+
115
+ ### Primitive FTPd
116
+
117
+ - Configuration tab
118
+ - UI
119
+ - Show notification to start/stop server(s): disable - this is necessary to determine whether Primitive FTPd is running on the phone or not, because the Automate flow determines whether the server is started with checking the existence of it's notification, and if the notification is always shown, that would make it false positive; please use another way, eg. a Quick Settings Tile to start/stop the server manually
120
+
121
+ ### Tailscale VPN (optional)
122
+
123
+ Follow Tailscale's instructions on how to configure Tailscale VPN on your phone and laptop.
124
+
125
+ For more details see: https://login.tailscale.com/start
126
+
127
+ ### Tailscale Funnel (optional)
128
+
129
+ You can configure Tailscale Funnel on your laptop (for incoming connections to this script's webhooks from the internet). Until the Tailscale VPN is up on the phone, the phone can't send information directly to your laptop, to this script's webhooks. But Tailscale Funnel makes it possible to access a Tailscale VPN connected device's services from the wider internet.
130
+
131
+ For more details see: https://tailscale.com/kb/1223/funnel
132
+
133
+ An example Tailscale Funnel config command for this script is: `tailscale funnel --bg --https=8443 --set-path=/prim-ctrl "http://127.0.0.1:12345"`
134
+
135
+ ## Usage
136
+
137
+ If you decide to use this script, I suggest to configure Tailscale VPN and Tailscale Funnel, this will provide the most functionality.
138
+
139
+ Without any VPN, the script will start and stop the Primitive FTPd app on your phone making a best effort and assumes the phone is on the same LAN (ie. zeroconf works). This is fine if you start the script manually and your phone is with you.
140
+
141
+ But if the script runs scheduled, we can't be sure whether the phone is on WiFi, is on the same WiFi as your laptop: it is better to configure the VPN and Funnel. And I suggest to use the backup and restore functionality also, in this case a scheduled script will not interfere with a manually started Primitive FTPd or VPN, you won't notice the synchronization is running while you are doing something else on the phone with the Primitive FTPd or the VPN.
142
+
143
+ Notes:
144
+ - Even when -b option is **not** used, the script will output 'connected=(local|remote)', what you can use to determine whether to use -a option for the prim-sync script
145
+
146
+ ### Some example
147
+
148
+ <details><summary>Unix</summary>
149
+
150
+ ```
151
+ prim-ctrl Automate youraccount@gmail.com "SOME MANUFACTURER XXX" automate your-phone-pftpd --tailscale tailxxxx.ts.net your-phone 2222 --funnel your-laptop 12345 /prim-ctrl 8443 -t -i start -b
152
+ prim-ctrl Automate youraccount@gmail.com "SOME MANUFACTURER XXX" automate your-phone-pftpd --tailscale tailxxxx.ts.net your-phone 2222 --funnel your-laptop 12345 /prim-ctrl 8443 -t -i stop -r ${PREV_STATE}
153
+ ```
154
+ </details>
155
+ <details><summary>Windows</summary>
156
+
157
+ ```
158
+ prim-ctrl Automate youraccount@gmail.com "SOME MANUFACTURER XXXX" automate your-phone-pftpd --tailscale tailxxxx.ts.net your-phone 2222 --funnel your-laptop 12345 /prim-ctrl 8443 -t -i start -b
159
+ prim-ctrl Automate youraccount@gmail.com "SOME MANUFACTURER XXXX" automate your-phone-pftpd --tailscale tailxxxx.ts.net your-phone 2222 --funnel your-laptop 12345 /prim-ctrl 8443 -t -i stop -r !PREV_STATE!
160
+ ```
161
+ </details>
162
+
163
+ ### Options
164
+
165
+ ```
166
+ usage: prim-ctrl Automate [-h] [-i {test,start,stop}] [-t] [-s] [--debug] [--tailscale tailnet remote-machine-name sftp-port] [--funnel local-machine-name local-port local-path external-port] [-ac] [-b] [-r STATE]
167
+ automate-account automate-device automate-tokenfile server-name
168
+
169
+ Remote control of your phone's Primitive FTPd and optionally Tailscale app statuses via the Automate app, for more details see https://github.com/lmagyar/prim-ctrl
170
+
171
+ Note: you must install Automate app on your phone, download prim-ctrl flow into it, and configure your Google account in the flow to receive messages (see the project's GitHub page for more details)
172
+ Note: optionally if your phone is not accessible on local network but your laptop is part of the Tailscale VPN then Tailscale VPN can be started on the phone
173
+ Note: optionally if your laptop is accessible through Tailscale Funnel then VPN on cellular can be refused and app statuses on the phone can be backed up and restored
174
+
175
+ Output: even when -b option is not used, the script will output 'connected=(local|remote)', what you can use to determine whether to use -a option for the prim-sync script
176
+
177
+ positional arguments:
178
+ automate-account your Google account email you set up in the Automate flow's first Set variable block's Value field
179
+ automate-device the device name you can see at the Automate flow's Cloud receive block's This device field
180
+ automate-tokenfile filename containing Automates's Secret that located under your .secrets folder
181
+ (generated on https://llamalab.com/automate/cloud, use the same Google account you set up on the Cloud receive block)
182
+ server-name the Servername configuration option from Primitive FTPd app
183
+
184
+ options:
185
+ -h, --help show this help message and exit
186
+ -i {test,start,stop}, --intent {test,start,stop}
187
+ what to do with the apps, default: test
188
+
189
+ logging:
190
+ -t, --timestamp prefix each message with an UTC timestamp
191
+ -s, --silent only errors printed
192
+ --debug use debug level logging and add stack trace for exceptions, disables the --silent and enables the --timestamp options
193
+
194
+ VPN:
195
+ To use --tailscale option you must install Tailscale and configure Tailscale VPN on your phone and your laptop
196
+ To use --funnel option you must configure Tailscale Funnel on your laptop for prim-ctrl's local webhook to accept responses from the Automate app
197
+ (eg.: tailscale funnel --bg --https=8443 --set-path=/prim-ctrl "http://127.0.0.1:12345")
198
+ Note: --funnel, --backup-state and --restore-state options can be used only when --tailscale is used
199
+ Note: --backup-state is accurate only, when --funnel is used
200
+ Note: --accept-cellular option can be used only when --funnel is used
201
+
202
+ --tailscale tailnet remote-machine-name sftp-port
203
+ tailnet: your Tailscale tailnet name (eg. tailxxxx.ts.net)
204
+ remote-machine-name: your phone's name within your tailnet (just the name, without the tailnet)
205
+ sftp-port: Primitive FTPd's sftp port
206
+ --funnel local-machine-name local-port local-path external-port
207
+ local-machine-name: your laptop's name within your tailnet (just the name, without the tailnet)
208
+ local-port: 12345 - if you used the example tailscale funnel command above (the local webhook will be started on this port)
209
+ local-path: /prim-ctrl - if you used the example tailscale funnel command above
210
+ external-port: 8443 - if you used the example tailscale funnel command above
211
+ -ac, --accept-cellular in case of start, if WiFi is not connected, don't return error, but start VPN up
212
+ -b, --backup-state in case of start, backup current state to stdout as single string (in case of an error, it will try to restore the original state but will not write it to stdout)
213
+ -r STATE, --restore-state STATE in case of stop, restore previous state from STATE (use -b to get a valid STATE string)
214
+ ```
215
+
@@ -0,0 +1,7 @@
1
+ prim_ctrl/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ prim_ctrl/__main__.py,sha256=SXH7tNGYvOAVSl8blNjC56ncvlvK0QDNbyJqUbZYorA,41180
3
+ prim_ctrl-0.3.0.dist-info/entry_points.txt,sha256=00c0ccpamWF4op6U9_KJYBSUfSmUgcFOAj3IWI2J1Gk,52
4
+ prim_ctrl-0.3.0.dist-info/LICENSE,sha256=HrhfyXIkWY2tGFK11kg7vPCqhgh5DcxleloqdhrpyMY,11558
5
+ prim_ctrl-0.3.0.dist-info/METADATA,sha256=hvwDmHA9A87o1f-bihl7OPX5291yYVTI-B4VHWlmJpc,12816
6
+ prim_ctrl-0.3.0.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
7
+ prim_ctrl-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: poetry-core 1.9.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ prim-ctrl=prim_ctrl.__main__:run
3
+