Add timezone support
This commit is contained in:
1 parent
fffc1b0c81
commit
a07943e645
8 files changed
+90
-6
No files matched your search
@@ -3,7 +3,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import timedelta, timezone, tzinfo
|
||||
from pathlib import Path
|
||||
|
||||
DEFAULT_ENV_FILE = Path(__file__).resolve().parent / ".env"
|
||||
@@ -12,11 +14,44 @@ HTTP_TIMEOUT_SECONDS = 20.0
|
||||
MEETINGS_PAGE_LIMIT = 200
|
||||
DEFAULT_STATE_FILE = "state.json"
|
||||
|
||||
_OFFSET_RE = re.compile(r"^(?:UTC|GMT)?\s*([+-])(\d{1,2})(?::?(\d{2}))?$", re.IGNORECASE)
|
||||
|
||||
|
||||
class ConfigError(Exception):
|
||||
"""Raised when required configuration is missing or invalid."""
|
||||
|
||||
|
||||
def _resolve_timezone(value: str) -> tzinfo | None:
|
||||
"""Resolve TIMEZONE to a tzinfo.
|
||||
|
||||
Accepts an IANA name (Europe/Moscow) or a GMT/UTC offset (GMT+3, UTC+05:30).
|
||||
Empty means use the machine's local timezone.
|
||||
"""
|
||||
name = (value or "").strip()
|
||||
if not name:
|
||||
return None
|
||||
if name.upper() in ("UTC", "GMT", "Z"):
|
||||
return timezone.utc
|
||||
|
||||
match = _OFFSET_RE.match(name)
|
||||
if match:
|
||||
sign = 1 if match.group(1) == "+" else -1
|
||||
hours = int(match.group(2))
|
||||
minutes = int(match.group(3) or 0)
|
||||
if hours > 23 or minutes > 59:
|
||||
raise ConfigError(f"invalid TIMEZONE offset {value!r}")
|
||||
return timezone(sign * timedelta(hours=hours, minutes=minutes), name.upper())
|
||||
|
||||
try:
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
return ZoneInfo(name)
|
||||
except (ValueError, KeyError) as exc:
|
||||
raise ConfigError(
|
||||
f"invalid TIMEZONE {value!r}; use an IANA name (Europe/Moscow) or an offset (GMT+3)"
|
||||
) from exc
|
||||
|
||||
|
||||
def _unquote(value: str) -> str:
|
||||
if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'):
|
||||
return value[1:-1]
|
||||
@@ -83,6 +118,8 @@ class Config:
|
||||
poll_interval_seconds: int = DEFAULT_POLL_INTERVAL_SECONDS
|
||||
state_file: str = DEFAULT_STATE_FILE
|
||||
socks5_proxy: str = ""
|
||||
# Timezone used to display meeting times; None means local time.
|
||||
timezone: tzinfo | None = None
|
||||
|
||||
|
||||
def load_config(env_file: Path | None = None) -> Config:
|
||||
@@ -105,4 +142,5 @@ def load_config(env_file: Path | None = None) -> Config:
|
||||
poll_interval_seconds=poll_interval,
|
||||
state_file=_env_str("BOT_STATE_FILE", default=DEFAULT_STATE_FILE),
|
||||
socks5_proxy=socks5_proxy,
|
||||
timezone=_resolve_timezone(_env_str("TIMEZONE")),
|
||||
)
|
||||
Reference in new issue
Block a user