Clean imports and check configuration
authorBenjamin Braatz <bb@bbraatz.eu>
Fri, 5 Mar 2021 09:09:57 +0000 (10:09 +0100)
committerBenjamin Braatz <bb@bbraatz.eu>
Fri, 5 Mar 2021 09:11:31 +0000 (10:11 +0100)
controlpi-plugins/wsserver.py

index e774526d6c8900904b46e0dfa3b0926dfd470cd1..0dcc0152a1252536804b18e060cabc85e663d81e 100644 (file)
@@ -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}.")