""" IANA timezone table for the device clock (firmware 3.0.0+, timezone mode "auto"). Devices evaluate a POSIX TZ rule string (e.g. "EET-2EEST,M3.5.0/3,M10.5.0/4"), not the IANA database, so whoever sets a device's timezone has to send the rule. This module is the single source of those rules for the console and the phone app (GET /api/public/timezones); the tablet app, which only talks to devices over local WebSocket, bundles a saved copy of the same response. Everything comes from the `tzdata` package pinned in requirements.txt (IANA release in `tzdata.IANA_VERSION`): the POSIX rule is the footer of each zone's TZif file, zone → country from zone.tab, country names from iso3166.tab. To pick up new DST rules, bump the pin — nothing is generated or committed by hand. The firmware side is project-vesper src/TimeKeeper/TimeZone.cpp; its host tests check that it evaluates every one of these rules the same way as CPython's zoneinfo. """ from __future__ import annotations import importlib.resources import re from datetime import datetime, timezone from functools import lru_cache from zoneinfo import ZoneInfo import tzdata # POSIX TZ: std offset [dst [offset] [,rule]] — only the offsets are needed here. _NAME = r"(?:<[^>]+>|[A-Za-z]{3,})" _OFFSET = r"([+-]?\d{1,3}(?::\d{1,2}){0,2})" _POSIX_RE = re.compile(rf"^{_NAME}{_OFFSET}(?:({_NAME}){_OFFSET}?(?:,.*)?)?$") def _tzdata_file(name: str): return importlib.resources.files("tzdata.zoneinfo").joinpath(*name.split("/")) def _hms_to_min(text: str) -> int: sign = -1 if text.startswith("-") else 1 parts = [int(p) for p in text.lstrip("+-").split(":")] parts += [0] * (3 - len(parts)) return sign * (parts[0] * 60 + parts[1] + (1 if parts[2] >= 30 else 0)) def posix_offsets(posix: str) -> tuple[int, int, bool]: """(std_offset_min, dst_offset_min, has_dst), east-positive minutes. POSIX offsets are west-positive ("EET-2" is UTC+2). dst_offset_min is the DST *amount* (DST total - standard), default one hour, matching the firmware's tz::makeAuto(). It can be negative (Europe/Dublin models winter as negative DST). """ m = _POSIX_RE.match(posix) if not m: raise ValueError(f"unparseable POSIX TZ rule: {posix!r}") std = -_hms_to_min(m.group(1)) if not m.group(2): return std, 0, False total = -_hms_to_min(m.group(3)) if m.group(3) else std + 60 return std, total - std, True def posix_rule(name: str) -> str | None: """POSIX TZ footer of a zone's TZif (v2+) file, or None.""" try: data = _tzdata_file(name).read_bytes() except (FileNotFoundError, IsADirectoryError, OSError): return None if not data.startswith(b"TZif") or data[4:5] < b"2": return None footer = data.rstrip(b"\n").rsplit(b"\n", 1)[-1].decode("ascii", "replace") return footer or None def _format_offset(minutes: int) -> str: sign = "+" if minutes >= 0 else "-" return f"UTC{sign}{abs(minutes) // 60:02d}:{abs(minutes) % 60:02d}" @lru_cache(maxsize=1) def _static_table() -> tuple[list[dict], dict[str, dict]]: """Countries (sorted by name) with their zones in zone.tab order, plus a name index. Only the parts that never change at runtime; offsets "now" are added per request.""" countries_by_code = {} for line in _tzdata_file("iso3166.tab").read_text(encoding="utf-8").splitlines(): if line and not line.startswith("#"): code, name = line.split("\t", 1) countries_by_code[code] = {"code": code, "name": name.strip(), "zones": []} zones_by_name: dict[str, dict] = {} for line in _tzdata_file("zone.tab").read_text(encoding="utf-8").splitlines(): if not line or line.startswith("#"): continue fields = line.split("\t") code, name = fields[0], fields[2] comment = fields[3].strip() if len(fields) > 3 else "" posix = posix_rule(name) country = countries_by_code.get(code) if not posix or country is None: continue std, dst, has_dst = posix_offsets(posix) zone = zones_by_name.get(name) if zone is None: zone = { "name": name, "city": name.rsplit("/", 1)[-1].replace("_", " "), "comment": comment, "posix": posix, "std_offset_min": std, "dst_offset_min": dst, "has_dst": has_dst, "countries": [], } zones_by_name[name] = zone zone["countries"].append(code) country["zones"].append(zone) countries = sorted((c for c in countries_by_code.values() if c["zones"]), key=lambda c: c["name"]) return countries, zones_by_name def _with_current(zone: dict, now: datetime) -> dict: local = now.astimezone(ZoneInfo(zone["name"])) offset = int(local.utcoffset().total_seconds() // 60) out = {k: v for k, v in zone.items() if k != "countries"} out["countries"] = list(zone["countries"]) out["current_offset_min"] = offset out["current_dst"] = bool(local.dst()) out["display"] = f"({_format_offset(offset)}) {zone['city']}" + (f" — {zone['comment']}" if zone["comment"] else "") return out def tzdata_version() -> str: return tzdata.IANA_VERSION def get_table(country: str | None = None, now: datetime | None = None) -> dict | None: """Full table, or one country's (ISO 3166 alpha-2, case-insensitive). None if unknown.""" now = now or datetime.now(timezone.utc) countries, _ = _static_table() if country: countries = [c for c in countries if c["code"] == country.upper()] if not countries: return None return { "tzdata_version": tzdata_version(), "generated_at": now.isoformat(timespec="seconds"), "countries": [ {"code": c["code"], "name": c["name"], "zones": [_with_current(z, now) for z in c["zones"]]} for c in countries ], } def get_zone(name: str, now: datetime | None = None) -> dict | None: """One zone. Also resolves IANA names that zone.tab doesn't list (aliases such as "Asia/Calcutta", or "UTC") — phones may report those as their own timezone.""" _, zones = _static_table() zone = zones.get(name) if zone is None: posix = posix_rule(name) if re.fullmatch(r"[A-Za-z0-9_+\-]+(/[A-Za-z0-9_+\-]+)*", name) else None if posix is None: return None std, dst, has_dst = posix_offsets(posix) zone = {"name": name, "city": name.rsplit("/", 1)[-1].replace("_", " "), "comment": "", "posix": posix, "std_offset_min": std, "dst_offset_min": dst, "has_dst": has_dst, "countries": []} result = _with_current(zone, now or datetime.now(timezone.utc)) result["tzdata_version"] = tzdata_version() return result