DeTTECT/editor.py

72 lines
2.1 KiB
Python
Raw Normal View History

2020-02-20 11:02:27 +00:00
import webbrowser
import os
import sys
import signal
from http.server import HTTPServer, SimpleHTTPRequestHandler
from socketserver import TCPServer
import threading
class QuietHTTPRequestHandler(SimpleHTTPRequestHandler):
def log_message(self, format, *args):
pass
def log_request(self, code='-', size='-'):
pass
2020-03-04 09:45:00 +00:00
class DeTTECTEditor:
2020-02-20 11:02:27 +00:00
def __init__(self, port):
"""
2020-03-04 09:45:00 +00:00
Constructor of the DeTTECTEditor class. Sets the SIGTERM (clean quit) en SIGINT (Ctrl+C) handlers and the default variables.
2020-02-20 11:02:27 +00:00
:param port: The port for the webserver to listen on
"""
signal.signal(signal.SIGTERM, self._signal_handler)
signal.signal(signal.SIGINT, self._signal_handler)
self.port = port
self.httpd = None
def _signal_handler(self, signal, frame):
"""
Handles the termination of the application.
:param signum: Indicator of the termination signal
:param frame:
"""
print("Shutting down webserver")
self.httpd.server_close()
self.httpd.shutdown()
def _run_webserver(self):
"""
Starts the webserver on the given port.
"""
try:
2020-03-04 09:45:00 +00:00
os.chdir('./editor/dist')
2020-02-20 11:02:27 +00:00
self.httpd = TCPServer(('', self.port), QuietHTTPRequestHandler)
2020-03-04 09:45:00 +00:00
print("Editor started at port %d" % self.port)
url = 'http://localhost:%d/dettect-editor' % self.port
2020-02-20 11:02:27 +00:00
if not os.getenv('DeTTECT_DOCKER_CONTAINER'):
print("Opening webbrowser: " + url)
webbrowser.open_new_tab(url)
else:
2020-03-04 09:45:00 +00:00
print("You can open the Editor on: " + url)
2020-02-20 11:02:27 +00:00
self.httpd.serve_forever()
except Exception as e:
print("Could not start webserver: " + str(e))
def start(self):
"""
2020-03-04 09:45:00 +00:00
Starts the Editor by starting a thread where the webserver runs in.
2020-02-20 11:02:27 +00:00
"""
thread = threading.Thread(target=self._run_webserver)
thread.start()
if __name__ == '__main__':
print("Please use dettect.py for running the DeTT&CT Editor. Run 'python dettect.py e -h' for more information.")