Example #1
0
    def post(self, request, project_id):
        """
        Adds a user to the admin group.

        Parameter
        ---------
        request : rest_framework.request.Request
            Object representing the request.
        project_id : int
            identifies the project in the database

        Returns
        -------
        rest_framework.response.Response
            Response containing the serialised list of admins or an error
            message.
        """

        project = Project.objects.as_admin(request.user, project_id)
        user = User.objects.get(pk=request.data.get('user_id'))

        try:
            Admins.objects.create(project=project, user=user)
        except IntegrityError:
            return Response(
                'The user is already an administrator of this project.',
                status=status.HTTP_400_BAD_REQUEST)

        refreshed_admins = Project.objects.get(pk=project_id).admins.all()
        serializer = UserSerializer(refreshed_admins, many=True)

        return Response({'users': serializer.data},
                        status=status.HTTP_201_CREATED)
Example #2
0
    def post(self, request, project_id):
        """
        Adds a user to the admin group.

        Parameter
        ---------
        request : rest_framework.request.Request
            Object representing the request.
        project_id : int
            identifies the project in the database

        Returns
        -------
        rest_framework.reponse.Response
            Response containing the serialised list of admins or an error
            message.
        """
        project = Project.objects.as_admin(request.user, project_id)

        try:
            user = User.objects.get(pk=request.DATA.get('userId'))
            Admins.objects.create(project=project, user=user)

            serializer = UserSerializer(project.admins.all(), many=True)
            return Response({'users': serializer.data},
                            status=status.HTTP_201_CREATED)
        except User.DoesNotExist:
            return Response(
                'The user you are trying to add to the user group does ' +
                'not exist',
                status=status.HTTP_400_BAD_REQUEST)
Example #3
0
    def post(self, request):
        """
        Adds a new superuser

        Parameters
        ----------
        request : rest_framework.request.Request
            Object representing the request

        Returns
        -------
        rest_framework.response.Response
            Contains the list of superusers or an error message
        """
        try:
            user = User.objects.get(pk=request.DATA.get('userId'))
            user.is_superuser = True
            user.save()

            superusers = User.objects.filter(is_superuser=True)
            serializer = UserSerializer(superusers, many=True)
            return Response(
                {'users': serializer.data},
                status=status.HTTP_201_CREATED
            )

        except User.DoesNotExist:
            return Response(
                'The user you are trying to add to the user group does ' +
                'not exist',
                status=status.HTTP_400_BAD_REQUEST
            )
Example #4
0
    def post(self, request, project_id):
        """
        Adds an admin to the group of admins.

        Parameters
        ----------
        request : rest_framework.request.Request
            Represents the HTTP request
        project_id : int
            Identifies the project in the database

        Returns
        -------
        rest_framework.response.Response
            Contains the serialised user group or an error message
        """

        project = Project.objects.as_admin(request.user, project_id)

        if project.islocked:
            return Response(
                {
                    'error':
                    'The project is locked. New administrators cannot ' +
                    'be added.'
                },
                status=status.HTTP_400_BAD_REQUEST)
        else:
            try:
                user = User.objects.get(pk=request.data.get('user_id'))
            except User.DoesNotExist:
                return Response(
                    {
                        'error':
                        'The user you are trying to add to the group ' +
                        'of administrators does not exist.'
                    },
                    status=status.HTTP_404_NOT_FOUND)

            try:
                Admins.objects.create(project=project, user=user)
            except IntegrityError:
                return Response(
                    {
                        'error':
                        'The user is already an administrator of this ' +
                        'project.'
                    },
                    status=status.HTTP_400_BAD_REQUEST)

            refreshed_admins = Project.objects.get(pk=project_id).admins.all()
            serializer = UserSerializer(refreshed_admins, many=True)

            return Response({'users': serializer.data},
                            status=status.HTTP_201_CREATED)
Example #5
0
class CommentSerializer(serializers.ModelSerializer):
    """
    Serialiser for geokey.contributions.models.Comment
    """
    creator = UserSerializer(fields=('id', 'display_name'), read_only=True)
    isowner = serializers.SerializerMethodField()

    class Meta:
        model = Comment
        fields = ('id', 'respondsto', 'created_at', 'text', 'isowner',
                  'creator', 'review_status')
        read_only = ('id', 'respondsto', 'created_at')

    def to_representation(self, obj):
        """
        Returns native represenation of the Comment. Adds reponses to comment

        Parameter
        ---------
        obj : geokey.contributions.models.Comment
            The instance that is serialised

        Returns
        -------
        dict
            Native represenation of the Comment

        """
        native = super(CommentSerializer, self).to_representation(obj)
        native['responses'] = CommentSerializer(obj.responses.all(),
                                                many=True,
                                                context=self.context).data

        return native

    def get_isowner(self, comment):
        """
        Returns True if the user serialising the Comment has created the
        comment

        Parameter
        ---------
        comment : geokey.contributions.models.Comment
            The instance that is serialised

        Returns
        -------
        Boolean
            indicating of user is creator of comment
        """
        if not self.context.get('user').is_anonymous():
            return comment.creator == self.context.get('user')
        else:
            return False
Example #6
0
    def post(self, request):
        """
        Handle POST request.

        Add a user to superusers.

        Parameters
        ----------
        request : rest_framework.request.Request
            Object representing the request.

        Returns
        -------
        rest_framework.response.Response
            Response to the request.
        """
        user = User.objects.get(pk=request.data.get('user_id'))
        user.is_superuser = True
        user.save()

        serializer = UserSerializer(User.objects.filter(is_superuser=True),
                                    many=True)
        return Response({'users': serializer.data},
                        status=status.HTTP_201_CREATED)
Example #7
0
class FileSerializer(serializers.ModelSerializer):
    """
    Serialiser for geokey.contributions.models.MediaFile instances
    """
    creator = UserSerializer(fields=('id', 'display_name'))
    isowner = serializers.SerializerMethodField()
    url = serializers.SerializerMethodField()
    file_type = serializers.SerializerMethodField()
    thumbnail_url = serializers.SerializerMethodField()

    class Meta:
        model = MediaFile
        fields = ('id', 'name', 'description', 'created_at', 'creator',
                  'isowner', 'url', 'thumbnail_url', 'file_type')

    def get_file_type(self, obj):
        """
        Returns the type of the MediaFile

        Parameter
        ---------
        obj : geokey.contributions.models.MediaFile
            The instance that is serialised

        Returns
        -------
        str
            The type of the, e.g. 'ImageFile'
        """
        return obj.type_name

    def get_isowner(self, obj):
        """
        Returns `True` if the user provided in the serializer context is the
        creator of this file

        Parameter
        ---------
        obj : geokey.contributions.models.MediaFile
            The instance that is serialised

        Returns
        -------
        Boolean
            indicating if user created the file
        """
        if not self.context.get('user').is_anonymous():
            return obj.creator == self.context.get('user')
        else:
            return False

    def get_url(self, obj):
        """
        Return the url to access this file based on its file type

        Parameter
        ---------
        obj : geokey.contributions.models.MediaFile
            The instance that is serialised

        Returns
        -------
        str
            The URL to embed the file on client side
        """
        if isinstance(obj, ImageFile):
            return obj.image.url
        elif isinstance(obj, VideoFile):
            return obj.youtube_link

    def _get_thumb(self, image, size=(300, 300)):
        """
        Returns the thumbnail of the media file base on the size privoded

        Parameter
        ---------
        image : Image
            The image to be thumbnailed
        size : tuple
            width and height of the thumbnail, defaults to 300 by 300

        Returns
        -------
        Image
            The thumbnail

        """
        thumbnailer = get_thumbnailer(image)
        thumb = thumbnailer.get_thumbnail({'crop': True, 'size': size})
        return thumb

    def get_thumbnail_url(self, obj):
        """
        Creates and returns a thumbnail for the MediaFile object

        Parameter
        ---------
        obj : geokey.contributions.models.MediaFile
            The instance that is serialised

        Returns
        -------
        str
            The url to embed thumbnails on client side
        """
        if isinstance(obj, ImageFile):
            # Some of the imported image files in the original community maps
            # seem to be broken. The error thrown when the image can not be
            # read is caught here.
            try:
                return self._get_thumb(obj.image).url
            except IOError:
                return ''

        elif isinstance(obj, VideoFile):
            if obj.thumbnail:
                # thumbnail has been downloaded, return the link
                return self._get_thumb(obj.thumbnail).url

            request = requests.get('http://img.youtube.com/vi/%s/0.jpg' %
                                   obj.youtube_id,
                                   stream=True)

            if request.status_code != requests.codes.ok:
                # Image not found, return placeholder thumbnail
                return '/static/img/play.png'

            lf = tempfile.NamedTemporaryFile()
            # Read the streamed image in sections
            for block in request.iter_content(1024 * 8):

                # If no more file then stop
                if not block:
                    break

                # Write image block to temporary file
                lf.write(block)

            file_name = obj.youtube_id + '.jpg'
            obj.thumbnail.save(file_name, files.File(lf))

            from PIL import Image

            w, h = Image.open(obj.thumbnail).size

            thumb = self._get_thumb(obj.thumbnail, size=(h, h))
            obj.thumbnail.save(file_name, thumb)

            return self._get_thumb(obj.thumbnail).url
Example #8
0
class SapelliLogFileSerializer(serializers.ModelSerializer):
    """Serializer for geokey_sapelli.models.SapelliLogFile instances."""

    creator = UserSerializer(fields=('id', 'display_name'))
    isowner = serializers.SerializerMethodField()
    url = serializers.SerializerMethodField()
    file_type = serializers.SerializerMethodField()

    class Meta:
        """Class meta information."""

        model = SapelliLogFile
        fields = ('id', 'name', 'created_at', 'uploaded_at', 'creator',
                  'isowner', 'url', 'file_type')

    def get_file_type(self, obj):
        """
        Return the type of the SapelliLogFile.

        Parameters
        ----------
        obj : geokey_sapelli.models.SapelliLogFile
            The instance that is being serialised.

        Returns
        -------
        str
            The type of the instance, in this case it's 'SapelliLogFile'.
        """
        return obj.type_name

    def get_isowner(self, obj):
        """
        Return `True` if the user is the creator of this file.

        Parameters
        ----------
        obj : geokey_sapelli.models.SapelliLogFile
            The instance that is being serialised.

        Returns
        -------
        Boolean
            Indicating if user created the file.
        """
        user = self.context.get('user')

        if not user.is_anonymous():
            return obj.creator == user

        return False

    def get_url(self, obj):
        """
        Return the URL to access this file.

        Parameters
        ----------
        obj : geokey_sapelli.models.SapelliLogFile
            The instance that is being serialised.

        Returns
        -------
        str
            The URL to access the file on client side.
        """
        return obj.file.url
Example #9
0
class FileSerializer(serializers.ModelSerializer):
    """
    Serialiser for geokey.contributions.models.MediaFile instances
    """
    creator = UserSerializer(fields=('id', 'display_name'))
    isowner = serializers.SerializerMethodField()
    url = serializers.SerializerMethodField()
    file_type = serializers.SerializerMethodField()
    thumbnail_url = serializers.SerializerMethodField()

    class Meta:
        model = MediaFile
        fields = ('id', 'name', 'description', 'created_at', 'creator',
                  'isowner', 'url', 'thumbnail_url', 'file_type')

    def get_file_type(self, obj):
        """
        Returns the type of the MediaFile

        Parameter
        ---------
        obj : geokey.contributions.models.MediaFile
            The instance that is serialised

        Returns
        -------
        str
            The type of the, e.g. 'ImageFile'
        """
        return obj.type_name

    def get_isowner(self, obj):
        """
        Returns `True` if the user provided in the serializer context is the
        creator of this file

        Parameter
        ---------
        obj : geokey.contributions.models.MediaFile
            The instance that is serialised

        Returns
        -------
        Boolean
            indicating if user created the file
        """
        if not self.context.get('user').is_anonymous():
            return obj.creator == self.context.get('user')
        else:
            return False

    def get_url(self, obj):
        """
        Return the url to access this file based on its file type

        Parameter
        ---------
        obj : geokey.contributions.models.MediaFile
            The instance that is serialised

        Returns
        -------
        str
            The URL to embed the file on client side
        """
        if isinstance(obj, ImageFile):
            return obj.image.url
        if isinstance(obj, DocumentFile):
            return obj.document.url
        elif isinstance(obj, VideoFile):
            return obj.youtube_link
        elif isinstance(obj, AudioFile):
            return obj.audio.url

    def _get_thumb(self, image, size=(300, 300)):
        """
        Returns the thumbnail of the media file base on the size privoded

        Parameter
        ---------
        image : Image
            The image to be thumbnailed
        size : tuple
            Width and height of the thumbnail, defaults to 300 by 300

        Returns
        -------
        Image
            The thumbnail
        """
        thumbnailer = get_thumbnailer(image)
        thumb = thumbnailer.get_thumbnail({'crop': True, 'size': size})
        return thumb

    def get_thumbnail_url(self, obj):
        """
        Creates and returns a thumbnail for the MediaFile object

        Parameter
        ---------
        obj : geokey.contributions.models.MediaFile
            The instance that is serialised

        Returns
        -------
        str
            The url to embed thumbnails on client side
        """
        if isinstance(obj, ImageFile):
            # Some of the imported image files in the original community maps
            # seem to be broken. The error thrown when the image can not be
            # read is caught here.
            try:
                return self._get_thumb(obj.image).url
            except (IOError, InvalidImageFormatError):
                return ''

        elif isinstance(obj, DocumentFile):
            if obj.thumbnail:
                # thumbnail has been generated, return the link
                return self._get_thumb(obj.thumbnail).url

            thumbnail_name = '%s_thumbnail.png' % obj.document

            # Save placeholder for current thumb which will be generated
            obj.thumbnail = thumbnail_name
            obj.save()

            pipe = subprocess.Popen(
                'convert -quality 95 -thumbnail %s %s/%s[0] %s/%s' % (
                    500,  # width of a generated thumb
                    settings.MEDIA_ROOT,
                    obj.document,
                    settings.MEDIA_ROOT,
                    '%s_thumbnail.png' % obj.document),
                shell=True,
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
            )
            output, error = pipe.communicate()

            if error:
                return None

            w, h = Image.open(obj.thumbnail).size

            # Crop and replace thumb based on whether height or width is smaller
            thumb = self._get_thumb(obj.thumbnail, size=(min(w, h), min(w, h)))
            obj.thumbnail.save(basename(obj.document.name), thumb)

            return self._get_thumb(obj.thumbnail).url

        elif isinstance(obj, VideoFile):
            if obj.thumbnail:
                # thumbnail has been downloaded, return the link
                return self._get_thumb(obj.thumbnail).url

            request = requests.get('http://img.youtube.com/vi/%s/0.jpg' %
                                   obj.youtube_id,
                                   stream=True)

            if request.status_code != requests.codes.ok:
                # Image not found, return placeholder thumbnail
                return '/static/img/play.png'

            lf = tempfile.NamedTemporaryFile()
            # Read the streamed image in sections
            for block in request.iter_content(1024 * 8):

                # If no more file then stop
                if not block:
                    break

                # Write image block to temporary file
                lf.write(block)

            file_name = obj.youtube_id + '.jpg'
            obj.thumbnail.save(file_name, files.File(lf))

            w, h = Image.open(obj.thumbnail).size

            thumb = self._get_thumb(obj.thumbnail, size=(h, h))
            obj.thumbnail.save(file_name, thumb)

            return self._get_thumb(obj.thumbnail).url

        elif isinstance(obj, AudioFile):
            return '/static/img/play.png'