microkodi/microkodi/main.py
2025-01-12 22:31:53 +01:00

102 lines
3.1 KiB
Python

from http.server import HTTPServer
import logging
import sys
import threading
import argparse
from pathlib import Path
import importlib.util
import time
from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine
from microkodi.jsonrpc import JsonRpcHandler, GlobalMethodHandler
from microkodi.ui.bridge import DataBridge
from microkodi.config import Config, load_config
from microkodi.cec_handler import CECHandler
from microkodi.repository import I
def run_kodi_server():
config: Config = I.get("Config")
logger = logging.getLogger("JsonRPCServer")
method_handler = GlobalMethodHandler()
I.register("GlobalMethodHandler", method_handler)
# Setup CEC
if config.cec:
I.register("CECHandler", CECHandler())
logger.info("Enabling CEC support")
# Load extra plugins
if config.scripts:
logger.info("Loading scripts...")
for name, path in config.scripts.items():
logger.debug("Trying to load %s (%s)", name, path)
if not Path(path).exists():
logger.warning("Failed to load %s: File does not exist", name)
continue
spec = importlib.util.spec_from_file_location(name, path)
module = importlib.util.module_from_spec(spec)
# Inject special globals
setattr(module, "I", I)
setattr(module, "logger", logging.getLogger(name))
spec.loader.exec_module(module)
if not hasattr(module, "init"):
logger.warning("Failed to load %s: No init function", name)
continue
init_method = getattr(module, "init")
init_method()
server = HTTPServer
httpd = HTTPServer((config.host, config.port,), JsonRpcHandler)
logger.info("Starting server on %s:%i", config.host, config.port)
httpd.serve_forever()
logger.info("Shutting down server")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--config", "-c", type=Path, help="Location of the config file")
parser.add_argument("--debug", action="store_true", default=False)
options = parser.parse_args()
logging.basicConfig(level=logging.DEBUG if options.debug else logging.INFO)
logger = logging.getLogger("ui")
# Load the config
config = load_config(options.config)
I.register("Config", config)
bridge = DataBridge()
I.register("DataBridge", bridge)
# Start the server
server_thread = threading.Thread(target=run_kodi_server, daemon=True)
server_thread.start()
# Setup the UI
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
engine.addImportPath(sys.path[0])
engine.rootContext().setContextProperty(
"wallpapers",
config.wallpapers,
)
engine.rootContext().setContextProperty(
"initialTime",
bridge.currentTime(),
)
engine.loadFromModule("qml", "Main")
if not engine.rootObjects():
sys.exit(-1)
engine.rootObjects()[0].setProperty("bridge", bridge)
exit_code = app.exec()
del engine
sys.exit(exit_code)