Пример #1
0
def get_top_tags(user):
    """Get list of top tags not followed by user"""
    cursor = request.args.get('cursor')
    items_per_page = current_app.config['ITEMS_PER_PAGE']
    nextCursor = None
    tags = None

    try:
        ord_tags = Tag.get_top_tags(user).subquery()
        query = db.session.query(Tag, ord_tags.c.nPosts).join(
            ord_tags,
            Tag.id == ord_tags.c.tags_id).order_by(ord_tags.c.nPosts.desc())

        if cursor == '0':
            tags = query.limit(items_per_page + 1).all()
        else:
            cursor = urlsafe_base64(cursor, from_base64=True)
            tags = query.filter(
                ord_tags.c.nPosts < cursor).limit(items_per_page + 1).all()
    except (exc.IntegrityError, ValueError) as e:
        db.session.rollback()
        print(e)
        return server_error('Something went wrong, please try again.')

    if len(tags) > items_per_page:
        nextCursor = urlsafe_base64(str(tags[items_per_page - 1][1]))

    return {
        'data': [tag[0].to_dict(user) for tag in tags[:items_per_page]],
        'nextCursor': nextCursor
    }
Пример #2
0
def get_notifications(user):
    cursor = request.args.get('cursor')
    items_per_page = current_app.config['ITEMS_PER_PAGE']
    nextCursor = None
    notifs = None

    try:
        if cursor == '0':
            notifs = user.get_notifications().limit(items_per_page + 1).all()
        else:
            cursor = urlsafe_base64(cursor, from_base64=True)
            notifs = user.get_notifications().filter(
                Notification.timestamp < cursor).limit(items_per_page +
                                                       1).all()

        if len(notifs) > items_per_page:
            nextCursor = urlsafe_base64(notifs[items_per_page -
                                               1].timestamp.isoformat())

        user.last_notif_read_time = datetime.utcnow()
        user.save()
    except (IntegrityError, ValueError) as e:
        db.session.rollback()
        print(e)
        return server_error('Something went wrong, please try again.')
    else:
        return {
            'data':
            NotificationSchema(many=True).dump(notifs[:items_per_page]),
            'nextCursor': nextCursor
        }
Пример #3
0
def get_post_comments(user, post_id):
    post = Post.find_by_id(post_id)

    if not post:
        return not_found('Post not found.')

    cursor = request.args.get('cursor')
    items_per_page = current_app.config['ITEMS_PER_PAGE']
    nextCursor = None
    query = ''

    if cursor == '0':
        query = post.comments.order_by(
            Post.created_on.desc()).limit(items_per_page + 1).all()
    else:
        cursor = urlsafe_base64(cursor, from_base64=True)
        query = post.comments.order_by(Post.created_on.desc()).filter(
            Post.created_on < cursor).limit(items_per_page + 1).all()

    if len(query) > items_per_page:
        nextCursor = urlsafe_base64(query[items_per_page -
                                          1].created_on.isoformat())

    comments = []
    for c in query[:items_per_page]:
        comment = c.to_dict(user)
        comment['parent'] = PostSchema(only=(
            'id',
            'body',
            'author',
        )).dump(c.parent)
        comments.append(comment)

    return {'data': comments, 'nextCursor': nextCursor}
Пример #4
0
def get_tag_posts(user, tag_name):
    top = request.args.get('top', default=False)
    latest = request.args.get('latest', default=False)
    cursor = request.args.get('cursor')
    items_per_page = current_app.config['ITEMS_PER_PAGE']
    nextCursor = None
    query = ''

    try:
        tag = Tag.query.filter_by(name=tag_name).first()
    except Exception as e:
        db.session.rollback()
        print(e)
        return server_error('An unexpected error occured.')

    try:
        sorted_posts = Post.get_by_reactions().subquery()
        tag_posts = Post.query.with_parent(tag).subquery()
        sort_top_posts = db.session.query(
            tag_posts, sorted_posts.c.sequence).join(
                sorted_posts, sorted_posts.c.id == tag_posts.c.id).subquery()
        top_posts = db.session.query(Post, sort_top_posts.c.sequence).join(
            sort_top_posts, Post.id == sort_top_posts.c.id).order_by(
                sort_top_posts.c.sequence.desc())
        latest_posts = Post.query.with_parent(tag).order_by(
            Post.created_on.desc())
    except Exception as e:
        db.session.rollback()
        print(e)
        return server_error('An unexpected error occured, please try again.')

    if cursor == '0' and latest:
        query = latest_posts.limit(items_per_page + 1).all()
    elif cursor == '0' and top:
        query = top_posts.limit(items_per_page + 1).all()
    else:
        if latest:
            cursor = urlsafe_base64(cursor, from_base64=True)
            query = latest_posts.filter(
                Post.created_on < cursor).limit(items_per_page + 1).all()
        else:
            cursor = urlsafe_base64(cursor, from_base64=True)
            query = top_posts.filter(
                sort_top_posts.c.sequence < cursor).limit(items_per_page +
                                                          1).all()

    if len(query) > items_per_page:
        nextCursor = urlsafe_base64(
            query[items_per_page - 1].created_on.isoformat()) \
                if latest else urlsafe_base64(
            str(query[items_per_page - 1][1]))

    posts = [post.to_dict(user) for post in query[:items_per_page]] \
        if latest else \
            [post[0].to_dict(user) for post in query[:items_per_page]]

    return {'data': posts, 'nextCursor': nextCursor}
Пример #5
0
def posts_feed(user):
    latest = request.args.get('latest')
    top = request.args.get('top')
    cursor = request.args.get('cursor')
    items_per_page = current_app.config['ITEMS_PER_PAGE']
    nextCursor = None
    query = ''

    try:
        followed_posts = user.get_followed_posts().subquery()
        posts_reactions = Post.get_reactions().subquery()
        top_followed_posts = db.session.query(
            followed_posts,
            func.row_number().over(order_by=posts_reactions.c.reactions).
            label('sequence')).outerjoin(
                posts_reactions,
                followed_posts.c.posts_id == posts_reactions.c.id).subquery()

        top_posts = db.session.query(Post, top_followed_posts.c.sequence).join(
            Post, top_followed_posts.c.posts_id == Post.id).order_by(
                top_followed_posts.c.sequence.desc())

        latest_posts = db.session.query(Post, followed_posts.c.posts_id).join(
            Post, Post.id == followed_posts.c.posts_id).order_by(
                Post.created_on.desc())
    except Exception as e:
        db.session.rollback()
        print(e)
        return server_error('An unexpected error occured, please try again.')

    if cursor == '0' and latest:
        query = latest_posts.limit(items_per_page + 1).all()
    elif cursor == '0' and top:
        query = top_posts.limit(items_per_page + 1).all()
    else:
        if latest:
            cursor = urlsafe_base64(cursor, from_base64=True)
            query = latest_posts.filter(
                Post.created_on < cursor).limit(items_per_page + 1).all()
        else:
            cursor = urlsafe_base64(cursor, from_base64=True)
            query = top_posts.filter(
                top_followed_posts.c.sequence < cursor).limit(items_per_page +
                                                              1).all()

    if len(query) > items_per_page:
        nextCursor = urlsafe_base64(
            query[items_per_page - 1][0].created_on.isoformat()) \
                if latest else urlsafe_base64(
            str(query[items_per_page - 1][1]))

    return {
        'data': [post[0].to_dict(user) for post in query[:items_per_page]],
        'nextCursor': nextCursor
    }
Пример #6
0
def get_chat_messages(user):
    username = request.args.get('username', '')
    cursor = request.args.get('cursor')
    items_per_page = current_app.config['ITEMS_PER_PAGE']
    a_user = Profile.find_by_username(username).user
    nextCursor = None
    msgs = None

    if not a_user:
        return not_found('User not found.')

    try:
        query = user.get_chat_messages(a_user)
        chat = user.get_chat(a_user)

        if cursor == '0':
            msgs = query.limit(items_per_page + 1).all()
        else:
            cursor = urlsafe_base64(cursor, from_base64=True)
            msgs = query.filter(
                Message.created_on < cursor).limit(items_per_page + 1).all()

        if len(msgs) > items_per_page:
            nextCursor = urlsafe_base64(msgs[items_per_page -
                                             1].created_on.isoformat())

        # check if lrm exist
        if chat:
            lrm = LastReadMessage.find_by_pk(user.id, chat.id)

            if lrm:
                lrm.timestamp = datetime.utcnow()
            else:
                lrm = LastReadMessage()
                lrm.user_id = user.id
                lrm.chat_id = chat.id
                lrm.timestamp = datetime.utcnow()
            lrm.save()
    except Exception as e:
        db.session.rollback()
        print(e)
        return server_error('Something went wrong, please try again.')
    else:
        return {
            'data': MessageSchema(many=True).dump(msgs[:items_per_page]),
            'nextCursor': nextCursor
        }
Пример #7
0
def get_posts(user):
    feed = request.args.get('feed')
    cursor = request.args.get('cursor')
    items_per_page = current_app.config['ITEMS_PER_PAGE']
    nextCursor = None
    query = ''

    try:
        sorted_posts = Post.get_by_reactions().subquery()
        top_posts = db.session.query(Post, sorted_posts.c.sequence).join(
            sorted_posts, sorted_posts.c.id == Post.id).order_by(
                sorted_posts.c.sequence.desc())
        latest_posts = Post.query.filter(Post.comment_id.is_(None)).order_by(
            Post.created_on.desc())
    except Exception as e:
        db.session.rollback()
        print(e)
        return server_error('An unexpected error occured, please try again.')

    if cursor == '0' and feed == 'latest':
        query = latest_posts.limit(items_per_page + 1).all()
    elif cursor == '0' and feed == 'top':
        query = top_posts.limit(items_per_page + 1).all()
    else:
        if feed == 'latest':
            cursor = urlsafe_base64(cursor, from_base64=True)
            query = latest_posts.filter(
                Post.created_on < cursor).limit(items_per_page + 1).all()
        else:
            cursor = urlsafe_base64(cursor, from_base64=True)
            query = top_posts.filter(
                sorted_posts.c.sequence < cursor).limit(items_per_page +
                                                        1).all()

    if len(query) > items_per_page:
        nextCursor = urlsafe_base64(
            query[items_per_page - 1].created_on.isoformat()) \
                if feed == 'latest' else urlsafe_base64(
            str(query[items_per_page - 1][1]))

    posts = [post.to_dict(user) for post in query[:items_per_page]] \
        if feed == 'latest' else \
            [post[0].to_dict(user) for post in query[:items_per_page]]

    return {'data': posts, 'nextCursor': nextCursor}
Пример #8
0
def get_liked_posts(user, username):
    """Get a users list of liked posts"""
    a_user = Profile.find_by_username(username).user

    if not a_user:
        return not_found('User not found.')

    cursor = request.args.get('cursor')
    items_per_page = current_app.config['ITEMS_PER_PAGE']
    nextCursor = None
    posts = None

    try:
        query = a_user.likes.order_by(Post.created_on.desc())
        if cursor == '0':
            posts = query.limit(items_per_page + 1).all()
        else:
            cursor = urlsafe_base64(cursor, from_base64=True)
            posts = query.filter(
                Post.created_on < cursor).limit(items_per_page + 1).all()
    except (exc.IntegrityError, ValueError) as e:
        db.session.rollback()
        print(e)
        return server_error('Something went wrong, please try again.')

    if len(posts) > items_per_page:
        nextCursor = urlsafe_base64(
            posts[items_per_page - 1].created_on.isoformat())

    liked_posts = []
    for p in posts[:items_per_page]:
        post = p.to_dict(user)

        if p.parent:
            post['parent'] = PostSchema(
                only=('id', 'body', 'author',)).dump(p.parent)
        liked_posts.append(post)

    return {
        'data': liked_posts,
        'nextCursor': nextCursor,
        'total': query.count(),
    }
Пример #9
0
def get_messages(user):
    cursor = request.args.get('cursor')
    items_per_page = current_app.config['ITEMS_PER_PAGE']
    last_messages = None
    nextCursor = None
    messages = []

    try:
        stmt, query = user.get_chat_last_messages()
        if cursor == '0':
            last_messages = query.limit(items_per_page + 1).all()
        else:
            cursor = urlsafe_base64(cursor, from_base64=True)
            last_messages = query.filter(
                stmt.c.last_messages < cursor).limit(items_per_page + 1).all()
    except (IntegrityError, ValueError) as e:
        db.session.rollback()
        print(e)
        return server_error('Something went wrong, please try again.')

    if len(last_messages) > items_per_page:
        nextCursor = urlsafe_base64(last_messages[items_per_page -
                                                  1].last_messages.isoformat())

    for msg, user1, user2, _ in last_messages[:items_per_page]:
        author = user2 if user.id == user1.id else user1
        last_read_msg = user.last_read_msg_ts(msg.chat_id)
        message = MessageSchema(exclude=('author_id', )).dump(msg)
        message['isRead'] = False if not last_read_msg else \
            last_read_msg.timestamp >= msg.created_on
        message['user'] = UserSchema(only=(
            'id',
            'profile',
        )).dump(author)
        messages.append(message)

    return {
        'data': messages,
        'nextCursor': nextCursor,
    }
Пример #10
0
def get_followers(user, username):
    """Get list of users following a user"""
    a_user = Profile.find_by_username(username).user

    if not a_user:
        return not_found('User not found.')

    cursor = request.args.get('cursor')
    items_per_page = current_app.config['ITEMS_PER_PAGE']
    nextCursor = None
    followers = None

    try:
        query = a_user.followers.order_by(User.id.desc())

        if cursor == '0':
            followers = query.limit(items_per_page + 1).all()
        else:
            cursor = int(urlsafe_base64(cursor, from_base64=True))
            followers = query.filter(
                User.id < cursor).limit(items_per_page + 1).all()

    except (exc.IntegrityError, ValueError):
        db.session.rollback()
        return server_error('Something went wrong, please try again.')
    else:
        if len(followers) > items_per_page:
            nextCursor = urlsafe_base64(str(followers[items_per_page - 1].id))

        user_followers = []
        for a_user in followers[:items_per_page]:
            follower = UserSchema(only=('id', 'profile',)).dump(a_user)
            follower['isFollowing'] = user.is_following(a_user)
            user_followers.append(follower)

        return {
            'data': user_followers,
            'total': query.count(),
            'nextCursor': nextCursor,
        }
Пример #11
0
def get_user_posts(user, username):
    """Get a users list of posts"""
    a_user = Profile.find_by_username(username).user

    if not a_user:
        return not_found('User not found.')

    cursor = request.args.get('cursor')
    items_per_page = current_app.config['ITEMS_PER_PAGE']
    nextCursor = None
    posts = None

    try:
        query = Post.query.with_parent(a_user).filter(
            Post.comment_id.is_(None)).order_by(Post.created_on.desc())

        if cursor == '0':
            posts = query.limit(items_per_page + 1).all()
        else:
            cursor = urlsafe_base64(cursor, from_base64=True)
            posts = query.filter(
                Post.created_on < cursor).limit(items_per_page + 1).all()
    except (exc.IntegrityError, ValueError) as e:
        db.session.rollback()
        print(e)
        return server_error('Something went wrong, please try again.')

    if len(posts) > items_per_page:
        nextCursor = urlsafe_base64(
            posts[items_per_page - 1].created_on.isoformat())

    return {
        'data': [post.to_dict(user) for post in posts[:items_per_page]],
        'nextCursor': nextCursor,
        'total': query.count(),
    }