Exemple #1
0
def add(request, extra_context=None, next_override=None,
        upload_form=UploadAvatarForm, *args, **kwargs):
    if extra_context is None:
        extra_context = {}
    avatar, avatars = _get_avatars(request.user)
    upload_avatar_form = upload_form(request.POST or None,
        request.FILES or None, user=request.user)
    if request.method == "POST" and 'avatar' in request.FILES:
        if upload_avatar_form.is_valid():
            avatar = Avatar(
                emailuser = request.user.username,
                primary = True,
            )
            image_file = request.FILES['avatar']
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            messages.success(request, _("Successfully uploaded a new avatar."))
            avatar_updated.send(sender=Avatar, user=request.user, avatar=avatar)
            return HttpResponseRedirect(next_override or _get_next(request))
        else:
            messages.error(request, upload_avatar_form.errors['avatar'])

        return HttpResponseRedirect(_get_next(request))
    else:
        # Only allow post request to change avatar.
        raise Http404
Exemple #2
0
def add(request, extra_context=None, next_override=None,
        upload_form=UploadAvatarForm, *args, **kwargs):
    if extra_context is None:
        extra_context = {}
    avatar, avatars = _get_avatars(request.user)
    upload_avatar_form = upload_form(request.POST or None,
        request.FILES or None, user=request.user)
    if request.method == "POST" and 'avatar' in request.FILES:
        if upload_avatar_form.is_valid():
            avatar = Avatar(
                emailuser = request.user.username,
                primary = True,
            )
            image_file = request.FILES['avatar']
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            messages.success(request, _("Successfully uploaded a new avatar."))
            avatar_updated.send(sender=Avatar, user=request.user, avatar=avatar)
            return HttpResponseRedirect(next_override or _get_next(request))
        else:
            messages.error(request, upload_avatar_form.errors['avatar'])

        return HttpResponseRedirect(_get_next(request))
    else:
        # Only allow post request to change avatar.
        raise Http404
Exemple #3
0
    def post(self, request):

        image_file = request.FILES.get('avatar', None)
        if not image_file:
            error_msg = 'avatar invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        (root, ext) = os.path.splitext(image_file.name.lower())
        if AVATAR_ALLOWED_FILE_EXTS and ext not in AVATAR_ALLOWED_FILE_EXTS:
            error_msg = _(
                u"%(ext)s is an invalid file extension. Authorized extensions are : %(valid_exts_list)s"
            ) % {
                'ext': ext,
                'valid_exts_list': ", ".join(AVATAR_ALLOWED_FILE_EXTS)
            }
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        if image_file.size > AVATAR_MAX_SIZE:
            error_msg = _(
                u"Your file is too big (%(size)s), the maximum allowed size is %(max_valid_size)s"
            ) % {
                'size': filesizeformat(image_file.size),
                'max_valid_size': filesizeformat(AVATAR_MAX_SIZE)
            }
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        username = request.user.username
        count = Avatar.objects.filter(emailuser=username).count()
        if AVATAR_MAX_AVATARS_PER_USER > 1 and count >= AVATAR_MAX_AVATARS_PER_USER:
            error_msg = _(
                u"You already have %(nb_avatars)d avatars, and the maximum allowed is %(nb_max_avatars)d."
            ) % {
                'nb_avatars': count,
                'nb_max_avatars': AVATAR_MAX_AVATARS_PER_USER
            }
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        try:
            avatar = Avatar(
                emailuser=username,
                primary=True,
            )
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            avatar_updated.send(sender=Avatar,
                                user=request.user,
                                avatar=avatar)
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        return Response({'success': True})
Exemple #4
0
    def post(self, request):

        image_file = request.FILES.get('avatar', None)
        avatar_size = request.data.get('avatar_size', 64)

        if not image_file:
            error_msg = 'avatar invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        try:
            avatar_size = int(avatar_size)
        except Exception as e:
            logger.error(e)
            error_msg = 'avatar_size invalid.'
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        (root, ext) = os.path.splitext(image_file.name.lower())
        if AVATAR_ALLOWED_FILE_EXTS and ext not in AVATAR_ALLOWED_FILE_EXTS:
            error_msg = _(u"%(ext)s is an invalid file extension. Authorized extensions are : %(valid_exts_list)s") % {'ext' : ext, 'valid_exts_list' : ", ".join(AVATAR_ALLOWED_FILE_EXTS)}
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        if image_file.size > AVATAR_MAX_SIZE:
            error_msg = _(u"Your file is too big (%(size)s), the maximum allowed size is %(max_valid_size)s") % { 'size' : filesizeformat(image_file.size), 'max_valid_size' : filesizeformat(AVATAR_MAX_SIZE)}
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        username = request.user.username
        count = Avatar.objects.filter(emailuser=username).count()
        if AVATAR_MAX_AVATARS_PER_USER > 1 and count >= AVATAR_MAX_AVATARS_PER_USER:
            error_msg = _(u"You already have %(nb_avatars)d avatars, and the maximum allowed is %(nb_max_avatars)d.") % { 'nb_avatars' : count, 'nb_max_avatars' : AVATAR_MAX_AVATARS_PER_USER}
            return api_error(status.HTTP_400_BAD_REQUEST, error_msg)

        try:
            avatar = Avatar(
                emailuser = username,
                primary = True,
            )
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            avatar_updated.send(sender=Avatar, user=request.user, avatar=avatar)
            avatar_url, is_default, date_uploaded = api_avatar_url(username, int(avatar_size))
        except Exception as e:
            logger.error(e)
            error_msg = 'Internal Server Error'
            return api_error(status.HTTP_500_INTERNAL_SERVER_ERROR, error_msg)

        return Response({'avatar_url': request.build_absolute_uri(avatar_url)})
Exemple #5
0
def change(request,
           extra_context=None,
           next_override=None,
           upload_form=UploadAvatarForm,
           primary_form=PrimaryAvatarForm,
           *args,
           **kwargs):
    if extra_context is None:
        extra_context = {}
    avatar, avatars = _get_avatars(request.user)
    if avatar:
        kwargs = {'initial': {'choice': avatar.id}}
    else:
        kwargs = {}
    upload_avatar_form = upload_form(user=request.user, **kwargs)
    primary_avatar_form = primary_form(request.POST or None,
                                       user=request.user,
                                       avatars=avatars,
                                       **kwargs)
    if request.method == "POST":
        updated = False
        if 'choice' in request.POST and primary_avatar_form.is_valid():
            avatar = Avatar.objects.get(
                id=primary_avatar_form.cleaned_data['choice'])
            avatar.primary = True
            avatar.save()
            updated = True
            messages.success(request, _("Successfully updated your avatar."))
        if updated:
            avatar_updated.send(sender=Avatar,
                                user=request.user,
                                avatar=avatar)
        return HttpResponseRedirect(next_override or _get_next(request))
    return render_to_response(
        'avatar/change.html',
        extra_context,
        context_instance=RequestContext(
            request, {
                'avatar': avatar,
                'avatars': avatars,
                'upload_avatar_form': upload_avatar_form,
                'primary_avatar_form': primary_avatar_form,
                'next': next_override or _get_next(request),
            }))
Exemple #6
0
def _update_user_avatar(user, pic):
    if not pic:
        return

    logger.info("retrieve pic from %s" % pic)

    filedata = urllib2.urlopen(pic)
    datatowrite = filedata.read()
    filename = '/tmp/%s.jpg' % user.username
    with open(filename, 'wb') as f:
        f.write(datatowrite)

    logger.info("save pic to %s" % filename)
    avatar = Avatar(emailuser=user.username, primary=True)
    avatar.avatar.save('image.jpg', File(open(filename)))
    avatar.save()
    avatar_updated.send(sender=Avatar, user=user, avatar=avatar)

    os.remove(filename)
Exemple #7
0
def _update_user_avatar(user, pic):
    if not pic:
        return

    logger.info("retrieve pic from %s" % pic)

    filedata = urllib2.urlopen(pic)
    datatowrite = filedata.read()
    filename = '/tmp/%s.jpg' % user.username
    with open(filename, 'wb') as f:
        f.write(datatowrite)

    logger.info("save pic to %s" % filename)
    avatar = Avatar(emailuser=user.username, primary=True)
    avatar.avatar.save(
        'image.jpg', File(open(filename))
    )
    avatar.save()
    avatar_updated.send(sender=Avatar, user=user, avatar=avatar)

    os.remove(filename)
Exemple #8
0
def delete(request, extra_context=None, next_override=None, *args, **kwargs):
    if extra_context is None:
        extra_context = {}
    avatar, avatars = _get_avatars(request.user)
    delete_avatar_form = DeleteAvatarForm(request.POST or None,
                                          user=request.user,
                                          avatars=avatars)
    if request.method == 'POST':
        if delete_avatar_form.is_valid():
            ids = delete_avatar_form.cleaned_data['choices']
            if unicode(avatar.id) in ids and avatars.count() > len(ids):
                # Find the next best avatar, and set it as the new primary
                for a in avatars:
                    if unicode(a.id) not in ids:
                        a.primary = True
                        a.save()
                        avatar_updated.send(sender=Avatar,
                                            user=request.user,
                                            avatar=avatar)
                        break

            # NOTE: `Avatar.objects.filter(id__in=ids).delete()` will NOT work
            # correctly. Sinct delete() on QuerySet will not call delete
            # method on avatar object.
            for a in Avatar.objects.filter(id__in=ids):
                a.delete()

            messages.success(request,
                             _("Successfully deleted the requested avatars."))
            return HttpResponseRedirect(next_override or _get_next(request))
    return render_to_response(
        'avatar/confirm_delete.html',
        extra_context,
        context_instance=RequestContext(
            request, {
                'avatar': avatar,
                'avatars': avatars,
                'delete_avatar_form': delete_avatar_form,
                'next': next_override or _get_next(request),
            }))
Exemple #9
0
def delete(request, extra_context=None, next_override=None, *args, **kwargs):
    if extra_context is None:
        extra_context = {}
    avatar, avatars = _get_avatars(request.user)
    delete_avatar_form = DeleteAvatarForm(request.POST or None,
        user=request.user, avatars=avatars)
    if request.method == 'POST':
        if delete_avatar_form.is_valid():
            ids = delete_avatar_form.cleaned_data['choices']
            if unicode(avatar.id) in ids and avatars.count() > len(ids):
                # Find the next best avatar, and set it as the new primary
                for a in avatars:
                    if unicode(a.id) not in ids:
                        a.primary = True
                        a.save()
                        avatar_updated.send(sender=Avatar, user=request.user, avatar=avatar)
                        break

            # NOTE: `Avatar.objects.filter(id__in=ids).delete()` will NOT work
            # correctly. Sinct delete() on QuerySet will not call delete
            # method on avatar object.
            for a in Avatar.objects.filter(id__in=ids):
                a.delete()

            messages.success(request, _("Successfully deleted the requested avatars."))
            return HttpResponseRedirect(next_override or _get_next(request))
    return render_to_response(
        'avatar/confirm_delete.html',
        extra_context,
        context_instance = RequestContext(
            request,
            { 'avatar': avatar,
              'avatars': avatars,
              'delete_avatar_form': delete_avatar_form,
              'next': next_override or _get_next(request), }
        )
    )
Exemple #10
0
def change(request, extra_context=None, next_override=None,
        upload_form=UploadAvatarForm, primary_form=PrimaryAvatarForm,
        *args, **kwargs):
    if extra_context is None:
        extra_context = {}
    avatar, avatars = _get_avatars(request.user)
    if avatar:
        kwargs = {'initial': {'choice': avatar.id}}
    else:
        kwargs = {}
    upload_avatar_form = upload_form(user=request.user, **kwargs)
    primary_avatar_form = primary_form(request.POST or None,
        user=request.user, avatars=avatars, **kwargs)
    if request.method == "POST":
        updated = False
        if 'choice' in request.POST and primary_avatar_form.is_valid():
            avatar = Avatar.objects.get(id=
                primary_avatar_form.cleaned_data['choice'])
            avatar.primary = True
            avatar.save()
            updated = True
            messages.success(request, _("Successfully updated your avatar."))
        if updated:
            avatar_updated.send(sender=Avatar, user=request.user, avatar=avatar)
        return HttpResponseRedirect(next_override or _get_next(request))
    return render_to_response(
        'avatar/change.html',
        extra_context,
        context_instance = RequestContext(
            request,
            { 'avatar': avatar,
              'avatars': avatars,
              'upload_avatar_form': upload_avatar_form,
              'primary_avatar_form': primary_avatar_form,
              'next': next_override or _get_next(request), }
        )
    )