""" Config related tools. """ import dataclasses import yaml from typing import Optional @dataclasses.dataclass class Config: username: str homeserver: str password: str alert_rooms: list[str] port: int = 8000 host: str = "127.0.0.1" endpoint: str = "/webhook" tls: bool = False tls_auth: bool = False tls_crt: Optional[str] = None tls_key: Optional[str] = None ca_crt: Optional[str] = None default_template: Optional[str] = None templates: dict[str, str] = dataclasses.field(default_factory=dict) def check_integrity(self)->bool: """ Check the integrity of the config. Raise an error if the config is invalid, should always return True (or raise an error). """ if self.tls_auth and not self.tls: raise ValueError("tls_auth is enable, but not tls.") if self.tls and self.tls_crt is None: raise ValueError("tls is enable but tls_crt was not provided") if self.tls and self.tls_key is None: raise ValueError("tls is enable but tls_key was not provided") if self.tls_auth and self.ca_crt is None: raise ValueError("tls_auth is enable, but ca_crt was not provided") return True def load_config(file:str)->Config: """ Load the config from the config file. """ with open(file, 'r') as f: data = yaml.load(f, Loader=yaml.loader.SafeLoader) config = Config(**data) config.check_integrity() return config