StarfallBot/app.py

82 lines
2.1 KiB
Python

import logging
import os
import sys
import threading
from threading import Thread
from time import sleep
from typing import final
from starfall.config import Config
from starfall.log import Log
from starfall.types import SnapshotQueue
from starfall.web import WebUI
@final
class Application:
app: WebUI
config: Config
log: Log
queue: SnapshotQueue
threads: dict[str, Thread]
def __init__(self):
"""Initializes the application and prepares all threads for launch."""
self.log = Log()
logging.getLogger("app").debug(
"OS Type: %s\nWorking Directory: %s\nApplication version: %s",
os.name,
os.path.realpath(os.curdir),
self.version(),
)
self.config = Config("config.toml", "config-sample.toml")
if not self.config.get("app.run", False):
logging.getLogger("app").critical(
"Config file disallows execution.\n"
+ "Please make the necessary changes to the configuration"
+ " file and relaunch the program:\n\t%s",
os.path.realpath(self.config.file_name),
)
sys.exit()
self.threads = {}
self.queue = SnapshotQueue()
self.app = WebUI()
def version(self):
with open("VERSION.md", "r") as file:
version = file.readline()
return version
def run(self):
"""
Starts all threads and monitors their active state.
This function runs indefinitely.
"""
self.threads["flask"] = Thread(
target=self.app.run,
args=(
self.config,
self.queue,
),
daemon=True,
)
self.threads["flask"].start()
while threading.active_count() > 0:
sleep(0.25)
self.monitor_queue()
def monitor_queue(self):
"""Monitors and logs all incoming messages in `self.queue`."""
for entry in self.queue.get_all_for_receiver("app"):
logging.getLogger("app").info("Received queue message: %r", entry)
if __name__ == "__main__":
Application().run()