import re from typing import Any import tornado from tornado import httputil from tornado.web import Application from core.config import ( BASE_URL, SERVER_OWNER_CALLSIGN, TELNET_SERVER_ADDRESS, TELNET_SERVER_ENABLED, TELNET_SERVER_PORT, WEB_UI_OPTIONS, ) from core.constants import SOFTWARE_VERSION from core.utils import infer_mode_type_from_mode, safe_json_dumps from webserver.handlers.api.options import build_options def dom_safe_name(name): """Strip characters from a name that are not allowed in HTML element IDs""" return re.sub(r"^[^A-Za-z0-9]+|\W+", "", name, flags=re.ASCII) class PageTemplateHandler(tornado.web.RequestHandler): """Handler for all HTML pages generated from templates""" def __init__( self, application: "Application", request: httputil.HTTPServerRequest, **kwargs: Any, ): self._template_name = None super().__init__(application, request, **kwargs) def initialize(self, template_name): self._template_name = template_name def get_template_namespace(self): """Provide variables and helper functions to all page templates""" namespace = super().get_template_namespace() namespace.update( # Various options options=build_options(), web_ui_options=WEB_UI_OPTIONS, # Other single static parameters software_version=SOFTWARE_VERSION, server_owner_callsign=SERVER_OWNER_CALLSIGN, baseurl=BASE_URL, telnet_server_enabled=TELNET_SERVER_ENABLED, telnet_server_address=TELNET_SERVER_ADDRESS, telnet_server_port=TELNET_SERVER_PORT, # Function references that templates need dom_safe_name=dom_safe_name, safe_json_dumps=safe_json_dumps, infer_mode_type_from_mode=infer_mode_type_from_mode, ) return namespace def get(self): self.render(f"{self._template_name}.html")