def get_user_post(user_id):
    page = int(request.args.get('page', '0'))
    itemPerPage = 10
    with get_connection(post, name='profile') as conn:
        resp = conn.get(ServiceURL.PROFILE_SERVICE + '/user_profile?profile_id=' + str(user_id))
        if resp.status_code != 200:
            raise CustomException('Cannot found user', 404)
    posts = Post.query.filter_by(author_id=user_id).paginate(page, itemPerPage, error_out=False)
    total = posts.total
    num_page = total // itemPerPage + 1
    if posts is None:
        return jsonify({'message': 'User have no post'}), 404
    list_post = list(map(lambda d: d.to_json_little(), posts.items))
    with get_connection(post, name='profile') as conn:
        resp = conn.get(ServiceURL.PROFILE_SERVICE + 'user_profile?profile_id=' + str(user_id))
        if resp.status_code != 200:
            raise CustomException('Cannot found post', 404)
    user = resp.json()
    return jsonify({
        'user': user,
        'posts': list_post,
        'page': page,
        'itemPerPage': itemPerPage,
        'total_pages': num_page,
        'total': total
    }), 200
def update_post(user_id):
    post_details = request.get_json()
    if post_details.get('author_id') != user_id:
        raise CustomException('You dont have permission to change this post', 403)
    post_update = Post.query.filter_by(post_id=post_details.get('post_id')).first()
    if post_update is None:
        raise CustomException('Cannot found post', 404)
    post_update.title = post_details.get('title')
    post_update.body_html = post_details.get('body')
    text = '.'.join(BeautifulSoup(post_details.get('body')).find_all(text=True))
    post_update.body = text
    tags = post_details.get('tags')
    tag_arr = tags.split(',')
    post_update.tags = []
    #try:
    for tag_name in tag_arr:
        tag_target = Tags.query.filter_by(name=tag_name).first()
        if tag_target is None:
            tag_insert = Tags(name=tag_name, url_image=f'https://placehold.jp/16/{get_color()}/ffffff/80x80.jpg?text={tag_name}&css=%7B%22padding%22%3A%223px%22%7D')
            db.session.add(tag_insert)
            db.session.flush()
            post_update.tags.append(tag_insert)
        else:
            post_update.tags.append(tag_target)
    db.session.add(post_update)
    db.session.flush()
    db.session.commit()
    #except:
    #    db.session.rollback()
    return jsonify({'message': 'Success',
                    'post_id': post_update.post_id}), 200
def unlike_post(post_id, user_id):
    post_like = Post.query.filter_by(post_id=post_id).first()
    if post_like is None:
        raise CustomException('Not found post', 404)
    like = post_like.like.filter_by(user_id=user_id).first()
    if like is not None:
        db.session.delete(like)
        db.session.commit()
        return jsonify({'message': 'Like Success'})
    raise CustomException('You not like this', 404)
def delete_user_details():
    user_id = request.args.get('user_id')
    if user_id is None:
        raise CustomException('Invalid request', status_code=404)
    userDetails = UserDetails.query.filter_by(user_id=user_id).first()
    if userDetails is None:
        raise CustomException('Cannot find User', 404)
    db.session.delete(userDetails)
    db.session.commit()
    return jsonify(userDetails.to_json()), 200
Beispiel #5
0
def delete_comment(user_id, comment_id):
    data = request.get_json()
    comment_id = int(comment_id)
    comment = Comments.query.filter_by(id=comment_id).first()
    if comment is None:
        raise CustomException('Cannot found comment', 404)
    if user_id != comment.user_id:
        raise CustomException('You dont have permisson', 403)
    db.session.delete(comment)
    db.session.commit()
    return jsonify({'': ''}), 204
Beispiel #6
0
def get_all_post_by_page():
    page = request.args.get('page') or '0'
    page = int(page)
    itemPerPage = request.args.get('items_per_page') or '20'
    itemPerPage = int(itemPerPage)
    type = int(request.args.get('type', '0'))
    req_from = request.args.get('from') or '2000-01-01 00:00:00'
    date_from = DateTimeCnv(req_from)
    req_to = request.args.get('to') or '3000-01-01 00:00:00'
    date_to = DateTimeCnv(req_to)
    current_user_id = request.args.get('user_current_id')
    if type == 0:
        posts = Post.query.filter(Post.date_post >= date_from).filter(Post.date_post <= date_to) \
            .order_by(Post.date_post.desc()) \
            .paginate(page, itemPerPage, error_out=False)
    else:
        if current_user_id is None:
            raise CustomException('You dont have permission', 403)
        posts = db.session.query(Post).join(Like, Post.post_id == Like.post_id).filter(Post.date_post >= date_from,
                                                                                       Post.date_post <= date_to,
                                                                                       Like.user_id == current_user_id) \
            .order_by(Post.date_post.desc()) \
            .paginate(page, itemPerPage, error_out=False)
    post_paginated = posts.items
    total = posts.total
    num_page = total // itemPerPage + 1
    list = [str(x.author_id) for x in post_paginated]
    str_list = ','.join(set(list))
    with get_connection(post, name='profile') as conn:
        resp = conn.get(ServiceURL.PROFILE_SERVICE +
                        'list_user_profile?list=' + str_list)
        if resp.status_code != 200:
            raise CustomException('Cannot found post', 404)
    data = resp.json().get('profile')
    list_post = []
    data_index = [x.get('user_id') for x in data]
    for element in post_paginated:
        index = data_index.index(element.author_id)
        json = element.to_json_summary(data[index])
        json['is_liked'] = False
        if current_user_id is not None:
            like = element.like.filter_by(user_id=current_user_id).first()
            if like is not None:
                json['is_liked'] = True
        list_post.append(json)
    return jsonify({
        'Post': list_post,
        'page': page,
        'itemPerPage': itemPerPage,
        'total_pages': num_page
    }), 200
def delete_post(post_id, user_id):
    post_del = Post.query.filter_by(post_id=post_id).first()
    if post_del is None:
        raise CustomException('Cannot found post', 404)
    db.session.delete(post_del)
    db.session.commit()
    return jsonify({'message': 'Delete Success'}), 200
Beispiel #8
0
def get_comment(post_id):
    page = int(request.args.get('page', '1'))
    item_per_page = int(request.args.get('item_per_page', '20'))
    comments_paginate = Comments.query.filter_by(post_id=post_id).order_by(
        Comments.date_comment.desc()).paginate(page,
                                               item_per_page,
                                               error_out=False)
    comment = comments_paginate.items
    current_user_id = int(request.args.get('current_user_id', '0'))
    list_user_id = [str(d.user_id) for d in comment]
    str_list = ','.join(list_user_id)
    with get_connection(post, name='profile') as conn:
        resp = conn.get(ServiceURL.PROFILE_SERVICE +
                        'list_user_profile?list=' + str_list)
        if resp.status_code != 200:
            raise CustomException('Cannot found post', 404)
    if comment is None:
        return jsonify({'message': 'There is some thing wrong'}), 500
    data = resp.json().get('profile')
    list_comment = []
    data_index = [x.get('user_id') for x in data]
    for element in comment:
        index = data_index.index(element.user_id)
        json = element.to_json(data[index], current_user_id)
        list_comment.append(json)
    total = comments_paginate.total
    num_page = total // item_per_page + 1
    return jsonify({
        'comments': list_comment,
        'page': page,
        'item_per_page': item_per_page,
        'total': num_page
    }), 200
Beispiel #9
0
def edit_comment(user_id):
    data = request.get_json()
    comment_id = int(data.get('comment_id', '0'))
    user_comment_id = int(data.get('user_comment_id'))
    comment = Comments.query.filter_by(id=comment_id).first()
    if comment is None:
        raise CustomException('Cannot found comment', 404)
    if user_id != user_comment_id:
        raise CustomException('You dont have permission', 403)
    comment.body_html = data.get('body')
    html = markdown(data.get('body'))
    list_text = BeautifulSoup(html, features='html.parser').find_all(text=True)
    comment.body = '.'.join(list_text)
    db.session.add(comment)
    db.session.commit()
    return jsonify({'': ''}), 204
 def inner_function(*args, **kwargs):
     with get_connection(blueprint, name='verify_jwt') as conn:
         token = request.args.get('token')
         if token is None:
             raise CustomException('User dont have permission', 403)
         param = {
             'token': token,
             'permissions': ','.join(str(x) for x in permissions)
         }
         resp = conn.get(ServiceURL.AUTH_SERVICE + 'verify_token',
                         params=param)
         if resp.status_code != 200:
             raise CustomException('User dont have permission', 403)
         body = resp.json()
         if not body.get('allowed'):
             raise CustomException('User dont have permission', 403)
         return func(*args, **kwargs, user_id=body.get('user_id'))
def put_user_profile(user_id):
    user_details = request.get_json()
    if user_details is None or user_id is None:
        raise CustomException('Invalid User', status_code=404)
    if int(user_details.get('user_id')) != user_id:
        raise CustomException(
            'You dont have permission to change this profile', 403)
    query = UserDetails.query.filter_by(user_id=user_id)
    userDetails = query.first()
    if userDetails is None:
        raise CustomException('Cannot found User', status_code=404)
    userDetails.name = user_details.get('name')
    userDetails.about_me = user_details.get('about_me')
    userDetails.address = user_details.get('address')
    userDetails.avatar_hash = 'https://www.w3schools.com/w3images/avatar2.png'
    db.session.commit()
    return jsonify(userDetails.to_json()), 200
def like_post(post_id, user_id):
    post_liked = Post.query.filter_by(post_id=post_id).first()
    if post_liked is None:
        raise CustomException('Not found post', 404)
    like = Like(user_id=user_id, post_id=post_id, date_like=datetime.utcnow())
    db.session.add(like)
    db.session.commit()
    return jsonify({'message': 'Like Success'})
def ping():
    user_id = request.args.get('user_id')
    userDetails = UserDetails.query.filter_by(user_id=user_id).first()
    if userDetails is None:
        raise CustomException('Cannot find User', 404)
    userDetails.ping()
    db.session.commit()
    return jsonify(userDetails.to_json()), 200
Beispiel #14
0
def follow_tag(user_id, tag_id):
    print(tag_id, user_id)
    tags = Tags.query.filter_by(tag_id=tag_id).first()
    if tags is None:
        raise CustomException('Cannot found tags', 404)
    tags_user = Tag_user.query.filter(Tag_user.tag_id == tag_id,
                                      Tag_user.user_id == user_id).first()
    if tags_user is not None:
        print(tags_user)
        raise CustomException('User followed tags', 500)
    try:
        tag_user = Tag_user(user_id=user_id, tag_id=tag_id)
        db.session.add(tag_user)
        db.session.commit()
        return jsonify({'message': 'Success'}), 200
    except:
        db.session.rollback()
        return jsonify({'error': 'Error'}), 500
def delete_follow(user_id):
    user_follow = request.args.get('user_follow')
    user = UserDetails.query.filter_by(user_id=user_id).first()
    if user is None or user_follow is None:
        raise CustomException('There some error', 500)
    user_follow = int(user_follow)
    user.un_follow(user_follow)
    db.session.commit()
    return jsonify({'message': 'Success'}), 200
def get_list_user():
    str_list = request.args.get('list')
    arr_id = str_list.split(',')
    list_profile = UserDetails.query.filter(
        UserDetails.user_id.in_(arr_id)).all()
    if list_profile is None:
        raise CustomException('Error while fetch User Profile', 404)
    return jsonify({'profile': list(map(lambda d: d.to_json(),
                                        list_profile))}), 200
Beispiel #17
0
def unlike_comment(user_id, comment_id):
    comment_id = int(comment_id)
    like_cmt = LikeComment.query.filter(
        LikeComment.comment_id == comment_id,
        LikeComment.user_id == user_id).first()
    if like_cmt is None:
        raise CustomException('Cannot found comment', 404)
    db.session.delete(like_cmt)
    db.session.commit()
    return jsonify({'': ''}), 204
Beispiel #18
0
def like_comment(user_id, comment_id):
    comment_id = int(comment_id)
    query_like = LikeComment.query.filter(
        LikeComment.comment_id == comment_id,
        LikeComment.user_id == user_id).first()
    if query_like is not None:
        raise CustomException(query_like.to_json(), 404)
    like_cmt = LikeComment(comment_id=comment_id, user_id=user_id)
    db.session.add(like_cmt)
    db.session.commit()
    return jsonify({'': ''}), 204
Beispiel #19
0
def unfollow_tag(user_id, tag_id):
    tag_user = Tag_user.query.filter(Tag_user.tag_id == tag_id,
                                     Tag_user.user_id == user_id).first()
    if tag_user is None:
        raise CustomException('Cannot find user_tag', 404)
    try:
        db.session.delete(tag_user)
        db.session.commit()
        return jsonify({'message': 'Success'}), 200
    except:
        db.session.rollback()
        return jsonify({'error': 'Error'}), 500
Beispiel #20
0
def get_post_by_tag(tag_id):
    page = int(request.args.get('page', '0'))
    current_user_id = int(request.args.get('current_user_id', '0'))
    itemPerPage = 20
    tags = Tags.query.filter(Tags.tag_id == tag_id).first()
    num_user = tags.tag_user.count()
    posts = tags.posts \
        .order_by(Post.date_post.desc()) \
        .paginate(page, itemPerPage, error_out=False)
    post_paginated = posts.items
    total = posts.total
    num_page = total // itemPerPage + 1
    list = [str(x.author_id) for x in post_paginated]
    str_list = ','.join(set(list))
    with get_connection(post, name='profile') as conn:
        resp = conn.get(ServiceURL.PROFILE_SERVICE +
                        'list_user_profile?list=' + str_list)
        if resp.status_code != 200:
            raise CustomException('Cannot found post', 404)
    data = resp.json().get('profile')
    list_post = []
    data_index = [x.get('user_id') for x in data]
    for element in post_paginated:
        index = data_index.index(element.author_id)
        json = element.to_json_summary(data[index])
        json['is_liked'] = False
        if current_user_id is not None:
            like = element.like.filter_by(user_id=current_user_id).first()
            if like is not None:
                json['is_liked'] = True
        list_post.append(json)
    is_followed = False
    if current_user_id is not None:
        print(current_user_id)
        tag_user = Tag_user.query.filter(
            Tag_user.tag_id == tag_id,
            Tag_user.user_id == current_user_id).first()
        print(tag_user)
        if tag_user is not None:
            is_followed = True
    return jsonify({
        'tag_id': tags.tag_id,
        'tag_name': tags.name,
        'url_image': tags.url_image,
        'Post': list_post,
        'is_followed': is_followed,
        'page': page,
        'itemPerPage': itemPerPage,
        'total_pages': num_page,
        'total': total,
        'num_follower': num_user
    }), 200
def get_all_followers(user_id):
    user = UserDetails.query.filter_by(user_id=user_id).first()
    if user is None:
        raise CustomException('Cannot find user', 404)
    user_followers = user.followers.paginate(0, 19, error_out=False)
    ret = list(map(lambda d: d.follower.to_short_json(), user_followers.items))
    total_followers = user_followers.total
    return jsonify({
        'user_id': user_id,
        'user_name': user.name,
        'followers': ret,
        'total_followers': total_followers
    }), 200
def get_post_by_id(post_id):
    post_current = Post.query.filter_by(post_id=post_id).first()
    cur_user_id = request.args.get('user_current_id')
    if cur_user_id is None:
        end_point = '/user_profile?profile_id=' + str(post_current.author_id)
    else:
        end_point = '/user_profile?profile_id=' + str(post_current.author_id) + '&my_user_id=' + str(cur_user_id)
    with get_connection(post, name='profile') as conn:
        resp = conn.get(ServiceURL.PROFILE_SERVICE + end_point)
        if resp.status_code != 200:
            raise CustomException('Cannot found post', 404)
    if post_current is None:
        raise CustomException('Cannot found post', 404)
    post_current.num_views += 1
    db.session.add(post_current)
    db.session.commit()
    ret = post_current.to_json_full(resp.json())
    ret['is_liked'] = False
    if cur_user_id is not None:
        like = post_current.like.filter_by(user_id=cur_user_id).first()
        if like is not None:
            ret['is_liked'] = True
    return jsonify(ret), 200
Beispiel #23
0
def search_post():
    type = request.args.get('type')
    key_word = request.args.get('key_word')
    page = int(request.args.get('page', '0'))
    itemPerPage = 20
    if type == 'title':
        posts = Post.query.filter(Post.title.like(f'%{key_word}%')) \
            .order_by(Post.date_post.desc()) \
            .paginate(page, itemPerPage, error_out=False)
    else:
        posts = Post.query.filter(db.or_(Post.body.like(f'%{key_word}%'), Post.title.like(f'%{key_word}%'))) \
            .order_by(Post.date_post.desc()) \
            .paginate(
            page, itemPerPage, error_out=False)
    post_paginated = posts.items
    total = posts.total
    num_page = total // itemPerPage + 1
    list = [str(x.author_id) for x in post_paginated]
    str_list = ','.join(set(list))
    with get_connection(post, name='profile') as conn:
        resp = conn.get(ServiceURL.PROFILE_SERVICE +
                        'list_user_profile?list=' + str_list)
        if resp.status_code != 200:
            raise CustomException('Cannot found post', 404)
    data = resp.json().get('profile')
    list_post = []
    data_index = [x.get('user_id') for x in data]
    for element in post_paginated:
        index = data_index.index(element.author_id)
        json = element.to_json_summary(data[index])
        json['is_liked'] = False
        current_user_id = request.args.get('user_current_id')
        if current_user_id is not None:
            like = element.like.filter_by(user_id=current_user_id).first()
            if like is not None:
                json['is_liked'] = True
        list_post.append(json)
    return jsonify({
        'Post': list_post,
        'page': page,
        'itemPerPage': itemPerPage,
        'total_pages': num_page
    }), 200
Beispiel #24
0
def add_comment(user_id):
    data = request.get_json()
    body = data.get('body')
    html = markdown(body)
    list_text = BeautifulSoup(html, features='html.parser').find_all(text=True)
    body_text = '.'.join(list_text)
    comment = Comments(body=body_text,
                       body_html=body,
                       post_id=data.get('post_id'),
                       date_comment=datetime.utcnow(),
                       user_id=user_id)
    with get_connection(post, name='profile') as conn:
        resp = conn.get(ServiceURL.PROFILE_SERVICE +
                        'user_profile?profile_id=' + str(comment.user_id))
        if resp.status_code != 200:
            raise CustomException('Cannot found post', 404)
    db.session.add(comment)
    db.session.commit()
    ret = comment.to_json(resp.json(), 0)
    return jsonify(ret), 200
Beispiel #25
0
def get_most_post():
    date_before_now = timedelta(days=7)
    previous_date = datetime.utcnow() - date_before_now
    sql_str = 'select posts.post_id, posts.title, case ' \
              'when count(posts.post_id) = 1 and like_table.post_id is null then 0 ' \
              'else count(posts.post_id) ' \
              'end ' \
              '* 10 ' \
              '+ posts.num_views  as reputation, posts.num_views,posts.author_id, count(like_table.post_id) from posts ' \
              'left join like_table on posts.post_id = like_table.post_id ' \
              'where posts.date_post > :date_before ' \
              'group by posts.post_id ' \
              'order by reputation desc ' \
              'limit 5'
    result = db.session.execute(sql_str, {'date_before': previous_date})
    result1 = [x for x in result]
    list_post = []
    list_author_id = set(map(lambda d: str(d[4]), result1))
    str_list = ','.join(list_author_id)
    with get_connection(post, name='profile') as conn:
        resp = conn.get(ServiceURL.PROFILE_SERVICE +
                        'list_user_profile?list=' + str_list)
        if resp.status_code != 200:
            raise CustomException('Cannot found post', 404)
    data = resp.json().get('profile')
    data_index = [int(x.get('user_id')) for x in data]
    for element in result1:
        author_id = element[4]
        index = data_index.index(author_id)
        json_ret = {
            'post_id': element[0],
            'title': element[1],
            'reputation': element[2],
            'num_views': element[3],
            'author': data[index],
            'num_like': element[5],
        }
        list_post.append(json_ret)
    return jsonify({'post': list_post})
def get_user_profile():
    user_id = request.args.get('profile_id')
    my_user_id = request.args.get('my_user_id')
    user_details = UserDetails.query.filter_by(user_id=user_id).first()
    if user_details is None:
        raise CustomException('Cannot found User', status_code=404)
    resp = user_details.to_json()
    resp['is_followed'] = False
    if my_user_id is not None:
        my_user = UserDetails.query.filter_by(user_id=my_user_id).first()
        if my_user is not None:
            if my_user.is_following(user_id):
                resp['is_followed'] = True
            else:
                resp['is_followed'] = False
    with get_connection(profile, name='verify_jwt') as conn:
        resp_profile = conn.get(ServiceURL.POST_SERVICE + str(user_id) +
                                '/total_posts')
        if resp_profile.status_code != 200:
            resp['total_posts'] = 0
        else:
            resp['total_posts'] = resp_profile.json().get('total_posts')
    return jsonify(resp), 200
def test():
    raise CustomException('Test', 404)
def get_all_followeds(user_id):
    user = UserDetails.query.filter_by(user_id=user_id).first()
    if user is None:
        raise CustomException('Cannot find user', 404)
    ret = list(map(lambda d: d.followed.to_short_json(), user.followed.all()))
    return jsonify(ret), 200