Esempio n. 1
0
def login_view(request):
    User = get_user_model()
    username = request.POST['username']
    password = request.POST['password']

    if (username == "") or (password == ""):
        return JsonResponse({"error": ErrorSerializer(get_error(103)).data},
                            status=status.HTTP_400_BAD_REQUEST)
    user = User.objects.filter(username=username).first()
    if user is None:
        return JsonResponse({"error": ErrorSerializer(get_error(101)).data},
                            status=status.HTTP_400_BAD_REQUEST)

    if not User.check_password(user, password):
        return JsonResponse({"error": ErrorSerializer(get_error(101)).data},
                            status=status.HTTP_400_BAD_REQUEST)

    serialized_user = UserSerializer(user).data
    access_token = generate_access_token(user)
    refresh_token = generate_refresh_token(user)

    return JsonResponse({
        "access_token": access_token,
        "refresh_token": refresh_token
    })
Esempio n. 2
0
def get_community_members(request):
    viewer = request.user
    cm_name = request.query_params.get('name', None)
    if cm_name is None:
        return JsonResponse({"error" : ErrorSerializer(get_error(103)).data}, status = status.HTTP_400_BAD_REQUEST)
    community = Community.objects.filter(name__iexact = cm_name.lower()).first()
    if community is None:
        return JsonResponse({"error" : ErrorSerializer(get_error(100)).data}, status = status.HTTP_404_NOT_FOUND)
    members = community.users.all()
    return JsonResponse({"members" : PublicProfileSerializer(members, many = True, context = {"viewer_id" : viewer.id}).data})
Esempio n. 3
0
def get_content(request):
    content_id = request.query_params.get('id', None)
    if (content_id is None):
        return JsonResponse({"error": ErrorSerializer(get_error(103)).data},
                            status=status.HTTP_400_BAD_REQUEST)
    content = Content.objects.filter(id=content_id).first()
    if content is None:
        return JsonResponse({"error": ErrorSerializer(get_error(100)).data},
                            status=status.HTTP_404_NOT_FOUND)
    serialized_content = ContentSerializer(content).data
    return JsonResponse({"content": serialized_content})
Esempio n. 4
0
def join_community(request):
    user = request.user
    cm_name = request.query_params.get('name')
    if cm_name is None:
        return JsonResponse({"error" : ErrorSerializer(get_error(103)).data}, status = status.HTTP_400_BAD_REQUEST)
    community = Community.objects.filter(name__iexact = cm_name.lower()).first()
    if community is None:
        return JsonResponse({"error" : ErrorSerializer(get_error(100)).data}, status = status.HTTP_404_NOT_FOUND)
    if user in community.users.all():
        return JsonResponse({"error" : ErrorSerializer(get_error(107)).data}, status = status.HTTP_400_BAD_REQUEST)
    community.users.add(user)
    return JsonResponse({"message" : "user added successfuly"})
Esempio n. 5
0
def leave_community(request):
    to_delete_user = request.user
    cm_name = request.query_params.get('name', None)
    if cm_name is None:
        return JsonResponse({"error" : ErrorSerializer(get_error(103)).data}, status = status.HTTP_400_BAD_REQUEST)
    community = Community.objects.filter(name__iexact = cm_name.lower()).first()
    if community is None:
        return JsonResponse({"error" : ErrorSerializer(get_error(100)).data}, status = status.HTTP_404_NOT_FOUND)
    if not(to_delete_user in community.users.all()):
        return JsonResponse({"error" : ErrorSerializer(get_error(100)).data}, status = status.HTTP_400_BAD_REQUEST)
    community.users.remove(to_delete_user)
    return JsonResponse({"message" : "user removed successfuly from community"})
Esempio n. 6
0
def get_public_profile(request):
    viewer = request.user
    username = request.query_params.get('username', None)
    if (username is None):
        return JsonResponse(ErrorSerializer(get_error(103)).data,
                            status=HTTPStatus.BAD_REQUEST)

    user = User.objects.filter(username=username).first()
    if (user is None):
        return JsonResponse(get_error_serialized(100, "User not found!").data,
                            status=HTTPStatus.NOT_FOUND)
    public_profile = PublicProfileSerializer(user,
                                             context={"viewer_id": viewer.id})
    data = public_profile.data
    data['follower'] = "5"
    data['follower'] = "10"
    data['nickname'] = user.first_name + ' ' + user.last_name
    user_posts = Post.objects.filter(author=user.id)
    if (user_posts is not None):
        data['posts_count'] = str(len(list(user_posts)))
    else:
        data['posts_count'] = "0"
    post_likes = list(PostLike.objects.filter(user=user.id))
    comment_likes = list(CommentLike.objects.filter(user=user.id))
    data['likes_count'] = len(post_likes) + len(comment_likes)
    comment_serializer = UserCommentSerializer(user)
    if (comment_serializer is not None):
        data['comments_count'] = str(
            len(comment_serializer.get_post_replies(user)) +
            len(comment_serializer.get_comment_replies(user)))
    else:
        data['comments_count'] = "0"
    return JsonResponse(data=data, status=HTTPStatus.OK)
Esempio n. 7
0
def get_hashtag_posts(request):
    hashtag_text = request.query_params.get('text', None)
    sort = request.query_params.get('sort', 'latest')
    viewer = None
    if not (request.user.is_anonymous):
        viewer = request.user.username
    if (hashtag_text is None):
        return JsonResponse(ErrorSerializer(get_error(103)).data,
                            status=HTTPStatus.BAD_REQUEST)
    hashtag = Hashtag.objects.filter(text=hashtag_text).first()
    if (hashtag is None):
        return JsonResponse(get_error_serialized(100,
                                                 "Hashtag not found!").data,
                            status=HTTPStatus.NOT_FOUND)
    records = PostHashtag.objects.filter(hashtag=hashtag.id)
    posts = [record.post for record in records]
    if (sort == 'latest'):
        posts = sorted(posts, key=lambda x: x.date_created)[::-1]
    elif (sort == 'popular'):
        posts = sorted(
            posts, key=lambda x: len(PostLike.objects.filter(post=x.id)))[::-1]
    return JsonResponse(
        {
            'hashtag':
            HashtagSerializer(hashtag).data,
            'posts':
            PostSerializer(posts, many=True, context={
                'viewer': viewer
            }).data
        },
        status=HTTPStatus.OK)
Esempio n. 8
0
def submit_reply_comment(request):
    user = request.user
    reply_to = request.data.get('reply_to_id')
    content = request.data.get('content')
    if not (user and reply_to and content):
        return JsonResponse(ErrorSerializer(get_error(103)).data,
                            status=HTTPStatus.BAD_REQUEST)
    comment = Comment.objects.filter(id=reply_to).first()
    if (comment is None):
        return JsonResponse(get_error_serialized(100,
                                                 "Comment not found!").data,
                            status=HTTPStatus.NOT_FOUND)
    data = {'author': user.id, 'content': content}
    new_comment = CommentSerializer(data=data)
    if (new_comment.is_valid()):
        new_comment.save()
    else:
        return JsonResponse(new_comment.errors, status=HTTPStatus.BAD_REQUEST)
    data = {'reply_to': reply_to, 'reply': new_comment.instance.id}
    reply_comment = CommentReplySerializer(data=data)
    if (reply_comment.is_valid()):
        reply_comment.save()
    else:
        return JsonResponse(reply_comment.errors,
                            status=HTTPStatus.BAD_REQUEST)
    return JsonResponse(
        {
            'message': 'Comment submitted.',
            'comment': DisplayCommentSerializer(new_comment.instance).data
        },
        status=HTTPStatus.CREATED)
Esempio n. 9
0
def submit_post_comment(request):
    user = request.user
    post_id = request.data.get('post')
    content = request.data.get('content')
    if not (content and post_id and user):
        return JsonResponse(ErrorSerializer(get_error(103)).data,
                            status=HTTPStatus.BAD_REQUEST)
    post = Post.objects.filter(id=post_id).first()
    if (post is None):
        return JsonResponse(get_error_serialized(100, "Post not found!").data,
                            status=HTTPStatus.NOT_FOUND)
    data = {'author': user.id, 'content': content}
    comment = CommentSerializer(data=data)
    if (comment.is_valid()):
        comment.save()
    else:
        return JsonResponse(comment.errors, status=HTTPStatus.BAD_REQUEST)
    data = {'post': post_id, 'reply': comment.instance.id}
    reply_post = PostReplySerializer(data=data)
    if (reply_post.is_valid()):
        reply_post.save()
    else:
        return JsonResponse(reply_post.errors, status=HTTPStatus.BAD_REQUEST)
    return JsonResponse(
        {
            'message': 'Comment submitted.',
            'comment': DisplayCommentSerializer(comment.instance).data
        },
        status=HTTPStatus.CREATED)
Esempio n. 10
0
class RequestSerializierRead(serializers.ModelSerializer):
    product = ProductSerializer(read_only=True)
    error = ErrorSerializer(read_only=True)

    class Meta:
        model = Request
        fields = ('__all__')
Esempio n. 11
0
def get_reply_comments(request):
    reply_to = request.query_params.get('reply_to', None)
    depth = request.query_params.get('depth', None)
    startIdx = request.query_params.get('start_index', None)
    length = request.query_params.get('max_len', None)
    reply_len = request.query_params.get('max_reply_len', None)
    viewer = request.query_params.get('viewer')
    if not (depth and reply_to and startIdx and length):
        return JsonResponse(ErrorSerializer(get_error(103)).data,
                            status=HTTPStatus.BAD_REQUEST)
    try:
        startIdx = int(startIdx)
        length = int(length)
    except:
        return JsonResponse(get_error_serialized(
            103, "Integer conversion error!").data,
                            status=HTTPStatus.BAD_REQUEST)
    if (viewer is None and not request.user.is_anonymous):
        viewer = request.user.username
    comment = Comment.objects.filter(id=reply_to).first()
    if (comment is None):
        return JsonResponse(get_error_serialized(100,
                                                 "Comment not found!").data,
                            status=HTTPStatus.NOT_FOUND)
    return JsonResponse(RepliedCommentSerializer(comment,
                                                 context={
                                                     'depth': depth,
                                                     'start_index': startIdx,
                                                     'max_len': reply_len,
                                                     'viewer': viewer,
                                                     'start_index': startIdx
                                                 }).data,
                        status=HTTPStatus.OK)
Esempio n. 12
0
def get_full_post(request):
    post_id = request.query_params.get('id', None)
    viewer = request.query_params.get('viewer', None)
    if post_id is None:
        return JsonResponse({"error": ErrorSerializer(get_error(103)).data},
                            status=status.HTTP_400_BAD_REQUEST)

    post = Post.objects.filter(id=post_id).first()
    if (viewer is None and not request.user.is_anonymous):
        viewer = request.user.username
    if post is None:
        return JsonResponse({"error": ErrorSerializer(get_error(100)).data},
                            status=status.HTTP_404_NOT_FOUND)

    serialized_post = PostSerializer(post, context={'viewer': viewer}).data

    return JsonResponse({"post": serialized_post})
Esempio n. 13
0
def get_user_posts(request):
    username = request.query_params.get('username', None)
    viewer = request.query_params.get('viewer', None)

    try:
        offset_str = request.query_params.get('offset', None)
        if not (offset_str is None): offset = int(offset_str)
    except:
        return JsonResponse({
            "error":
            get_error_serialized(110, 'offset must be integer').data
        })

    if (username is None):
        return JsonResponse({"error": ErrorSerializer(get_error(103)).data},
                            status=status.HTTP_400_BAD_REQUEST)
    author = User.objects.filter(username=username).first()
    if (viewer is None and not request.user.is_anonymous):
        viewer = request.user.username
    if author is None:
        return JsonResponse({"error": ErrorSerializer(get_error(100)).data},
                            status=status.HTTP_404_NOT_FOUND)

    author_id = author.id

    all_posts = list(Post.objects.filter(author=author_id))

    all_posts.sort(key=lambda post: post.date_created, reverse=True)

    if not (offset_str is None):
        all_posts = all_posts[PCOUNT * offset:PCOUNT * (offset + 1)]

    serialized_posts = PostSerializer(all_posts,
                                      many=True,
                                      context={
                                          "author_depth": False,
                                          'content_depth': False,
                                          'viewer': viewer
                                      }).data

    serialized_author = PublicProfileSerializer(author).data

    return JsonResponse({
        "author": serialized_author,
        "all_user_posts": serialized_posts
    })
Esempio n. 14
0
def get_community(request):
    cm_name = request.query_params.get('name', None)
    summery = request.query_params.get('summery', 'f')
    if cm_name is None:
        return JsonResponse({"error" : ErrorSerializer(get_error(103)).data}, status = status.HTTP_400_BAD_REQUEST)
    community = Community.objects.filter(name__iexact = cm_name.lower()).first()
    if community is None:
        return JsonResponse({"error" : ErrorSerializer(get_error(100)).data}, status = status.HTTP_404_NOT_FOUND)

    if summery == 't':
        community_serialized = CommunitySmallSerializer(community).data
    elif summery == 'f':
        community_serialized = CommunityCompleteSerializer(community).data
    else:
        return JsonResponse({"error" : ErrorSerializer(get_error(103)).data}, status = status.HTTP_400_BAD_REQUEST)

    return JsonResponse({"community" : community_serialized})
Esempio n. 15
0
def register_view(request):
    if request.method == 'POST':

        first_name = request.data.get('first_name')
        last_name = request.data.get('last_name')
        username = request.data.get('username')
        email = request.data.get('email')
        password = request.data.get('password')

        User = get_user_model()

        if User.objects.all().count() != 0:
            last_id = User.objects.last().id
        else:
            last_id = 0
        to_create_id = last_id + 1
        to_create_user = User(id=to_create_id,
                              first_name=first_name,
                              last_name=last_name,
                              username=username,
                              email=email)
        to_create_user.set_password(password)
        serialized_user = UserSerializer(to_create_user).data

        if first_name == "" or last_name == "" or username == "" or email == "" or password == "":
            return JsonResponse(
                {"error": ErrorSerializer(get_error(103)).data},
                status=status.HTTP_400_BAD_REQUEST)

        elif User.objects.filter(username=username).exists():
            return JsonResponse(
                {"error": ErrorSerializer(get_error(104)).data},
                status=status.HTTP_400_BAD_REQUEST)

        elif User.objects.filter(email=email).exists():
            return JsonResponse(
                {"error": ErrorSerializer(get_error(105)).data},
                status=status.HTTP_400_BAD_REQUEST)

        else:
            to_create_user.save()
            return JsonResponse({
                "user": serialized_user,
                "message": "User created successfuly"
            })
Esempio n. 16
0
def get_post_likes(request):
    post_id = request.query_params.get('id', None)
    if (post_id is None):
        return JsonResponse(ErrorSerializer(get_error(103)).data,
                            status=HTTPStatus.BAD_REQUEST)
    post = Post.objects.filter(id=post_id).first()
    if (post is None):
        return JsonResponse(get_error_serialized(100, "Post not found!").data,
                            status=HTTPStatus.NOT_FOUND)
    return JsonResponse(ViewPostLikesSerializer(post).data,
                        status=HTTPStatus.OK)
Esempio n. 17
0
def get_community_posts(request):
    viewer = request.user
    cm_name = request.query_params.get('name', None)
    if cm_name is None:
        return JsonResponse({"error" : ErrorSerializer(get_error(103)).data}, status = status.HTTP_400_BAD_REQUEST)
    community = Community.objects.filter(name__iexact = cm_name.lower()).first()
    if community is None:
        return JsonResponse({"error" : ErrorSerializer(get_error(100)).data}, status = status.HTTP_404_NOT_FOUND)
        
    try:
        offset_str = request.query_params.get('offset', None)
        if not(offset_str is None): offset = int(offset_str)
    except:
        return JsonResponse({"error" : get_error_serialized(110, 'offset must be integer').data})
    
    posts = list(Post.objects.filter(community = community.id))
    posts.sort(key = lambda post : post.date_created, reverse = True)

    if not(offset_str is None):
        posts = posts[PCOUNT * offset: PCOUNT * (offset + 1)]
    return JsonResponse({"posts" : PostSerializer(posts, context = {"content_depth" : False, "viewer" : viewer.username}, many = True).data})
Esempio n. 18
0
def get_comment_likes(request):
    comment_id = request.query_params.get('id', None)
    if (comment_id is None):
        return JsonResponse(ErrorSerializer(get_error(103)).data,
                            status=HTTPStatus.BAD_REQUEST)
    comment = Comment.objects.filter(id=comment_id).first()
    if (comment is None):
        return JsonResponse(get_error_serialized(100,
                                                 "Coment not found!").data,
                            status=HTTPStatus.NOT_FOUND)
    return JsonResponse(ViewCommentLikesSerializer(comment).data,
                        status=HTTPStatus.OK)
Esempio n. 19
0
def get_post_comments(request):
    post_id = request.query_params.get('post_id', None)
    depth = request.query_params.get('depth', '0')
    startIdx = request.query_params.get('start_index', None)
    length = request.query_params.get('max_len', None)
    reply_len = request.query_params.get('max_reply_len', None)
    viewer = request.query_params.get('viewer')
    if not (depth and post_id and startIdx and length):
        return JsonResponse(ErrorSerializer(get_error(103)).data,
                            status=HTTPStatus.BAD_REQUEST)
    try:
        startIdx = int(startIdx)
        length = int(length)
        depth = int(depth)
    except:
        return JsonResponse(get_error_serialized(
            103, "Integer conversion error!").data,
                            status=HTTPStatus.BAD_REQUEST)
    if (viewer is None and not request.user.is_anonymous):
        viewer = request.user.username
    post = Post.objects.filter(id=post_id).first()
    if (post is None):
        return JsonResponse(get_error_serialized(100, "Post not found!").data,
                            status=HTTPStatus.NOT_FOUND)
    post_comments = PostReply.objects.filter(post=post_id)
    result = []
    post_comments = list(post_comments)
    total_comments = len(post_comments)
    if (startIdx >= len(post_comments)):
        post_comments = []
    else:
        post_comments = post_comments[startIdx:startIdx + length]
    for comment in list(post_comments):
        comment = comment.reply
        if (comment is None):
            continue
        result.append(
            RepliedCommentSerializer(comment,
                                     context={
                                         'depth': str(depth - 1),
                                         'max_len': reply_len,
                                         'viewer': viewer,
                                         'start_index': startIdx
                                     }).data)
    return JsonResponse(
        {
            'post_id': post_id,
            'total_comments': total_comments,
            'retrived_comments_count': len(result),
            'comments': result
        },
        status=HTTPStatus.OK)
Esempio n. 20
0
def submit_post_likes(request):
    post_id = request.data.get('post_id')
    user = request.user
    if not (post_id and user):
        return JsonResponse(ErrorSerializer(get_error(103)).data,
                            status=HTTPStatus.BAD_REQUEST)
    post = Post.objects.filter(id=post_id).first()
    if (post is None):
        return JsonResponse(get_error_serialized(100, "Post not found!").data,
                            status=HTTPStatus.NOT_FOUND)
    like_ = PostLike.objects.filter(post=post_id, user=user.id).first()
    if (like_ is not None):
        return JsonResponse(ErrorSerializer(get_error(110)).data,
                            status=HTTPStatus.BAD_REQUEST)
    data = {'post': post_id, 'user': user.id}
    like = PostLikeSerializer(data=data)
    if (like.is_valid()):
        like.save()
    else:
        return JsonResponse(like.errors, status=HTTPStatus.BAD_REQUEST)
    return JsonResponse({'message': 'Like submitted.'},
                        status=HTTPStatus.CREATED)
Esempio n. 21
0
def home_posts(request):
    user = request.user
    order_key = request.query_params.get('order_key', 'new')  # hot, new, top
    if not order_key in ['hot', 'new', 'top']:
        return JsonResponse({"error": ErrorSerializer(get_error(108)).data},
                            status=status.HTTP_400_BAD_REQUEST)

    category_filter = request.query_params.get('category_filter', None)
    if (category_filter is not None) and (len(category_filter) > 2):
        cf_mapped = categoryname_mapper(category_filter)
        if cf_mapped is not None: category_filter = cf_mapped

    try:
        offset_str = request.query_params.get('offset', None)
        if not (offset_str is None): offset = int(offset_str)
    except:
        return JsonResponse({
            "error":
            get_error_serialized(110, 'offset must be integer').data
        })

    communities = [com.id for com in user.in_community.all()]
    followings = [
        user.following_user for user in UserFollowing.objects.filter(user=user)
    ]

    posts = []
    if (category_filter is None) or (category_filter == ''):
        posts = Post.objects.filter(
            Q(community_id__in=communities) | Q(author=user)
            | Q(author__in=followings))
    else:
        posts = Post.objects.filter(
            Q(category=category_filter)
            & (Q(community_id__in=communities) | Q(author=user)
               | Q(author_id__in=followings)))
    posts = list(set(posts))

    ordered_posts = order_posts(posts, order_key)

    if not (offset_str is None):
        ordered_posts = ordered_posts[PCOUNT * offset:PCOUNT * (offset + 1)]

    serialized_posts = PostSerializer(ordered_posts,
                                      context={
                                          "author_depth": True,
                                          "content_depth": False,
                                          "viewer": user.username
                                      },
                                      many=True)
    return JsonResponse({"posts": serialized_posts.data})
Esempio n. 22
0
def delete_comment(request):
    user = request.user
    comment_id = request.data.get('id', None)
    if comment_id is None:
        return JsonResponse(ErrorSerializer(get_error(103)).data,
                            status=HTTPStatus.BAD_REQUEST)
    comment = Comment.objects.filter(id=comment_id, author=user.id).first()
    if (comment is None):
        return JsonResponse(get_error_serialized(100,
                                                 "Comment not found!").data,
                            status=HTTPStatus.NOT_FOUND)
    recursively_delete_comment(comment)
    return JsonResponse({'message': "Comment deleted successfully."},
                        status=HTTPStatus.OK)
Esempio n. 23
0
def get_user_likes(request):
    username = request.query_params.get('username', None)
    viewer = request.query_params.get('viewer', None)
    if not (username):
        return JsonResponse(ErrorSerializer(get_error(103)).data,
                            status=HTTPStatus.BAD_REQUEST)
    user = User.objects.filter(username=username).first()
    if (user is None):
        return JsonResponse(get_error_serialized(100, "User not found!").data,
                            status=HTTPStatus.NOT_FOUND)
    if not (request.user.is_anonymous) and viewer is None:
        viewer = request.user.username
    return JsonResponse(UserLikesSerializer(user, context={
        'viewer': viewer
    }).data,
                        status=HTTPStatus.OK)
Esempio n. 24
0
def get_user_comments(request):
    username = request.query_params.get('username')
    viewer = request.query_params.get('viewer')
    if not (username):
        return JsonResponse(ErrorSerializer(get_error(103)).data,
                            status=HTTPStatus.BAD_REQUEST)
    if (viewer is None and not request.user.is_anonymous):
        viewer = request.user.username
    user = User.objects.filter(username=username).first()
    if (user is None):
        return JsonResponse(get_error_serialized(100, "User not found!").data,
                            status=HTTPStatus.NOT_FOUND)
    return JsonResponse(data=UserCommentSerializer(user,
                                                   context={
                                                       'viewer': viewer
                                                   }).data,
                        status=HTTPStatus.OK)
Esempio n. 25
0
def delete_post_like(request):
    user = request.user
    post_id = request.data.get('id', None)
    if not (post_id and user):
        return JsonResponse(ErrorSerializer(get_error(103)).data,
                            status=HTTPStatus.BAD_REQUEST)
    post = Post.objects.filter(id=post_id).first()
    if (post is None):
        return JsonResponse(get_error_serialized(100, "Post not found!").data,
                            status=HTTPStatus.NOT_FOUND)
    like = PostLike.objects.filter(user=user.id, post=post.id).first()
    if (like is None):
        return JsonResponse(get_error_serialized(100, "Like not found!").data,
                            status=HTTPStatus.NOT_FOUND)
    like.delete()
    return JsonResponse({"message": "Like deleted successfully."},
                        status=HTTPStatus.OK)
Esempio n. 26
0
def update_post(request, is_draft=False):
    post_id = request.data.get('id')
    if is_draft:
        post = DraftPost.objects.filter(id=post_id).first()
    else:
        post = Post.objects.filter(id=post_id).first()

    if post is None:
        return JsonResponse(
            {"error": get_error_serialized(100, 'Post not found!').data},
            status=status.HTTP_400_BAD_REQUEST)

    user = request.user

    if post.author_id != user.id:
        return JsonResponse({"error": ErrorSerializer(get_error(106)).data},
                            status=status.HTTP_403_FORBIDDEN)

    # 'title', 'description', 'content', 'header_image' are valid for field update
    new_title = request.data.get('title', None)
    new_des = request.data.get('description', None)
    new_content = request.data.get('content', None)
    new_image = request.data.get('header_image', None)

    if new_title is not None:
        post.title = new_title
        post.save(update_fields=['title'])

    if new_des is not None:
        post.description = new_des
        post.save(update_fields=['description'])

    if new_content is not None:
        content_id = post.post_content_id
        content_finded = Content.objects.filter(id=content_id).first()
        content_finded.content_text = new_content
        content_finded.save(update_fields=['content_text'])

    if new_image is not None:
        post.header_image = new_image
        post.save(update_fields=['header_image'])

    return JsonResponse({"message": "All fields updated successfuly"})
Esempio n. 27
0
def get_similar_to(request):
    string = request.query_params.get('text', None)
    if (string is None):
        return JsonResponse(ErrorSerializer(get_error(103)).data,
                            status=HTTPStatus.BAD_REQUEST)
    hashtags = Hashtag.objects.all()
    if string == "":
        return JsonResponse(
            {'hashtags': HashtagSerializer(hashtags, many=True).data},
            status=HTTPStatus.OK)
    edit_distances = {}
    for hashtag in hashtags:
        edit_distances[hashtag] = edit_distance(string, hashtag.text,
                                                len(string), len(hashtag.text))
    hashtags = sorted(list(hashtags), key=lambda h: edit_distances[h])
    result = [h for h in hashtags if edit_distances[h] < len(h.text)]
    return JsonResponse(
        {'hashtags': HashtagSerializer(result, many=True).data},
        status=HTTPStatus.OK)
Esempio n. 28
0
def delete_post(request, is_draft=False):
    author = request.user
    post_id = request.query_params.get('id', None)
    if post_id is None:
        return JsonResponse(
            {"error": get_error_serialized(103, 'id field is required').data},
            status=status.HTTP_400_BAD_REQUEST)
    if is_draft:
        post = DraftPost.objects.filter(id=post_id).first()
    else:
        post = Post.objects.filter(id=post_id).first()
    if post is None:
        return JsonResponse(
            {"error": get_error_serialized(100, 'Post not found!').data},
            status=status.HTTP_400_BAD_REQUEST)
    if author.id == post.author_id:
        post.delete()
        return JsonResponse(
            {"message": f"Post with ID:{post_id} deleted successfuly"})
    else:
        return JsonResponse({"error": ErrorSerializer(get_error(106)).data},
                            status=status.HTTP_403_FORBIDDEN)
Esempio n. 29
0
def create_post(request, is_draft=False):
    author = request.user
    author_id = author.id

    # is_draft = request.data.get('is_draft', False)

    title = request.data.get('title', '')
    content = request.data.get('content',
                               '')  # A base64 string for psot content
    category = request.data.get('category', None)
    content_type = request.data.get(
        'content_type', 'OT')  # AV: ArticleView, OI: OnlyImage, OT: OnlyText
    description = request.data.get('description', '')
    community_name = request.data.get('community_name')
    hashtags = request.data.get('hashtags')

    community = Community.objects.filter(
        name__iexact=community_name.lower()).first()
    if community is None and not (community_name is None
                                  or community_name == ''):
        return JsonResponse({"error": ErrorSerializer(get_error(100)).data},
                            status=status.HTTP_400_BAD_REQUEST)

    if community_name == '':
        community_name = None

    if category is None or category == "":
        post_category = None
    else:
        if len(category) > 2:
            category = next(
                (cat[0] for cat in categories_list if cat[1] == category),
                'XXXX')
        post_category = Category.objects.filter(name=category).first()
        if post_category is None:
            return JsonResponse(
                {
                    "error":
                    get_error_serialized(100,
                                         'This category is not allowed').data
                },
                status=status.HTTP_400_BAD_REQUEST)

    header_image = request.data.get('header_image')

    post_content = Content(content_type=content_type, content_text=content)
    post_content.save()

    if is_draft:
        to_create_post = DraftPost(title=title,
                                   description=description,
                                   post_content=post_content,
                                   category=post_category,
                                   community=community,
                                   author=author)
    else:
        if not (community_name is None) and community.disabeled_users.filter(
                username=author.username).exists():
            return JsonResponse({"error": get_error_serialized(119).data},
                                status=status.HTTP_400_BAD_REQUEST)
        to_create_post = Post(title=title,
                              description=description,
                              post_content=post_content,
                              category=post_category,
                              community=community,
                              author=author)
    to_create_post.save()

    # adding image field after saving post in database because of image name is generated based on post_id
    # and post_id is declared after saving post in database
    to_create_post.header_image = header_image
    to_create_post.save(update_fields=['header_image'])
    hashtags = HashtagListSerializer(data=request.data)
    if (hashtags.is_valid()):
        texts = hashtags.data['hashtags']
        value = submit_post_hashtags(to_create_post, texts)
        print(value)
    serialized_post = PostSerializer(to_create_post).data
    return JsonResponse({
        "post_created":
        serialized_post,
        "message":
        f"Post created successfuly. author ID: {author_id}, post content ID: {post_content.id}"
    })