import json import os from loguru import logger from pydantic import BaseModel class Settings(BaseModel): def update(self, params): self.admin_roles = params["admin_roles"] self.allow_create_admins_by_admins = params["allow_create_admins_by_admins"] self.allow_create_admins = params["allow_create_admins"] self.allow_create_users = params["allow_create_users"] self.allow_create_groups = params["allow_create_groups"] self.allow_create_pictures = params["allow_create_groups"] admin_roles: list[str] = ["admin"] allow_create_admins_by_admins: bool = True allow_create_admins: bool = True allow_create_users: bool = True allow_create_groups: bool = True allow_create_pictures: bool = False json_path = "data/" json_settings_name = "settings.json" settings = Settings() def settings_up(): global settings, json_path, json_settings_name logger.info("Configuring settings for startup") try: if not(os.path.exists(json_path)): os.mkdir(json_path) logger.debug(f"Created '{json_path}' directory") if os.path.exists(json_path + json_settings_name): load_settings() else: with open(json_path + json_settings_name, "w") as f: json.dump(settings.model_dump_json(), f, ensure_ascii = False, indent=4) logger.info("Wrote settings to the JSON") logger.info("Successfully configured settings") except Exception as e: logger.error(f"Failed to configure settings during startup: {e}") raise e def settings_down(): global settings, json_path, json_settings_name logger.info("Saving settings for shutdown") try: with open(json_path + json_settings_name, "w") as f: json.dump(settings.model_dump_json(), f, ensure_ascii = False, indent=4) logger.info("Wrote settings to the JSON") logger.success("Successfully saved settings") except Exception as e: logger.error(f"Failed to save settings during shutdown: {e}") def reset_settings(): global settings, json_path, json_settings_name logger.info("Resetting settings") print(settings) settings = Settings() print(settings) with open(json_path + json_settings_name, "w") as f: json.dump(settings.model_dump_json(), f, ensure_ascii = False, indent=4) logger.info("Wrote settings to the JSON") def load_settings(): global settings, json_path, json_settings_name logger.info("Loading settings") with open(json_path + json_settings_name, "r") as f: json_settings = json.load(f) settings = Settings.model_validate_json(json_settings) logger.info("Loaded settings from the JSON") def save_settings(): global settings, json_path, json_settings_name with open(json_path + json_settings_name, "w") as f: json.dump(settings.model_dump_json(), f, ensure_ascii = False, indent=4) logger.info("Wrote settings to the JSON")