Exemplo n.º 1
0
def find_movie_by_gid(gid: str) -> Movie:
    session = Session()
    try:
        movie: Movie = session.query(Movie).filter_by(gid=gid).one_or_none()
        return movie
    except Exception as e:
        log.error(e)
        return None
    finally:
        session.close()
Exemplo n.º 2
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()
Exemplo n.º 3
0
def get_room_by_room_gid(room_gid: str) -> Room:
    session = Session()
    try:
        room: Room = session.query(Room).filter_by(
            room_gid=room_gid).one_or_none()
        return room
    except Exception as e:
        log.error(e)
        return None
    finally:
        session.close()
Exemplo n.º 4
0
def validate(uuid: str) -> User:
    if not uuid:
        return None
    session = Session()
    try:
        user: User = session.query(User).filter_by(uuid=uuid).one_or_none()
        return user
    except Exception as e:
        log.error(e)
        return None
    finally:
        session.close()
Exemplo n.º 5
0
def create_movie(user: User, request: REQUEST):
    valid, msg = validate_request(request, {
        'name': str,
        'description': str,
        'premiere_date': str
    })
    if not valid:
        return proto.malformed_request('create_movie', msg)
    movie: Movie = Movie.from_dict(request)
    if not movie:
        return proto.malformed_request('create_movie', 'Parsing failed')
    movie.gid = generate_random_string(8)
    session = Session()
    try:
        session.add(movie)
        session.commit()

        # checking if there are movies stored in redis
        if rd.check_if_movies_list_exists():
            # if yes then delete entries
            rd.del_movies_list()

        return proto.ok({'gid': movie.gid})
    except Exception as e:
        log.error(e)
        return proto.internal_error('Error while retrieving users')
    finally:
        session.close()
Exemplo n.º 6
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()
Exemplo n.º 7
0
def load_room_history(room_id: int) -> List[DICT]:
    session = Session()
    try:
        messages = session.query(
            User.uuid, User.username,
            Message.id, Message.msg, Message.created).join(
                Message, User.messages).filter(Message.room == room_id).all()
        log.debug(messages)
        return _msgs_to_json(messages)
    except Exception as e:
        log.error(e)
        return None
    finally:
        session.close()
Exemplo n.º 8
0
def list_movies():
    # checking redis
    movies = rd.get_movies_list()
    if movies:
        return proto.ok(movies)

    session = Session()
    try:
        movies: Sequence[Movie] = session.query(Movie).all()
        movie_list = [movie.to_dict() for movie in movies]
        rd.set_movies_list(movie_list)
        return proto.ok(movie_list)
    except Exception as e:
        log.error(e)
        return proto.internal_error('Error while retrieving users')
    finally:
        session.close()
Exemplo n.º 9
0
def generate_room_gid(length: int = 8) -> str:
    alphanumerics = string.ascii_letters + string.digits
    availables = re.sub(CONFUSING_CHARS, '', alphanumerics)
    session = Session()
    try:
        while True:
            room_gid = ''.join(
                secrets.choice(availables) for i in range(length))
            room: Room = session.query(Room).filter_by(
                room_gid=room_gid).one_or_none()
            if not room:
                return room_gid
    except Exception as e:
        log.error(e)
        return None
    finally:
        session.close()
Exemplo n.º 10
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()
Exemplo n.º 11
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()
Exemplo 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()
Exemplo n.º 13
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()
Exemplo n.º 14
0
def authorize(headers: HEADERS):
    token = headers.get('authorization')
    if not token:
        return None
    session = Session()
    try:
        user_session: UserSession = session.query(UserSession).filter_by(
            session_key=token).one_or_none()
        if not user_session: return None
        user: User = session.query(User).filter_by(
            id=user_session.id).one_or_none()
        return user
    except Exception as e:
        log.error(e)
        return None
    finally:
        session.close()
Exemplo 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()
Exemplo n.º 16
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()