예제 #1
0
    def on_message(self, msg):
        data = proto.json_decode(msg)

        if data['type'] == 'auth':
            if bool(data.get('sid', None)):
                try:
                    int(data['sid'])  # check that sid is number, not word
                    self.user_sid = data['sid']
                    self.user_login = yield tornado.gen.Task(
                        self.client.hget, 'sid:login:all', self.user_sid)
                    self.users[self.user_sid] = self
                    self.user_timezone = yield tornado.gen.Task(
                        self.client.hget, 'timezones', self.user_sid)
                    self.timezones[self.user_sid] = self.user_timezone
                    self.authenticated = True
                    self.send(
                        proto.json_encode({
                            "body": "You was authorized",
                            'type': 'alert'
                        }))
                except Exception, e:
                    logging.info("bad user's sid: " + str(data['sid']))
            else:
                self.send(
                    proto.json_encode({
                        "body": "You did not authorize",
                        'type': 'alert'
                    }))
                self.close()
예제 #2
0
    def broadcast(self, clients, msg):
        """Optimized `broadcast` implementation. Depending on type of the session, will json-encode
        message once and will call either `send_message` or `send_jsonifed`.

        `clients`
            Clients iterable
        `msg`
            Message to send
        """
        json_msg = None

        count = 0

        for c in clients:
            sess = c.session
            if not sess.is_closed:
                if sess.send_expects_json:
                    if json_msg is None:
                        json_msg = proto.json_encode(msg)
                    sess.send_jsonified(json_msg, False)
                else:
                    sess.send_message(msg, stats=False)

                count += 1

        self.stats.on_pack_sent(count)
예제 #3
0
파일: router.py 프로젝트: kevinlu310/GeThem
    def broadcast(self, clients, msg):
        """Optimized `broadcast` implementation. Depending on type of the session, will json-encode
        message once and will call either `send_message` or `send_jsonifed`.

        `clients`
            Clients iterable
        `msg`
            Message to send
        """
        json_msg = None

        count = 0

        for c in clients:
            sess = c.session
            if not sess.is_closed:
                if sess.send_expects_json:
                    if json_msg is None:
                        json_msg = proto.json_encode(msg)
                    sess.send_jsonified(json_msg, False)
                else:
                    sess.send_message(msg, False)

                count += 1

        self.stats.on_pack_sent(count)
예제 #4
0
    def send(self, message):
        """Send message to the client.

        `message`
            Message to send.
        """
        if not self.is_closed:
            self.session.send_message(proto.json_encode(message))
예제 #5
0
    def send_message(self, msg, stats=True, binary=False):
        """Send or queue outgoing message

        `msg`
            Message to send
        `stats`
            If set to True, will update statistics after operation completes
        """
        self.send_jsonified(proto.json_encode(msg), stats)
예제 #6
0
    def send_message(self, msg, stats=True, binary=False):
        """Send or queue outgoing message

        `msg`
            Message to send
        `stats`
            If set to True, will update statistics after operation completes
        """
        self.send_jsonified(proto.json_encode(msg), stats)
예제 #7
0
 def send_pack(self, message):
     try:
         # TODO: Just do escaping
         self.write('<script>\np(%s);\n</script>\r\n' % proto.json_encode(message))
         self.flush()
     except IOError:
         # If connection dropped, make sure we close offending session instead
         # of propagating error all way up.
         self._detach()
         self.session.delayed_close()
예제 #8
0
    def on_message(self, msg):
        data = proto.json_decode(msg)

        if data['type'] == 'auth':
            if bool(data.get('sid', None)):
                try:
                    int(data['sid'])  # check that sid is number, not word
                    self.user_sid = data['sid']
                    self.user_login = yield tornado.gen.Task(self.client.hget, 'sid:login:all', self.user_sid)
                    self.users[self.user_sid] = self
                    self.user_timezone = yield tornado.gen.Task(self.client.hget, 'timezones', self.user_sid)
                    self.timezones[self.user_sid] = self.user_timezone
                    self.authenticated = True
                    self.send(proto.json_encode({"body": "You was authorized", 'type': 'alert'}))
                except Exception, e:
                    logging.info("bad user's sid: " + str(data['sid']))
            else:
                self.send(proto.json_encode({"body": "You did not authorize", 'type': 'alert'}))
                self.close()
예제 #9
0
    def get(self):
        self.preflight()
        self.disable_cache()
        self.set_header('Content-Type', 'application/json; charset=UTF-8')

        options = dict(websocket=self.server.websockets_enabled,
                       cookie_needed=self.server.cookie_needed,
                       origins=['*:*'],
                       entropy=random.randint(0, MAXSIZE))

        self.write(json_encode(options))
예제 #10
0
 def _start_view_log(self):
     log_path = LOG_DIR
     if log_path is None:
         log_path = os.path.realpath(os.path.join(os.path.realpath(os.path.dirname(__file__)), 'logs'))
     log_path = os.path.join(log_path, self._channel, datetime.now().strftime('%Y'), datetime.now().strftime('%m'))
     self._log = os.path.join(log_path, datetime.now().strftime('%d%m%y.log'))
     if not os.path.isfile(self._log):
         self.send(proto.json_encode({'error': 'Not found logs'}))
     self._last_check = os.stat(self._log)[8]
     self._last_seek = 0
     self._send_new_messages()
예제 #11
0
 def send_pack(self, message):
     try:
         # TODO: Just do escaping
         self.write('<script>\np(%s);\n</script>\r\n' %
                    proto.json_encode(message))
         self.flush()
     except IOError:
         # If connection dropped, make sure we close offending session instead
         # of propagating error all way up.
         self._detach()
         self.session.delayed_close()
예제 #12
0
    def get(self):
        self.preflight()
        self.disable_cache()
        self.set_header('Content-Type', 'application/json; charset=UTF-8')

        options = dict(websocket=self.server.websockets_enabled,
                       cookie_needed=self.server.cookie_needed,
                       origins=['*:*'],
                       entropy=random.randint(0, sys.maxint))

        self.write(json_encode(options))
예제 #13
0
    def broadcast(self, clients, message):
        msg = proto.json_encode(message)

        # We don't want to use len() because clients might be iterator and
        # not a list.
        count = 0

        for c in clients:
            if not c.is_closed:
                c.session.send_message(msg)
                count += 1

        self.session.stats.on_pack_sent(count)
예제 #14
0
 def _send_new_messages(self):
     with open(self._log) as f:
         f.seek(self._last_seek)
         messages = f.readlines()
         res = []
         for m in messages:
             msg = m.split('|')
             res.append({
                 'date': msg[0],
                 'user': msg[1],
                 'message': '|'.join(msg[2:])
             })
         self._last_seek = f.tell()
         self.send(proto.json_encode(res))
예제 #15
0
파일: htmlfile.py 프로젝트: pavanfan/spiro
    def send_pack(self, message):
        # TODO: Just do escaping
        msg = '<script>\np(%s);\n</script>\r\n' % proto.json_encode(message)

        try:
            self.write(msg)
            self.flush()
        except IOError:
            # If connection dropped, make sure we close offending session instead
            # of propagating error all way up.
            self.session.delayed_close()
            self._detach()

        # Close connection based on amount of data transferred
        if self.should_finish(len(msg)):
            self._detach()
            self.safe_finish()
예제 #16
0
    def broadcast_channel(self, chan, clients, msg):
        json_msg = None

        count = 0

        for c in clients:
            sess = c.session
            if not sess.is_closed:
                if sess.send_expects_json:
                    if json_msg is None:
                        json_msg = proto.json_encode(msg)
                    sess.send_jsonified(json_msg, False)
                else:
                    sess.send_message_channel(chan, msg, stats=False)

                count += 1

        self.stats.on_pack_sent(count)
예제 #17
0
    def send_pack(self, message, binary=False):
        if binary:
            raise Exception('binary not supported for HtmlFileTransport')

        # TODO: Just do escaping
        msg = '<script>\np(%s);\n</script>\r\n' % proto.json_encode(message)

        self.active = False

        try:
            self.notify_sent(len(message))

            self.write(msg)
            self.flush(callback=self.send_complete)
        except IOError:
            # If connection dropped, make sure we close offending session instead
            # of propagating error all way up.
            self.session.delayed_close()
            self._detach()
예제 #18
0
    def send_pack(self, message):
        try:
            # TODO: Just escape
            msg = '%s(%s);\r\n' % (self.callback, proto.json_encode(message))

            self.set_header('Content-Type', 'application/javascript; charset=UTF-8')
            self.set_header('Content-Length', len(msg))

            # TODO: Fix me
            self.set_header('Etag', 'dummy')

            self.write(msg)
        except IOError:
            # If connection dropped, make sure we close offending session instead
            # of propagating error all way up.
            self.session.delayed_close()

        self._detach()

        self.safe_finish()
예제 #19
0
    def send_pack(self, message, binary=False):
        if binary:
            raise Exception('binary not supported for JSONPTransport')

        self.active = False

        try:
            # TODO: Just escape
            msg = '%s(%s);\r\n' % (self.callback, proto.json_encode(message))

            self.set_header('Content-Type', 'application/javascript; charset=UTF-8')
            self.set_header('Content-Length', len(msg))

            # TODO: Fix me
            self.set_header('Etag', 'dummy')

            self.write(msg)
            self.flush(callback=self.send_complete)
        except IOError:
            # If connection dropped, make sure we close offending session instead
            # of propagating error all way up.
            self.session.delayed_close()
    def send_pack(self, message, binary=False):
        if binary:
            raise Exception('binary not supported for JSONPTransport')

        self.active = False

        try:
            # TODO: Just escape
            msg = '%s(%s);\r\n' % (self.callback, proto.json_encode(message))

            self.set_header('Content-Type',
                            'application/javascript; charset=UTF-8')
            self.set_header('Content-Length', len(msg))

            # TODO: Fix me
            self.set_header('Etag', 'dummy')

            self.write(msg)
            self.flush(callback=self.send_complete)
        except IOError:
            # If connection dropped, make sure we close offending session instead
            # of propagating error all way up.
            self.session.delayed_close()
예제 #21
0
class PlansqTornadoChat(SockJSConnection):
    users = dict()
    timezones = dict()
    client = tornadoredis_client()

    def on_open(self, info):
        self.authenticated = False
        self.sids_logins = dict()

    @tornado.gen.engine
    def on_message(self, msg):
        data = proto.json_decode(msg)

        if data['type'] == 'auth':
            if bool(data.get('sid', None)):
                try:
                    int(data['sid'])  # check that sid is number, not word
                    self.user_sid = data['sid']
                    self.user_login = yield tornado.gen.Task(
                        self.client.hget, 'sid:login:all', self.user_sid)
                    self.users[self.user_sid] = self
                    self.user_timezone = yield tornado.gen.Task(
                        self.client.hget, 'timezones', self.user_sid)
                    self.timezones[self.user_sid] = self.user_timezone
                    self.authenticated = True
                    self.send(
                        proto.json_encode({
                            "body": "You was authorized",
                            'type': 'alert'
                        }))
                except Exception, e:
                    logging.info("bad user's sid: " + str(data['sid']))
            else:
                self.send(
                    proto.json_encode({
                        "body": "You did not authorize",
                        'type': 'alert'
                    }))
                self.close()

        elif data['type'] == 'message':
            if all([x in data for x in ['type', 'recipient', 'body', 'sender']]) \
                    and data['sender'] == self.user_sid:
                recipient = data['recipient']

                try:
                    int(recipient)  # check that sid is number, not word
                except Exception, e:
                    logging.info('sid of recipient is not number')
                    return

                self.thread = "_".join([
                    str(x)
                    for x in sorted([int(self.user_sid),
                                     int(recipient)])
                ])

                if recipient not in self.sids_logins:
                    recipient_login = yield tornado.gen.Task(
                        self.client.hget, 'sid:login:all', recipient)
                    self.sids_logins[recipient] = recipient_login

                # Save to Redis
                data_to_send = {
                    'thread_id':
                    self.thread,
                    'sender':
                    self.user_login,
                    'recipient':
                    self.sids_logins[recipient],
                    'body':
                    data['body'],
                    'datetime':
                    (datetime.now() - datetime(1970, 1, 1)).total_seconds()
                }

                yield tornado.gen.Task(self.client.sadd,
                                       "thread:" + self.thread,
                                       proto.json_encode(data_to_send))
                yield tornado.gen.Task(self.client.sadd, 'new_threads:all',
                                       "thread:" + self.thread)

                # Send to Socket
                data_to_send['type'] = 'message'
                data_to_send['datetime_'] = utc_to_localtime(
                    data_to_send['datetime'], self.user_timezone)
                self.send(proto.json_encode(data_to_send))

                # if recipient is online
                if recipient in self.users:
                    timezone = self.timezones[
                        recipient] if recipient in self.timezones else utc
                    data_to_send['datetime_'] = utc_to_localtime(
                        data_to_send['datetime'], timezone)
                    self.users[recipient].send(proto.json_encode(data_to_send))
예제 #22
0
    def broadcast(self, clients, message):
        msg = proto.json_encode(message)

        for c in clients:
            if not c.is_closed:
                c.session.send_message(msg)
예제 #23
0
 def _send_stats(self):
     data = proto.json_encode(BroadcastRouter.stats.dump())
     self.send(data)
예제 #24
0
 def notify(action):
     self.send(proto.json_encode(
         [action]))  # TODO consider sending all actions at once
예제 #25
0
 def _send_stats(self):
     data = proto.json_encode(BroadcastRouter.stats.dump())
     self.send(data)
예제 #26
0
 def notify(action):
     self.send(proto.json_encode([action]))  # TODO consider sending all actions at once