from flask import current_app, request from flask_login import current_user from . import db, socketio from .decorators import socketio_admin_required, socketio_login_required from .models import User import json import jsonpatch ''' ' A list containing session ids of connected Socket.IO sessions, to keep track ' of all connected sessions, which is used to determine the runtimes of ' associated background tasks. ''' connected_sessions = [] @socketio.on('connect') def connect(): ''' ' The Socket.IO module creates a session id (sid) for each request. ' On connect the sid is saved in the connected sessions list. ''' connected_sessions.append(request.sid) @socketio.on('disconnect') def disconnect(): ''' ' On disconnect the session id gets removed from the connected sessions ' list. ''' connected_sessions.remove(request.sid) @socketio.on('start_user_session') @socketio_login_required def start_user_session(user_id): if not (current_user.id == user_id or current_user.is_administrator): return socketio.start_background_task(user_session, current_app._get_current_object(), user_id, request.sid) def user_session(app, user_id, session_id): ''' ' Sends initial user data to the client. Afterwards it checks every 3s if ' changes to the initial values appeared. If changes are detected, a ' RFC 6902 compliant JSON patch gets send. ''' init_event = 'user_{}_init'.format(user_id) patch_event = 'user_{}_patch'.format(user_id) with app.app_context(): # Gather current values from database. user = User.query.get(user_id) user_dict = user.to_dict() # Send initial values to the client. socketio.emit(init_event, json.dumps(user_dict), room=session_id) while session_id in connected_sessions: # Get new values from the database db.session.refresh(user) new_user_dict = user.to_dict() # Compute JSON patches. user_patch = jsonpatch.JsonPatch.from_diff(user_dict, new_user_dict) # In case there are patches, send them to the client. if user_patch: socketio.emit(patch_event, user_patch.to_string(), room=session_id) # Set new values as references for the next iteration. user_dict = new_user_dict socketio.sleep(3)