Beispiel #1
0
    def delete(self, request, id, Format=None):
        logger.info('-' * 100)
        logger.info(f'Submission "{id}" delete =>')

        # Gets the reddit instance from the user in request (ClientOrg)
        reddit, client_org = Utils.new_client_request(request.user)
        # Get subreddit instance with the name provided
        submission = SubmissionsUtils.get_sub_if_exists(id, reddit)
        if not submission:
            raise exceptions.NotFound(
                detail={'detail': f'No submission exists with the id: {id}.'}
            )

        status_code = status.HTTP_200_OK
        if not reddit.read_only:
            # Only can delete the submission if author is the same as the reddit instance
            # So check for submission redditor and reddit redditor
            submission_redditor = submission.author
            if submission_redditor:
                redditor_id, redditor_name = ClientsUtils.get_redditor_id_name(
                    client_org
                )
                if submission_redditor.id == redditor_id:
                    # Try to delete the submission now
                    try:
                        submission.delete()
                        msg = f'Submission \'{id}\' successfully deleted.'
                        logger.info(msg)
                    except Exception as ex:
                        msg = (
                            f'Error deleting submission. Exception raised: {repr(ex)}.'
                        )
                        status_code = status.HTTP_503_SERVICE_UNAVAILABLE
                        logger.error(msg)
                else:
                    msg = (
                        f'Cannot delete the submission with id: {id}. '
                        f'The authenticated reddit user u/{redditor_name} '
                        f'needs to be the same as the submission\'s author u/{submission_redditor.name}'
                    )
                    status_code = status.HTTP_403_FORBIDDEN
                    logger.info(msg)
            else:
                msg = (
                    f'Cannot delete the submission with id: {id}. '
                    'The submission was already deleted or there is no '
                    'way to verify the author at this moment.'
                )
                status_code = status.HTTP_404_NOT_FOUND
                logger.info(msg)
        else:
            msg = (
                f'Reddit instance is read only. Cannot delete submission with id: {id}.'
            )
            status_code = status.HTTP_405_METHOD_NOT_ALLOWED
            logger.warn(msg)

        return Response({'detail': msg}, status=status_code)
Beispiel #2
0
    def patch(self, request, id, Format=None):
        logger.info('-' * 100)
        logger.info(f'Comment "{id}" patch =>')

        # Gets the reddit instance from the user in request (ClientOrg)
        reddit, client_org = Utils.new_client_request(request.user)
        comment = CommentsUtils.get_comment_if_exists(id, reddit)
        if comment is None:
            raise exceptions.NotFound(
                detail={'detail': f'No comment exists with the id: {id}.'})

        # Get the markdown content from json body attribute
        markdown_body = Utils.validate_body_value(request.data.get('body'))

        status_code = status.HTTP_200_OK
        updated_comment_data = None
        if not reddit.read_only:
            # Only can modify the comment if author is the same as the client redditor
            # So check for comment redditor and client data
            comment_redditor = comment.author
            redditor_id, redditor_name = ClientsUtils.get_redditor_id_name(
                client_org)

            if comment_redditor.id == redditor_id:
                # Try to delete the comment now
                try:
                    updated_comment = comment.edit(markdown_body)
                    # Here I need to call refresh() to get the actual replies count
                    updated_comment.refresh()
                    updated_comment_data = CommentsUtils.get_comment_data(
                        updated_comment)
                    msg = f'Comment \'{updated_comment.id}\' successfully edited.'
                    logger.info(msg)
                except Exception as ex:
                    msg = f'Error edit comment. Exception raised: {repr(ex)}.'
                    status_code = status.HTTP_503_SERVICE_UNAVAILABLE
                    logger.error(msg)
            else:
                msg = (
                    f'Cannot edit the comment with id: {id}. '
                    f'The authenticated reddit user u/{redditor_name} '
                    f'needs to be the same as the comment\'s author u/{comment_redditor.name}'
                )
                status_code = status.HTTP_403_FORBIDDEN
                logger.info(msg)
        else:
            msg = f'Reddit instance is read only. Cannot edit comment with id: {id}.'
            status_code = status.HTTP_405_METHOD_NOT_ALLOWED
            logger.warn(msg)

        return Response({
            'detail': msg,
            'comment': updated_comment_data
        },
                        status=status_code)
Beispiel #3
0
    def post(self, request, id, Format=None):
        logger.info('-' * 100)
        logger.info(f'Submission "{id}" reply =>')

        # Gets the reddit instance from the user in request (ClientOrg)
        reddit, client_org = Utils.new_client_request(request.user)
        # Get subreddit instance with the name provided
        submission = SubmissionsUtils.get_sub_if_exists(id, reddit)
        if not submission:
            raise exceptions.NotFound(
                detail={'detail': f'No submission exists with the id: {id}.'}
            )

        # Get the markdown content from json body attribute
        markdown_body = Utils.validate_body_value(request.data.get('body'))

        comment_data = None
        status_code = status.HTTP_201_CREATED
        if not reddit.read_only:
            # Try to post the comment to the submission
            try:
                comment = submission.reply(markdown_body)
                comment_data = CommentsUtils.get_comment_data(comment)
                _, redditor_name = ClientsUtils.get_redditor_id_name(client_org)
                msg = (
                    f'New comment posted by u/{redditor_name} with id \'{comment.id}\' '
                    f'to submission with id: {id}'
                )
                logger.info(msg)
            except Exception as ex:
                if isinstance(ex, Forbidden):
                    msg = (
                        f'Cannot create a comment in submission with id: {id}. '
                        f'Forbidden exception: {repr(ex)}'
                    )
                    status_code = status.HTTP_403_FORBIDDEN
                else:
                    msg = (
                        f'Error creating comment in submission with id: {id}. '
                        f'Exception raised: {repr(ex)}.'
                    )
                    status_code = status.HTTP_503_SERVICE_UNAVAILABLE
                logger.error(msg)
        else:
            msg = f'Reddit instance is read only. Cannot create comment in submission with id: {id}.'
            status_code = status.HTTP_405_METHOD_NOT_ALLOWED
            logger.warn(msg)

        return Response({'detail': msg, 'comment': comment_data}, status=status_code)
Beispiel #4
0
 def setUp(self):
     # I need to insert a dummy client and add the token key in the client
     # credentials for authorizing all requests by the test client
     token_key = ClientsUtils.insert_dummy_client()
     self.client = APIClient()
     self.client.credentials(HTTP_AUTHORIZATION=f'Bearer {token_key}')
Beispiel #5
0
    def post(self, request, id, Format=None):
        logger.info('-' * 100)
        logger.info(f'Submission "{id}" crosspost =>')

        # Gets the reddit instance from the user in request (ClientOrg)
        reddit, client_org = Utils.new_client_request(request.user)
        # Get subreddit instance with the name provided
        submission = SubmissionsUtils.get_sub_if_exists(id, reddit)
        if not submission:
            raise exceptions.NotFound(
                detail={'detail': f'No submission exists with the id: {id}.'}
            )

        # Get required data values from json, in this case only the subreddit name
        # to crosspost the submission
        subreddit = SubredditsUtils.check_and_get_sub(
            subreddit_name := request.data.get('subreddit'), reddit
        )

        # Now get the optional data values
        title = request.data.get('title', None)
        flair_id = request.data.get('flair_id', None)
        flair_text = request.data.get('flair_text', None)
        send_replies = request.data.get('send_replies', True)
        nsfw = request.data.get('nsfw', False)
        spoiler = request.data.get('spoiler', False)

        status_code = status.HTTP_201_CREATED
        crosspost_data = None
        if not reddit.read_only:
            # Try to do the crosspost submission now
            try:
                crosspost = submission.crosspost(
                    subreddit, title, send_replies, flair_id, flair_text, nsfw, spoiler
                )
                crosspost_data = SubmissionsUtils.get_submission_data(crosspost)
                _, redditor_name = ClientsUtils.get_redditor_id_name(client_org)
                msg = (
                    f'New crosspost submission created in r/{subreddit_name} '
                    f'by u/{redditor_name} with id: {crosspost.id}.'
                )
                logger.info(msg)
            except Exception as ex:
                if isinstance(ex, Forbidden):
                    msg = (
                        f'Cannot create the crosspost submission with id: {id}. '
                        f'Forbidden exception: {repr(ex)}'
                    )
                    status_code = status.HTTP_403_FORBIDDEN
                else:
                    msg = (
                        f'Error creating crosspost submission with id: {id}. '
                        f'Exception raised: {repr(ex)}.'
                    )
                    status_code = status.HTTP_503_SERVICE_UNAVAILABLE
                logger.error(msg)
        else:
            msg = f'Reddit instance is read only. Cannot create crosspost submission with id: {id}.'
            status_code = status.HTTP_405_METHOD_NOT_ALLOWED
            logger.warn(msg)

        return Response(
            {'detail': msg, 'cross_submission': crosspost_data}, status=status_code
        )
Beispiel #6
0
    def post(self, request, name, Format=None):
        logger.info('-' * 100)
        logger.info(f'Subreddit "{name}" post submission =>')

        # Gets the reddit instance from the user in request (ClientOrg)
        reddit, client_org = Utils.new_client_request(request.user)
        # Get subreddit instance with the name provided
        subreddit = SubredditsUtils.get_sub_if_available(name, reddit)
        if subreddit is None:
            raise exceptions.NotFound(
                detail={
                    'detail': f'No subreddit exists with the name: {name}.'
                })

        # Get required data values
        title = request.data.get('title')
        if title is None:
            raise exceptions.ParseError(
                detail={
                    'detail': f'A title must be provided in the json data.'
                })
        selftext = request.data.get('selftext')
        url = request.data.get('url')

        if not selftext and not url:
            # Then it can be an image or video/gif post
            image_path = request.data.get('image_path')
            if not image_path:
                video_path = request.data.get('video_path')
                if video_path:
                    videogif = request.data.get('videogif', False)
                    thumbnail_path = request.data.get('thumbnail_path')
                else:
                    raise exceptions.ParseError(
                        detail={
                            'detail':
                            ('Either a selftext, url, image_path or video_path '
                             'must be provided in the json data.')
                        })

        # Now get optional data values
        flair_id = request.data.get('flair_id')
        flair_text = request.data.get('flair_text')
        resubmit = request.data.get('resubmit', True)
        send_replies = request.data.get('send_replies', True)
        nsfw = request.data.get('nsfw', False)
        spoiler = request.data.get('spoiler', False)
        collection_id = request.data.get('collection_id', False)

        status_code = status.HTTP_201_CREATED
        submission_data = None
        if not reddit.read_only:
            try:
                submission = None
                if selftext or url:
                    submission = subreddit.submit(
                        title,
                        selftext,
                        url,
                        flair_id,
                        flair_text,
                        resubmit,
                        send_replies,
                        nsfw,
                        spoiler,
                        collection_id,
                    )
                elif image_path:
                    # Not waiting the response here.. Not using websockets
                    subreddit.submit_image(
                        title,
                        image_path,
                        flair_id,
                        flair_text,
                        resubmit,
                        send_replies,
                        nsfw,
                        spoiler,
                        collection_id=collection_id,
                        without_websockets=True,
                    )
                else:
                    # Not waiting the response here.. Not using websockets
                    subreddit.submit_video(
                        title,
                        video_path,
                        videogif,
                        thumbnail_path,
                        flair_id,
                        flair_text,
                        resubmit,
                        send_replies,
                        nsfw,
                        spoiler,
                        collection_id=collection_id,
                        without_websockets=True,
                    )
                _, redditor_name = ClientsUtils.get_redditor_id_name(
                    client_org)
                if submission:
                    msg = f'New text/link submission created in r/{name} by u/{redditor_name} with id: {submission.id}.'
                    submission_data = SubmissionsUtils.get_submission_data(
                        submission)
                else:
                    msg = f'New image/video/gif submission created in r/{name} by u/{redditor_name}.'
                logger.info(msg)
            except Exception as ex:
                msg = f'Error creating submission. Exception raised: {repr(ex)}.'
                status_code = status.HTTP_503_SERVICE_UNAVAILABLE
                logger.error(msg)
        else:
            msg = f'Reddit instance is read only. Cannot submit a post creation in r/{name}.'
            status_code = status.HTTP_405_METHOD_NOT_ALLOWED
            logger.warn(msg)

        return Response({
            'detail': msg,
            'submission': submission_data
        },
                        status=status_code)