From 43b9a8d0fee519857484cf548d7a87bf26ad811a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Louis=20V=C3=A9zina?= <5130500+morpheus65535@users.noreply.github.com> Date: Tue, 17 Dec 2019 23:37:38 -0500 Subject: [PATCH] Added server side events (SSE) to update client datatables. --- bazarr/SSE.py | 33 +++++++++++++++++++++++++++++++++ bazarr/api.py | 16 +++++++++++++++- bazarr/templates/test.html | 7 ++++++- 3 files changed, 54 insertions(+), 2 deletions(-) create mode 100644 bazarr/SSE.py diff --git a/bazarr/SSE.py b/bazarr/SSE.py new file mode 100644 index 000000000..9c9c03183 --- /dev/null +++ b/bazarr/SSE.py @@ -0,0 +1,33 @@ +from __future__ import absolute_import +from collections import deque +import json +import time + + +class EventStream: + """ + This class is used to read or write items to the notifications deque. + """ + + def __init__(self): + self.queue = deque(maxlen=10) + + def write(self, msg): + """ + :param msg: The message to display. + :type msg: str + """ + + self.queue.append("data:" + msg + "\n\n") + + def read(self): + """ + :return: Return the oldest notification available. + :rtype: str + """ + + if self.queue or (len(self.queue) > 0): + return self.queue.popleft() + + +event_stream = EventStream() diff --git a/bazarr/api.py b/bazarr/api.py index 6e94b8932..0f093fa09 100644 --- a/bazarr/api.py +++ b/bazarr/api.py @@ -14,11 +14,14 @@ from database import database from helper import path_replace, path_replace_reverse, path_replace_movie, path_replace_reverse_movie from get_languages import load_language_in_db, alpha2_from_language, alpha3_from_language, language_from_alpha2, \ alpha3_from_alpha2 +from SSE import event_stream from flask import Flask, jsonify, request, render_template +import flask from flask_restful import Resource, Api app = Flask(__name__) +app.debug = True api = Api(app) load_language_in_db() @@ -28,6 +31,17 @@ def test(): return render_template('test.html') +@app.route('/event') +def event(): + return flask.Response(event_stream.read(), mimetype="text/event-stream") + + +@app.route('/write') +def write(): + event_stream.write('fake message') + return "", 200 + + class Badges(Resource): def get(self): result = { @@ -438,4 +452,4 @@ api.add_resource(WantedSeries, '/api/wanted_series') api.add_resource(WantedMovies, '/api/wanted_movies') if __name__ == '__main__': - app.run(port=6767, debug=True) + app.run(port=6767, threaded=True) diff --git a/bazarr/templates/test.html b/bazarr/templates/test.html index 50fc7eff0..a0519eb94 100644 --- a/bazarr/templates/test.html +++ b/bazarr/templates/test.html @@ -23,7 +23,7 @@ \ No newline at end of file