Beispiel #1
0
 def test_get_post_with_comments_url(self):
     """Testing TestCreatePostEndpoint returns comment url"""
     self.client.force_authenticate(user=self.author)
     res1 = self.client.post(self.create_post_url, PAYLOAD)
     post_id = res1.data['id']
     post_object = Post.objects.get(id=post_id)
     Comment.objects.create(author=AuthorProfileSerializer(
         self.author).data,
                            comment="First comment",
                            post=post_object)
     Comment.objects.create(author=AuthorProfileSerializer(
         self.author).data,
                            comment="Second comment",
                            post=post_object)
     res2 = self.client.get(self.create_post_url, PAYLOAD)
     self.assertEqual(res2.data[0]['count'], 2)
 def payload(self, author):
     payload = {
         'comment': CONTENT,
         'contentType': Comment.CT_MARKDOWN,
         'author': AuthorProfileSerializer(author).data,
     }
     return payload
    def test_get_id_url(self):
        """Test get comment url """
        comment = Comment.objects.create(
            author=AuthorProfileSerializer(self.author).data,
            comment=COMMENT_CONTENT,
            post=self.post,
        )

        self.assertRegex(comment.get_id_url(), r'^http.+/author/.+/posts/.+/comments/.+$')
    def test_create_plain_text_comment(self):
        """Test Comment Object can choose plain text for content"""
        comment = Comment.objects.create(
            author=AuthorProfileSerializer(self.author).data,
            comment=COMMENT_CONTENT,
            post=self.post,
            contentType=Comment.CT_PLAIN
        )

        self.assertTrue(comment.contentType, Comment.CT_PLAIN)
    def test_create_comment(self):
        """Test creation of Comment Object"""
        comment = Comment.objects.create(
            author=AuthorProfileSerializer(self.author).data,
            comment=COMMENT_CONTENT,
            post=self.post,
        )

        self.assertEqual(comment.type, 'comment')
        self.assertEqual(comment.author['username'], self.author.username)
        self.assertTrue(isinstance(comment.id, uuid.UUID))
        self.assertEqual(comment.comment, COMMENT_CONTENT)
        self.assertTrue(isinstance(comment.published, datetime))
        self.assertTrue(comment.contentType, Comment.CT_MARKDOWN)
Beispiel #6
0
    def retrieve(self, request, *args, **kwargs):
        admin_approval_safeguard(self)
        request_author_id = self.kwargs['id']
        try:
            models.Following.objects.get(author=request_author_id)
        except:
            return Response({'error': ["Author not found"]},
                            status=status.HTTP_404_NOT_FOUND)

        local_friends = models.Following.get_all_local_friends(
            self, request_author_id)
        remote_friends_list = list(
            models.Following.get_all_remote_friends(
                self, request_author_id).values())
        local_friends_list = AuthorProfileSerializer(local_friends,
                                                     many=True).data

        for item in local_friends_list:
            remote_friends_list.append(item)

        return Response({
            'type': 'friends',
            'items': remote_friends_list,
        })
 def get_followers(self, obj):
     followersObj = obj.all().first()
     allFollowers = followersObj.followers.all()
     return [AuthorProfileSerializer(obj).data for obj in allFollowers]
Beispiel #8
0
 def object(self):
     return AuthorProfileSerializer(self.author).data
Beispiel #9
0
 def actor(self): 
     return AuthorProfileSerializer(self.follower).data
Beispiel #10
0
class FollowersSerializer(serializers.ModelSerializer):
    followers = AuthorProfileSerializer(read_only=True, many=True)

    class Meta:
        model = models.Followers
        fields = ('followers', )
Beispiel #11
0
 def get_friends(self, obj):
     friends = AuthorProfileSerializer(obj.friends(), many=True)
     return friends.data
Beispiel #12
0
class FriendSerializer(serializers.ModelSerializer):
    following = AuthorProfileSerializer(read_only=True, many=True)

    class Meta:
        model = models.Author
        fields = ('following', )
 def receive_comments_payload(self, author):
     payload = {
         'author': AuthorProfileSerializer(author).data,
     }
     return payload
Beispiel #14
0
    def post(self, request, *args, **kwargs):
        admin_approval_safeguard(self)
        request_author_id = self.kwargs['id']
        request_foreign_author_id = self.kwargs['foreignId']
        try:
            author_following = models.Following.objects.get(
                author=request_author_id)
        except:
            return Response({'error': ["Author not found"]},
                            status=status.HTTP_404_NOT_FOUND)

        # Check required fields in the body
        try:
            actor_host = request.data['actor']['host']
            object_host = request.data['object']['host']
        except:
            return Response({'error': ['Please provide required fields']},
                            status=status.HTTP_400_BAD_REQUEST)

        try:
            # Remote following
            if actor_host == utils.HOST and object_host != utils.HOST:
                remote_following_ids = author_following.remote_following.keys()
                if request_foreign_author_id in remote_following_ids:
                    return Response({
                        'type':
                        'following',
                        'items': [{
                            'status': True,
                            'author': request_author_id,
                            'following': request_foreign_author_id,
                        }]
                    })
            # Local following
            elif actor_host == utils.HOST and object_host == utils.HOST:
                try:
                    author = models.Author.objects.get(
                        id=request_foreign_author_id)
                except:
                    Response({'error': ["Following Author doesn't exist"]},
                             status=status.HTTP_400_BAD_REQUEST)

                local_following = author_following.following.all()
                local_following_json = AuthorProfileSerializer(local_following,
                                                               many=True).data
                for i in local_following_json:
                    if (i.get('id') == request_foreign_author_id):
                        return Response({
                            'type':
                            'following',
                            'items': [{
                                'status': True,
                                'author': request_author_id,
                                'following': request_foreign_author_id,
                            }]
                        })

            return Response({
                'type':
                'following',
                'items': [{
                    'status': False,
                    'author': request_author_id,
                    'following': request_foreign_author_id,
                }]
            })
        except:
            return Response({'error': ["Bad Request"]},
                            status=status.HTTP_400_BAD_REQUEST)
Beispiel #15
0
    def update(self, request, *args, **kwargs):
        request_author_id = self.kwargs['id']
        request_foreign_author_id = self.kwargs['foreignId']

        if (request_author_id == request_foreign_author_id):
            return Response({'error': ['You cannot follow yourself']},
                            status=status.HTTP_400_BAD_REQUEST)
        # TODO: Clean up this code
        elif (not self.request.user.adminApproval):
            raise AuthenticationFailed(
                detail={"error": ["User has not been approved by admin"]})

        # Check required fields in the body
        try:
            actor_data = request.data['actor']
            actor_host = request.data['actor']['host']
            actor_id = request.data['actor']['id']
            object_host = request.data['object']['host']
            object_data = request.data['object']
            object_id = request.data['object']['id']
        except:
            return Response({'error': ['Please provide required fields']},
                            status=status.HTTP_400_BAD_REQUEST)

        # Handle all cases
        inboxData = {}
        # Remote Follower
        if object_host == utils.HOST and actor_host != utils.HOST:
            try:
                author_obj = models.Author.objects.get(id=request_author_id)
            except:
                raise ValidationError({"error": ["Author not found"]})

            author = models.Followers.objects.get(author=author_obj)
            actor_data["id"] = request_foreign_author_id
            author.remoteFollowers[request_foreign_author_id] = actor_data

            author.save()

            inboxData = request.data
        # Local Follower
        elif object_host == utils.HOST and actor_host == utils.HOST:
            if str(request_foreign_author_id) != str(request.user.id):
                return Response(
                    {
                        'error': [
                            'This is not your account, you cannot follow this author'
                        ]
                    },
                    status=status.HTTP_401_UNAUTHORIZED)

            try:
                foreign_author_obj = models.Author.objects.get(
                    id=request_foreign_author_id)
                foreign_author_following = models.Following.objects.get(
                    author=foreign_author_obj)
                author_obj = models.Author.objects.get(id=request_author_id)
                author_follower = models.Followers.objects.get(
                    author=author_obj)
            except:
                return Response({'error': ["Author not found"]},
                                status=status.HTTP_404_NOT_FOUND)

            author_follower.followers.add(foreign_author_obj)
            author_follower.save()
            foreign_author_following.following.add(author_obj)
            foreign_author_following.save()

            inboxData['type'] = 'follow'
            inboxData[
                'summary'] = f"{foreign_author_obj.username} wants to follow {author_obj.username}"
            inboxData['actor'] = AuthorProfileSerializer(
                foreign_author_obj).data
            inboxData['object'] = AuthorProfileSerializer(author_follower).data
        # us following remote author
        elif object_host != utils.HOST and actor_host == utils.HOST:
            # For Team 6
            if object_host == TEAM6_HOST:
                correct_url = formaturl(object_host)
                parsed_uri = urlparse(correct_url)
                object_host = '{uri.scheme}://{uri.netloc}/'.format(
                    uri=parsed_uri)
                print(object_host)
                try:
                    node = Node.objects.get(remote_server_url=object_host)

                    response = requests.put(
                        f"{object_host}author/{request_author_id}/followers/{request_foreign_author_id}",
                        json=request.data,
                        auth=(node.konnection_username,
                              node.konnection_password))

                    if response.status_code != 201:
                        # Their problem
                        return Response(
                            {'error': ['Contact team 6 for the error']},
                            status=response.status_code)
                    else:
                        author = models.Following.objects.get(
                            author=request_foreign_author_id)
                        object_data["id"] = request_author_id

                        author.remote_following[
                            request_author_id] = object_data

                        author.save()

                        return Response({'message': ['Successful']},
                                        status=response.status_code)
                except Exception:
                    # Our problem
                    return Response({'error': ["Bad request"]},
                                    status=status.HTTP_400_BAD_REQUEST)

            parsed_uri = urlparse(object_host)
            object_host = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)

            try:
                node = Node.objects.get(remote_server_url=object_host)
                response = requests.put(
                    f"{object_host}api/author/{request_author_id}/followers/{request_foreign_author_id}/",
                    json=request.data,
                    auth=(node.konnection_username, node.konnection_password))

                if response.status_code != 201:
                    # Their problem
                    return Response({'error': ['Following unsuccessful']},
                                    status=response.status_code)
                else:
                    author = models.Following.objects.get(
                        author=request_foreign_author_id)
                    author.remote_following[object_id] = object_data
                    author.save()

                    return Response({'message': ['Successful']},
                                    status=response.status_code)
            except Exception:
                # Our problem
                return Response({'error': ["Bad request"]},
                                status=status.HTTP_400_BAD_REQUEST)

        else:
            return Response({'error': ['Bad request']},
                            status=status.HTTP_400_BAD_REQUEST)

        inbox = Inbox.objects.get(author=author_obj)
        inbox.items.append(inboxData)
        inbox.save()

        return Response({
            'type':
            'follow',
            'items': [{
                'status': True,
                'author': request_author_id,
                'follower': request_foreign_author_id,
            }]
        })
Beispiel #16
0
 def get_author(self, obj):
     author = AuthorProfileSerializer(obj.author).data
     return author