From: Benjamin Braatz Date: Fri, 5 Mar 2021 09:09:57 +0000 (+0100) Subject: Clean imports and check configuration X-Git-Tag: v0.3.0~43 X-Git-Url: http://git.graph-it.com/?a=commitdiff_plain;h=4bfbae89e03bc5428d9706361a9605e80c14e540;p=graphit%2Fcontrolpi-wsserver.git Clean imports and check configuration --- diff --git a/controlpi-plugins/wsserver.py b/controlpi-plugins/wsserver.py index e774526..0dcc015 100644 --- a/controlpi-plugins/wsserver.py +++ b/controlpi-plugins/wsserver.py @@ -4,12 +4,11 @@ TODO: documentation, doctests, resilient conf-parsing """ import os import json -import websockets from websockets import (WebSocketServerProtocol, ConnectionClosedOK, - ConnectionClosedError) + ConnectionClosedError, serve) from websockets.http import Headers from http import HTTPStatus -from typing import Union, Optional, Tuple, Iterable, Mapping +from typing import Optional, Tuple from controlpi import BasePlugin, MessageBus, Message, PluginConfiguration @@ -68,13 +67,14 @@ class WSServer(BasePlugin): if path == '/': path = '/index.html' response_headers = Headers() - response_headers['Server'] = 'consolepi-wsserver websocket server' + response_headers['Server'] = 'controlpi-wsserver websocket server' response_headers['Connection'] = 'close' file_path = os.path.realpath(os.path.join(self._web_root, path[1:])) if os.path.commonpath((self._web_root, file_path)) != self._web_root \ or not os.path.exists(file_path) \ or not os.path.isfile(file_path): - return HTTPStatus.NOT_FOUND, response_headers, b'File not found!' + return (HTTPStatus.NOT_FOUND, response_headers, + f"File '{path}' not found!".encode()) mime_type = 'application/octet-stream' extension = file_path.split('.')[-1] if extension == 'html': @@ -89,13 +89,21 @@ class WSServer(BasePlugin): return HTTPStatus.OK, response_headers, body def _process_conf(self, conf: PluginConfiguration) -> None: + if 'port' not in conf: + print(f"'port' not configured for WSServer '{self._name}'." + " Using 80.") + conf['port'] = 80 self._port = conf['port'] + if 'web root' not in conf: + print(f"'web root' not configured for WSServer '{self._name}'." + " Using 'web'.") + conf['web root'] = 'web' self._web_root = os.path.realpath(os.path.join(os.getcwd(), conf['web root'])) super()._process_conf(conf) async def run(self) -> None: await super().run() - await websockets.serve(self._handler, port=self._port, - process_request=self._process_request) + await serve(self._handler, port=self._port, + process_request=self._process_request) print(f"WSServer '{self._name}' serving on port {self._port}.")