2
0

add time helpers to MacPublicState for views

This commit is contained in:
Stefan Bühler 2022-04-08 16:35:53 +02:00
parent daf21d0afd
commit 156e11a882
2 changed files with 32 additions and 0 deletions

View File

@ -1,5 +1,6 @@
from __future__ import annotations from __future__ import annotations
import capport.utils.zoneinfo
import dataclasses import dataclasses
import datetime import datetime
import ipaddress import ipaddress
@ -79,6 +80,18 @@ class MacPublicState:
def captive(self) -> bool: def captive(self) -> bool:
return not self.allowed 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: def to_rfc8908(self, config: Config) -> quart.Response:
response: typing.Dict[str, typing.Any] = { response: typing.Dict[str, typing.Any] = {
'user-portal-url': quart.url_for('index', _external=True), 'user-portal-url': quart.url_for('index', _external=True),

View File

@ -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