Beispiel #1
0
 def on_message(self, message):
     print('received message: %s' %message)
     data = message.split("_")
     id = data[0]
     data = data[1:]
     if id == "exit":
         ioloop.add_callback(ioloop.stop)
     if id == "set":
         value = int(data[1])
         pin = int(data[0])
         change_pin(pin,value)
     elif id == "remove":
         ioloop.remove_timeout(rules[int(data[0])])
         rules.pop(int(data[0]))
         send_message("remove_"+data[0])
     elif id == "ruleon":
         value = int(data[1])
         pin = int(data[0])
         timestamp = time.mktime(datetime.datetime(int(data[3]),int(data[4]),int(data[5]),int(data[6]),int(data[7]),int(data[8])).timetuple())
         ioloop.add_callback(setTimmer,timestamp,pin,value,message)
     elif id == "rulein":
         value = int(data[1])
         pin = int(data[0])
         timestamp = time.time()+int(data[3])*3600+int(data[4])*60+int(data[5])
         ioloop.add_callback(setTimmer,timestamp,pin,value,message)
Beispiel #2
0
    def authenticate_client(self, msg):
        if self.authenticated:
            self.session.send_message({
                'req_id': msg['req_id'],
                'type': 'response',
                'response': {
                    'result': 'error',
                    'msg': 'Already authenticated'
                }
            })
            return

        user_profile = get_user_profile(self.browser_session_id)
        if user_profile is None:
            raise SocketAuthError('Unknown or missing session')
        self.session.user_profile = user_profile

        if msg['request']['csrf_token'] != self.csrf_token:
            raise SocketAuthError('CSRF token does not match that in cookie')

        if not 'queue_id' in msg['request']:
            raise SocketAuthError("Missing 'queue_id' argument")

        queue_id = msg['request']['queue_id']
        client = get_client_descriptor(queue_id)
        if client is None:
            raise SocketAuthError('Bad event queue id: %s' % (queue_id, ))

        if user_profile.id != client.user_profile_id:
            raise SocketAuthError(
                "You are not the owner of the queue with id '%s'" %
                (queue_id, ))

        self.authenticated = True
        register_connection(queue_id, self)

        response = {
            'req_id': msg['req_id'],
            'type': 'response',
            'response': {
                'result': 'success',
                'msg': ''
            }
        }

        status_inquiries = msg['request'].get('status_inquiries')
        if status_inquiries is not None:
            results = {}
            for inquiry in status_inquiries:
                status = redis_client.hgetall(req_redis_key(inquiry))
                if len(status) == 0:
                    status['status'] = 'not_received'
                if 'response' in status:
                    status['response'] = ujson.loads(status['response'])
                results[str(inquiry)] = status
            response['response']['status_inquiries'] = results

        self.session.send_message(response)
        ioloop = tornado.ioloop.IOLoop.instance()
        ioloop.remove_timeout(self.timeout_handle)
Beispiel #3
0
 def accept(self, player):
     self.accepted.add(player)
     self.host.broadcast(self.user_sockets, make_pkt("game.invite.accept", self.make_id_pkt(player.uname)))
     # Start game if everybody has accepted and cancel the invite timeout
     if self.accepted == set(self.user_sockets):
         ioloop.remove_timeout(self.invite_tout_handle)
         self.start()
Beispiel #4
0
def remove_timeout(handler): 
    """ 
    Removes the given timeout. 

    Thin wrapper over Tornado's `IOLoop.add_timeout`. 
    """
    ioloop = tornado.ioloop.IOLoop.instance()
    ioloop.remove_timeout(handler) 
    def _timer_stop(self):
        if self._timer is None:
            return
        elif self._single:
            ioloop = tornado.ioloop.IOLoop.instance()
            ioloop.remove_timeout(self._timer)
        else:
            self._timer.stop()

        self._timer = None
    def _timer_stop(self):
        if self._timer is None:
            return
        elif self._single:
            ioloop = tornado.ioloop.IOLoop.instance()
            ioloop.remove_timeout(self._timer)
        else:
            self._timer.stop()

        self._timer = None
Beispiel #7
0
    def authenticate_client(self, msg: Dict[str, Any]) -> None:
        if self.authenticated:
            self.session.send_message({'req_id': msg['req_id'], 'type': 'response',
                                       'response': {'result': 'error',
                                                    'msg': 'Already authenticated'}})
            return

        user_profile = get_user_profile(self.browser_session_id)
        if user_profile is None:
            raise JsonableError(_('Unknown or missing session'))
        self.session.user_profile = user_profile

        if 'csrf_token' not in msg['request']:
            # Debugging code to help with understanding #6961
            logging.error("Invalid websockets auth request: %s" % (msg['request'],))
            raise JsonableError(_('CSRF token entry missing from request'))
        if not _compare_salted_tokens(msg['request']['csrf_token'], self.csrf_token):
            raise JsonableError(_('CSRF token does not match that in cookie'))

        if 'queue_id' not in msg['request']:
            raise JsonableError(_("Missing 'queue_id' argument"))

        queue_id = msg['request']['queue_id']
        client = get_client_descriptor(queue_id)
        if client is None:
            raise BadEventQueueIdError(queue_id)

        if user_profile.id != client.user_profile_id:
            raise JsonableError(_("You are not the owner of the queue with id '%s'") % (queue_id,))

        self.authenticated = True
        register_connection(queue_id, self)

        response = {'req_id': msg['req_id'], 'type': 'response',
                    'response': {'result': 'success', 'msg': ''}}

        status_inquiries = msg['request'].get('status_inquiries')
        if status_inquiries is not None:
            results = {}  # type: Dict[str, Dict[str, str]]
            for inquiry in status_inquiries:
                status = redis_client.hgetall(req_redis_key(inquiry))  # type: Dict[bytes, bytes]
                if len(status) == 0:
                    result = {'status': 'not_received'}
                elif b'response' not in status:
                    result = {'status': status[b'status'].decode('utf-8')}
                else:
                    result = {'status': status[b'status'].decode('utf-8'),
                              'response': ujson.loads(status[b'response'])}
                results[str(inquiry)] = result
            response['response']['status_inquiries'] = results

        self.session.send_message(response)
        ioloop = tornado.ioloop.IOLoop.instance()
        ioloop.remove_timeout(self.timeout_handle)
Beispiel #8
0
    def authenticate_client(self, msg: Dict[str, Any]) -> None:
        if self.authenticated:
            self.session.send_message({'req_id': msg['req_id'], 'type': 'response',
                                       'response': {'result': 'error',
                                                    'msg': 'Already authenticated'}})
            return

        user_profile = get_user_profile(self.browser_session_id)
        if user_profile is None:
            raise JsonableError(_('Unknown or missing session'))
        self.session.user_profile = user_profile

        if 'csrf_token' not in msg['request']:
            # Debugging code to help with understanding #6961
            logging.error("CSRF token missing from websockets auth request: %s" % (msg['request'],))
            raise JsonableError(_('CSRF token entry missing from request'))
        if not _compare_salted_tokens(msg['request']['csrf_token'], self.csrf_token):
            raise JsonableError(_('CSRF token does not match that in cookie'))

        if 'queue_id' not in msg['request']:
            raise JsonableError(_("Missing 'queue_id' argument"))

        queue_id = msg['request']['queue_id']
        client = get_client_descriptor(queue_id)
        if client is None:
            raise BadEventQueueIdError(queue_id)

        if user_profile.id != client.user_profile_id:
            raise JsonableError(_("You are not the owner of the queue with id '%s'") % (queue_id,))

        self.authenticated = True
        register_connection(queue_id, self)

        response = {'req_id': msg['req_id'], 'type': 'response',
                    'response': {'result': 'success', 'msg': ''}}

        status_inquiries = msg['request'].get('status_inquiries')
        if status_inquiries is not None:
            results = {}  # type: Dict[str, Dict[str, str]]
            for inquiry in status_inquiries:
                status = redis_client.hgetall(req_redis_key(inquiry))  # type: Dict[bytes, bytes]
                if len(status) == 0:
                    result = {'status': 'not_received'}
                elif b'response' not in status:
                    result = {'status': status[b'status'].decode('utf-8')}
                else:
                    result = {'status': status[b'status'].decode('utf-8'),
                              'response': ujson.loads(status[b'response'])}
                results[str(inquiry)] = result
            response['response']['status_inquiries'] = results

        self.session.send_message(response)
        ioloop = tornado.ioloop.IOLoop.instance()
        ioloop.remove_timeout(self.timeout_handle)
Beispiel #9
0
 def refresh_timeout(self, callback, timeout=None):
     if self.callback is not None:
         raise MultipleRequest
     if self.replies is None:
         raise InvalidRequest
     if self.timeout is not None:
         ioloop.remove_timeout(self.timeout)
         self.timeout = None
     self.callback = callback
     if timeout is not None:
         self.timeout = ioloop.add_timeout(
             datetime.timedelta(seconds=timeout), self._timeout)
Beispiel #10
0
 def refresh_timeout(self, callback, timeout=None):
     if self.callback is not None:
         raise MultipleRequest
     if self.replies is None:
         raise InvalidRequest
     if self.timeout is not None:
         ioloop.remove_timeout(self.timeout)
         self.timeout = None
     self.callback = callback
     if timeout is not None:
         self.timeout = ioloop.add_timeout(
             datetime.timedelta(seconds=timeout), self._timeout)
Beispiel #11
0
 def disconnect_handler(self, client_closed: bool=False) -> None:
     if self.current_handler_id:
         clear_descriptor_by_handler_id(self.current_handler_id, None)
         clear_handler_by_id(self.current_handler_id)
         if client_closed:
             logging.info("Client disconnected for queue %s (%s via %s)" %
                          (self.event_queue.id, self.user_profile_email,
                           self.current_client_name))
     self.current_handler_id = None
     self.current_client_name = None
     if self._timeout_handle is not None:
         ioloop = tornado.ioloop.IOLoop.instance()
         ioloop.remove_timeout(self._timeout_handle)
         self._timeout_handle = None
Beispiel #12
0
    def read_block(self, obd2id, mode, pid, timeout=0.5):
        current = greenlet.getcurrent()
        s = self.read_waiters[(obd2id, mode, pid)]
        s.add(current)

        def timeout_cb():
            s.remove(current)
            current.throw(IOError('Read timeout exceeded'))

        _t = ioloop.add_timeout(time.time() + timeout, timeout_cb)
        frame = current.parent.switch()
        ioloop.remove_timeout(_t)

        return frame
Beispiel #13
0
  def read_block(self, obd2id, mode, pid, timeout=0.5):
    current = greenlet.getcurrent()
    s = self.read_waiters[(obd2id, mode, pid)]
    s.add(current)

    def timeout_cb():
      s.remove(current)
      current.throw(IOError('Read timeout exceeded'))

    _t = ioloop.add_timeout(time.time() + timeout, timeout_cb)
    frame = current.parent.switch()
    ioloop.remove_timeout(_t)

    return frame
Beispiel #14
0
 def text(self, text, timeout=None):
     """Draws a text with an optional timeout in miliseconds.
     After that, the last frame is restored.
     """
     image = Image.new(self.device.mode, self.device.size)
     draw = ImageDraw.Draw(image)
     draw.text((5, 35), text, fill='white', align='center', font=self.font)
     self.draw(image, frame=False)
     if timeout:
         ioloop = tornado.ioloop.IOLoop.current()
         if self.runner:
             ioloop.remove_timeout(self.runner)
         func = functools.partial(self.draw, self.frame, frame=False)
         self.runner = ioloop.call_later(timeout / 1000.0, func)
Beispiel #15
0
 def disconnect_handler(self, client_closed: bool=False) -> None:
     if self.current_handler_id:
         clear_descriptor_by_handler_id(self.current_handler_id, None)
         clear_handler_by_id(self.current_handler_id)
         if client_closed:
             logging.info("Client disconnected for queue %s (%s via %s)" %
                          (self.event_queue.id, self.user_profile_email,
                           self.current_client_name))
     self.current_handler_id = None
     self.current_client_name = None
     if self._timeout_handle is not None:
         ioloop = tornado.ioloop.IOLoop.instance()
         ioloop.remove_timeout(self._timeout_handle)
         self._timeout_handle = None
Beispiel #16
0
 def send(self, source, message):
     if self.replies is None or source not in self.replies:
         raise InvalidRequest
     if self.replies[source] is not None:
         raise MultipleRequest
     self.replies[source] = message
     self.replies_remaining -= 1
     if self.replies_remaining == 0:
         if self.timeout is not None:
             ioloop.remove_timeout(self.timeout)
             self.timeout = None
         if self.callback is not None:
             callback, self.callback = self.callback, None
             replies, self.replies = self.replies, None
             callback(replies)
Beispiel #17
0
 def send(self, source, message):
     if self.replies is None or source not in self.replies:
         raise InvalidRequest
     if self.replies[source] is not None:
         raise MultipleRequest
     self.replies[source] = message
     self.replies_remaining -= 1
     if self.replies_remaining == 0:
         if self.timeout is not None:
             ioloop.remove_timeout(self.timeout)
             self.timeout = None
         if self.callback is not None:
             callback, self.callback = self.callback, None
             replies, self.replies = self.replies, None
             callback(replies)
Beispiel #18
0
 def push():
     for app, app_config in info.gramexlog.apps.items():
         for item in app_config.queue:
             item['_index'] = app_config.get('index', app)
         try:
             helpers.bulk(app_config.conn, app_config.queue)
             app_config.queue.clear()
         except Exception:
             # TODO: If the connection broke, re-create it
             # This generic exception should be caught for thread to continue its execution
             app_log.exception('gramexlog: push to %s failed', app)
     if 'handle' in info.gramexlog:
         ioloop.remove_timeout(info.gramexlog.handle)
     # Call again after flush seconds
     info.gramexlog.handle = ioloop.call_later(flush, push)
Beispiel #19
0
    def authenticate_client(self, msg):
        # type: (Dict[str, Any]) -> None
        if self.authenticated:
            self.session.send_message({'req_id': msg['req_id'], 'type': 'response',
                                       'response': {'result': 'error', 'msg': 'Already authenticated'}})
            return

        user_profile = get_user_profile(self.browser_session_id)
        if user_profile is None:
            raise SocketAuthError('Unknown or missing session')
        self.session.user_profile = user_profile

        if not _compare_salted_tokens(msg['request']['csrf_token'], self.csrf_token):
            raise SocketAuthError('CSRF token does not match that in cookie')

        if 'queue_id' not in msg['request']:
            raise SocketAuthError("Missing 'queue_id' argument")

        queue_id = msg['request']['queue_id']
        client = get_client_descriptor(queue_id)
        if client is None:
            raise SocketAuthError('Bad event queue id: %s' % (queue_id,))

        if user_profile.id != client.user_profile_id:
            raise SocketAuthError("You are not the owner of the queue with id '%s'" % (queue_id,))

        self.authenticated = True
        register_connection(queue_id, self)

        response = {'req_id': msg['req_id'], 'type': 'response',
                    'response': {'result': 'success', 'msg': ''}}

        status_inquiries = msg['request'].get('status_inquiries')
        if status_inquiries is not None:
            results = {}
            for inquiry in status_inquiries:
                status = redis_client.hgetall(req_redis_key(inquiry))
                if len(status) == 0:
                    status['status'] = 'not_received'
                if 'response' in status:
                    status['response'] = ujson.loads(status['response'])
                results[str(inquiry)] = status
            response['response']['status_inquiries'] = results

        self.session.send_message(response)
        ioloop = tornado.ioloop.IOLoop.instance()
        ioloop.remove_timeout(self.timeout_handle)
 def on_game_exited(self):
     if self.ai_interval:
         ioloop.remove_timeout(self.ai_interval)
Beispiel #21
0
 def on_game_exited(self):
     if self.ai_interval:
         ioloop.remove_timeout(self.ai_interval)
Beispiel #22
0
    def end_game(self):
        ioloop.remove_timeout(self.draw_timeout)
        start_draw()

        self.ended = True
Beispiel #23
0
    def stop(self):
        print("Stopping game forced")
        self.end_game()

        while self.timers:
            ioloop.remove_timeout(self.timers.pop())
Beispiel #24
0
 def on_close(self) :
     ioloop = tornado.ioloop.IOLoop.instance()
     if (self.timeout) :
         ioloop.remove_timeout(self.timeout)
Beispiel #25
0
 def cancel(self, uname=None):
     print(self.id, "canceled")
     # It's safe to unconditionally cancel the invite timeout
     ioloop.remove_timeout(self.invite_tout_handle)
     self.host.broadcast(self.user_sockets, make_pkt("game.invite.decline", self.make_id_pkt(uname)))
Beispiel #26
0
def timeout_remove(obj):
  ioloop.remove_timeout(obj)