from flask_jwt_extended import verify_jwt_in_request, get_jwt_identity, verify_jwt_in_request, decode_token from flask_socketio import emit, disconnect from flask import current_app, request from common.extensions import socketio @socketio.on('connect') def handle_connect(): try: # Extract token from the auth object token = request.args.get('token') if not token: raise Exception("Missing Authorization Token") current_app.logger.debug(f'SocketIO: Received token: {token}') # Verify token decoded_token = decode_token(token.split(" ")[1]) # Split to remove "Bearer " prefix tenant_id = decoded_token["identity"]["tenant_id"] current_app.logger.info(f'SocketIO: Tenant {decoded_token["identity"]["tenant_id"]} connected') # communicate connection to client emit('connect', {'status': 'Connected', 'tenant_id': tenant_id}) except Exception as e: current_app.logger.error(f'SocketIO: Connection failed: {e}') # communicate connection problem to client emit('connect', {'status': 'Connection Failed'}) disconnect() @socketio.on('disconnect') def handle_disconnect(): current_app.logger.debug('SocketIO: Client disconnected') @socketio.on('user_message') def handle_message(data): try: current_app.logger.debug(f"SocketIO: Received message from tenant {data['tenantId']}: {data['message']}") verify_jwt_in_request() current_tenant = get_jwt_identity() print(f'Tenant {current_tenant["tenant_id"]} sent a message: {data}') # Store interaction in the database response = { 'tenantId': data['tenantId'], 'message': 'This is a bot response. Actual implementation still required.', 'messageId': 'bot-message-id', 'algorithm': 'alg1' } current_app.logger.debug(f"SocketIO: Bot response: {response}") emit('bot_response', response, broadcast=True) except Exception as e: current_app.logger.error(f'SocketIO: Message handling failed: {e}') disconnect()