NucelarMonitor/Python/Models/RouteModel.py

62 lines
2.3 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from typing import Any, Callable, Self
from re import Pattern as REPattern, compile as re_compile, IGNORECASE as RE_IGNORE_CASE, Match as REMatch
from Abstracts.ControllerAbstract import ControllerAbstract
from Interfaces.Application.NucelarMonitorInterface import NucelarMonitorInterface
from Utils.Patterns import RE
from Models.RequestModel import RequestModel
from Models.ResponseModel import ResponseModel
from Utils.Utils import Utils
class RouteModel:
def __init__(self:Self, nucelar_monitor:NucelarMonitorInterface, inputs:str|dict[str, Any|None]|tuple[str, str, list[str]]) -> None:
self.method:str = ""
self.route:REPattern
self.path:str|None = None
self.action:Callable[[RequestModel, ResponseModel], tuple[Any|None, int]]|None = None
self.permissions:list[str] = []
self.variables:list[str] = []
self.error:int = 0
if isinstance(inputs, str):
matches:REMatch[str]|None = RE.ROUTE.match(inputs)
if matches is None:
self.error = 1
return
method:str|None
route:str
action:str|None
controller:str|None
permissions:str|None
method, route, action, controller, self.path, permissions = matches.groups()
self.method = (method or "get").lower()
self.route = re_compile(route, RE_IGNORE_CASE)
def callback(matches:REMatch) -> str:
self.variables.append(matches.group(1))
return r'([^\/]+)'
self.route = re_compile(r'^' + RE.ROUTE_KEY.sub(callback, Utils.to_regular_expression(
route[:-1] if route[-1] == "/" else route
)) + (r'\/?' if self.path is None else r'(\/.*)?') + r'$')
self.path and self.variables.append("path")
if permissions:
self.permissions = [permission.strip() for permission in permissions.split(",") if permission.strip()]
if controller and action:
controller_item:ControllerAbstract = nucelar_monitor.controllers.get(controller)
if controller_item:
self.action = controller_item.get_action(action)