Example #1
0
    def get(cls, request, *args, **kwargs):

        log.info("solving get message request")
        log.info(request)

        if kwargs.get('id', None) is not None:
            msg_id = kwargs['id']

            message = MessageModel.objects.get(id=msg_id)

            return Response(request, status_code=200, body=message.serialize())

        try:
            room_id = request.args['room_id']

        except KeyError:
            return Response(request, status_code=400)

        except TypeError:
            return Response(request, status_code=400)

        room = RoomModel.objects.get(id=room_id)
        messages = MessageModel.objects.filter(
            room_id=room).order_by('-created_at')[:50]

        response_body = []
        for message in messages:
            response_body.append(message.serialize())

        return Response(request, status_code=200, body=response_body)
    def wrapper(*args, **kwargs):

        request = args[1]
        headers = request.headers
        web_socket = request.web_socket

        token = headers.get('Authorization', None)

        if token is None:
            return Response(request, status_code=401)

        data = jwt.decode(token.split(' ')[1], secret)

        try:
            if time.time() - data['cat'] > 36000:
                return Response(request, status_code=401)

        except KeyError:
            return Response(request, status_code=401)

        uid = data['uid']
        CLIENTS[web_socket] = uid

        try:
            user = UserModel.objects.get(id=uid)
        except ObjectDoesNotExist:
            return Response(request,
                            status_code=404,
                            error='User does not exist')
        else:
            request.user = user

        return f(*args, **kwargs)
Example #3
0
    def delete(cls, request, *args, **kwargs):

        log.info("solving delete room request")
        log.info(request)

        try:
            room_id = kwargs['id']

        except KeyError:
            log.error('KeyError')
            return Response(request, status_code=400)

        try:
            room = RoomModel.objects.get(id=room_id)

        except ObjectDoesNotExist:
            log.error('ObjectDoesNotExist')
            return Response(request,
                            status_code=404,
                            error='Room does not exist')

        if len(ROOMS[room.id]) > 0:
            return Response(request,
                            status_code=400,
                            error='Room must be empty to be deleted')
        ROOMS.pop(room.id)
        room.delete()

        return Response(request, status_code=200)
Example #4
0
    def post(cls, request, *args, **kwargs):

        log.info("solving register request")
        log.info(request)

        try:
            username = request.body['username']
            password = request.body['password']

        except KeyError:
            log.error('KeyError')
            return Response(request, status_code=400)

        try:
            UserModel.objects.get(name=username)

        except ObjectDoesNotExist:

            log.error('ObjectDoesNotExist')
            user = UserModel()
            hash_password = bcrypt.hashpw(password.encode('utf-8'),
                                          bcrypt.gensalt())
            user.add_entry(username, hash_password)
            user.save()

            return Response(request, status_code=200, body=user.serialize())

        return Response(request,
                        status_code=400,
                        error='User already in database')
Example #5
0
    def put(cls, request, *args, **kwargs):

        log.info("solving put room request")
        log.info(request)

        try:
            body = request.body
            room_id = kwargs['d']
            room_topic = body['topic']

        except KeyError:
            log.error('KeyError')
            return Response(request, status_code=400)

        try:
            room = RoomModel.objects.get(id=room_id)

        except ObjectDoesNotExist:
            log.error('ObjectDoesNotExist')
            return Response(request,
                            status_code=404,
                            error='Room does not exist')

        room.topic = room_topic
        room.save()

        return Response(request, status_code=200, body=room.serialize())
Example #6
0
    def post(cls, request, *args, **kwargs):

        log.info("solving create room request")
        log.info(request)

        try:
            body = request.body
            room_name = body['name']
            room_topic = body['topic']

        except KeyError:
            log.error('KeyError')
            return Response(request, status_code=400)

        try:
            room = RoomModel.objects.get(name=room_name)
            return Response(request, status_code=400, body=room.serialize())

        except ObjectDoesNotExist:

            log.error('ObjectDoesNotExist')
            new_room = RoomModel()
            new_room.add_entry(room_name, room_topic)
            new_room.save()

            created_room = RoomModel.objects.get(name=room_name)
            ROOMS[created_room.id] = set()
            ROOMS[created_room.id].add(request.web_socket)

            return Response(request,
                            status_code=200,
                            body=created_room.serialize())
Example #7
0
    def delete(cls, request, *args, **kwargs):

        print("solving leave request")
        log.info(request)

        try:
            body = request.body
            room_id = body['room_id']

        except KeyError:
            log.error('KeyError')
            return Response(request, status_code=400)

        try:
            room = RoomModel.objects.get(id=room_id)

        except ObjectDoesNotExist:
            log.error('ObjectDoesNotExist')
            return Response(request,
                            status_code=404,
                            error='Room does not exist')

        if request.web_socket not in ROOMS[room.id]:
            return Response(request,
                            status_code=400,
                            error='User was not joined')
        ROOMS[room.id].remove(request.web_socket)

        return Response(request, status_code=200)
Example #8
0
    def post(cls, request, *args, **kwargs):

        print("solving join request")
        print(request)

        try:
            body = request.body
            room_id = body['room_id']

        except KeyError:
            log.error('KeyError')
            return Response(request, status_code=400)

        try:
            room = RoomModel.objects.get(id=room_id)

        except ObjectDoesNotExist:
            log.error('ObjectDoesNotExist')
            return Response(request,
                            status_code=404,
                            error='Room does not exist')

        if ROOMS.get(room.id, None) is None:
            ROOMS[room.id] = set()

        ROOMS[room.id].add(request.web_socket)
        messages = MessageModel.objects.filter(
            room_id=room).order_by('-created_at')[:5]

        response_body = []
        for message in messages:
            response_body.append(message.serialize())

        return Response(request, status_code=200, body=response_body)
Example #9
0
        def future_done(f):
            try:
                res = f.result()
            except Exception:
                res = Response(req, 500)

            print(ROOMS)
            self.write_message(json.dumps(res.to_dict()))
Example #10
0
    def get(cls, request, *args, **kwargs):

        log.info("solving get room request")
        log.info(request)

        response_body = []

        if kwargs.get('id', None) is not None:
            room_id = kwargs['id']
            room = RoomModel.objects.get(id=room_id)

            return Response(request, status_code=200, body=room.serialize())

        for room in RoomModel.objects.all():
            response_body.append(room.serialize())

        return Response(request, status_code=200, body=response_body)
Example #11
0
def send_notification(web_socket):
    req = Request(web_socket,
                  id=-1,
                  verb='POST',
                  url='/notifications',
                  body='Timer expired')

    web_socket.write_message(
        json.dumps(Response(req, status_code=200, body=req.body).to_dict()))
Example #12
0
    def on_message(self, message):

        print("on message" + message)
        msg_dict = json.loads(message)

        args = msg_dict.get('args', None)

        req = Request(self,
                      msg_dict['id'],
                      msg_dict['verb'],
                      msg_dict['url'],
                      body=msg_dict.get('body'),
                      headers=msg_dict.get('headers'),
                      args=args)

        def future_done(f):
            try:
                res = f.result()
            except Exception:
                res = Response(req, 500)

            print(ROOMS)
            self.write_message(json.dumps(res.to_dict()))

        handler, handler_kwargs = Router.get_handler(req.url)

        if handler is None:
            result = Response(req, 404)
        else:
            method = getattr(handler, req.verb.lower(), None)

            if method:
                result = method(req, **handler_kwargs)

                if isinstance(result, tornado.concurrent.Future):
                    tornado.ioloop.IOLoop.current().add_future(
                        result, future_done)
                    return
            else:
                result = Response(req, 405)

        show_rooms()

        self.write_message(json.dumps(result.to_dict()))
Example #13
0
    def post(cls, request,  *args, **kwargs):

        log.info("solving message request")
        log.info(request)

        try:
            body = request.body
            uid = request.user.id
            msg = body['message']
            room_id = body['room_id']

        except KeyError:
            raise gen.Return(Response(request, status_code=400))

        try:
            RoomModel.objects.get(id=room_id)

        except ObjectDoesNotExist:
            raise gen.Return(Response(request, status_code=404, error='Room does not exist'))

        if uid not in ROOMS[room_id]:
            raise gen.Return(Response(request, status_code=400, error='User must be in this room'))

        handler, kw_args = Parser.get_handler(msg)
        if handler == send_notification:
            tornado.ioloop.IOLoop.current().add_timeout(time.time() + float(kw_args.get('seconds')),
                                                        handler, request.web_socket)
            raise gen.Return(Response(request, status_code=200))

        preview = None

        if handler == get_preview:
            preview = yield get_preview(kw_args.get('url'))

        message = MessageModel()
        message.add_entry(UserModel.objects.get(id=uid), RoomModel.objects.get(id=room_id), msg)
        message.save()

        # update headers before broadcast
        request.headers = {}
        msg = message.serialize()
        msg['preview'] = {'code': preview.code if preview else None,
                          'length': len(preview.body)if preview else 0}

        message_to_send = Response(request, 200,
                                   body=msg)

        # get users connected to the room
        try:
            sockets_to_broadcast = ROOMS[room_id]
        except KeyError:
            raise gen.Return(Response(request, status_code=400, error='Room not active'))

        # send each of them a message
        broadcast(sockets_to_broadcast, message_to_send, request.web_socket)

        raise gen.Return(Response(request, status_code=200, body=msg))
Example #14
0
    def post(cls, request, *args, **kwargs):

        print("solving login request")
        log.info(request)

        try:
            username = request.body['username']
            password = request.body['password']
            web_socket = request.web_socket

        except KeyError:
            log.error('KeyError')
            return Response(request, 400, error='Missing argument')

        # TODO: not necessary
        if CLIENTS[web_socket] is not None:
            return Response(request, 400, error='Already logged in')

        try:
            user = UserModel.objects.get(name=username)

        except ObjectDoesNotExist:
            log.error('ObjectDoesNotExist')
            return Response(request, 404, error='username or password wrong')

        password = password.encode('utf-8')
        password_hash = user.password.encode('utf-8')

        if not bcrypt.checkpw(password, password_hash):
            return Response(request, 401)

        enc = jwt.encode({'uid': user.id, 'cat': time.time()}, secret)
        CLIENTS[web_socket] = user.id

        response_body = user.serialize()
        response_body['token'] = enc

        return Response(request, status_code=200, body=response_body)
Example #15
0
 def post(cls, request, *args, **kwargs):
     return Response(request, status_code=405)