danbooru-bot/config.py
mctaylors f7a9bf9f13
change: remove implicitly set variable types
Signed-off-by: mctaylors <cantsendmails@mctaylors.ru>
2025-07-23 02:59:10 +03:00

94 lines
2.4 KiB
Python

import configparser
from os import path
import requests
config_file = "config.ini"
_c = configparser.ConfigParser()
_c.optionxform = str
def init_config() -> None:
if not _validate_config():
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": "",
"HTTPS": 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:
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:
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", "HTTPS")):
self.protocol = "https"
general = None
app = None