Files
sigcal/src/sigcal_bot/config.py
T
kawaiipunk add77f6cb8 Rename to sigcal-bot
- package src/sigcal_bot, distribution and CLI sigcal-bot
- environment variables SIGCAL_BOT_*
- database file, container names, user agents, logs and QR device name
- docs and changelog updated
2026-11-18 17:06:40 +00:00

263 lines
8.6 KiB
Python

# SPDX-License-Identifier: GPL-3.0-or-later
# Copyright (C) 2026 kawaiipunk
"""Configuration loading and defaults."""
from __future__ import annotations
import os
import re
import tomllib
from dataclasses import dataclass, field
from datetime import time
from pathlib import Path
class ConfigError(Exception):
"""Raised when the configuration file is invalid."""
# ---------------------------------------------------------------------------
# small parsers
# ---------------------------------------------------------------------------
_DURATION_RE = re.compile(r"^\s*(\d+)\s*([smhdw])\s*$", re.IGNORECASE)
_DURATION_UNITS = {
"s": 1,
"m": 60,
"h": 3600,
"d": 86400,
"w": 604800,
}
def parse_duration(value: str | int) -> int:
"""Parse '3d', '2h', '90m', '1w' into seconds. Bare ints are seconds."""
if isinstance(value, int):
return value
match = _DURATION_RE.match(value)
if not match:
raise ConfigError(f"invalid duration: {value!r} (use e.g. '3d', '2h', '30m')")
return int(match.group(1)) * _DURATION_UNITS[match.group(2).lower()]
def parse_clock(value: str) -> time:
try:
hour, minute = (int(part) for part in value.split(":"))
return time(hour, minute)
except (ValueError, TypeError) as exc:
raise ConfigError(f"invalid time of day: {value!r}") from exc
def parse_window(value: str) -> tuple[time, time]:
try:
start, end = value.split("-")
except ValueError as exc:
raise ConfigError(f"invalid window: {value!r} (use '08:00-10:00')") from exc
start_time, end_time = parse_clock(start), parse_clock(end)
if end_time <= start_time:
raise ConfigError(f"window must end after it starts: {value!r}")
return start_time, end_time
# ---------------------------------------------------------------------------
# config sections
# ---------------------------------------------------------------------------
@dataclass(frozen=True)
class SignalConfig:
api_url: str
number: str
group_id: str
text_mode: str = "normal"
@dataclass(frozen=True)
class CalendarConfig:
url: str
timezone: str = "Europe/London"
refresh_minutes: int = 15
window_days: int = 60
@dataclass(frozen=True)
class PostingConfig:
windows: tuple[tuple[time, time], ...] = ((time(8, 0), time(10, 0)), (time(18, 0), time(21, 0)))
urgent_guard_minutes: int = 60
@dataclass(frozen=True)
class AnnounceConfig:
enabled: bool = True
max_days_ahead: int = 30
backfill: bool = False
@dataclass(frozen=True)
class RemindersConfig:
enabled: bool = True
lead_times: tuple[str, ...] = ("3d",)
fallback_to_day_of: bool = True
day_of_time: time = time(9, 0)
@dataclass(frozen=True)
class ImagesConfig:
enabled: bool = True
max_pixels: int = 1600
max_bytes: int = 400_000
max_images_per_post: int = 3
timeout_seconds: float = 10.0
scrape_event_page: bool = True
@dataclass(frozen=True)
class FormatConfig:
show_title: bool = True
show_hashtags: bool = True
show_time: bool = True
show_location: bool = True
show_link: bool = True
shorten_links: bool = False
@dataclass(frozen=True)
class WatchdogConfig:
enabled: bool = True
notify_number: str | None = None
feed_failures: int = 3
send_failures: int = 3
alert_cooldown_hours: float = 6.0
daily_heartbeat: bool = False
@dataclass(frozen=True)
class Config:
signal: SignalConfig
calendar: CalendarConfig
posting: PostingConfig = field(default_factory=PostingConfig)
announce: AnnounceConfig = field(default_factory=AnnounceConfig)
reminders: RemindersConfig = field(default_factory=RemindersConfig)
images: ImagesConfig = field(default_factory=ImagesConfig)
format: FormatConfig = field(default_factory=FormatConfig)
watchdog: WatchdogConfig = field(default_factory=WatchdogConfig)
db_path: Path = Path("data/sigcal-bot.sqlite3")
cache_dir: Path = Path("cache")
config_path: Path | None = None
base_dir: Path = Path(".")
def _section(data: dict, name: str) -> dict:
value = data.get(name, {})
if not isinstance(value, dict):
raise ConfigError(f"[{name}] must be a table")
return value
def _windows(raw: object) -> tuple[tuple[time, time], ...]:
if not isinstance(raw, list) or not raw:
raise ConfigError("posting.windows must be a non-empty list of 'HH:MM-HH:MM'")
windows = tuple(sorted(parse_window(str(item)) for item in raw))
return windows
def load_config(path: str | Path) -> Config:
config_path = Path(path).expanduser().resolve()
try:
data = tomllib.loads(config_path.read_text(encoding="utf-8"))
except FileNotFoundError as exc:
raise ConfigError(f"config file not found: {config_path}") from exc
except tomllib.TOMLDecodeError as exc:
raise ConfigError(f"invalid TOML in {config_path}: {exc}") from exc
base_dir = config_path.parent
signal = _section(data, "signal")
for key in ("api_url", "number", "group_id"):
if not signal.get(key):
raise ConfigError(f"signal.{key} is required")
calendar = _section(data, "calendar")
if not calendar.get("url"):
raise ConfigError("calendar.url is required")
posting = _section(data, "posting")
announce = _section(data, "announce")
reminders = _section(data, "reminders")
images = _section(data, "images")
fmt = _section(data, "format")
watchdog = _section(data, "watchdog")
storage = _section(data, "storage")
lead_times = tuple(str(lead) for lead in reminders.get("lead_times", ["3d"]))
for lead in lead_times:
parse_duration(lead)
db_path = Path(os.environ.get("SIGCAL_BOT_DB", storage.get("db", "data/sigcal-bot.sqlite3")))
cache_dir = Path(os.environ.get("SIGCAL_BOT_CACHE", storage.get("cache", "cache")))
if not db_path.is_absolute():
db_path = base_dir / db_path
if not cache_dir.is_absolute():
cache_dir = base_dir / cache_dir
return Config(
signal=SignalConfig(
api_url=str(signal["api_url"]).rstrip("/"),
number=str(signal["number"]),
group_id=str(signal["group_id"]),
text_mode=str(signal.get("text_mode", "normal")),
),
calendar=CalendarConfig(
url=str(calendar["url"]),
timezone=str(calendar.get("timezone", "Europe/London")),
refresh_minutes=int(calendar.get("refresh_minutes", 15)),
window_days=int(calendar.get("window_days", 60)),
),
posting=PostingConfig(
windows=_windows(posting.get("windows", ["08:00-10:00", "18:00-21:00"])),
urgent_guard_minutes=int(posting.get("urgent_guard_minutes", 60)),
),
announce=AnnounceConfig(
enabled=bool(announce.get("enabled", True)),
max_days_ahead=int(announce.get("max_days_ahead", 30)),
backfill=bool(announce.get("backfill", False)),
),
reminders=RemindersConfig(
enabled=bool(reminders.get("enabled", True)),
lead_times=lead_times,
fallback_to_day_of=bool(reminders.get("fallback_to_day_of", True)),
day_of_time=parse_clock(str(reminders.get("day_of_time", "09:00"))),
),
images=ImagesConfig(
enabled=bool(images.get("enabled", True)),
max_pixels=int(images.get("max_pixels", 1600)),
max_bytes=int(images.get("max_bytes", 400_000)),
max_images_per_post=int(images.get("max_images_per_post", 3)),
timeout_seconds=float(images.get("timeout_seconds", 10)),
scrape_event_page=bool(images.get("scrape_event_page", True)),
),
format=FormatConfig(
show_title=bool(fmt.get("show_title", True)),
show_hashtags=bool(fmt.get("show_hashtags", True)),
show_time=bool(fmt.get("show_time", True)),
show_location=bool(fmt.get("show_location", True)),
show_link=bool(fmt.get("show_link", True)),
shorten_links=bool(fmt.get("shorten_links", False)),
),
watchdog=WatchdogConfig(
enabled=bool(watchdog.get("enabled", True)),
notify_number=(
str(watchdog["notify_number"]) if watchdog.get("notify_number") else None
),
feed_failures=int(watchdog.get("feed_failures", 3)),
send_failures=int(watchdog.get("send_failures", 3)),
alert_cooldown_hours=float(watchdog.get("alert_cooldown_hours", 6)),
daily_heartbeat=bool(watchdog.get("daily_heartbeat", False)),
),
db_path=db_path,
cache_dir=cache_dir,
config_path=config_path,
base_dir=base_dir,
)