Пример #1
0
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
Пример #2
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
Пример #3
0
def verify_login():
    token = request.args.get('token')
    if token is None:
        return jsonify({
            'message': 'verify Fail'
        }), 403
    user_id_decode = decode_jwt_token(token)
    user = User.query.filter_by(id=user_id_decode).first()
    if user is None:
        return jsonify({
            'message': 'there is some thing wrong. Login again'
        }), 403
    with get_connection(auth, name='auth_service') as conn:
        resp = conn.get(ServiceURL.PROFILE_SERVICE + 'user_profile?profile_id=' + str(user_id_decode))
        if resp.status_code != 200:
            return jsonify({'message': 'Error here'}), 403
    return jsonify({
        'message': 'Valid User',
        'user_id': user_id_decode,
        'user_username': user.username,
        'user_name': resp.json().get('name'),
        'user_email': resp.json().get('email'),
        'user_avatar': resp.json().get('avatar_hash'),
        'is_admin': user.can(Permission.ADMIN)
    }), 200
Пример #4
0
def authenticate():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')
    user = User.query.filter_by(username=username).first()
    if user is None:
        return jsonify({'message': 'Invalid Username'}), 403
    if not user.verify_password(password):
        return jsonify({'message': 'Invalid Password'}), 403
    jwt = generate_jwt_token(user.id)
    with get_connection(auth, name='auth_service') as conn:
        resp = conn.get(ServiceURL.PROFILE_SERVICE + 'user_profile?profile_id=' + str(user.id))
        if resp.status_code != 200:
            return jsonify({'message': 'Cannot found profile'}), 403
    if not user.confirmed:
        return jsonify({'message': 'Your account is not confirmed'}), 403
    return jsonify({
        'jwt': jwt,
        'user_id': user.id,
        'user_username': user.username,
        'user_name': resp.json().get('name'),
        'user_email': resp.json().get('email'),
        'user_avatar': resp.json().get('avatar_hash'),
        'is_admin': user.can(Permission.ADMIN)
    }), 200
Пример #5
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
Пример #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
Пример #7
0
def sign_up_user():
    data = request.get_json()
    user_name = data.get('username')
    email = data.get('email')
    password = data.get('password')
    if User.query.filter_by(username=user_name).first() is not None:
        resp = jsonify({'message': 'User is already exist'})
        resp.status_code = 403
        return resp

    if User.query.filter_by(email=email).first() is not None:
        resp = jsonify({'message': 'Email is already exist'})
        resp.status_code = 403
        return resp
    user = User(username=data.get('username'), email=data.get('email'), password=data.get('password'))
    try:
        # fake confirm first
        user.confirmed = 0
        db.session.add(user)
        db.session.commit()
        # add user profile
        with get_connection(auth, name='auth_service') as conn:
            user_details = {
                'profile_id': user.id,
                'email': user.email,
                'name': data.get('name'),
            }
            resp = conn.post(ServiceURL.PROFILE_SERVICE + 'user_profile', json=user_details)
        if resp.status_code != 200:
            print('Error when create user profile')
            raise Exception()
        # Send message to rabbitMQ to send email
        data = {
            'user_email': email,
            'user_id': user.id,
            'user_name': user.username
        }
        mail_sender = MailSender(exchange='mail_service', routing_key='confirm.resend', data=data)
        mail_sender.send()
        return jsonify({
            'username': user.username,
            'roles': user.roles.name
        }), 200
    except:
        db.session.rollback()
        raise
        return jsonify({
            'message': 'There is some error',
        }), 500
Пример #8
0
 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'))
Пример #9
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
Пример #10
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
Пример #11
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})
Пример #12
0
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
Пример #13
0
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