from glob import glob from os.path import exists import eventlet import socketio from pycs.ApplicationStatus import ApplicationStatus from pycs.frontend.FileProvider import FileProvider class WebServer: def __init__(self, app_status: ApplicationStatus): # initialize web server if exists('webui/index.html'): print('production build') files = FileProvider(app_status) # find svg icons and add them as separate static files to # set their correct mime type / content_type static_files = {'/': 'webui/'} for path in glob('webui/img/*.svg'): path = path.replace('\\', '/') static_files[path[5:]] = {'content_type': 'image/svg+xml', 'filename': path} self.__sio = socketio.Server() self.__app = socketio.WSGIApp(self.__sio, files, static_files=static_files) else: print('development build') files = FileProvider(app_status, cors=True) self.__sio = socketio.Server(cors_allowed_origins='*') self.__app = socketio.WSGIApp(self.__sio, files) # save every change in application status and send it to the client app_status.subscribe(self.__update_application_status, immediate=True) # define events @self.__sio.event def connect(id, msg): self.__sio.emit('app_status', self.__status, to=id) @self.__sio.on('set') def set_status(id, msg): path = msg['path'].split('/') value = msg['value'] obj = app_status for p in path[:-1]: obj = obj[p] obj[path[-1]] = value @self.__sio.on('add') def add_status(id, msg): path = msg['path'].split('/') value = msg['value'] obj = app_status for p in path[:-1]: obj = obj[p] obj[path[-1]].append(value) # finally start web server host = app_status['settings']['frontend']['host'] port = app_status['settings']['frontend']['port'] eventlet.wsgi.server(eventlet.listen((host, port)), self.__app) def __update_application_status(self, status): self.__status = status self.__sio.emit('app_status', status)