Esempio n. 1
0
def send_message(request: REQUEST, headers: HEADERS):
    user = validate_http(headers)
    if not user:
        return proto.error(400, 'Unknown user')
    for p in ['room_gid', 'msg']:
        if not request.get(p):
            return proto.malformed_request('send_message', request,
                                           f'Missing param: {p}')
    room_gid = request.get('room_gid')
    msg = request.get('msg')
    room = get_room_by_room_gid(room_gid)
    if not room:
        return proto.error(404, 'Unknown room')

    message = Message()
    message.room = room.id
    message.sender = user.id
    message.msg = msg
    message.created = datetime.now()

    session = Session()
    try:
        session.add(message)
        session.commit()
        emmitNewMsg(session, room_gid, message.id)
        return proto.ok()
    except Exception as e:
        log.error(e)
        return proto.internal_error('Error while adding msg')
    finally:
        session.close()
Esempio n. 2
0
def room_history(query_params: REQUEST, headers: HEADERS):
    user = validate_http(headers)
    if not user:
        return proto.error(400, 'Unknown user')
    for p in ['room_gid']:
        if not query_params.get(p):
            return proto.malformed_request('send_message', query_params,
                                           f'Missing param: {p}')
    room_gid = query_params.get('room_gid')
    room = get_room_by_room_gid(room_gid)
    if not room:
        return proto.error(404, 'Unknown room')
    msg = load_room_history(room.id)
    log.debug(msg)
    return proto.ok(msg)
Esempio n. 3
0
def register_user(request: REQUEST) -> RESPONSE:
    for p in ['login', 'password', 'username']:
        if not request.get(p):
            return proto.malformed_request('register_user', request,
                                           f'Missing param: {p}')
    user = User()
    user.login = request.get('login')
    user.password = request.get('password')
    user.username = request.get('username')
    user.uuid = str(uuid1())
    session = Session()
    try:
        users = session.query(User).filter_by(login=user.login).one_or_none()
    except Exception as e:
        session.close()
        log.error(e)
        return proto.internal_error('Error while retrieving users')

    if users:
        return proto.error(400, 'User already exists')
    try:
        session.add(user)
        session.commit()
        return proto.ok()
    except Exception as e:
        log.error(e)
        return proto.internal_error('Error while registering user')
    finally:
        session.close()
Esempio n. 4
0
def login_user(request: REQUEST) -> RESPONSE:
    for p in ['login', 'password']:
        if not request.get(p):
            return proto.malformed_request('login_user', request,
                                           f'Missing param: {p}')
    login = request.get('login')
    password = request.get('password')
    log.debug(f'login: {login}, password: {password}')
    session = Session()
    try:
        user: User = session.query(User).filter_by(
            login=login, password=password).one_or_none()
        if not user:
            return proto.error(400, 'Login or password is invalid')
        user_session = UserSession()
        user_session.user = user.id
        log.debug(user_session.id)
        user_session.session_key = generate_random_string(64)
        session.add(user_session)
        session.commit()
        log.debug(user_session.id)
        return proto.ok({
            'username': user.username,
            'token': user_session.session_key
        })
    except Exception as e:
        log.error(e)
        return proto.internal_error('Error while retrieving users')
    finally:
        session.close()
Esempio n. 5
0
 def wrapper(*args, **kwargs):
     args = list(args)
     user: User = authorize(args[0])
     if not user:
         return proto.error(403, "Unknown user")
     args.pop(0)
     args.insert(0, user)
     return fun(*args, **kwargs)
Esempio n. 6
0
def _forward_json_to(fun):
    try:
        raw_body = app.current_request.raw_body
        log.info(f"raw_body of request: {raw_body}")
        params = json.loads(raw_body.decode())
    except json.decoder.JSONDecodeError:
        log.error('Invalid data')
        return proto.error(400, 'Invalid data.')
    else:
        return fun(params)
Esempio n. 7
0
def _forward_json_to(fun):
    try:
        raw_body = request.get_data()
        log.info(f"raw_body of request: {raw_body}")
        params = json.loads(raw_body.decode())
    except json.decoder.JSONDecodeError:
        log.error('Invalid data')
        return jsonify(proto.error(400, 'Invalid data.'))
    else:
        return jsonify(fun(params))
Esempio n. 8
0
def _forward_json_and_headers_to(fun):
    try:
        raw_body = app.current_request.raw_body
        log.info(f"raw_body of request: {raw_body}")
        params = json.loads(raw_body.decode())
        headers_as_json = (dict(
            (k.lower(), v) for k, v in app.current_request.headers.items()))
        log.debug(f'headers: {headers_as_json}')
    except json.decoder.JSONDecodeError:
        log.error('Invalid data')
        return proto.error(400, 'Invalid data.')
    else:
        return fun(headers_as_json, params)
Esempio n. 9
0
def create_review(user: User, request: REQUEST):
    valid, msg = validate_request(request, {
        'content': str,
        'mark': int,
        'movie_gid': str
    })
    if not valid:
        return proto.malformed_request('create_review', msg)
    movie = find_movie_by_gid(request['movie_gid'])
    if not movie:
        return proto.error(404, 'Movie not found')
    review: Review = Review.from_dict(request)
    if not review:
        return proto.error(500, "Couldn't add review to db")
    review.movie = movie.id
    review.author = user.id
    session = Session()
    try:
        session.add(review)
        session.commit()
        # ######### V1
        # checking if there are reviews stored in redis for given movie
        if rd.check_if_exists_reviews_for_movie(movie.gid):
            # if yes then delete entries
            rd.del_reviews_for_movie(movie.gid)
        # checking if there are reviews stored in redis for given movie
        if rd.check_if_exists_movie_score(movie.gid):
            # if yes then delete entries
            rd.del_movie_score(movie.gid)
        # ######### V2
        review_name = rd.store_review(review)
        rd.add_review_to_reviews_store(request['movie_gid'], review_name)
        return proto.ok()
    except Exception as e:
        log.error(e)
        return proto.internal_error('Error while retrieving users')
    finally:
        session.close()
Esempio n. 10
0
def _forward_json_and_headers_to(fun):
    try:

        raw_body = request.get_data()
        log.info(f"raw_body of request: {raw_body}")
        params = json.loads(raw_body.decode())
        headers_as_json = (dict(
            (k.lower(), v) for k, v in request.headers.items()))
        log.info(f'headers: {headers_as_json}')
    except json.decoder.JSONDecodeError:
        log.error('Invalid data')
        return jsonify(proto.error(400, 'Invalid data'))
    else:
        return jsonify(fun(params, headers_as_json))
Esempio n. 11
0
def find_movie(headers: HEADERS, query_params: REQUEST):
    if not (query_params and query_params.get('gid')):
        return proto.malformed_request('find_movie', 'Missing gid query_param')
    movie_gid = query_params.get('gid')

    # checking redis
    movie = rd.get_movie(movie_gid)
    if movie:
        return proto.ok(movie)

    movie = find_movie_by_gid(movie_gid)
    if movie:
        movie_dct = movie.to_dict(True)
        rd.set_movie(movie_gid, movie_dct)
        return proto.ok(movie_dct)
    return proto.error(404, 'Movie not found')
Esempio n. 12
0
def create_room(request: REQUEST, headers: HEADERS):
    user = validate_http(headers)
    if not user:
        return proto.error(400, 'Unknown user')
    room = Room()
    room.room_gid = str(generate_room_gid())
    if not room.room_gid:
        return proto.internal_error("Couldn't connect to db")
    room.created = datetime.now()
    room.owner = user.id

    session = Session()
    try:
        session.add(room)
        session.commit()
        return proto.ok({'room_gid': room.room_gid})
    except Exception as e:
        log.error(e)
        return proto.internal_error('Error while creating room')
    finally:
        session.close()
Esempio n. 13
0
def get_avg_score(headers: HEADERS, query_params: REQUEST):
    if not (query_params and query_params.get('gid')):
        return proto.malformed_request('find_movie', 'Missing gid query_param')
    movie_gid = query_params.get('gid')
    # # ###### V1
    # score_in_rd = rd.get_reviews_list_from_store(movie_gid)
    # if score_in_rd:
    #     log.info('Getting score from redis')
    #     return proto.ok({
    #         'avg_score': score_in_rd
    #     })
    # ###### V2
    start = time.time()
    score = rd.get_movie_score(movie_gid)
    end = time.time()  # here

    if score:
        log.info(f'Execution took: {end - start} seconds')  # here
        return proto.ok({'avg_score': score})
    log.info('Getting score from DB')
    session = Session()
    try:
        start = time.time()
        result = session.execute(
            text(
                "select avg(mark) from reviews where movie=(select id from movies where gid=:gid);"
            ), {'gid': movie_gid})
        avg_score = result.first()[0]
        end = time.time()  # here
        log.info(f'Execution took: {end - start} seconds')  # here
        if avg_score:
            rd.set_movie_score(movie_gid, avg_score)
            return proto.ok({'avg_score': float(avg_score)})
        return proto.ok({'avg_score': None})
    except Exception as e:
        log.error(e)
        return proto.error(400, str(e))
    finally:
        session.close()
Esempio n. 14
0
def list_reviews(headers: HEADERS, query_params: REQUEST):
    if not (query_params and query_params.get('gid')):
        return proto.malformed_request('list_reviews',
                                       'Missing gid query_param')
    movie_gid = query_params.get('gid')

    # ------------ comment start -------
    # checking redis
    start = time.time()  # here
    reviews = rd.get_reviews_for_movie(movie_gid)
    end = time.time()  # here
    if reviews:
        log.info(f'Execution took: {end - start} seconds')  # here
        return proto.ok(reviews)
    # ------------ comment end --------
    # doesn't exist, pooling from db
    movie = find_movie_by_gid(movie_gid)
    if not movie:
        return proto.error(404, 'Movie not found')
    session = Session()
    try:
        start = time.time()  # here
        reviews = session.query(
            User.username, Review.created, Review.mark, Review.content).join(
                Review, User.reviews).filter(Review.movie == movie.id).all()
        converted = _reviews_to_json(reviews)
        end = time.time()  # here
        log.info(f'Execution took: {end - start} seconds')  # here
        # saving reviews to redis
        rd.set_reviews_for_movie(movie_gid, converted)
        return proto.ok(converted)
    except Exception as e:
        log.error(e)
        return proto.internal_error('Error while retrieving reviews')
    finally:
        session.close()
Esempio n. 15
0
def login_user(request: REQUEST) -> RESPONSE:
    for p in ['login', 'password']:
        if not request.get(p):
            return proto.malformed_request('login_user', request,
                                           f'Missing param: {p}')
    login = request.get('login')
    password = request.get('password')
    log.debug(f'login: {login}, password: {password}')
    session = Session()
    try:
        user: User = session.query(User).filter_by(
            login=login, password=password).one_or_none()
        if not user:
            return proto.error(400, 'Login or password is invalid')
        return proto.ok({
            'username': user.username,
            'uuid': user.uuid,
        })
    except Exception as e:
        session.close()
        log.error(e)
        return proto.internal_error('Error while retrieving users')
    finally:
        session.close()