2014-09-14 00:22:28 +00:00
|
|
|
import os.path
|
|
|
|
import tornado.web
|
2014-09-16 21:40:25 +00:00
|
|
|
import tornado.websocket
|
|
|
|
import logging
|
2014-09-17 01:58:56 +00:00
|
|
|
import json
|
2014-11-26 03:18:21 +00:00
|
|
|
from .. import flow
|
2014-09-14 00:22:28 +00:00
|
|
|
|
|
|
|
|
2014-09-14 00:33:07 +00:00
|
|
|
class IndexHandler(tornado.web.RequestHandler):
|
|
|
|
def get(self):
|
|
|
|
self.render("index.html")
|
|
|
|
|
|
|
|
|
2014-11-26 03:18:21 +00:00
|
|
|
class WebSocketEventBroadcaster(tornado.websocket.WebSocketHandler):
|
|
|
|
connections = None # raise an error if inherited class doesn't specify its own instance.
|
2014-09-16 21:40:25 +00:00
|
|
|
|
|
|
|
def open(self):
|
2014-11-26 03:18:21 +00:00
|
|
|
self.connections.add(self)
|
2014-09-16 21:40:25 +00:00
|
|
|
|
|
|
|
def on_close(self):
|
2014-11-26 03:18:21 +00:00
|
|
|
self.connections.remove(self)
|
2014-09-16 21:40:25 +00:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def broadcast(cls, type, data):
|
2014-11-26 03:18:21 +00:00
|
|
|
message = json.dumps(
|
|
|
|
{
|
|
|
|
"type": type,
|
|
|
|
"data": data
|
|
|
|
}
|
|
|
|
)
|
2014-09-16 21:40:25 +00:00
|
|
|
for conn in cls.connections:
|
|
|
|
try:
|
2014-11-26 03:18:21 +00:00
|
|
|
conn.write_message(message)
|
2014-09-16 21:40:25 +00:00
|
|
|
except:
|
|
|
|
logging.error("Error sending message", exc_info=True)
|
|
|
|
|
|
|
|
|
2014-11-26 03:18:21 +00:00
|
|
|
class FlowsHandler(tornado.web.RequestHandler):
|
|
|
|
def get(self):
|
|
|
|
self.write(dict(
|
|
|
|
flows=[f.get_state(short=True) for f in self.application.state.flows]
|
|
|
|
))
|
|
|
|
|
|
|
|
|
|
|
|
class FlowUpdates(WebSocketEventBroadcaster):
|
|
|
|
connections = set()
|
|
|
|
|
|
|
|
|
|
|
|
class ClientConnection(WebSocketEventBroadcaster):
|
|
|
|
connections = set()
|
|
|
|
|
|
|
|
|
2014-09-14 00:22:28 +00:00
|
|
|
class Application(tornado.web.Application):
|
2014-11-26 03:18:21 +00:00
|
|
|
def __init__(self, state, debug):
|
|
|
|
self.state = state
|
2014-09-14 00:22:28 +00:00
|
|
|
handlers = [
|
2014-09-14 00:33:07 +00:00
|
|
|
(r"/", IndexHandler),
|
2014-09-16 21:40:25 +00:00
|
|
|
(r"/updates", ClientConnection),
|
2014-11-26 03:18:21 +00:00
|
|
|
(r"/flows", FlowsHandler),
|
|
|
|
(r"/flows/updates", FlowUpdates),
|
2014-09-14 00:22:28 +00:00
|
|
|
]
|
|
|
|
settings = dict(
|
|
|
|
template_path=os.path.join(os.path.dirname(__file__), "templates"),
|
|
|
|
static_path=os.path.join(os.path.dirname(__file__), "static"),
|
|
|
|
xsrf_cookies=True,
|
|
|
|
cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
|
|
|
|
debug=debug,
|
|
|
|
)
|
|
|
|
tornado.web.Application.__init__(self, handlers, **settings)
|
|
|
|
|