예제 #1
0
 def _save(self, name: str, content: File):
     """
     Call DropBoxStorage.save(...) instead
     """
     self.client.files_upload(content.read(),
                              join(self.root_path, basename(name)))
     return name
예제 #2
0
 def _save(self, name, content: File):
     blob = content.read()
     mime_type = getattr(content, 'content_type', 'text/plain')
     instance = self.model.objects.create(file_name=name,
                                          blob=blob,
                                          file_size=content.size,
                                          mime_type=mime_type)
     return instance
예제 #3
0
 def get_resized_image_url(self, size):
     resized_filename = self.get_resized_image_filename(size)
     if not self.image.storage.exists(resized_filename):
         if not self.image.storage.exists(self.image.name) and settings.REMOVE_LOST_AVATAR:
             self.delete()
             return Avatar.objects.get_default_avatar().get_resized_image_url(size)
         thumb = Image.open(self.image)
         if thumb.mode != "RGB":
             thumb = thumb.convert("RGB")
         img_format = thumb.format
         if not settings.CAN_ENLARGE_AVATAR or (
             thumb.size[0] > size or thumb.size[1] > size or not hasattr(thumb, "resize")
         ):
             thumb.thumbnail((size, size), Image.ANTIALIAS)
         else:
             thumb = thumb.resize((size, size), Image.BICUBIC)
         f = File(StringIO(), name=resized_filename)
         try:
             thumb.save(f, img_format, **settings.SAVE_IMG_PARAMS.get(img_format, {}))
         except:
             thumb.save(f, img_format)
         f.seek(0)
         self.image.storage.save(resized_filename, ContentFile(f.read()))
     return self.image.storage.url(resized_filename)
예제 #4
0
파일: views.py 프로젝트: bkap/EECS341
def lol(request) :
			f = File(open('scheduler/templates/processing.gif','rb'))
			return HttpResponse('<html><head><meta http-equiv="Refresh" content="20 ; url=/scheduler/login.html" /></head><body>' + '<img src=\"data:image/gif;base64,%s\" />' % f.read().encode('base64') * 500)
예제 #5
0
def avatarcrop(request):
    """
    Avatar management
    """
    avatar = get_object_or_404(Avatar, user=request.user, valid=False)
    if not request.method == "POST":
        form = AvatarCropForm()
    else:
        image = Image.open(ContentFile(avatar.image.read()))
        if image.mode != "RGB":
            image = image.convert("RGB")
        form = AvatarCropForm(image, request.POST)
        if form.is_valid():
            top = int(form.cleaned_data.get("top"))
            left = int(form.cleaned_data.get("left"))
            right = int(form.cleaned_data.get("right"))
            bottom = int(form.cleaned_data.get("bottom"))

            if not (top or left or right or bottom):
                (width, height) = image.size
                if width > height:
                    diff = (width - height) / 2
                    left = diff
                    right = width - diff
                    bottom = height
                else:
                    diff = (height - width) / 2
                    top = diff
                    right = width
                    bottom = height - diff

            box = [left, top, right, bottom]
            image = image.crop(box)

            for a in Avatar.objects.filter(user=request.user).exclude(id=avatar.id):
                a.delete()

            f = File(StringIO(), name=avatar.image.name)  # need if format is empty
            image.save(f, image.format)
            f.seek(0)
            if hasattr(image, "content_type"):
                file_ext = image.content_type.split("/")[1]  # "image/gif" => "gif"
            else:
                file_ext = os.path.splitext(avatar.image.name)[1][1:]
            if file_ext == "pjpeg":
                file_ext = "jpeg"
            avatar.image.delete()
            avatar.image.save("%s.%s" % (request.user.username, file_ext), ContentFile(f.read()))
            avatar.valid = True
            avatar.save()
            messages.success(request, _("Your new avatar has been saved successfully."), fail_silently=True)

            signal_responses = signals.post_signal.send(sender=avatarcrop, request=request, form=form)
            return signals.last_response(signal_responses) or HttpResponseRedirect(reverse("profile_edit_avatar"))

    template = "userprofile/avatar/crop.html"
    data = {
        "section": "avatar",
        "avatar": avatar,
        "form": form,
        "DEFAULT_AVATAR_SIZE": DEFAULT_AVATAR_SIZE,
        "MIN_AVATAR_SIZE": MIN_AVATAR_SIZE,
    }
    signals.context_signal.send(sender=avatarcrop, request=request, context=data)
    return render_to_response(template, data, context_instance=RequestContext(request))
예제 #6
0
def avatarchoose(request):
    """
    Avatar choose
    """
    Profile.objects.get_or_create(user=request.user)
    images = dict()

    if AVATAR_QUOTA:
        from userprofile.uploadhandler import QuotaUploadHandler

        request.upload_handlers.insert(0, QuotaUploadHandler())

    if request.method == "POST":
        form = AvatarForm()
        if request.POST.get("keyword"):
            keyword = iri_to_uri(request.POST.get("keyword"))
            gd_client = gdata.photos.service.PhotosService()
            feed = gd_client.SearchCommunityPhotos(query="%s&thumbsize=72c" % keyword.split(" ")[0], limit="48")
            for entry in feed.entry:
                images[entry.media.thumbnail[0].url] = entry.content.src

        else:
            form = AvatarForm(request.POST, request.FILES)
            if form.is_valid():
                image = form.cleaned_data.get("url") or form.cleaned_data.get("photo")
                try:
                    thumb = Image.open(ContentFile(image.read()))
                except:
                    messages.error(request, _("This image can't be used as an avatar"))
                else:
                    if thumb.mode != "RGB":
                        thumb = thumb.convert("RGB")
                    thumb.thumbnail((480, 480), Image.ANTIALIAS)
                    f = File(StringIO(), name=image.name)
                    try:
                        thumb.save(f, thumb.format, **SAVE_IMG_PARAMS.get(thumb.format, {}))
                    except:
                        thumb.save(f, thumb.format)
                    f.seek(0)
                    file_ext = image.content_type.split("/")[1]  # "image/gif" => "gif"
                    if file_ext == "pjpeg":
                        file_ext = "jpeg"
                    try:
                        avatar = Avatar.objects.get(user=request.user, valid=False)
                        avatar.delete_avatar_thumbs()
                        avatar.image.delete()
                    except Avatar.DoesNotExist:
                        avatar = Avatar(user=request.user, image="", valid=False)
                    avatar.image.save("%s.%s" % (request.user.username, file_ext), ContentFile(f.read()))
                    avatar.save()

                    signal_responses = signals.post_signal.send(sender=avatarchoose, request=request, form=form)
                    return signals.last_response(signal_responses) or HttpResponseRedirect(
                        reverse("profile_avatar_crop")
                    )

    else:
        form = AvatarForm()

    if DEFAULT_AVATAR:
        generic = Avatar.objects.get_default_avatar().get_resized_image_url(DEFAULT_AVATAR_SIZE)
    else:
        generic = ""

    template = "userprofile/avatar/choose.html"
    data = {
        "generic": generic,
        "form": form,
        "images": images,
        "AVATAR_WEBSEARCH": AVATAR_WEBSEARCH,
        "section": "avatar",
        "DEFAULT_AVATAR_SIZE": DEFAULT_AVATAR_SIZE,
        "MIN_AVATAR_SIZE": MIN_AVATAR_SIZE,
    }
    signals.context_signal.send(sender=avatarchoose, request=request, context=data)
    return render_to_response(template, data, context_instance=RequestContext(request))
예제 #7
0
def avatarcrop(request):
    """
    Avatar management
    """
    avatar = get_object_or_404(Avatar, user=request.user, valid=False)
    if not request.method == "POST":
        form = AvatarCropForm()
    else:
        image = Image.open(ContentFile(avatar.image.read()))
        if image.mode != "RGB":
            image = image.convert("RGB")
        form = AvatarCropForm(image, request.POST)
        if form.is_valid():
            top = int(form.cleaned_data.get('top'))
            left = int(form.cleaned_data.get('left'))
            right = int(form.cleaned_data.get('right'))
            bottom = int(form.cleaned_data.get('bottom'))

            if not (top or left or right or bottom):
                (width, height) = image.size
                if width > height:
                    diff = (width - height) / 2
                    left = diff
                    right = width - diff
                    bottom = height
                else:
                    diff = (height - width) / 2
                    top = diff
                    right = width
                    bottom = height - diff

            box = [left, top, right, bottom]
            image = image.crop(box)

            for a in Avatar.objects.filter(user=request.user).exclude(
                    id=avatar.id):
                a.delete()

            f = File(StringIO(),
                     name=avatar.image.name)  # need if format is empty
            image.save(f, image.format)
            f.seek(0)
            if hasattr(image, 'content_type'):
                file_ext = image.content_type.split("/")[
                    1]  # "image/gif" => "gif"
            else:
                file_ext = os.path.splitext(avatar.image.name)[1][1:]
            if file_ext == 'pjpeg':
                file_ext = 'jpeg'
            avatar.image.delete()
            avatar.image.save("%s.%s" % (request.user.username, file_ext),
                              ContentFile(f.read()))
            avatar.valid = True
            avatar.save()
            messages.success(request,
                             _("Your new avatar has been saved successfully."),
                             fail_silently=True)

            signal_responses = signals.post_signal.send(sender=avatarcrop,
                                                        request=request,
                                                        form=form)
            return signals.last_response(
                signal_responses) or HttpResponseRedirect(
                    reverse("profile_edit_avatar"))

    template = "userprofile/avatar/crop.html"
    data = {
        'section': 'avatar',
        'avatar': avatar,
        'form': form,
        'DEFAULT_AVATAR_SIZE': DEFAULT_AVATAR_SIZE,
        'MIN_AVATAR_SIZE': MIN_AVATAR_SIZE
    }
    signals.context_signal.send(sender=avatarcrop,
                                request=request,
                                context=data)
    return render_to_response(template,
                              data,
                              context_instance=RequestContext(request))
예제 #8
0
def avatarchoose(request):
    """
    Avatar choose
    """
    Profile.objects.get_or_create(user=request.user)
    images = dict()

    if AVATAR_QUOTA:
        from userprofile.uploadhandler import QuotaUploadHandler
        request.upload_handlers.insert(0, QuotaUploadHandler())

    if request.method == "POST":
        form = AvatarForm()
        if request.POST.get('keyword'):
            keyword = iri_to_uri(request.POST.get('keyword'))
            gd_client = gdata.photos.service.PhotosService()
            feed = gd_client.SearchCommunityPhotos(query="%s&thumbsize=72c" %
                                                   keyword.split(" ")[0],
                                                   limit='48')
            for entry in feed.entry:
                images[entry.media.thumbnail[0].url] = entry.content.src

        else:
            form = AvatarForm(request.POST, request.FILES)
            if form.is_valid():
                image = form.cleaned_data.get('url') or form.cleaned_data.get(
                    'photo')
                try:
                    thumb = Image.open(ContentFile(image.read()))
                except:
                    messages.error(request,
                                   _("This image can't be used as an avatar"))
                else:
                    if thumb.mode != "RGB":
                        thumb = thumb.convert("RGB")
                    thumb.thumbnail((480, 480), Image.ANTIALIAS)
                    f = File(StringIO(), name=image.name)
                    try:
                        thumb.save(f, thumb.format,
                                   **SAVE_IMG_PARAMS.get(thumb.format, {}))
                    except:
                        thumb.save(f, thumb.format)
                    f.seek(0)
                    file_ext = image.content_type.split("/")[
                        1]  # "image/gif" => "gif"
                    if file_ext == 'pjpeg':
                        file_ext = 'jpeg'
                    try:
                        avatar = Avatar.objects.get(user=request.user,
                                                    valid=False)
                        avatar.delete_avatar_thumbs()
                        avatar.image.delete()
                    except Avatar.DoesNotExist:
                        avatar = Avatar(user=request.user,
                                        image="",
                                        valid=False)
                    avatar.image.save(
                        "%s.%s" % (request.user.username, file_ext),
                        ContentFile(f.read()))
                    avatar.save()

                    signal_responses = signals.post_signal.send(
                        sender=avatarchoose, request=request, form=form)
                    return signals.last_response(
                        signal_responses) or HttpResponseRedirect(
                            reverse("profile_avatar_crop"))

    else:
        form = AvatarForm()

    if DEFAULT_AVATAR:
        generic = Avatar.objects.get_default_avatar().get_resized_image_url(
            DEFAULT_AVATAR_SIZE)
    else:
        generic = ""

    template = "userprofile/avatar/choose.html"
    data = {
        'generic': generic,
        'form': form,
        "images": images,
        'AVATAR_WEBSEARCH': AVATAR_WEBSEARCH,
        'section': 'avatar',
        'DEFAULT_AVATAR_SIZE': DEFAULT_AVATAR_SIZE,
        'MIN_AVATAR_SIZE': MIN_AVATAR_SIZE
    }
    signals.context_signal.send(sender=avatarchoose,
                                request=request,
                                context=data)
    return render_to_response(template,
                              data,
                              context_instance=RequestContext(request))