Esempio n. 1
0
 def chat_authenticate(self, event):
     token = event.get('access_token', None)
     user = authenticate(token)
     self.user = user
     if (user.is_anonymous):
         self.send(
             json.dumps({
                 "error":
                 get_error_serialized(AUTHENTICATION_FAILED).data
             }))
         self.close()
         return
     if (user.username != self.room_name):
         self.send(
             json.dumps(
                 {"error": get_error_serialized(PERMISSION_DENIED).data}))
         self.close()
         return
     last_seen_data = LastSeen.objects.filter(user=user).first()
     if (last_seen_data is None):
         last_seen_data = LastSeen.objects.create(user=self.user)
     # last_seen_data.last_seen = now()
     last_seen_data.save()
     record = Clients.objects.filter(
         username=user, channel_name=self.channel_name).first()
     if (record is None):
         Clients.objects.create(username=user,
                                channel_name=self.channel_name)
     self.send(
         json.dumps({
             "type": "chat.authenticate",
             "message": "Authenticatied."
         }))
Esempio n. 2
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. 3
0
def posts_by_hashtag(request):
    user = request.user

    hashtag_text = request.query_params.get('hashtag', None)
    if hashtag_text == "": hashtag_text = None

    if hashtag_text is None:
        return JsonResponse(
            {
                "error":
                get_error_serialized(103, 'hashtag field is required').data
            },
            status=status.HTTP_400_BAD_REQUEST)

    hashtag = Hashtag.objects.filter(text=hashtag_text).first()

    if hashtag is None:
        return JsonResponse(
            {"error": get_error_serialized(100, 'Hashtag not found').data},
            status=status.HTTP_404_NOT_FOUND)

    posts_found_id = PostHashtag.objects.filter(hashtag=hashtag).values_list(
        'post', flat=True)
    posts_found = Post.objects.filter(Q(pk__in=posts_found_id))
    return JsonResponse({
        "posts":
        PostSerializer(posts_found,
                       many=True,
                       context={
                           "content_depth": False
                       }).data
    })
def delete_community(request):
    user = request.user

    community_name = request.data.get('community_name', None)

    community = Community.objects.filter(
        name__iexact=community_name.lower()).first()
    if community is None:
        return JsonResponse(
            {"error": get_error_serialized(100, 'Community not found').data},
            status=status.HTTP_404_NOT_FOUND)

    if community.admin != user:
        return JsonResponse(
            {
                "error":
                get_error_serialized(
                    106,
                    'Only community admin is allowed for this request').data
            },
            status=status.HTTP_404_NOT_FOUND)

    community.delete()

    return JsonResponse({"message": "Community deleted successfuly"})
Esempio n. 5
0
def send_unfollow(request):
    user = request.user

    to_unfollow_username = request.query_params.get('to_unfollow', None)
    if to_unfollow_username is None:
        return JsonResponse({
            "error":
            get_error_serialized(
                103, 'Username of to unfollow user must be sended').data
        })

    to_unfollow = User.objects.filter(username=to_unfollow_username).first()
    if to_unfollow is None:
        return JsonResponse({
            "error":
            get_error_serialized(
                100, 'User with sended username does not exists').data
        })

    finded_following = UserFollowing.objects.filter(
        user=user, following_user=to_unfollow).first()

    if finded_following is None:
        return JsonResponse({"error": get_error_serialized(111).data})

    finded_following.delete()

    return JsonResponse(
        {"message": f"User {to_unfollow_username} unfollowed successfuly"})
Esempio n. 6
0
def send_follow(request):
    user = request.user

    to_follow_username = request.data.get('to_follow', None)
    if to_follow_username is None:
        return JsonResponse({
            "error":
            get_error_serialized(
                103, 'Username of to follow user must be sended').data
        })

    to_follow = User.objects.filter(username=to_follow_username).first()
    if to_follow is None:
        return JsonResponse({
            "error":
            get_error_serialized(
                100, 'User with sended username does not exists').data
        })

    if UserFollowing.objects.filter(user=user,
                                    following_user=to_follow).exists():
        return JsonResponse({"error": get_error_serialized(112).data})

    UserFollowing.objects.create(user=user, following_user=to_follow)

    return JsonResponse({
        "message":
        f"user {to_follow.username} followed by {user.username} successfuly"
    })
Esempio n. 7
0
def user_followings(request):
    viewer = request.user
    username = request.query_params.get('username', None)
    if username is None:
        return JsonResponse(
            {"error": get_error_serialized(103, 'Username is required').data})

    user = User.objects.filter(username=username).first()
    if user is None:
        return JsonResponse({
            "error":
            get_error_serialized(
                100, 'User with sended username does not exists').data
        })

    user_following_ids = list(
        UserFollowing.objects.filter(user=user).values_list('following_user'))

    # replace viewer followings to first
    user_following_ids.sort(key=lambda user_id: UserFollowing.objects.filter(
        user=viewer.id, following_user=user_id).exists(),
                            reverse=True)

    # replace viewer to first place
    # viewer_index = user_following_ids.index(viewer.id)
    # user_following_ids[0], user_following_ids[viewer_index] = user_following_ids[viewer_index], user_following_ids[0]

    user_followings = [
        User.objects.get(id=user_id[0]) for user_id in user_following_ids
    ]
    user_followings_serialized = PublicProfileSerializer(
        user_followings, context={"viewer_id": viewer.id}, many=True)
    return JsonResponse({"user_followings": user_followings_serialized.data})
Esempio n. 8
0
 def chat_user_profile(self, event):
     username = event.get("username", None)
     if (username is None):
         self.send(
             json.dumps({
                 "error":
                 get_error_serialized(MISSING_REQUIRED_FIELDS).data
             }))
         return
     User = get_user_model()
     user = User.objects.filter(username=username).first()
     if user is None:
         self.send(
             json.dumps({
                 "error":
                 get_error_serialized(OBJECT_NOT_FOUND,
                                      detail="user not found.").data
             }))
         return
     self.send(
         json.dumps({
             "type": "chat.user.profile",
             "user": PublicProfileSerializer(user).data
         }))
     return
Esempio n. 9
0
 def chat_message_get(self, event):
     if (self.user is None):
         self.send(
             json.dumps({
                 "error":
                 get_error_serialized(AUTHENTICATION_REQUIRED).data
             }))
         return
     other_user = event.get("from", None)
     offset = event.get("offset", None)
     count = event.get("count", None)
     if (other_user is None):
         self.send(
             json.dumps({
                 "error":
                 get_error_serialized(MISSING_REQUIRED_FIELDS).data
             }))
         return
     offset = utils.int_try_parse(offset, 0)
     count = utils.int_try_parse(count, utils.INFINITY)
     Users = get_user_model()
     other_user = Users.objects.filter(username=other_user).first()
     if (other_user is None):
         self.send(
             json.dumps({
                 "error":
                 get_error_serialized(
                     MISSING_REQUIRED_FIELDS,
                     detail="User to get messages not found!").data
             }))
         return
     chats = list(
         DirectChatMessage.objects.filter(_from=self.user, _to=other_user))
     chats += list(
         DirectChatMessage.objects.filter(_from=other_user, _to=self.user))
     chats = sorted(chats, key=lambda x: x.date)[::-1]
     result = []
     if (offset < len(chats)):
         chats = chats[offset:offset + count]
     else:
         chats = []
     for chat in chats:
         result.append(
             DirectChatViewSerializer(chat,
                                      context={
                                          "target_username":
                                          self.user.username
                                      }).data)
     self.send(
         json.dumps({
             "type": "chat.message.get",
             "_user": PublicProfileSerializer(other_user).data,
             "data": json.dumps(result)
         }))
Esempio n. 10
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. 11
0
def send_report(request):
    user = request.user

    post_id = request.data.get('post_id', None)
    subjects = request.data.get('subjects', None)
    description = request.data.get('description', None)

    if subjects is None or len(subjects) == 0 or post_id is None:
        return JsonResponse(
            {
                "error":
                get_error_serialized(
                    103, 'post_id, subjects fields is required').data
            },
            status=status.HTTP_400_BAD_REQUEST)

    subjects_obj = []
    for subject in subjects:
        report_subject = ReportSubject.objects.filter(text=subject).first()
        if report_subject is None:
            return JsonResponse(
                {
                    "error":
                    get_error_serialized(
                        100,
                        f'This subject is not allowed: \'{subject}\'').data
                },
                status=status.HTTP_400_BAD_REQUEST)
        subjects_obj.append(report_subject)

    report_post = Post.objects.filter(id=post_id).first()
    if report_post is None:
        return JsonResponse(
            {"error": get_error_serialized(100, 'Post not found').data},
            status=status.HTTP_404_NOT_FOUND)

    if Reports.objects.filter(user=user, post=report_post).exists():
        return JsonResponse({"error": get_error_serialized(115).data},
                            status=status.HTTP_406_NOT_ACCEPTABLE)

    created_report = Reports.objects.create(user=user,
                                            post=report_post,
                                            description=description)
    for subject in subjects_obj:
        PostReport.objects.create(subject=subject, report=created_report)

    report_post.reports_number += 1

    return JsonResponse(
        {"message": f"report to post with id:{post_id} sended"})
Esempio n. 12
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. 13
0
 def chat_users(self, event):
     if (self.user is None):
         self.send(
             json.dumps({
                 "error":
                 get_error_serialized(AUTHENTICATION_REQUIRED).data
             }))
         return
     chats_from_user = list(
         DirectChatMessage.objects.filter(_from=self.user))
     chats_to_user = list(DirectChatMessage.objects.filter(_to=self.user))
     records = chats_from_user + chats_to_user
     records = sorted(records, key=lambda x: x.date)[::-1]
     users = []
     for record in records:
         if (record._from.id == self.user.id and record._to not in users):
             users.append(record._to)
         elif (record._to.id == self.user.id and record._from not in users):
             users.append(record._from)
     result = []
     for user in users:
         result.append(
             ChatUsersSerializer(user,
                                 context={
                                     "target_username": self.user.username
                                 }).data)
     self.send(json.dumps({"type": "chat.users", "data": result}))
Esempio n. 14
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. 15
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. 16
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. 17
0
def search_in_users(request):

    serach_key = request.query_params.get('key', None)
    if (serach_key is None):
        return JsonResponse(
            {'error': get_error_serialized(103, 'key parameter is required')},
            status=HTTPStatus.BAD_REQUEST)

    data_usernames = []
    data_firstnames = []
    data_lastnames = []
    for user in User.objects.all():
        data_usernames.append((user.username, user.id))
        data_firstnames.append((user.first_name, user.id))
        data_lastnames.append((user.last_name, user.id))

    all_users_finded = []
    all_users_finded.extend(list(set(search(serach_key, data_usernames))))

    all_users_finded.extend(list(set(search(serach_key, data_firstnames))))

    all_users_finded.extend(list(set(search(serach_key, data_lastnames))))

    all_users_finded_ = User.objects.filter(Q(id__in=all_users_finded))

    return JsonResponse({
        "users_finded":
        PublicProfileSerializer(all_users_finded_, many=True).data
    })
def update_community(request):
    user = request.user

    community_name = request.data.get('community_name', None)

    community = Community.objects.filter(
        name__iexact=community_name.lower()).first()
    if community is None:
        return JsonResponse(
            {"error": get_error_serialized(100, 'Community not found').data},
            status=status.HTTP_404_NOT_FOUND)

    if community.admin != user:
        return JsonResponse(
            {
                "error":
                get_error_serialized(
                    106,
                    'Only community admin is allowed for this request').data
            },
            status=status.HTTP_404_NOT_FOUND)

    new_name = request.data.get('name', None)
    new_about = request.data.get('about', None)
    new_pic = request.data.get('picture', None)
    new_banner = request.data.get('banner_picture', None)

    if not (new_name is None):
        if Community.objects.filter(name__iexact=new_name.lower()).exists():
            return JsonResponse({"error": get_error_serialized(109).data},
                                status=status.HTTP_400_BAD_REQUEST)
        community.name = new_name.lower()
        community.save(update_fields=['name'])

    if not (new_about is None):
        community.about = new_about
        community.save(update_fields=['about'])

    if not (new_pic is None):
        community.picture = new_pic
        community.save(update_fields=['picture'])

    if not (new_banner is None):
        community.banner_picture = new_banner
        community.save(update_fields=['banner_picture'])

    return JsonResponse({"message": "all fields updated successfuly"})
Esempio n. 19
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. 20
0
 def chat_message_see(self, event):
     other_side_message_type = "chat.message.saw"
     chat_id = event.get("id", None)
     if (self.user is None):
         self.send(
             json.dumps({
                 "error":
                 get_error_serialized(AUTHENTICATION_REQUIRED).data
             }))
         return
     if (chat_id is None):
         self.send(
             json.dumps({
                 "error":
                 get_error_serialized(MISSING_REQUIRED_FIELDS).data
             }))
         return
     chat = DirectChatMessage.objects.filter(id=chat_id).first()
     if (chat is None):
         self.send(
             json.dumps({
                 "error":
                 get_error_serialized(OBJECT_NOT_FOUND,
                                      detail="chat not found.").data
             }))
         return
     if (chat._to != self.user):
         self.send(
             json.dumps(
                 {"error": get_error_serialized(PERMISSION_DENIED).data}))
         return
     chat.seen = True
     chat.save()
     other_side = chat._from
     other_side_sessions = Clients.objects.filter(username=other_side)
     data = {
         "type": other_side_message_type,
         "id": chat_id,
         'user': PublicProfileSerializer(self.user).data,
         'uuid': str(chat.uuid)
     }
     for session in other_side_sessions:
         channel_layer = get_channel_layer()
         async_to_sync(channel_layer.send)(session.channel_name, data)
Esempio n. 21
0
def reports_number(request):
    post_id = request.query_params.get('post_id', None)
    if post_id is None:
        return JsonResponse(
            {
                "error":
                get_error_serialized(103, 'post_id field is required').data
            },
            status=status.HTTP_400_BAD_REQUEST)

    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_404_NOT_FOUND)

    reports_number = Reports.objects.filter(post=post).count()

    return JsonResponse({"reports_number": reports_number})
Esempio n. 22
0
 def chat_control(self, event):
     _from = event.get("from", None)
     _to = event.get("to", None)
     data = event.get("data", None)
     if (self.user is None):
         self.send(
             json.dumps({
                 "error":
                 get_error_serialized(AUTHENTICATION_REQUIRED).data
             }))
         return
     if (_to is None and _from is None) or (
         (_to is not None and _from is not None) or data is None):
         self.send(
             json.dumps({
                 "error":
                 get_error_serialized(MISSING_REQUIRED_FIELDS).data
             }))
         return
     User = get_user_model()
     if (_to is not None):
         user_to = User.objects.filter(username=_to).first()
         if (user_to is None):
             self.send(
                 json.dumps({
                     "error":
                     get_error_serialized(OBJECT_NOT_FOUND,
                                          detail="user not found.").data
                 }))
             return
         active_sessions = Clients.objects.filter(username=user_to)
         for session in active_sessions:
             send_data = {
                 "type": "chat.control",
                 "from": self.user.username,
                 "data": data
             }
             channel_layer = get_channel_layer()
             async_to_sync(channel_layer.send)(session.channel_name,
                                               send_data)
     #recieved control message from other users so send it to client
     elif (_from is not None):
         self.send(json.dumps(event))
def disable_user(request):
    user = request.user

    community_name = request.data.get('community_name', None)
    if community_name is None:
        return JsonResponse(
            {
                "error":
                get_error_serialized(
                    103, '\'community_name\' field is required').data
            },
            status=status.HTTP_400_BAD_REQUEST)

    community = Community.objects.filter(
        name__iexact=community_name.lower()).first()
    if community is None:
        return JsonResponse(
            {"error": get_error_serialized(100, 'Community not found').data},
            status=status.HTTP_404_NOT_FOUND)

    if community.admin != user:
        return JsonResponse(
            {
                "error":
                get_error_serialized(
                    106,
                    'Only community admin is allowed for this request').data
            },
            status=status.HTTP_404_NOT_FOUND)

    username = request.data.get('username', None)

    dis_user = User.objects.filter(username=username).first()
    if dis_user is None:
        return JsonResponse(
            {"error": get_error_serialized(100, 'User not found').data},
            status=status.HTTP_400_BAD_REQUEST)

    community.disabeled_users.add(dis_user)

    return JsonResponse(
        {"message": "User added to disabeled users successfuly"})
Esempio n. 24
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. 25
0
def post_reports(request):
    post_id = request.query_params.get('post_id', None)
    if post_id is None:
        return JsonResponse(
            {
                "error":
                get_error_serialized(103, 'post_id field is required').data
            },
            status=status.HTTP_400_BAD_REQUEST)

    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_404_NOT_FOUND)

    all_reports = Reports.objects.filter(post=post)

    return JsonResponse(
        {"reports": ReportSerializer(all_reports, many=True).data})
def remove_user(request):
    user = request.user

    community_name = request.data.get('community_name', None)

    community = Community.objects.filter(
        name__iexact=community_name.lower()).first()
    if community is None:
        return JsonResponse(
            {"error": get_error_serialized(100, 'Community not found').data},
            status=status.HTTP_404_NOT_FOUND)

    if community.admin != user:
        return JsonResponse(
            {
                "error":
                get_error_serialized(
                    106,
                    'Only community admin is allowed for this request').data
            },
            status=status.HTTP_404_NOT_FOUND)

    username = request.data.get('username', None)

    del_user = User.objects.filter(username=username).first()
    if del_user is None:
        return JsonResponse(
            {"error": get_error_serialized(100, 'User not found').data},
            status=status.HTTP_400_BAD_REQUEST)

    if not community.users.filter(username=username).exists():
        return JsonResponse({"error": get_error_serialized(117).data},
                            status=status.HTTP_400_BAD_REQUEST)

    if del_user == user:
        return JsonResponse({"error": get_error_serialized(118).data},
                            status=status.HTTP_400_BAD_REQUEST)

    community.users.remove(del_user)

    return JsonResponse({"message": "User removed from community successfuly"})
Esempio n. 27
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)
def is_admin(request):
    user = request.user
    communtiy_name = request.query_params.get('community', None)
    if communtiy_name is None:
        return JsonResponse(
            {
                "error":
                get_error_serialized(103,
                                     '\'community\' field is required').data
            },
            status=status.HTTP_400_BAD_REQUEST)

    community = Community.objects.filter(
        name__iexact=communtiy_name.lower()).first()
    if community is None:
        return JsonResponse(
            {"error": get_error_serialized(100, 'Community not found').data},
            status=status.HTTP_404_NOT_FOUND)

    is_admin = community.admin == user
    return JsonResponse({"is_admin": is_admin})
Esempio n. 29
0
 def get_usneen_messages_count(self, instance):
     target_username = self.context.get("target_username", None)
     target = User.objects.filter(username=target_username).first()
     if (target is None):
         return {
             "error":
             get_error_serialized(OBJECT_NOT_FOUND,
                                  detail="User not found.")
         }
     records = list(
         DirectChatMessage.objects.filter(_from=instance, _to=target))
     return len([r for r in records if not r.seen])
Esempio n. 30
0
def update_password(request):
    user = request.user

    old_pass = request.data.get('old_password', None)
    new_pass = request.data.get('new_password', None)

    if not (old_pass and new_pass):
        return JsonResponse(
            {
                "error":
                get_error_serialized(
                    103, "new_password or old_password field is required").data
            },
            status=status.HTTPStatus.BAD_REQUEST)

    if not User.check_password(user, old_pass):
        return JsonResponse({"error": get_error_serialized(101).data},
                            status=HTTPStatus.BAD_REQUEST)

    user.set_password(new_pass)
    user.save(update_fields=['password'])

    return JsonResponse({"message": "password successfuly updated"})