diff --git a/wrolpi/plugins/videos/api.py b/wrolpi/plugins/videos/api.py index 7ab558d5..f218f763 100644 --- a/wrolpi/plugins/videos/api.py +++ b/wrolpi/plugins/videos/api.py @@ -35,10 +35,12 @@ class SettingsAPI(object): return json.dumps({'success': 'Settings saved'}) -def newline_streamer(func): - def add_newlines(*a, **kw): - yield from (f'{i}\n' for i in func(*a, **kw)) - return add_newlines +def json_statuses_streamer(func): + """Wraps status lines in JSON objects. Adds a new line after each JSON string.""" + def wrap(*a, **kw): + yield from (json.dumps({'status': i}) + '\n' for i in func(*a, **kw)) + yield json.dumps({'success': 'stream-complete'}) + '\n' + return wrap @cherrypy.expose @@ -47,11 +49,10 @@ class Refresh(object): def POST(self): cherrypy.response.headers['Content-Type'] = 'text/event-stream' - @newline_streamer + @json_statuses_streamer def streamer(): with get_db_context(commit=True) as (db_conn, db): yield from refresh_videos(db) - yield 'stream-complete' return streamer() @@ -64,12 +65,11 @@ class Download(object): def POST(self): cherrypy.response.headers['Content-Type'] = 'text/event-stream' - @newline_streamer + @json_statuses_streamer def streamer(): with get_db_context(commit=True) as (db_conn, db): yield from update_channels(db_conn, db) yield from download_all_missing_videos(db_conn, db) - yield 'stream-complete' return streamer() diff --git a/wrolpi/plugins/videos/test/test_api.py b/wrolpi/plugins/videos/test/test_api.py index 1362c5e4..c294fe6f 100644 --- a/wrolpi/plugins/videos/test/test_api.py +++ b/wrolpi/plugins/videos/test/test_api.py @@ -57,11 +57,13 @@ class TestAPI(unittest.TestCase): # TODO this test is very fragile :( streamer = api.settings.refresh.POST() - statuses = list(streamer) - self.assertIn('Verifying videos in DB exist in file system\n', statuses) - self.assertIn('Deleting video files no longer in file system\n', statuses) - self.assertIn('Checking Big Buck Bunny directory for new videos\n', statuses) - self.assertEqual('stream-complete\n', statuses[-1]) + statuses = [json.loads(s) for s in streamer] + self.assertEqual({'success': 'stream-complete'}, statuses.pop(-1)) + + statuses = [s['status'] for s in statuses] + self.assertIn('Verifying videos in DB exist in file system', statuses) + self.assertIn('Deleting video files no longer in file system', statuses) + self.assertIn('Checking Big Buck Bunny directory for new videos', statuses) with get_db_context() as (db_conn, db): Video, Channel = db['video'], db['channel']