"""Module for generating and reading config""" import json import aiofiles import os import traceback from datatypes import AppConfig import util DEFAULT_CONFIG = { "matrix_homeserver": "https://matrix.domain.net", "matrix_user": "short_username", "store_dir": "session_storage", "web_ip": "0.0.0.0", "web_port": 4980, "fails_to_ban": 50, "ban_duration": 600 } # # PRIVATE # async def write_default_config(path: str) -> None: try: async with aiofiles.open(path, "w") as f: await f.write(json.dumps(DEFAULT_CONFIG, indent=4)) util.log_info(f"Default config is saved to `{path}`") except: traceback.print_exc() # # PUBLIC # async def load_config(path: str = "config.json") -> AppConfig | None: """Load config from specified path. Creates default config if it does not exist (but still returns None).""" # no file if not os.path.isfile(path): await write_default_config(path) return None # open and read try: async with aiofiles.open(path, "r") as f: j = json.loads((await f.read()).strip()) except: traceback.print_exc() return None # parse try: cfg = AppConfig(**j) return cfg except: traceback.print_exc() return None