Exemplo n.º 1
0
    def user_preprocessor_update_single(instance_id=None, **kw):
        """Create an User specific PATCH_SINGLE and PUT_SINGLE preprocessor.

        Accepts two arguments, `instance_id`, the primary key of the
        instance of the model to patch, and `data`, the dictionary of fields
        to change on the instance.
        """
        logger.info('`user_preprocessor_update_single` used for endpoint')

        if request.args.get('access_token', '') or \
                request.headers.get('Authorization'):

            authorization = verify_authorization()
            if (int(authorization.id) == int(instance_id)):
                logger.debug('User %d updating their account' %
                             (authorization.id))

                pass
            elif check_roles('admin', authorization.roles):
                logger.info('Administrator with id %d is updating user id %d' %
                            (authorization.id, int(instance_id)))
                pass
            else:
                logger.info('User %d attempted to access a User UPDATE_SINGLE '
                            'for another user account' % (authorization.id))
                abort(403)
        else:
            logger.info('Anonymous user attempted to access User'
                        'UPDATE_SINGLE')
            abort(403)
Exemplo n.º 2
0
def upload_file(source_file, acl='public-read'):
    """Upload a File Object Directly to our server."""
    logger.debug('[MEDIA utilities:upload_file] File upload process started')

    basepath = current_app.config['MEDIA_BASE_PATH']
    directory = current_app.config['MEDIA_DIRECTORY']

    """
    Prepare the file for processing
    """
    extension = os.path.splitext(source_file.filename)[1]
    secure_filename = uuid4().hex + extension

    filepath = os.path.join(directory, secure_filename)
    fileurl = os.path.join(basepath, secure_filename)

    try:
        logger.debug('Saving file source information to server')
        source_file.save(filepath)
    except Exception:
        logger.debug('Exception raised saving file source to server')
        raise

    logger.debug('File upload process completed with original:%s' % (fileurl))
    return {
        'original': fileurl
    }
Exemplo n.º 3
0
def create(image, name, suffix, extension, directory, size={}):
    """Create an image according to spec."""
    logger.debug('[MEDIA utilities:create] Image creation process started')

    filename = name + suffix + extension
    filepath = os.path.join(directory, 'images', filename)

    with image.clone() as temporary_image:

        if 'width' in size and 'height' in size:
            thumbnail(temporary_image, size.get('width'), size.get('height'))

        temporary_image.save(filename=filepath)

    logger.debug('Image creation completed with file:`%s`' % (filename))
    return filename
Exemplo n.º 4
0
def thumbnail(image, width=1280, height=1280):
    """Create a square thumbnail based on an image, a width, and height."""
    logger.debug('Thumbnail creation started')

    dst_landscape = 1 > image.width / image.height

    wh = image.width if dst_landscape else image.height

    image.crop(
        left=int((image.width - wh) / 2),
        top=int((image.height - wh) / 2),
        width=int(wh),
        height=int(wh)
    )

    image.resize(width, height)
    logger.debug('[MEDIA utilities:thumbnail] Thumbnail creation completed')
Exemplo n.º 5
0
def upload_image(source_file, acl='public-read'):
    """Upload File Object."""
    logger.debug('[MEDIA utilities:upload_image] Image upload process started')

    basepath = current_app.config['MEDIA_BASE_PATH'] + 'images/'
    directory = current_app.config['MEDIA_DIRECTORY']

    """
    Prepare the file for processing
    """
    source_filename = secure_filename(source_file.filename)
    source_extension = os.path.splitext(source_filename)[1]

    destination_filename = uuid4().hex

    try:
        image = Image(file=source_file)
        image.format = 'jpeg'
        image.compression_quality = 75
        logger.debug('Completed creating image object `%s`' % (image))
    except Exception:
        logger.debug('Couldn\'t create transformable image object')
        raise

    try:
        """
        Fix EXIF Orientation
        """
        _orientation = image.metadata.get('exif:Orientation')

        if _orientation == '1':
            pass
        elif _orientation == '2':
            image.flop()
        elif _orientation == '3':
            image.rotate(180)
        elif _orientation == '4':
            image.flop()
            image.rotate(180)
        elif _orientation == '5':
            image.flip()
            image.rotate(90)
        elif _orientation == '6':
            image.rotate(90)
        elif _orientation == '7':
            image.flip()
            image.rotate(270)
        elif _orientation == '8':
            image.rotate(270)

        """
        ORIGINAL:
        """
        original_filename = create(**{
            'image': image,
            'name': destination_filename,
            'suffix': '_original',
            'extension': source_extension,
            'directory': directory
        })

        logger.debug('Completed rotating original orientation')
    except Exception:
        logger.debug('Exception raised trying to rotate original orientation')
        raise

    try:
        """
        SQUARE: We save this at @2x of 640px (1280px)
        """
        square_retina_filename = create(**{
            'image': image,
            'name': destination_filename,
            'suffix': '_square@2x',
            'extension': source_extension,
            'size': {
                'width': 1280,
                'height': 1280
            },
            'directory': directory
        })

        square_filename = create(**{
            'image': image,
            'name': destination_filename,
            'suffix': '_square',
            'extension': source_extension,
            'size': {
                'width': 640,
                'height': 640
            },
            'directory': directory
        })

        """
        THUMBNAIL: We save this at @2x of 256px (512px)
        """
        thumbnail_retina_filename = create(**{
            'image': image,
            'name': destination_filename,
            'suffix': '_thumbnail@2x',
            'extension': source_extension,
            'size': {
                'width': 512,
                'height': 512
            },
            'directory': directory
        })

        thumbnail_filename = create(**{
            'image': image,
            'name': destination_filename,
            'suffix': '_thumbnail',
            'extension': source_extension,
            'size': {
                'width': 256,
                'height': 256
            },
            'directory': directory
        })

        """
        Icon: We save this at @2x of 64px (128px)
        """
        icon_retina_filename = create(**{
            'image': image,
            'name': destination_filename,
            'suffix': '_icon@2x',
            'extension': source_extension,
            'size': {
                'width': 128,
                'height': 128
            },
            'directory': directory
        })

        icon_filename = create(**{
            'image': image,
            'name': destination_filename,
            'suffix': '_icon',
            'extension': source_extension,
            'size': {
                'width': 64,
                'height': 64
            },
            'directory': directory
        })

        logger.debug('Image upload process complete')
        return {
            'original': os.path.join(basepath, original_filename),
            'square': os.path.join(basepath, square_filename),
            'square_retina': os.path.join(basepath, square_retina_filename),
            'thumbnail': os.path.join(basepath, thumbnail_filename),
            'thumbnail_retina': os.path.join(basepath,
                                             thumbnail_retina_filename),
            'icon': os.path.join(basepath, icon_filename),
            'icon_retina': os.path.join(basepath, icon_retina_filename)
        }
    except Exception:
        logger.debug('Exception raised trying to create multiple formats')
        raise
Exemplo n.º 6
0
def allowed_file(filename):
    """Ensure file upload being attempted is of an allowed file type."""
    logger.debug('Checking if file name is valid')

    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
Exemplo n.º 7
0
def image_post(oauth_request):
    """Image Post."""
    logger.debug('Begin processing image processing request')
    """
    Check to see that one and only one file has been attached to this request
    before proceding with the file upload
    """
    if not len(request.files) or len(request.files) > 1:
        return abort(400, 'Please attach a single file to this request')
    """Check to see if there is an `image` attribute in the `request.files`."""
    if 'image' not in request.files:
        logger.debug('Missing `image` attribute in `request.files`')

    _file = request.files['image']
    logger.debug('request.files with value of `%s`' % (_file))
    """
    Upload the file to our server
    """
    output = upload_image(_file)

    if not output:
        logger.debug('Output from image processing return `None`')
        return jsonify(
            **{
                'code': 415,
                'status': 'Unsupported Media Type',
                'message':
                'Unable to process image at the `upload_image` method'
            }), 415
    """
    Create and Save the new Media object
    """
    logger.debug('Ouput accepted as `%s`, save Image object' % (output))
    media = Image(
        **{
            'original': output['original'],
            'square': output['square'],
            'square_retina': output['square_retina'],
            'thumbnail': output['thumbnail'],
            'thumbnail_retina': output['thumbnail_retina'],
            'icon': output['icon'],
            'icon_retina': output['icon_retina'],
            'filename': _file.filename,
            'filetype': _file.mimetype,
            'filesize': _file.content_length,
            'created_on': datetime.now().isoformat(),
            'creator_id': oauth_request.user.id
        })
    logger.debug('Image object created successfully `%s`' % (media))

    db.session.add(media)
    db.session.commit()

    logger.debug('Image object committed to database')
    """
    Return the finalized Image resource
    """
    _return_value = {
        'id': media.id,
        'created_on': media.created_on,
        'modified_on': media.modified_on,
        'creator_id': media.creator_id,
        'original': media.original,
        'square': media.square,
        'square_retina': media.square_retina,
        'thumbnail': media.thumbnail,
        'thumbnail_retina': media.thumbnail_retina,
        'icon': media.icon,
        'icon_retina': media.icon_retina,
        'filename': media.filename,
        'filetype': media.filetype,
        'filesize': media.filesize,
        'caption': media.caption,
        'caption_link': media.caption_link
    }

    logger.debug('Completed processing image processing request')
    return jsonify(**_return_value), 200