import configparser from os import path from typing import Optional import requests config_file = "config.ini" _c = configparser.ConfigParser() _c.optionxform = str def init_config() -> None: if _validate_config() is False: print("Config is invalid.") exit(1) _c.read("config.ini", "utf-8") global general, app general = _General() app = _App() def _validate_config() -> bool: default_config = { "General": {"Token": "", "SourceUrl": ""}, "App": { "Name": "Danbooru", "Host": "danbooru.donmai.us", "HostName": "", "PreferSecureProtocol": True, }, } if not path.exists(config_file): for section, options in default_config.items(): _c[section] = options with open(config_file, "w") as cf: _c.write(cf) print(f"{config_file} generated successfully.") else: _c.read(config_file, "utf-8") is_valid = True for section, options in default_config.items(): if not _c.has_section(section): print(f"Missing section: [{section}]") is_valid = False for option in options: if not _c.has_option(section, option): print(f"Missing option: '{option}' in section [{section}]") is_valid = False if not is_valid: return False if _c.get("App", "Name") == "": print(f"Empty option: 'Name' in section [App]") return False try: response = requests.get( f"http://{_c.get("App", "Host")}/status.json", timeout=10 ) if response.status_code != 200: raise requests.exceptions.InvalidURL except requests.exceptions.RequestException: print(f"Unable to validate: 'Host' in section [App]") return False return True class _General: token: str sourceurl: Optional[str] def __init__(self): self.token = _c.get("General", "Token") self.sourceurl = _c.get("General", "SourceUrl") if not self.sourceurl.startswith("http://") and not self.sourceurl.startswith( "https://" ): self.sourceurl = None class _App: name: str host: str hostname: str def __init__(self): self.name = _c.get("App", "Name") self.host = _c.get("App", "Host") self.hostname = _c.get("App", "HostName") if not self.hostname: self.hostname = self.host self.protocol = "http" if eval(_c.get("App", "PreferSecureProtocol")): self.protocol = "https" general = None app = None