Preliminary work for better socket.io event handling.

This commit is contained in:
Patrick Jentsch 2021-09-22 13:52:51 +02:00
parent d29190907f
commit e0219e84c9

View File

@ -7,7 +7,7 @@ from ..models import User
''' '''
' A list containing session ids of connected Socket.IO sessions, to keep track ' A list containing session ids of Socket.IO sessions, to keep track
' of all connected sessions, which can be used to determine the runtimes of ' of all connected sessions, which can be used to determine the runtimes of
' associated background tasks. ' associated background tasks.
''' '''
@ -22,21 +22,22 @@ sessions = []
def socketio_connect(): def socketio_connect():
''' '''
' The Socket.IO module creates a session id (sid) for each request. ' The Socket.IO module creates a session id (sid) for each request.
' On connect the sid is saved in the connected sessions list. ' On connect the sid is saved in the sessions list.
''' '''
sessions.append(request.sid) sessions.append(request.sid)
return {'code': 200, 'msg': 'OK'}
@socketio.on('disconnect') @socketio.on('disconnect')
def socketio_disconnect(): def socketio_disconnect():
''' '''
' On disconnect the session id gets removed from the connected sessions ' On disconnect the session id gets removed from the sessions list.
' list.
''' '''
try: try:
sessions.remove(request.sid) sessions.remove(request.sid)
except ValueError: except ValueError:
pass pass
return {'code': 200, 'msg': 'OK'}
@socketio.on('start_user_session') @socketio.on('start_user_session')
@ -58,18 +59,15 @@ def socketio_start_user_session(user_id):
join_room(room) join_room(room)
@socketio.on('stop_user_session') @socketio.on('users.request')
@socketio_login_required @socketio_login_required
def socketio_stop_user_session(user_id): def socketio_start_session(user_id):
user = User.query.get(user_id) user = User.query.get(user_id)
if user is None: if user is None:
response = {'code': 404, 'msg': 'Not found'} response = {'code': 404, 'msg': 'Not found'}
socketio.emit('stop_user_session', response, room=request.sid)
elif not (user == current_user or current_user.is_administrator): elif not (user == current_user or current_user.is_administrator):
response = {'code': 403, 'msg': 'Forbidden'} response = {'code': 403, 'msg': 'Forbidden'}
socketio.emit('stop_user_session', response, room=request.sid)
else: else:
response = {'code': 200, 'msg': 'OK'} response = {'code': 200, 'msg': 'OK', 'payload': user.to_dict()}
socketio.emit('stop_user_session', response, room=request.sid) join_room('users.{}'.format(user.id))
room = 'user_{}'.format(user.id) return response
leave_room(room)