Files
2026-matrix-csonac/config.py
Nikita Tyukalov, ASUS, Linux 2c05443c89 Initial commit
2026-08-17 03:33:54 +03:00

53 lines
1.2 KiB
Python

"""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"
}
#
# 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:
return None