ovdashboard/api/ovdashboard_api/config.py

65 lines
1.3 KiB
Python

"""
Python representation of the "config.txt" file inside the WebDAV directory.
"""
from io import BytesIO
from typing import Any
from pydantic import BaseModel
from tomli import loads as toml_loads
from tomli_w import dump as toml_dump
from webdav3.exceptions import RemoteResourceNotFound
from .dav_file import DavFile
class TickerConfig(BaseModel):
"""
Sections "[ticker.*]" in "config.txt".
"""
separator: str = " +++ "
comment_marker: str = "#"
class ImageConfig(BaseModel):
"""
Sections "[image.*]" in "config.txt".
"""
mode: str = "RGB"
save_params: dict[str, Any] = {
"format": "JPEG",
"quality": 85,
}
class Config(BaseModel):
"""
Main representation of "config.txt".
"""
ticker: TickerConfig = TickerConfig()
image: ImageConfig = ImageConfig()
@classmethod
async def get(cls) -> "Config":
"""
Load the configuration instance from the server using `TOML`.
"""
dav_file = DavFile("ovdashboard/config.txt")
try:
return cls.parse_obj(
toml_loads(await dav_file.string)
)
except RemoteResourceNotFound:
buffer = BytesIO()
toml_dump(cls().dict(), buffer)
buffer.seek(0)
await dav_file.dump(buffer.read())
return cls()