2014-05-04 17:26:43 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
# vi:si:et:sw=4:sts=4:ts=4
|
|
|
|
from __future__ import division
|
|
|
|
|
|
|
|
from tornado.websocket import WebSocketHandler
|
|
|
|
from tornado.ioloop import IOLoop
|
|
|
|
import json
|
|
|
|
|
2014-05-21 22:41:29 +00:00
|
|
|
from oxtornado import json_dumps
|
2014-05-04 17:26:43 +00:00
|
|
|
|
|
|
|
import state
|
|
|
|
|
2014-05-18 03:01:24 +00:00
|
|
|
import logging
|
2014-05-17 14:26:59 +00:00
|
|
|
logger = logging.getLogger('oml.websocket')
|
|
|
|
|
2014-05-04 17:26:43 +00:00
|
|
|
|
|
|
|
class Handler(WebSocketHandler):
|
|
|
|
|
2014-08-12 12:51:38 +00:00
|
|
|
def check_origin(self, origin):
|
|
|
|
# allow access to websocket from site, installer and loader (local file)
|
|
|
|
return self.request.host in origin \
|
2014-08-12 13:35:50 +00:00
|
|
|
or origin == 'http://127.0.0.1:9842' \
|
2014-08-12 12:51:38 +00:00
|
|
|
or origin == 'null'
|
|
|
|
|
2014-05-04 17:26:43 +00:00
|
|
|
def open(self):
|
2014-08-12 13:35:50 +00:00
|
|
|
if self.request.headers['origin'] not in ('null', 'http://127.0.0.1:9842') \
|
2014-08-12 12:51:38 +00:00
|
|
|
and self.request.host not in self.request.headers['origin']:
|
2014-05-17 14:26:59 +00:00
|
|
|
logger.debug('reject cross site attempt to open websocket %s', self.request)
|
2014-05-14 09:57:11 +00:00
|
|
|
self.close()
|
2014-05-26 11:21:19 +00:00
|
|
|
if self not in state.websockets:
|
|
|
|
state.websockets.append(self)
|
|
|
|
|
2014-05-04 17:26:43 +00:00
|
|
|
|
|
|
|
#websocket calls
|
|
|
|
def on_message(self, message):
|
2014-05-26 11:21:19 +00:00
|
|
|
action, data = json.load(message)
|
|
|
|
if state.tasks:
|
|
|
|
state.tasks.queue(action, data)
|
2014-05-04 17:26:43 +00:00
|
|
|
|
|
|
|
def on_close(self):
|
2014-05-26 11:21:19 +00:00
|
|
|
if self in state.websockets:
|
|
|
|
state.websockets.remove(self)
|
|
|
|
|
|
|
|
def post(self, event, data):
|
|
|
|
message = json_dumps([event, data])
|
|
|
|
main = IOLoop.instance()
|
|
|
|
main.add_callback(lambda: self.write_message(message))
|
2014-05-04 17:26:43 +00:00
|
|
|
|
|
|
|
def trigger_event(event, data):
|
|
|
|
if len(state.websockets):
|
2014-05-17 14:57:34 +00:00
|
|
|
logger.debug('trigger event %s %s %s', event, data, len(state.websockets))
|
2014-05-04 17:26:43 +00:00
|
|
|
for ws in state.websockets:
|
|
|
|
try:
|
2014-05-26 11:21:19 +00:00
|
|
|
ws.post(event, data)
|
2014-05-04 17:26:43 +00:00
|
|
|
except:
|
2014-05-18 03:01:24 +00:00
|
|
|
logger.debug('failed to send to ws %s %s %s', ws, event, data, exc_info=1)
|