This repository has been archived on 2020-03-24. You can view files and clone it, but cannot push or open issues or pull requests.
quay/endpoints/realtime.py

81 lines
2.1 KiB
Python

import logging
import redis
import json
from functools import wraps
from flask import request, make_response, Blueprint, abort, Response
from flask.ext.login import current_user, logout_user
from data import model, userevent
from app import app
logger = logging.getLogger(__name__)
realtime = Blueprint('realtime', __name__)
def api_login_required(f):
@wraps(f)
def decorated_view(*args, **kwargs):
if not current_user.is_authenticated():
abort(401)
if (current_user and current_user.db_user() and
current_user.db_user().organization):
abort(401)
if (current_user and current_user.db_user() and
current_user.db_user().robot):
abort(401)
return f(*args, **kwargs)
return decorated_view
@realtime.route("/user/")
@api_login_required
def index():
debug_template = """
<html>
<head>
</head>
<body>
<h1>Server sent events</h1>
<div id="event"></div>
<script type="text/javascript">
var eventOutputContainer = document.getElementById("event");
var evtSrc = new EventSource("/realtime/user/subscribe?events=docker-cli");
evtSrc.onmessage = function(e) {
console.log(e.data);
eventOutputContainer.innerHTML = e.data;
};
</script>
</body>
</html>
"""
return(debug_template)
@realtime.route("/user/test")
@api_login_required
def user_test():
evt = userevent.UserEvent('logs.quay.io', current_user.db_user().username)
evt.publish_event_data('test', {'foo': 2})
return 'OK'
@realtime.route("/user/subscribe")
@api_login_required
def user_subscribe():
def wrapper(listener):
for event_id, data in listener.event_stream():
message = {'event': event_id, 'data': data}
json_string = json.dumps(message)
yield 'data: %s\n\n' % json_string
events = request.args.get('events', '').split(',')
if not events:
abort(404)
listener = userevent.UserEventListener('logs.quay.io', current_user.db_user().username, events)
return Response(wrapper(listener), mimetype="text/event-stream")