From 156e11a8820a16aa046f1fd725563e74a8dc993b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20B=C3=BChler?= Date: Fri, 8 Apr 2022 16:35:53 +0200 Subject: [PATCH] add time helpers to MacPublicState for views --- src/capport/cptypes.py | 13 +++++++++++++ src/capport/utils/zoneinfo.py | 19 +++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 src/capport/utils/zoneinfo.py diff --git a/src/capport/cptypes.py b/src/capport/cptypes.py index 39b86d8..cbab847 100644 --- a/src/capport/cptypes.py +++ b/src/capport/cptypes.py @@ -1,5 +1,6 @@ from __future__ import annotations +import capport.utils.zoneinfo import dataclasses import datetime import ipaddress @@ -79,6 +80,18 @@ class MacPublicState: def captive(self) -> bool: return not self.allowed + @property + def allowed_remaining_duration(self) -> str: + mm, ss = divmod(self.allowed_remaining, 60) + hh, mm = divmod(mm, 60) + return f'{hh}:{mm:02}:{ss:02}' + + @property + def allowed_until(self) -> typing.Optional[datetime.datetime]: + zone = capport.utils.zoneinfo.get_local_timezone() + now = datetime.datetime.now(zone).replace(microsecond=0) + return now + datetime.timedelta(seconds=self.allowed_remaining) + def to_rfc8908(self, config: Config) -> quart.Response: response: typing.Dict[str, typing.Any] = { 'user-portal-url': quart.url_for('index', _external=True), diff --git a/src/capport/utils/zoneinfo.py b/src/capport/utils/zoneinfo.py new file mode 100644 index 0000000..1363f11 --- /dev/null +++ b/src/capport/utils/zoneinfo.py @@ -0,0 +1,19 @@ +from __future__ import annotations + +import typing +import zoneinfo + + +_zoneinfo: typing.Optional[zoneinfo.ZoneInfo] = None + + +def get_local_timezone(): + global _zoneinfo + if not _zoneinfo: + try: + with open('/etc/timezone') as f: + key = f.readline().strip() + _zoneinfo = zoneinfo.ZoneInfo(key) + except (OSError, zoneinfo.ZoneInfoNotFoundError): + _zoneinfo = zoneinfo.ZoneInfo('UTC') + return _zoneinfo