class Region: def __init__(self, region_group, stream_id, position_x, position_y, caption=None, width=0, height=0, focus_x=None, focus_y=None, text=None, region_id=None): if region_id: self.region_id = region_id else: self.region_id = uuid.uuid4().hex self.region_group = region_group self.stream_id = stream_id self.x = position_x self.y = position_y self.caption = caption self.width = width self.height = height self.focus_x = focus_x self.focus_y = focus_y self.text = text self.visible = True self.spine = Spine() Regions.add(self) self.spine.trigger_event( "visionRegionChange", self.stream_id, {"action":"add", "region":self._region_info()} ) def _region_info(self): return { "region_id": self.region_id, "group": self.region_group, "stream_id": self.stream_id, "x": self.x, "y": self.y, "caption": self.caption, "width": self.width, "height": self.height, "focus_x": self.focus_x, "focus_y": self.focus_y, "text": self.text, "visible": self.visible } def update(self): self.spine.trigger_event( "visionRegionChange", self.stream_id, {"action":"update", "region":self._region_info()} ) def invalidate(self): Regions.remove(self) self.spine.trigger_event( "visionRegionChange", self.stream_id, {"action":"invalidate", "region":self._region_info()} )
class _SpineProtocol(WebSocketServerProtocol): def __init__(self): self.spine = Spine() WebSocketServerProtocol.__init__(self) self.handlers = {"command": [], "query": [], "event": []} self.authenticated = False self.session = None self.user = None self._authorization = Authorization() def add_command_handler(self, command): found = False for command_handler in self.handlers["command"]: if command_handler.command == command: found = True if not found: self.handlers["command"] += [_WebCommandHandler(command, self)] def add_query_handler(self, query): found = False for query_handler in self.handlers["query"]: if query_handler.query == query: found = True if not found: self.handlers["query"] += [_WebQueryHandler(query, self)] def add_event_handler(self, event, id_event): #print("ah", event, id_event) found = False for event_handler in self.handlers["event"]: if event_handler.event == event and event_handler.id_event == id_event: found = True if not found: self.handlers["event"] += [_WebEventHandler(event, id_event, self)] def send_response(self, id, response, state="ok", message=""): res = { "id": id, "messageType": "response", "state": state, "message": message, "response": response } jsonres = json.dumps(res, ensure_ascii=False).encode('utf8') self.sendMessage(jsonres, False) def onConnect(self, request): #print("Web socket Client connecting: {}".format(request.peer)) pass def onOpen(self): if self._authorization.active: res = {"messageType": "authenticate"} else: self.authenticated = True res = { "messageType": "session_authenticated", "session": "123456", } jsonres = json.dumps(res, ensure_ascii=False).encode('utf8') self.sendMessage(jsonres, False) def onMessage(self, payload, is_binary): try: obj = json.loads(payload.decode('utf8')) if obj["messageType"] == "authenticate": session, user = self._authorization.authorize( obj["userName"], obj["password"]) if session is None: print("authorization failed for:", obj["userName"]) res = { "messageType": "authentication_failed", } #self.close() else: self.session = session self.user = user self.authenticated = True res = { "messageType": "session_authenticated", "session": session, } jsonres = json.dumps(res, ensure_ascii=False).encode('utf8') self.sendMessage(jsonres, False) elif obj["messageType"] == "logoff": self.authenticated = False self.session = None self._authorization.remove_session(obj["session"]) res = {"messageType": "session_logoff"} jsonres = json.dumps(res, ensure_ascii=False).encode('utf8') self.sendMessage(jsonres, False) else: self.spine.log.debug("WS onMessage:{0}", obj) if not self.authenticated: pass elif obj["messageType"] == "query": res = self.spine.send_query(obj["query"], *obj["args"], injected="socketSpine", session=self.user) self.spine.log.debug("query response:{0}", res) self.send_response(obj["id"], res) elif obj["messageType"] == "registerQueryHandler": self.add_query_handler(obj["query"]) self.send_response(None, None) elif obj["messageType"] == "command": self.spine.send_command(obj["command"], *obj["args"], injected="socketSpine", session=self.user) self.send_response(obj["id"], None) elif obj["messageType"] == "registerCommandHandler": self.add_command_handler(obj["command"]) self.send_response(obj["id"], None) elif obj["messageType"] == "event": self.spine.trigger_event(obj["event"], obj["id"], obj["args"], injected="socketSpine") self.send_response(obj["id"], None) elif obj["messageType"] == "registerEventHandler": self.add_event_handler(obj["event"], obj["eventId"]) self.send_response(obj["id"], None) except: self.spine.log.exception("WS onMessage exception")
class _SpineProtocol(WebSocketServerProtocol): loop = None def __init__(self): self.spine = Spine() WebSocketServerProtocol.__init__(self) self.handlers = {"command":[], "query":[], "event":[], "stream":[]} self.authenticated = False self.session = None self.user = None self._authorization = Authorization() @classmethod def broadcast_message(cls, connection, data, is_binary=False): #for c in set(cls.connections): cls.loop.call_soon_threadsafe(cls.sendMessage, connection, data, is_binary) def add_command_handler(self, command): found = False for command_handler in self.handlers["command"]: if command_handler.command == command: found = True if not found: self.handlers["command"] += [_WebCommandHandler(command, self)] def add_query_handler(self, query): found = False for query_handler in self.handlers["query"]: if query_handler.query == query: found = True if not found: self.handlers["query"] += [_WebQueryHandler(query, self)] def add_event_handler(self, event, id_event): found = False for event_handler in self.handlers["event"]: if event_handler.event == event and event_handler.id_event == id_event: found = True if not found: self.handlers["event"] += [_WebEventHandler(event, id_event, self)] def add_stream_handler(self, stream_id, stream_event): found = False for stream_handler in self.handlers["stream"]: if stream_handler.stream_id == stream_id: if stream_event and stream_handler.stream_event == stream_event: found = True elif not stream_event: found = True if not found: self.handlers["stream"] += [_WebStreamHandler(stream_id, stream_event, self)] def remove_stream_handler(self, stream_id, stream_event): #print("r", stream_id, stream_event) found_handler = None for stream_handler in self.handlers["stream"]: if stream_handler.stream_id == stream_id: if stream_event and stream_handler.stream_event == stream_event: found_handler = stream_handler elif not stream_event: found_handler = stream_handler if found_handler: found_handler.close() self.handlers["stream"].remove(found_handler) def send_response(self, id, response, state="ok", message=""): res = { "id":id, "messageType":"response", "state":state, "message":message, "response":response } jsonres = json.dumps(res, ensure_ascii=False).encode('utf8') self.sendMessage(jsonres, False) def onConnect(self, request): pass def onOpen(self): if self._authorization.active: res = { "messageType":"authenticate" } else: self.authenticated = True res = { "messageType":"session_authenticated", "session":"123456", } jsonres = json.dumps(res, ensure_ascii=False).encode('utf8') self.sendMessage(jsonres, False) # @asyncio.coroutine # def async_query(self, query, query_args, injected, session): # def do_req(): # return self.spine.send_query(query, *query_args, injected=injected, session=session) # #self.spine.log.debug("query response:{0}", res) # #self.send_response(obj["id"], res) # #return requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass')) # req = self.loop.run_in_executor(None, do_req) # resp = yield from req # return resp def onMessage(self, payload, is_binary): try: obj = json.loads(payload.decode('utf8')) if obj["messageType"] == "authenticate": session, user = self._authorization.authorize(obj["userName"], obj["password"]) if session is None: if obj["userName"] == "anonymous": self.spine.log.warning("Anonymous user disabled") else: self.spine.log.warning("authorization failed for: %s", obj["userName"]) res = { "messageType":"authentication_failed", } #self.close() else: self.session = session self.user = user self.authenticated = True res = { "messageType":"session_authenticated", "session":session, } jsonres = json.dumps(res, ensure_ascii=False).encode('utf8') self.sendMessage(jsonres, False) elif obj["messageType"] == "logoff": self.authenticated = False self.session = None self._authorization.remove_session(obj["session"]) res = { "messageType":"session_logoff" } jsonres = json.dumps(res, ensure_ascii=False).encode('utf8') self.sendMessage(jsonres, False) else: #self.spine.log.debug("WS onMessage:{0}", obj) if not self.authenticated: pass elif obj["messageType"] == "query": #res = yield from self.async_query(obj["query"], obj["args"], injected="socketSpine", session=self.user) res = self.spine.send_query(obj["query"], *obj["args"], injected="socketSpine", session=self.user) self.spine.log.debug("query response:{0}", res) self.send_response(obj["id"], res) elif obj["messageType"] == "registerQueryHandler": self.add_query_handler(obj["query"]) self.send_response(None, None) elif obj["messageType"] == "command": self.spine.send_command(obj["command"], *obj["args"], injected="socketSpine", session=self.user) self.send_response(obj["id"], None) elif obj["messageType"] == "registerCommandHandler": self.add_command_handler(obj["command"]) self.send_response(obj["id"], None) elif obj["messageType"] == "event": self.spine.trigger_event( obj["event"], obj["id"], obj["args"], injected="socketSpine" ) self.send_response(obj["id"], None) elif obj["messageType"] == "registerEventHandler": self.add_event_handler(obj["event"], obj["eventId"]) self.send_response(obj["id"], None) elif obj["messageType"] == "registerStreamHandler": self.add_stream_handler(obj["streamId"], obj["streamEvent"]) self.send_response(obj["id"], None) elif obj["messageType"] == "removeStreamHandler": self.remove_stream_handler(obj["streamId"], obj["streamEvent"]) self.send_response(obj["id"], None) except: self.spine.log.exception("WS onMessage exception")