93 lines
2.7 KiB
Python
93 lines
2.7 KiB
Python
import logging
|
|
import threading
|
|
|
|
from flask_jwt_extended import verify_jwt_in_request, get_current_user, jwt_required, get_jwt_claims, get_jwt_identity
|
|
from flask_login import current_user
|
|
from flask_socketio import SocketIO, emit
|
|
from jwt import ExpiredSignatureError
|
|
|
|
from backend import app
|
|
|
|
logger = logging.getLogger("lrc.websocket")
|
|
|
|
async_mode = 'threading' # set to traditional python threading model
|
|
# async_mode = None
|
|
socketio = SocketIO(app, cors_allowed_origins="*", async_mode=async_mode)
|
|
|
|
|
|
class WebSocketBase:
|
|
def __init__(self, flask_app_context=None):
|
|
if flask_app_context is None:
|
|
self.flask_app_context = app
|
|
self.socket_thread = None
|
|
|
|
def start_websocket_in_thread(self, host=None, port=None, debug=None):
|
|
self.socket_thread = threading.Thread(
|
|
target=self.start_websocket,
|
|
args=(host, port, debug))
|
|
self.socket_thread.start()
|
|
return self.socket_thread
|
|
|
|
def start_websocket(self, host=None, port=None, debug=None):
|
|
if debug is None:
|
|
debug = self.flask_app_context.debug
|
|
socketio.run(self.flask_app_context, host=host, port=port, debug=debug)
|
|
|
|
def send_test_msg(self):
|
|
socketio.emit('test', "tolle nachricht")
|
|
|
|
@staticmethod
|
|
@socketio.on('connect')
|
|
def connect_handler():
|
|
logger.debug("new connection...")
|
|
try:
|
|
print(verify_jwt_in_request())
|
|
print(get_jwt_identity())
|
|
except ExpiredSignatureError:
|
|
logger.info("user is not authenticated! Signature expired.")
|
|
except Exception as e:
|
|
logger.info("user is not authenticated!")
|
|
print(str(e))
|
|
print(type(e))
|
|
print("not allowed!!")
|
|
return False # not allowed here
|
|
logger.debug("user is authenticated")
|
|
print("allowed!")
|
|
return True
|
|
|
|
@staticmethod
|
|
@socketio.on('message')
|
|
def handle_message(message):
|
|
print('received message: ' + message)
|
|
|
|
@staticmethod
|
|
@socketio.on('json')
|
|
def handle_json(json):
|
|
print('received json: ' + str(json))
|
|
|
|
@staticmethod
|
|
def _request_request_recorder_status_update():
|
|
pass
|
|
|
|
@staticmethod
|
|
def _test_on_msg_func():
|
|
pass
|
|
|
|
@staticmethod
|
|
@socketio.on('update_message_test_blabla')
|
|
def handle_msg(msg=None):
|
|
print('received msg: ' + str(msg))
|
|
socketio.on_event('my event', WebSocketBase._test_on_msg_func, namespace='/')
|
|
|
|
@staticmethod
|
|
@socketio.on_error()
|
|
def handle_error(error):
|
|
logger.error(error)
|
|
print(error)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
wsb = WebSocketBase()
|
|
# wsb.start_websocket_in_thread(debug=True)
|
|
wsb.start_websocket(debug=True)
|