ovdashboard/api/ovdashboard_api/config.py

137 lines
2.9 KiB
Python

"""
Python representation of the "config.txt" file inside the WebDAV directory.
"""
import tomllib
from io import BytesIO
from logging import getLogger
from typing import Any
import tomli_w
from pydantic import BaseModel
from webdav3.exceptions import RemoteResourceNotFound
from .dav_common import caldav_list
from .dav_file import DavFile
from .settings import SETTINGS
_logger = getLogger(__name__)
class TickerUIConfig(BaseModel):
"""
Configuration for how the UI displays the ticker content.
"""
color: str = "primary"
class TickerConfig(TickerUIConfig):
"""
Section "[ticker]" in "config.txt".
Combined configuration for the ticker.
"""
file_name: str = "ticker"
separator: str = " +++ "
comment_marker: str = "#"
class ImageUIConfig(BaseModel):
"""
Configuration for how the UI displays the image carousel.
"""
height: int = 300
contain: bool = False
speed: int = 10000
class ImageConfig(ImageUIConfig):
"""
Sections "[image*]" in "config.txt".
"""
mode: str = "RGB"
save_params: dict[str, Any] = {
"format": "JPEG",
"quality": 85,
}
class CalendarUIConfig(BaseModel):
"""
Configuration for how the UI displays the calendar carousel.
"""
speed: int = 10000
class CalendarConfig(CalendarUIConfig):
"""
Sections "[calendar*]" in "config.txt".
"""
future_days: int = 365
aggregates: dict[str, list[str]] = {}
class ServerUIConfig(BaseModel):
"""
Section "[server]" in "config.txt".
"""
name: str = "OEKZident"
host: str = "https://oekzident.de"
class LogoUIConfig(BaseModel):
"""
Section "[logo]" in "config.txt".
"""
above: str = "Technisches Hilfswerk"
below: str = "OV Musterstadt"
class Config(BaseModel):
"""
Main representation of "config.txt".
"""
image_dir: str = "image"
text_dir: str = "text"
file_dir: str = "file"
logo: LogoUIConfig = LogoUIConfig()
image: ImageConfig = ImageConfig()
server: ServerUIConfig = ServerUIConfig()
ticker: TickerConfig = TickerConfig()
calendar: CalendarConfig = CalendarConfig()
@classmethod
async def get(cls) -> "Config":
"""
Load the configuration instance from the server using `TOML`.
"""
dav_file = DavFile(SETTINGS.config_path)
try:
cfg = cls.model_validate(tomllib.loads(await dav_file.as_string))
except RemoteResourceNotFound:
_logger.warning(
f"Config file {SETTINGS.config_path!r} not found, creating ..."
)
cfg = cls()
cfg.calendar.aggregates["All Events"] = list(await caldav_list())
buffer = BytesIO()
tomli_w.dump(cfg.model_dump(), buffer)
buffer.seek(0)
await dav_file.write(buffer.read())
return cfg