Ejemplo n.º 1
0
def upload_image(
    image_data, extension, description, album, photographer, credits, licence, content_type, tags, uploader
):
    """Note that the provided file extension will be standardized and may change, so callers should take care to use
    the extension of the returned image object if needed further."""
    conn = boto.connect_s3(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
    bucket = conn.get_bucket(settings.AWS_S3_BUCKET)

    image_key = Image.generate_unique_random_key()
    pil_image = PIL.Image.open(BytesIO(image_data))
    extension = standardize_extension(extension)

    # cannot write P mode as JPEG; see http://stackoverflow.com/q/21669657/302484
    if extension == "jpeg" and pil_image.mode == "P":
        pil_image = pil_image.convert("RGB")

    exif_json = json.dumps(get_exif_tags(image_data))
    image_file_tags = xmp.find_keywords(image_data)
    thumbs = [{"size": size, "data": create_thumb(pil_image, extension, size)} for size in settings.THUMB_SIZES]

    key = bucket.new_key("%s/%s.%s" % (settings.AWS_S3_FOLDERS["imagearchive"], image_key, extension))
    key.content_type = content_type
    key.set_contents_from_string(image_data, policy="public-read")

    for thumb in thumbs:
        key = bucket.new_key(
            "%s/%s-%s.%s" % (settings.AWS_S3_FOLDERS["imagearchive"], image_key, thumb["size"], extension)
        )
        key.content_type = content_type
        key.set_contents_from_string(thumb["data"], policy="public-read")

    image = Image(
        key=image_key,
        extension=extension,
        hash=sha1(image_data).hexdigest(),
        description=description,
        album=album,
        photographer=photographer,
        credits=credits,
        licence=licence,
        exif=exif_json,
        uploader=uploader,
        width=pil_image.size[0],
        height=pil_image.size[1],
    )
    image.save()

    for tag in [tag.lower() for tag in image_file_tags + tags]:
        obj, created = Tag.objects.get_or_create(name=tag)
        image.tags.add(obj)

    return image
Ejemplo n.º 2
0
def upload_image(image_data, extension, description, album, photographer, credits, licence, content_type, tags, uploader):
    """Note that the provided file extension will be standardized and may change, so callers should take care to use
    the extension of the returned image object if needed further."""
    conn = boto.connect_s3(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
    bucket = conn.get_bucket(s3_bucket())

    image_key = Image.generate_unique_random_key()
    pil_image = PIL.Image.open(StringIO(image_data))
    extension = standardize_extension(extension)

    # cannot write P mode as JPEG; see http://stackoverflow.com/q/21669657/302484
    if extension == 'jpeg' and pil_image.mode == 'P':
        pil_image = pil_image.convert('RGB')

    exif_json = json.dumps(get_exif_tags(pil_image))
    image_file_tags = xmp.find_keywords(image_data)
    thumbs = [{'size': size, 'data': create_thumb(pil_image, extension, size)} for size in settings.THUMB_SIZES]

    # Give boto an encoded str, not unicode
    if type(content_type) == unicode:
        content_type = content_type.encode('utf-8')

    key = bucket.new_key("%s%s.%s" % (settings.AWS_IMAGEGALLERY_PREFIX, image_key, extension))
    key.content_type = content_type
    key.set_contents_from_string(image_data, policy='public-read')

    for thumb in thumbs:
        key = bucket.new_key("%s%s-%s.%s" % (settings.AWS_IMAGEGALLERY_PREFIX, image_key, thumb['size'], extension))
        key.content_type = content_type
        key.set_contents_from_string(thumb['data'], policy='public-read')

    image = Image(
        key=image_key,
        extension=extension,
        hash=sha1(image_data).hexdigest(),
        description=description,
        album=album,
        photographer=photographer,
        credits=credits,
        licence=licence,
        exif=exif_json,
        uploader=uploader,
        width=pil_image.size[0],
        height=pil_image.size[1])
    image.save()

    for tag in [tag.lower() for tag in image_file_tags + tags]:
        obj, created = Tag.objects.get_or_create(name=tag)
        image.tags.add(obj)

    return image
Ejemplo n.º 3
0
def upload(request):
    try:
        image_file = request.FILES['file']
    except KeyError:
        raise PermissionDenied

    if not validator.name(request.POST.get('name', '')):
        raise PermissionDenied

    if not validator.phone(request.POST.get('phone', '')):
        raise PermissionDenied

    if not validator.email(request.POST.get('email', '')):
        raise PermissionDenied

    if len(request.POST.get('description', '').strip()) == 0:
        raise PermissionDenied

    post_name = request.POST['name'].strip()
    post_phone = request.POST['phone'].strip()
    post_email = request.POST['email'].strip()
    post_description = request.POST['description'].strip()

    try:
        conn = boto.connect_s3(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
        bucket = conn.get_bucket(s3_bucket())

        image_key = Image.generate_unique_random_key()
        data = image_file.read()
        ext = image_file.name.split(".")[-1].lower()
        pil_image = PIL.Image.open(StringIO(data))
        exif_json = json.dumps(get_exif_tags(pil_image))
        image_file_tags = xmp.find_keywords(data)
        thumbs = [{'size': size, 'data': create_thumb(pil_image, ext, size)} for size in settings.THUMB_SIZES]

        if pil_image.size[0] < MIN_SIZE or pil_image.size[1] < MIN_SIZE:
            return HttpResponseBadRequest(json.dumps({
                'files': [{
                    'name': image_file.name,
                    'size': image_file.size,
                    'error': u"Bildet må være minst 800x800 piksler",
                }]
            }))

        # Give boto an encoded str, not unicode
        content_type = image_file.content_type.encode('utf-8')

        key = boto.s3.key.Key(bucket, '%s%s.%s' % (settings.AWS_IMAGEGALLERY_PREFIX, image_key, ext))
        key.content_type = content_type
        key.set_contents_from_string(data, policy='public-read')

        for thumb in thumbs:
            key = boto.s3.key.Key(bucket, '%s%s-%s.%s' % (settings.AWS_IMAGEGALLERY_PREFIX, image_key, thumb['size'], ext))
            key.content_type = content_type
            key.set_contents_from_string(thumb['data'], policy='public-read')

        destination_album = Fotokonkurranse.objects.get().album
        licence_text = "Kan brukes i DNTs egne kommunikasjonskanaler som magasiner, nettsider og sosiale medier, i PR og for bruk av DNTs sponsorer."

        image = Image(
            key=image_key,
            extension=ext,
            hash=sha1(data).hexdigest(),
            description=post_description,
            album=destination_album,
            photographer=post_name,
            credits="%s / DNTs fotokonkurranse" % post_name,
            licence="%s Kontakt: %s (%s / %s)" % (licence_text, post_name, post_phone, post_email),
            exif=exif_json,
            uploader=request.user if not request.user.is_anonymous() else None,
            width=pil_image.size[0],
            height=pil_image.size[1])
        image.save()

        for tag in [tag.lower() for tag in image_file_tags]:
            obj, created = Tag.objects.get_or_create(name=tag)
            image.tags.add(obj)

        # Note that we're caching the email address for one hour and not resending the email receipt
        # for further uploads from that address during this period.
        if cache.get('fotokonkurranse.emails.%s' % post_email) is None:
            # Set the cache quickly when we know we're going to send an email. Don't wait until after
            # it's sent, because other upload requests may try to send meanwhile and we don't want them to.
            cache.set('fotokonkurranse.emails.%s' % post_email, True, 60 * 60)
            try:
                t = loader.get_template('central/fotokonkurranse/email_confirmation.txt')
                c = RequestContext(request, {
                    'user_name': post_name,
                })
                send_mail(EMAIL_CONFIRMATION_SUBJECT, t.render(c), settings.DEFAULT_FROM_EMAIL, [post_email])
            except (SMTPException, SSLError):
                cache.delete('fotokonkurranse.emails.%s' % post_email)
                logger.warning(u"Kvitteringsepost for fotokonkurranse feilet",
                    exc_info=sys.exc_info(),
                    extra={'request': request}
                )

        return HttpResponse(json.dumps({
            'files': [{
                'name': image_file.name,
                'size': image_file.size,
                'url': '',
                'thumbnailUrl': '',
                'deleteUrl': '',
                'deleteType': '',
            }]
        }))
    except Exception as e:
        logger.error(u"Feil ved opplasting av bilde til fotokonkurranse",
            exc_info=sys.exc_info(),
            extra={'request': request}
        )
        return HttpResponseBadRequest(json.dumps({
            'files': [{
                'name': image_file.name,
                'size': image_file.size,
                'error': "Exception ved bildeopplasting: %s" % e,
            }]
        }))
Ejemplo n.º 4
0
def upload_image(request):
    try:
        if len(request.FILES.getlist('files')) == 0:
            result = json.dumps({'status': 'no_files'})
            return render(request, 'central/admin/images/iframe.html', {'result': result})

        conn = boto.connect_s3(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
        bucket = conn.get_bucket(settings.AWS_S3_BUCKET)

        ids = []
        album = None if request.POST['album'] == '' else Album.objects.get(id=request.POST['album'])
        for image in request.FILES.getlist('files'):
            image_key = Image.generate_unique_random_key()
            data = image.read()
            ext = image.name.split(".")[-1].lower()
            pil_image = PIL.Image.open(BytesIO(data))
            exif_json = json.dumps(get_exif_tags(data))
            tags = xmp.find_keywords(data)
            thumbs = [{'size': size, 'data': create_thumb(pil_image, ext, size)} for size in settings.THUMB_SIZES]

            key = bucket.new_key("%s/%s.%s" % (settings.AWS_S3_FOLDERS['imagearchive'], image_key, ext))
            key.content_type = image.content_type
            key.set_contents_from_string(data, policy='public-read')

            for thumb in thumbs:
                key = bucket.new_key("%s/%s-%s.%s" % (
                    settings.AWS_S3_FOLDERS['imagearchive'],
                    image_key,
                    thumb['size'],
                    ext
                ))
                key.content_type = image.content_type
                key.set_contents_from_string(thumb['data'], policy='public-read')

            image = Image(
                key=image_key,
                extension=ext,
                hash=sha1(data).hexdigest(),
                description='',
                album=album,
                photographer='',
                credits='',
                licence='',
                exif=exif_json,
                uploader=request.user,
                width=pil_image.size[0],
                height=pil_image.size[1])
            image.save()

            for tag in [tag.lower() for tag in tags]:
                obj, created = Tag.objects.get_or_create(name=tag)
                image.tags.add(obj)

            ids.append(image.id)
        result = json.dumps({
            'status': 'success',
            'ids': ids
        })
        return render(request, 'central/admin/images/iframe.html', {'result': result})
    except(IOError, KeyError):
        logger.warning(
            "Kunne ikke parse opplastet bilde, antar at det er ugyldig bildefil",
            exc_info=sys.exc_info(),
            extra={'request': request}
        )
        result = json.dumps({'status': 'parse_error'})
        return render(request, 'central/admin/images/iframe.html', {'result': result})
    except Exception:
        logger.error(
            "Ukjent exception ved bildeopplasting",
            exc_info=sys.exc_info(),
            extra={'request': request}
        )
        result = json.dumps({'status': 'unknown_exception'})
        return render(request, 'central/admin/images/iframe.html', {'result': result})