nopaque/app/main/events.py

78 lines
2.5 KiB
Python

from flask import request
from flask_login import current_user, login_required
from flask_socketio import send
from .. import create_app, db, socketio
from ..models import User
import json
import os
stop = []
@socketio.on('connect')
@login_required
def connect():
print('{} connected'.format(current_user.username))
send('You entered the room {}'.format(request.sid),
room=request.sid)
if request.sid in stop:
stop.remove(request.sid)
socketio.start_background_task(background_task,
current_user.id,
request.sid)
@socketio.on('disconnect')
@login_required
def disconnect():
stop.append(request.sid)
print('{} disconnected'.format(current_user.username))
def background_task(user_id, session_id):
'''
' Check user jobs every 3 seconds and emit a json patch on change
'''
app = create_app(os.getenv('FLASK_CONFIG') or 'default', main=False)
corpora = []
jobs = []
with app.app_context():
user = db.session.query(User).filter_by(id=user_id).first()
for corpus in user.corpora:
corpora.append(corpus.to_dict())
socketio.emit('init-corpora',
{'data': json.dumps(corpora)},
room=session_id)
for job in user.jobs:
jobs.append(job.to_dict())
socketio.emit('init-jobs',
{'data': json.dumps(jobs)},
room=session_id)
while True:
if session_id in stop:
break
print(session_id + ' running')
socketio.emit('message', 'heartbeat', room=session_id)
new_corpora = []
new_jobs = []
for corpus in user.corpora:
new_corpora.append(corpus.to_dict())
for job in user.jobs:
new_jobs.append(job.to_dict())
# socketio.send('new_corpora: ' + json.dumps(new_corpora), room=session_id)
# socketio.send('new_jobs: ' + json.dumps(new_jobs), room=session_id)
# TODO: calculate json patch: new_corpora <-> corpora
# TODO: calculate json patch: new_jobs <-> jobs
# socketio.emit('update-corpora', {data: corpora_patch}, room=session_id)
# socketio.emit('update-jobs', {data: jobs_patch}, room=session_id)
corpora = new_corpora
jobs = new_jobs
socketio.sleep(3)
# TODO: Implement maximum runtime for this thread.
print(session_id + ' stopped')