Пример #1
0
def get_user_avatar(backend, details, response, social_user, uid,\
                    user, *args, **kwargs):
    url = None
    if backend.__class__ == FacebookBackend:
        url = "http://graph.facebook.com/%s/picture?type=large" % response['id']

    print response.keys()
    if url:
        print url
        avtr = Avatar(
                user = user,
                primary = True,
            )
        image_request = requests.get(url)
        print image_request.headers
        content_type=image_request.headers['content-type']
        print content_type
        filename = user.username
        if content_type == 'image/jpeg':
            filename = "%s.jpg" % user.username
        if content_type == 'image/png':
            filename = "%s.png" % user.username
        image_file = SimpleUploadedFile(
            filename,
            image_request.content,
            content_type=content_type
        )
        print image_file.__dict__
        avtr.avatar.save(image_file.name, image_file)
        avtr.save()
Пример #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(
                user = request.user,
                primary = True,
            )
            image_file = request.FILES['avatar']
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            request.user.message_set.create(
                message=_("Successfully uploaded a new avatar."))
            if notification:
                _notification_updated(request, avatar)
            return HttpResponseRedirect(next_override or _get_next(request))
    data = { 
        'avatar': avatar, 
        'avatars': avatars, 
        'upload_avatar_form': upload_avatar_form,
        'next': next_override or _get_next(request),
        'view_user': request.user,
        'page_class': 'avatar-page',
    }
    if extra_context:
        data.update(extra_context)

    return render_into_skin('avatar/add.html', data, request)
Пример #3
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(
                user = request.user,
                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))
    return render_to_response(
            'avatar/add.html',
            extra_context,
            context_instance = RequestContext(
                request,
                { 'avatar': avatar, 
                  'avatars': avatars, 
                  'upload_avatar_form': upload_avatar_form,
                  'next': next_override or _get_next(request), }
            )
        )
Пример #4
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(user=request.user, primary=True)
            image_file = request.FILES['avatar']

            filename_parts = os.path.splitext(image_file.name)
            extension = filename_parts[1]
            filename = '%s%s' % (uuid.uuid4(), extension)

            avatar.avatar.save(filename, image_file)
            avatar.save()
            messages.success(request, _("Successfully uploaded a new avatar."))
            avatar_updated.send(sender=Avatar, user=request.user, avatar=avatar)
            return redirect(next_override or _get_next(request))
    context = {
        'avatar': avatar,
        'avatars': avatars,
        'upload_avatar_form': upload_avatar_form,
        'next': next_override or _get_next(request),
    }
    context.update(extra_context)
    return render(request, 'avatar/add.html', context)
Пример #5
0
def avatar_crop(request, id=None):
    """
    Avatar management, creates a new avatar and makes it default
    """
    if id:
        avatar = get_object_or_404(Avatar, id=id, user=request.user)
    else:
        avatar = get_object_or_404(Avatar, user=request.user, primary=True)

    if (avatar.avatar.width<=avatar.avatar.height):
        result = "width"
    else:
        result = "height"

    if not request.method == "POST":
        form = AvatarCropForm()
    else:
        try:
            orig = avatar.avatar.storage.open(avatar.avatar.name, 'rb').read()
            image = Image.open(StringIO(orig))
        except IOError:
            return
        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'))

            box = [ left, top, right, bottom ]
            (w, h) = image.size
            if result=="width":
                box = map(lambda x: x*h/AVATAR_CROP_MAX_SIZE, box)
            else:
                box = map(lambda x: x*w/AVATAR_CROP_MAX_SIZE, box)

            image = image.crop(box)
            if image.mode != 'RGB':
                image = image.convert('RGB')

            thumb = StringIO()
            image.save(thumb, AVATAR_THUMB_FORMAT, quality=AVATAR_THUMB_QUALITY)
            thumb_file = ContentFile(thumb.getvalue())

            base_name, ext = os.path.splitext(avatar.avatar.name)
            thumb = avatar.avatar.storage.save("%s_cropped%s" % (base_name, ext), thumb_file)
            Avatar.objects.filter(id=avatar.id).update(primary=False)
            new_avatar = Avatar(user=request.user, primary=True, avatar=thumb)
            new_avatar.save()
            request.user.message_set.create(
                message=ugettext("Your new avatar has been saved successfully."))
            return HttpResponseRedirect(reverse("avatar_change"))

    return render_to_response("avatar_crop/crop.html", {
        'AVATAR_CROP_MAX_SIZE': AVATAR_CROP_MAX_SIZE,
        'dim': result,
        'avatar': avatar,
        'form': form
    }, context_instance=RequestContext(request))
Пример #6
0
def update_from_facebook(user, facebook_obj):
    """docstring for update_from_facebook"""
    profile = getattr(facebook_obj, 'profile', None)
    if not profile:
        facebook_obj.profile = facebook_obj.graph.get_object("me")
        profile = facebook_obj.profile
    # update django user information
    user.email = profile['email']
    user.first_name = profile['first_name']
    user.last_name = profile['last_name']
    user.save()
    # update pinax profile information
    pinax_profile = Profile.objects.get(user=user)
    pinax_profile.name = profile['name']
    pinax_profile.save()
    # populate email address in emailconfirmation app
    email = EmailAddress.objects.create(user=user, email=profile['email'], verified=True)
    email.set_as_primary(conditional=True)
    email.save()
    # save profile picture
    picture = urllib2.urlopen("http://graph.facebook.com/%s/picture" % facebook_obj.uid)
    picture_file = ContentFile(picture.read())
    avatar = Avatar(
        user = user,
        primary = True,
    )
    avatar.avatar.save('%s.jpg' % facebook_obj.uid, picture_file)
    avatar.save()
Пример #7
0
def upload_avatar(request):
    '''
    Upload avatar image
    '''
    response = {}
    status = 405
    if request.is_ajax() and request.method == 'POST':

        avatar, avatars = avatarviews._get_avatars(request.user)
        upload_avatar_form = UploadAvatarForm(None,
                                              request.FILES,
                                              user=request.user)
        if upload_avatar_form.is_valid():
            avatar = Avatar(
                user=request.user,
                primary=True,
            )
            image_file = request.FILES['avatar']
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            avatar_updated.send(sender=Avatar,
                                user=request.user,
                                avatar=avatar)
            response['avatar'] = userutil.get_user_avatar_url(
                request.user)['url']
            status = 200
    return JsonResponse(response, status=status)
Пример #8
0
def upload_avatar_js(request):
    '''
    Upload avatar image
    '''
    response = {}
    status = 405
    if request.is_ajax() and request.method == 'POST':

        avatar, avatars = avatarviews._get_avatars(request.user)
        upload_avatar_form = UploadAvatarForm(
            None,
            request.FILES,
            user=request.user
        )
        if upload_avatar_form.is_valid():
            avatar = Avatar(
                user=request.user,
                primary=True,
            )
            image_file = request.FILES['avatar']
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            avatar_updated.send(
                sender=Avatar,
                user=request.user,
                avatar=avatar
            )
            response['avatar'] = userutil.get_user_avatar_url(request.user)
            status = 200
    return JsonResponse(
        response,
        status=status
    )
Пример #9
0
def user_signed_up_(request, user, sociallogin=None, **kwargs):
	'''
	When a social account is created successfully and this signal is received,
	django-allauth passes in the sociallogin param, giving access to metadata on the remote account, e.g.:

	sociallogin.account.provider  # e.g. 'twitter'
	sociallogin.account.get_avatar_url()
	sociallogin.account.get_profile_url()
	sociallogin.account.extra_data['screen_name']

	See the socialaccount_socialaccount table for more in the 'extra_data' field.
	'''

	if sociallogin:
	# Extract first / last names from social nets and store on Profile record
		if sociallogin.account.provider == 'facebook':
			user.profile.first_name = sociallogin.account.extra_data['first_name']
			user.profile.last_name = sociallogin.account.extra_data['last_name']

		if sociallogin.account.provider == 'google':
			user.profile.first_name = sociallogin.account.extra_data['given_name']
			user.profile.last_name = sociallogin.account.extra_data['family_name']
	
		user.profile.save()
	
		mage_avatar = user.profile.download_avatar(sociallogin.account.get_avatar_url())
		avatar = Avatar(user=user,primary=True, avatar=image_avatar)
		avatar.save()
Пример #10
0
def create_details(strategy, details, *args, user=None, **kwargs):
    # link affiliation
    affiliation_kwargs = details.get('tmp_affiliation')
    if affiliation_kwargs:
        try:
            affiliation = Affiliation.objects.get(**affiliation_kwargs)
            user.affiliation = affiliation
        except Affiliation.DoesNotExist:
            form = UserAffiliationForm(affiliation_kwargs)
            if form.is_valid:
                affiliation = form.save()
                user.affiliation = affiliation
    # link avatar
    if user and not user.avatar_set.exists():
        photo_url = details.get('photo')
        if not photo_url:
            photo_url = settings.AVATAR_DEFAULT_URL
        url_parsed = urlparse(photo_url)
        photo_filename = os.path.basename(url_parsed.path)
        local_filename, headers = urllib.request.urlretrieve(photo_url)
        avatar = Avatar(user=user, primary=True)
        with open(local_filename, 'rb') as f:
            avatar.avatar.save(photo_filename, File(f))
        avatar.save()

    # link title
    user.title = details.get('title', '')
    # link position
    user.position = details.get('position', '')

    user.save()

    return {}
Пример #11
0
def upload_avatar_js(request):
    '''
    Upload avatar image
    '''
    response = {}
    status = 405
    if request.is_ajax() and request.method == 'POST':
        from avatar.models import Avatar
        from avatar import views as avatarviews
        from avatar.forms import UploadAvatarForm
        from avatar.signals import avatar_updated
        avatar, avatars = avatarviews._get_avatars(request.user)
        upload_avatar_form = UploadAvatarForm(None, request.FILES, user=request.user)
        if upload_avatar_form.is_valid():
            avatar = Avatar(
                user = request.user,
                primary = True,
            )
            image_file = request.FILES['avatar']
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            avatar_updated.send(sender=Avatar, user=request.user, avatar=avatar)
            response['avatar'] = accountutil.get_user_avatar_url(request.user)
            status = 200
    return HttpResponse(
        simplejson.dumps(response),
        content_type = 'application/json; charset=utf8',
        status=status
    )
Пример #12
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(
                user = request.user,
                primary = True,
            )
            image_file = request.FILES['avatar']
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            request.user.message_set.create(
                message=_("Successfully uploaded a new avatar."))
            if notification:
                _notification_updated(request, avatar)
            return HttpResponseRedirect(next_override or _get_next(request))
    data = { 
        'avatar': avatar, 
        'avatars': avatars, 
        'upload_avatar_form': upload_avatar_form,
        'next': next_override or _get_next(request),
        'view_user': request.user,
        'page_class': 'avatar-page',
    }
    if extra_context:
        data.update(extra_context)

    return render(request, 'avatar/add.html', data)
Пример #13
0
def upload(request, user_id=None):
    user = get_object_or_404(User, pk=user_id)
    if request.method == 'POST':
        if 'avatar' in request.FILES:
            form = UploadAvatarForm(
                            request.POST,
                            request.FILES,
                            user=user)
            if form.is_valid():
                avatar = Avatar(user=user, primary=True)
                image_file = request.FILES['avatar']
                avatar.avatar.save(image_file.name, image_file)
                avatar.save()
                sizes = avatar_settings.AVATAR_AUTO_GENERATE_SIZES
                for size in sizes:
                    avatar.create_thumbnail(size)
                avatar_updated.send(sender=Avatar, user=user, avatar=avatar)
                user.avatar_type = 'a'
                user.clear_avatar_urls()
                user.save()
                message = _('Avatar uploaded and set as primary')
            else:
                errors = get_error_list(form)
                message = ', '.join(map(lambda v: force_str(v), errors))
        else:
            message = _('Please choose file to upload')

        request.session['askbot_avatar_status_message'] = message

    return redirect_to_show_list(user_id)
Пример #14
0
def user_signed_up_(request, user, sociallogin=None, **kwargs):
    '''
	When a social account is created successfully and this signal is received,
	django-allauth passes in the sociallogin param, giving access to metadata on the remote account, e.g.:

	sociallogin.account.provider  # e.g. 'twitter'
	sociallogin.account.get_avatar_url()
	sociallogin.account.get_profile_url()
	sociallogin.account.extra_data['screen_name']

	See the socialaccount_socialaccount table for more in the 'extra_data' field.
	'''

    if sociallogin:
        # Extract first / last names from social nets and store on Profile record
        if sociallogin.account.provider == 'facebook':
            user.profile.first_name = sociallogin.account.extra_data[
                'first_name']
            user.profile.last_name = sociallogin.account.extra_data[
                'last_name']

        if sociallogin.account.provider == 'google':
            user.profile.first_name = sociallogin.account.extra_data[
                'given_name']
            user.profile.last_name = sociallogin.account.extra_data[
                'family_name']

        user.profile.save()

        mage_avatar = user.profile.download_avatar(
            sociallogin.account.get_avatar_url())
        avatar = Avatar(user=user, primary=True, avatar=image_avatar)
        avatar.save()
Пример #15
0
def save_facebook_picture(user, fb_id, token="", check_avatar=True):
	if check_avatar and Avatar.objects.filter(user=user).count():
		return

	args = {"width": "420", "access_token": token}
	url = "https://graph.facebook.com/" + fb_id + "/picture?" + urllib.urlencode(args)
	file = urllib.urlopen(url)
	file_contents = file.read()
	file_type = imghdr.what('', file_contents)
	if not is_correct_image_file_type(file_type):
		return
	avatar_path = avatar_file_path(user, file_type, fb_id)
	full_path = os.path.join(settings.MEDIA_ROOT, avatar_path)
	head = os.path.split(full_path)[0]

	try:
		if not os.path.exists(head):
			os.makedirs(head)
		local_file = open(full_path, "wb")
		local_file.write(file_contents)
		local_file.close()
		avatar = Avatar(
			user=user,
			primary=True,
			avatar=avatar_path,
		)
		avatar.save()
	except Exception:
		pass
	finally:
		file.close()
Пример #16
0
def upload_avatar_js(request):
    '''
    Upload avatar image
    '''
    response = {}
    status = 405
    if request.is_ajax() and request.method == 'POST':
        from avatar.models import Avatar
        from avatar import views as avatarviews
        from avatar.forms import UploadAvatarForm
        from avatar.signals import avatar_updated
        avatar, avatars = avatarviews._get_avatars(request.user)
        upload_avatar_form = UploadAvatarForm(None,
                                              request.FILES,
                                              user=request.user)
        if upload_avatar_form.is_valid():
            avatar = Avatar(
                user=request.user,
                primary=True,
            )
            image_file = request.FILES['avatar']
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            avatar_updated.send(sender=Avatar,
                                user=request.user,
                                avatar=avatar)
            response['avatar'] = accountutil.get_user_avatar_url(request.user)
            status = 200
    return HttpResponse(simplejson.dumps(response),
                        content_type='application/json; charset=utf8',
                        status=status)
Пример #17
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(user=request.user, primary=True)
            image_file = request.FILES["avatar"]
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            request.user.message_set.create(message=_("Successfully uploaded a new avatar."))
            if notification:
                _notification_updated(request, avatar)
            return HttpResponseRedirect(next_override or _get_next(request))
    data = {
        "avatar": avatar,
        "avatars": avatars,
        "upload_avatar_form": upload_avatar_form,
        "next": next_override or _get_next(request),
        "view_user": request.user,
        "page_class": "avatar-page",
    }
    if extra_context:
        data.update(extra_context)

    return render(request, "avatar/add.html", data)
Пример #18
0
def add_avatar_for_user(request, for_user=None, extra_context=None,
        next_override=None,
        upload_form=UploadAvatarForm, *args, **kwargs):
    target_user = get_object_or_404(User, username=for_user, is_active=True)
    if not AVATAR_ADMIN_TEST(request, target_user):
        raise PermissionDenied
    if extra_context is None:
        extra_context = {}
    avatar, avatars = _get_avatars(target_user)
    upload_avatar_form = upload_form(request.POST or None,
        request.FILES or None, user=target_user)
    if request.method == "POST" and 'avatar' in request.FILES:
        if upload_avatar_form.is_valid():
            avatar = Avatar(
                user = target_user,
                primary = True,
            )
            image_file = request.FILES['avatar']
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            messages.add_message(request, messages.INFO, _("Successfully uploaded a new avatar"))
            avatar_updated.send(sender=Avatar, user=target_user, avatar=avatar)
            return redirect(next_override or _get_next(request))
    context = {
        'avatar': avatar,
        'avatars': avatars,
        'target_user': target_user,
        'upload_avatar_form': upload_avatar_form,
        'next': next_override or _get_next(request),
    }
    context.update(extra_context)
    return render(request, 'avatar/add_for_user.html', context)
Пример #19
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(user=request.user, 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 redirect(next_override or _get_next(request))
    context = {
        'avatar': avatar,
        'avatars': avatars,
        'upload_avatar_form': upload_avatar_form,
        'next': next_override or _get_next(request),
    }
    context.update(extra_context)
    return render(request, 'avatar/add.html', context)
Пример #20
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
Пример #21
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":
        if upload_avatar_form.is_valid():
            avatar = Avatar(user=request.user, primary=True)
            image_file = upload_avatar_form.cleaned_data['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 redirect(next_override or _get_next(request))
    context = {
        'avatar': avatar,
        'avatars': avatars,
        'upload_avatar_form': upload_avatar_form,
        'next': next_override or _get_next(request),
    }
    context.update(extra_context)
    template_name = settings.AVATAR_ADD_TEMPLATE or 'avatar/add.html'
    return render(request, template_name, context)
Пример #22
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(
                user = request.user,
                primary = True,
            )
            image_file = request.FILES['avatar']
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            request.user.message_set.create(
                message=_("Successfully uploaded a new avatar."))
            avatar_updated.send(sender=Avatar, user=request.user, avatar=avatar)
            return HttpResponseRedirect(next_override or _get_next(request))
    return render_to_response(
            'avatar/add.html',
            extra_context,
            context_instance = RequestContext(
                request,
                { 'avatar': avatar, 
                  'avatars': avatars, 
                  'upload_avatar_form': upload_avatar_form,
                  'next': next_override or _get_next(request), }
            )
        )
Пример #23
0
def AvatarAdd(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(user=request.user, primary=True)
            image_file = request.FILES['avatar']
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            invalidate_cache(request.user)
            messages.success(request, _("Successfully uploaded a new avatar."))
            avatar_updated.send(sender=Avatar,
                                user=request.user,
                                avatar=avatar)
            return render(request, 'auth/avatar_change.html')
    context = {
        'avatar': avatar,
        'avatars': avatars,
        'upload_avatar_form': upload_avatar_form,
        'next': next_override,
    }
    context.update(extra_context)
    template_name = 'auth/avatar_add.html'
    return render(request, template_name, context)
Пример #24
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(
                user = request.user,
                primary = True,
            )
            image_file = request.FILES['avatar']
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            updated = True
            request.user.message_set.create(
                message=_(u"Zdjęcie zostało pomyślnie dodane."))
            if notification:
                _notification_updated(request, avatar)
    return render_to_response(
            'avatar/add.html',
            extra_context,
            context_instance = RequestContext(
                request,
                { 'avatar': avatar, 
                  'avatars': avatars, 
                  'upload_avatar_form': upload_avatar_form,
                  'next': next_override or _get_next(request), }
            )
        )
Пример #25
0
    def generate_default_avatar(self):
        from cStringIO import StringIO
        from django.core.files.uploadedfile import SimpleUploadedFile
        from PIL import Image, ImageFont, ImageDraw
        from avatar.models import Avatar

        tmpname = '%s.png' % self.get_uhash()
        code = self.get_color_code()
        mode = "RGB"
        W, H = settings.SIMPLEAVATAR_SIZE
        font = ImageFont.truetype(settings.SIMPLEAVATAR_FONT, 256)
        text = self.user.username[:1].upper()

        im = Image.new(mode, (W, H), code)
        draw = ImageDraw.Draw(im)
        text_x, text_y = font.getsize(text)
        x = (W - text_x) / 2.0
        y = ((H - text_y) / 2.0) - (text_y / 2.0)
        draw.text((x, y), text, font=font, fill=(255, 255, 255, 100))

        # Write new avatar to memory.
        tmphandle = StringIO()
        im.save(tmphandle, 'png')
        tmphandle.seek(0)

        suf = SimpleUploadedFile(tmpname,
                                 tmphandle.read(),
                                 content_type='image/png')
        av = Avatar(user=self.user, primary=True)
        av.avatar.save(tmpname, suf, save=False)
        av.save()
Пример #26
0
def upload(request, user_id=None):
    user = get_object_or_404(User, pk=user_id)
    if request.method == 'POST':
        if 'avatar' in request.FILES:
            form = UploadAvatarForm(request.POST, request.FILES, user=user)
            if form.is_valid():
                avatar = Avatar(user=user, primary=True)
                image_file = request.FILES['avatar']
                avatar.avatar.save(image_file.name, image_file)
                avatar.save()
                sizes = avatar_settings.AVATAR_AUTO_GENERATE_SIZES
                for size in sizes:
                    avatar.create_thumbnail(size)
                avatar_updated.send(sender=Avatar, user=user, avatar=avatar)
                user.avatar_type = 'a'
                user.clear_avatar_urls()
                user.save()
                message = _('Avatar uploaded and set as primary')
            else:
                errors = get_error_list(form)
                message = u', '.join(map(lambda v: force_unicode(v), errors))
        else:
            message = _('Please choose file to upload')

        request.session['askbot_avatar_status_message'] = message

    return redirect_to_show_list(user_id)
Пример #27
0
def change_avatar(request,
                  target_obj,
                  target_type,
                  from_name,
                  extra_context={},
                  next_override=None,
                  current_app='plus_groups',
                  namespace='groups',
                  **kwargs):

    # XXX some of this should probably be refactored into the model layer
    target = target_obj.get_ref()
    avatars = Avatar.objects.filter(target=target).order_by('-primary')
    if avatars.count() > 0:
        avatar = avatars[0]
        kwargs = {'initial': {'choice': avatar.id}}
    else:
        avatar = None
        kwargs = {}

    primary_avatar_form = PrimaryAvatarForm(request.POST or None,
                                            target=target,
                                            **kwargs)
    if request.method == "POST":
        if 'avatar' in request.FILES:
            path = avatar_file_path(target=target,
                                    filename=request.FILES['avatar'].name)
            avatar = Avatar(
                target=target,
                primary=True,
                avatar=path,
            )
            new_file = avatar.avatar.storage.save(path,
                                                  request.FILES['avatar'])
            avatar.save()
            request.user.message_set.create(
                message=_("Successfully uploaded a new avatar."))
        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()

            request.user.message_set.create(
                message=_("Successfully updated your 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,
                'primary_avatar_form': primary_avatar_form,
                'next': next_override or _get_next(request),
                'target': target_obj,
                'target_type': target_type,
                'from_name': from_name,
            }))
Пример #28
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(user=request.user, primary=True)
            image_file = request.FILES["avatar"]
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            messages.add_message(request, messages.INFO, _("Successfully uploaded a new avatar"))
            avatar_updated.send(sender=Avatar, user=request.user, avatar=avatar)
            return HttpResponseRedirect(next_override or _get_next(request))
    return render_to_response(
        "avatar/add.html",
        extra_context,
        context_instance=RequestContext(
            request,
            {
                "avatar": avatar,
                "avatars": avatars,
                "upload_avatar_form": upload_avatar_form,
                "next": next_override or _get_next(request),
            },
        ),
    )
Пример #29
0
    def process_request(self, request):
        # AuthenticationMiddleware is required so that request.user exists.
        if not hasattr(request, 'user'):
            raise ImproperlyConfigured(
                "The Django remote user auth middleware requires the"
                " authentication middleware to be installed.  Edit your"
                " MIDDLEWARE_CLASSES setting to insert"
                " 'django.contrib.auth.middleware.AuthenticationMiddleware'"
                " before the RemoteUserMiddleware class.")
        try:
            username = request.META[self.header]
        except KeyError:
            # If specified header doesn't exist then remove any existing
            # authenticated remote-user, or return (leaving request.user set to
            # AnonymousUser by the AuthenticationMiddleware).
            if self.force_logout_if_no_header and request.user.is_authenticated:
                self._remove_invalid_user(request)
            return
        # If the user is already authenticated and that user is the user we are
        # getting passed in the headers, then the correct user is already
        # persisted in the session and we don't need to continue.
        if request.user.is_authenticated:
            #if request.user.get_username() == self.clean_username(username, request):
            if request.user.get_username() == username[:username.find("@")]:
                return
            else:
                # An authenticated user is associated with the request, but
                # it does not match the authorized user in the header.
                self._remove_invalid_user(request)

        # We are seeing this user for the first time in this session, attempt
        # to authenticate the user.
        user = auth.authenticate(remote_user=username)
        if user:
            # User is valid.  Set request.user and persist user in the session
            # by logging the user in.
            request.user = user
            auth.login(request, user)
            if user.email != username:
                user.email = username
                user.email_isvalid = True
                user.first_name = request.META['HTTP_X_AUTH_GIVEN_NAME']
                user.last_name = request.META['HTTP_X_AUTH_FAMILY_NAME']
                user.real_name = user.first_name + ' ' + user.last_name
                user.save()

            # If there's no avatar directory for this user on disk, retrieve the avatar from google
            # and set as primary
            if not os.path.exists("/var/askbot-site/askbot/upfiles/avatars/" + username[:username.find("@")]):
                result = urllib.urlretrieve(request.META['HTTP_X_AUTH_PICTURE'])
                avatar = Avatar(user=user, primary=True)
                avatar.avatar.save("/var/askbot-site/askbot/upfiles/avatars/" + username[:username.find("@")], File(open(result[0])))
                avatar.save()
                sizes = avatar_settings.AVATAR_AUTO_GENERATE_SIZES
                for size in sizes:
                    avatar.create_thumbnail(size)
                user.avatar_type = 'a'
                user.clear_avatar_urls()
                user.save()
Пример #30
0
def change(request, extra_context={}, next_override=None):
    avatars = Avatar.objects.filter(user=request.user).order_by('-primary')
    if avatars.count() > 0:
        avatar = avatars[0]
        kwargs = {'initial': {'choice': avatar.id}}
    else:
        avatar = None
        kwargs = {}
    primary_avatar_form = PrimaryAvatarForm(request.POST or None,
                                            user=request.user,
                                            **kwargs)
    if request.method == "POST":
        updated = False
        if 'avatar' in request.FILES:
            path = avatar_file_path(user=request.user,
                                    filename=request.FILES['avatar'].name)
            avatar = Avatar(
                user=request.user,
                primary=True,
                avatar=path,
            )
            new_file = avatar.avatar.storage.save(path,
                                                  request.FILES['avatar'])
            avatar.save()
            updated = True
            request.user.message_set.create(
                message=_("Successfully uploaded a new avatar."))
        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
            request.user.message_set.create(
                message=_("Successfully updated your avatar."))
        if updated and notification:
            notification.send([request.user], "avatar_updated", {
                "user": request.user,
                "avatar": avatar
            })
            if friends:
                notification.send(
                    (x['friend']
                     for x in Friendship.objects.friends_for_user(request.user)
                     ), "avatar_friend_updated", {
                         "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,
                'primary_avatar_form': primary_avatar_form,
                'next': next_override or _get_next(request),
            }))
Пример #31
0
def change_avatar(request, id, extra_context={}, next_override=None):
    user_edit = get_object_or_404(User, pk=id)
    try:
        profile = Profile.objects.get(user=user_edit)
    except Profile.DoesNotExist:
        profile = Profile.objects.create_profile(user=user_edit)
        
    #if not has_perm(request.user,'profiles.change_profile',profile): raise Http403
    if not profile.allow_edit_by(request.user): raise Http403
    
    avatars = Avatar.objects.filter(user=user_edit).order_by('-primary')
    if avatars.count() > 0:
        avatar = avatars[0]
        kwargs = {'initial': {'choice': avatar.id}}
    else:
        avatar = None
        kwargs = {}
    primary_avatar_form = PrimaryAvatarForm(request.POST or None, user=user_edit, **kwargs)
    if request.method == "POST":
        updated = False
        if 'avatar' in request.FILES:
            path = avatar_file_path(user=user_edit, 
                filename=request.FILES['avatar'].name)
            avatar = Avatar(
                user = user_edit,
                primary = True,
                avatar = path,
            )
            new_file = avatar.avatar.storage.save(path, request.FILES['avatar'])
            avatar.save()
            updated = True
            request.user.message_set.create(
                message=_("Successfully uploaded a new avatar."))
        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
            request.user.message_set.create(
                message=_("Successfully updated your avatar."))
        if updated and notification:
            notification.send([request.user], "avatar_updated", {"user": user_edit, "avatar": avatar})
            #if friends:
            #    notification.send((x['friend'] for x in Friendship.objects.friends_for_user(user_edit)), "avatar_friend_updated", {"user": user_edit, "avatar": avatar})
        return HttpResponseRedirect(reverse('profile', args=[user_edit.username]))
        #return HttpResponseRedirect(next_override or _get_next(request))
    return render_to_response(
        'profiles/change_avatar.html',
        extra_context,
        context_instance = RequestContext(
            request,
            {'user_this': user_edit,
              'avatar': avatar, 
              'avatars': avatars,
              'primary_avatar_form': primary_avatar_form,
              'next': next_override or _get_next(request), }
        )
    )
Пример #32
0
 def create_avatar(self, target, avatar_file):
     avatar = Avatar(
             content_object=target,
             primary=True,
         )
     avatar.avatar.save(avatar_file.name, avatar_file)
     avatar.save()
     return avatar
Пример #33
0
    def handle(self, *args, **options):
        user_num = args[0] if len(args) > 0 else 1
        response = urllib2.urlopen(
            "http://api.randomuser.me/?results=%s" % user_num)
        data = json.load(response)
        for u in data['results']:
            # Create user
            newUser = User()
            newUser.first_name = u['user']['name']['first']
            newUser.last_name = u['user']['name']['last']
            newUser.username = u['user']['username']
            newUser.email = '%[email protected] ' % u['user']['username']
            newUser.set_password(u['user']['username'])
            newUser.save()

            # Validate email address
            EmailAddress.objects.create(user=newUser,
                                        email=newUser.email,
                                        primary=True,
                                        verified=True)

            # Add avatar to user
            image_url = u['user']['picture']['large']
            import requests
            import tempfile
            from django.core import files

            # Steam the image from the url
            request = requests.get(image_url, stream=True)

            # Create a temporary file
            lf = tempfile.NamedTemporaryFile(
                suffix='.' + request.url.split('/')[-1].split('.')[-1],
                prefix=newUser.username)

            # import ipdb
            # ipdb.set_trace()

            # 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)

            newAvatar = Avatar()
            newAvatar.avatar = files.File(lf)
            newAvatar.primary = True
            newAvatar.user = newUser
            newAvatar.save()

            self.stdout.write('New user created: %s.' % newUser)

        self.stdout.write('Successfully created %s new users.' % user_num)
Пример #34
0
def test_ambassadors_list(db, client):
    test_country_name = "Austria"
    test_country_code = "AT"

    test_username = "******"
    test_email = "*****@*****.**"
    test_first_name = "Testko"
    test_last_name = "Test"
    test_full_name = test_first_name + " " + test_last_name

    test_ambassador = User.objects.create(
        username=test_username, email=test_email, first_name=test_first_name, last_name=test_last_name
    )
    test_ambassador_profile = UserProfile.objects.create(user=test_ambassador, country=test_country_code)

    group = Group.objects.get(name="ambassadors")
    group.user_set.add(test_ambassador)

    with open(local(__file__).dirname + "/../../static/img/team/alja.jpg") as fp:
        io = StringIO.StringIO()
        io.write(fp.read())
        uploaded_picture = InMemoryUploadedFile(io, None, "alja17.jpg", "jpeg", io.len, None)
        uploaded_picture.seek(0)

    avatar = Avatar(user=test_ambassador, primary=True)
    avatar.avatar.save(uploaded_picture.name, uploaded_picture)
    avatar.save()

    new_avatar = get_primary_avatar(test_ambassador, size=80)
    test_amb_avatar = new_avatar.avatar_url(80)

    response = client.get(reverse("web.ambassadors"))

    # We're expecting to the Ambassador under the right country,
    # with the right avatar and the right email contact
    expected_result = """
	<h2 class="clearfix">%s</h2>
	<div class="ambassador clearfix">
	<img src="%s" alt="%s" width="80" height="80" class="img-circle" />
	<h4>%s&nbsp;<span>&nbsp;<a alt="Send me an email" href="mailto:%s"><i class="fa fa-envelope"></i></a>
	""" % (
        test_country_name,
        test_amb_avatar,
        test_username,
        test_full_name,
        test_email,
    )

    expected_result = expected_result.replace("\t", "").replace("\n", "")
    ambassadors_content = response.content.replace("\t", "").replace("\n", "")

    # Check this test and modify it to integrating the Ambassadors page changes
    # assert expected_result in ambassadors_content

    test_ambassador.delete()
    avatar.delete()
Пример #35
0
 def save(self, *args, **kwargs):
     request = self.context.get('request')
     user = request.user
     if 'avatar' in request.FILES:
         avatar = Avatar(user=user, primary=True)
         image_file = request.FILES['avatar']
         avatar.avatar.save(image_file.name, image_file)
         avatar.save()
         avatar_updated.send(sender=Avatar, user=user, avatar=avatar)
     return user
Пример #36
0
def webcam_upload(request, id):
    # TODO: add proper security by attaching session to flash request
    user = get_object_or_404(User, pk=id)
    if request.method == "POST":
        avatar = Avatar(user=user, primary=True)
        avatar.avatar.save("%s_webcam_%s.jpg" %
                          (user.pk, Avatar.objects.filter(user=user).count()),
                           ContentFile(request.raw_post_data))
        avatar.save()
        messages.success(request, _("Successfully uploaded a new avatar."))
        return HttpResponse(status=200, content="ok")
Пример #37
0
def webcam_upload(request, id):
    # TODO: add proper security by attaching session to flash request
    user = get_object_or_404(User, pk=id)
    if request.method == "POST":
        avatar = Avatar(user=user, primary=True)
        avatar.avatar.save("%s_webcam_%s.jpg" %
                          (user.pk, Avatar.objects.filter(user=user).count()),
                           ContentFile(request.raw_post_data))
        avatar.save()
        messages.success(request, _("Successfully uploaded a new avatar."))
        return HttpResponse(status=200, content="ok")
Пример #38
0
 def post(self, *args, **kwargs):
     avatar, avatars = _get_avatars(self.request.user)
     if 'add' in self.request.POST and 'avatar' in self.request.FILES:
         upload_avatar_form = UploadAvatarForm(self.request.POST,
                                               self.request.FILES,
                                               user=self.request.user)
         if upload_avatar_form.is_valid():
             avatar = Avatar(user=self.request.user, primary=True)
             image_file = self.request.FILES['avatar']
             avatar.avatar.save(image_file.name, image_file)
             avatar.save()
             messages.success(self.request,
                              'Successfully uploaded a new avatar.')
             avatar_updated.send(sender=Avatar,
                                 user=self.request.user,
                                 avatar=avatar)
         return HttpResponseRedirect(reverse('avatar_change'))
     elif 'change' in self.request.POST:
         primary_avatar_form = PrimaryAvatarForm(self.request.POST,
                                                 user=self.request.user,
                                                 avatars=avatars)
         if 'choice' in self.request.POST and primary_avatar_form.is_valid(
         ):
             avatar = Avatar.objects.get(
                 id=primary_avatar_form.cleaned_data['choice'])
             avatar.primary = True
             avatar.save()
             avatar_updated.send(sender=Avatar,
                                 user=self.request.user,
                                 avatar=avatar)
             messages.success(self.request,
                              'Successfully updated your avatar.')
         return HttpResponseRedirect(reverse('avatar_change'))
     elif 'delete' in self.request.POST:
         delete_avatar_form = PrimaryAvatarForm(self.request.POST,
                                                user=self.request.user,
                                                avatars=avatars)
         if delete_avatar_form.is_valid():
             ids = delete_avatar_form.cleaned_data['choice']
             if six.text_type(
                     avatar.id) in ids and avatars.count() > len(ids):
                 for a in avatars:
                     if six.text_type(a.id) not in ids:
                         a.primary = True
                         a.save()
                         avatar_updated.send(sender=Avatar,
                                             user=self.request.user,
                                             avatar=avatar)
                         break
             Avatar.objects.filter(id__in=ids).delete()
             messages.success(self.request,
                              'Selected avatar successfully deleted.')
         return HttpResponseRedirect(reverse('avatar_change'))
     return HttpResponseRedirect(reverse('avatar_change'))
Пример #39
0
def add_new_avatar(request, upload_avatar_form):
    if upload_avatar_form.is_valid():
        avatar = Avatar(user=request.user, primary=True)
        image_file = request.FILES["avatar"]
        avatar.avatar.save(image_file.name, image_file)
        avatar.save()
        request.user.message_set.create(message=_("Successfully uploaded a new avatar."))
        if notification:
            _notification_updated(request, avatar)
        return True
    return False
Пример #40
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)
    result = "width"

    kwargs = {}
    if avatar:
        try:
            if avatar.avatar.width <= avatar.avatar.height:
                result = "height"
            else:
                result = "width"
            kwargs = {'initial': {'choice': avatar.id}}
        except IOError:
            avatar.delete()
            avatar = None

    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(
                user = request.user,
                primary = True,
            )
            image_file = request.FILES['avatar']
            avatar.avatar.save(image_file.name.encode('utf8'), image_file)
            avatar.save()
            if avatar.avatar.width <= avatar.avatar.height:
                result = "height"
            else:
                result = "width"
            messages.success(request, _("Successfully uploaded a new avatar."))
            avatar_updated.send(sender=Avatar, user=request.user, avatar=avatar)
            return HttpResponse(json.dumps({'avatar_url': avatar.avatar.url, 'dim':result }), mimetype='text/html', content_type="text/plain")

    return render_to_response(
        'avatar/change.html',
        extra_context,
        context_instance = RequestContext(
            request,
            { 'avatar': avatar,
              'avatars': avatars,
              'dim': result,
              'AVATAR_CROP_MAX_SIZE': AVATAR_CROP_MAX_SIZE,
              #'upload_avatar_form': upload_avatar_form,
              'crop_form':AvatarCropForm,
              'next': next_override or _get_next(request), }
        )
    )
Пример #41
0
 def save(self):
     if 'avatar' in self.files:
         avatar = Avatar(user=self.user, primary=True)
         image_file = self.files['avatar']
         avatar.avatar.save(image_file.name, image_file)
         avatar.save()
         avatar_updated.send(sender=Avatar, user=self.user, avatar=avatar)
     self.user.first_name = self.cleaned_data['first_name']
     self.user.last_name = self.cleaned_data['last_name']
     self.user.profile.summary = self.cleaned_data['summary']
     self.user.profile.save()
     self.user.save()
Пример #42
0
    def save_avatar(self, logo):
        'Sets an avatar'

        self.avatar_set.all().delete()
        if logo:
            avatar = Avatar(
                user = self,
                primary = True,
            )
            image_file = logo
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
Пример #43
0
def test_ambassadors_list(db, client):
    test_country_name = "Austria"
    test_country_code = "AT"

    test_username = '******'
    test_email = '*****@*****.**'
    test_first_name = 'Testko'
    test_last_name = 'Test'
    test_full_name = test_first_name + " " + test_last_name

    test_ambassador = User.objects.create(username=test_username,
                                          email=test_email,
                                          first_name=test_first_name,
                                          last_name=test_last_name)
    test_ambassador_profile = UserProfile.objects.create(
        user=test_ambassador, country=test_country_code)

    group = Group.objects.get(name="ambassadors")
    group.user_set.add(test_ambassador)

    with open(local(__file__).dirname + '/../../static/img/team/alja.jpg') as fp:
        io = StringIO.StringIO()
        io.write(fp.read())
        uploaded_picture = InMemoryUploadedFile(
            io, None, "alja17.jpg", "jpeg", io.len, None)
        uploaded_picture.seek(0)

    avatar = Avatar(user=test_ambassador, primary=True)
    avatar.avatar.save(uploaded_picture.name, uploaded_picture)
    avatar.save()

    new_avatar = get_primary_avatar(test_ambassador, size=80)
    test_amb_avatar = new_avatar.avatar_url(80)

    response = client.get(reverse('web.ambassadors'))

    # We're expecting to the Ambassador under the right country,
    # with the right avatar and the right email contact
    expected_result = '''
	<h2 class="clearfix">%s</h2>
	<div class="ambassador clearfix">
	<img src="%s" alt="%s" width="80" height="80" class="img-circle" />
	<h4>%s&nbsp;<span>&nbsp;<a alt="Send me an email" href="mailto:%s"><i class="fa fa-envelope"></i></a>
	''' % (test_country_name, test_amb_avatar, test_username, test_full_name, test_email)

    expected_result = expected_result.replace('\t', '').replace('\n', '')
    ambassadors_content = response.content.replace('\t', '').replace('\n', '')

# Check this test and modify it to integrating the Ambassadors page changes
    # assert expected_result in ambassadors_content

    test_ambassador.delete()
    avatar.delete()
def make_avatar(old_user):
    if old_user["profileicon"]:
        icon = path_to_profileimages+old_user["profileicon"]
        user = User.objects.get(pk=get_new_id("user", old_user["user_id"]))
        path = avatar_file_path(user=user, filename=old_user["profileicon"])
        avatar = Avatar(
            user = user,
            primary = True,
            avatar = path,
        )
        new_file = avatar.avatar.storage.save(path, ContentFile(open(icon, "r").read()))
        avatar.save()
Пример #45
0
def change(request, extra_context={}, next_override=None):
    avatars = Avatar.objects.filter(user=request.user).order_by('-primary')
    if avatars.count() > 0:
        avatar = avatars[0]
        kwargs = {'initial': {'choice': avatar.id}}
    else:
        avatar = None
        kwargs = {}
    primary_avatar_form = PrimaryAvatarForm(
        request.POST or None, user=request.user, **kwargs)
    if request.method == "POST":
        updated = False
        if 'avatar' in request.FILES:
            path = avatar_file_path(user=request.user,
                                    filename=request.FILES['avatar'].name)
            avatar = Avatar(
                user=request.user,
                primary=True,
                avatar=path,
            )
            new_file = avatar.avatar.storage.save(
                path, request.FILES['avatar'])
            avatar.save()
            updated = True
            messages.info(request,
                _("Successfully uploaded a new avatar."))
        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.info(request,
                _("Successfully updated your avatar."))
        if updated and notification:
            notification.send([request.user], "avatar_updated", {
                              "user": request.user, "avatar": avatar})
            if friends:
                notification.send((x['friend'] for x in Friendship.objects.friends_for_user(
                    request.user)), "avatar_friend_updated", {"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,
             'primary_avatar_form': primary_avatar_form,
             'next': next_override or _get_next(request), }
        )
    )
Пример #46
0
def change_avatar(request, target_obj, target_type, from_name, extra_context={}, 
                  next_override=None, current_app='plus_groups',namespace='groups',**kwargs):

    # XXX some of this should probably be refactored into the model layer 
    target = target_obj.get_ref()
    avatars = Avatar.objects.filter(target=target).order_by('-primary')
    if avatars.count() > 0:
        avatar = avatars[0]
        kwargs = {'initial': {'choice': avatar.id}}
    else:
        avatar = None
        kwargs = {}

    primary_avatar_form = PrimaryAvatarForm(request.POST or None, target=target, **kwargs)
    if request.method == "POST":
        if 'avatar' in request.FILES:
            path = avatar_file_path(target=target, 
                filename=request.FILES['avatar'].name)
            avatar = Avatar(
                target = target,
                primary = True,
                avatar = path,
            )
            new_file = avatar.avatar.storage.save(path, request.FILES['avatar'])
            avatar.save()
            request.user.message_set.create(
                message=_("Successfully uploaded a new avatar."))
        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()
            
            request.user.message_set.create(
                message=_("Successfully updated your 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,
              'primary_avatar_form': primary_avatar_form,
              'next': next_override or _get_next(request),
              'target' : target_obj,
              'target_type' : target_type,
              'from_name' : from_name,
              }
        )
    )
Пример #47
0
    def change_avatar(self, request):
        avatars = Avatar.objects.filter(user=request.user).order_by('-primary')
        if avatars.count() > 0:
            avatar = avatars[0]

        if 'avatar_file' in request.FILES:
            path = avatar_file_path(user=request.user,filename=request.FILES['avatar_file'].name)
            avatar = Avatar(
                user = request.user,
                primary = True,
                avatar = path,
            )
            new_file = avatar.avatar.storage.save(path, request.FILES['avatar_file'])
            avatar.save()
Пример #48
0
def oauth_callback(request):
    code = request.GET['code']
    url = 'https://api.weibo.com/oauth2/access_token'
    values = {
        'client_id': '2027959579',
        'client_secret': 'f839c30fc7681ba271dd28d2356b37d4',
        'grant_type': 'authorization_code',
        'redirect_uri': 'themer.chinacloudapp.cn/callback',
        'code': code
    }
    data = urllib.parse.urlencode(values)
    data = data.encode('ascii')
    req = urllib.request.Request(url, data)
    response = urllib.request.urlopen(req)
    r = response.read().decode('utf-8')
    result = json.loads(r)
    print(result)
    access_token = result['access_token']
    uid = result['uid']
    expire_time = result['expires_in']

    d = get_info(access_token, uid)



    try:
        user = User.objects.get(username=uid)
    except:
        user = User.objects.create_user(uid, '[email protected]', '********')
        user.save()
    user = authenticate(username=uid, password='******')
    login(request, user)

    with urllib.request.urlopen(d['avatar']) as response:
        data = response.read()
        avatar = Avatar(user=user, primary=True)
        image_name = str(uuid.uuid4()) + ".jpg"
        avatar.avatar = ContentFile(data, image_name)
        avatar.save()

    try:
        ouser = MyUser.objects.get(user=user)
    except:
        ouser = MyUser(user=user)
    ouser.type = 1
    ouser.access_token = access_token
    ouser.expire_time = int(expire_time)
    ouser.username = d['name']
    ouser.save()
    return redirect('/timeline')
Пример #49
0
def make(request,
         img_url=None,
         extra_context={},
         next_override=None,
         upload_form=UploadAvatarForm,
         make_primary=True):
    upload_avatar_form = upload_form({'url': img_url},
                                     request.FILES or None,
                                     user=request.user)
    if img_url and upload_avatar_form.is_valid():
        img = urlopen(img_url)
        img_name = img_url.split('/')[-1]
        img_name = img_name.split('?')[0]
        keepcharacters = ('.', '_')
        file_name = "".join(c for c in img_name
                            if c.isalnum() or c in keepcharacters).rstrip()
        temp_img = NamedTemporaryFile()
        temp_img.write(img.read())
        temp_img.flush()
        image = Image.open(temp_img.name)
        if image.mode != "RGB":
            image = image.convert("RGB")
        size = image.size
        prop = 200.0 / float(image.size[0])
        size = (int(prop * float(image.size[0])),
                int(prop * float(image.size[1])))
        image.thumbnail(size, Image.ANTIALIAS)
        image.save(temp_img.name, 'JPEG')
        avatar = Avatar(user=request.user, primary=make_primary)
        avatar.avatar.save(''.join([file_name, '.jpg']), File(temp_img))
        avatar.save()
        if request.is_ajax():
            return HttpResponse('ok')
        if make_primary:
            messages.success(request, _(AVATAR_UPDATED_MSG))
        else:
            messages.success(request, _(AVATAR_UPLOADED_MSG))
        return HttpResponseRedirect(next_override or _get_next(request))
    else:
        if request.is_ajax():
            return HttpResponse(upload_avatar_form.non_field_errors())
        if request.method == "GET":
            for error in upload_avatar_form.non_field_errors():
                messages.error(request, _(error))
    next = request.META.get('HTTP_REFERER', None)
    #return change(request, img_url, next_override=next_override)
    #if 'next' in request.REQUEST:
    return HttpResponseRedirect(next_override or '%s?url=%s&next=%s' %
                                (reverse('avatar_change'), img_url, next))
Пример #50
0
def change(request, extra_context={}, next_override=None):
    avatars = Avatar.objects.filter(user=request.user).order_by("-primary")
    if avatars.count() > 0:
        avatar = avatars[0]
        kwargs = {"initial": {"choice": avatar.id}}
    else:
        avatar = None
        kwargs = {}
    primary_avatar_form = PrimaryAvatarForm(request.POST or None, user=request.user, **kwargs)
    if request.method == "POST":
        updated = False
        if "avatar" in request.FILES:
            path = avatar_file_path(user=request.user, filename=request.FILES["avatar"].name)
            avatar = Avatar(user=request.user, primary=True, avatar=path)
            new_file = avatar.avatar.storage.save(path, request.FILES["avatar"])
            avatar.save()
            updated = True
            # request.user.message_set.create(
            #    message=_("Successfully uploaded a new avatar."))
        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
            # request.user.message_set.create(
            #    message=_("Successfully updated your avatar."))
        if updated and notification:
            notification.send([request.user], "avatar_updated", {"user": request.user, "avatar": avatar})
            if friends:
                notification.send(
                    (x["friend"] for x in Friendship.objects.friends_for_user(request.user)),
                    "avatar_friend_updated",
                    {"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,
                "primary_avatar_form": primary_avatar_form,
                "next": next_override or _get_next(request),
            },
        ),
    )
Пример #51
0
def change_avatar(request):
    '''Customised version of the default add avatar view from the django-avatar
    app. Changed to allow the form to be embedded on the main DWAD profile
    page.'''
    upload_avatar_form = UploadAvatarForm(request.POST or None,
                                          request.FILES or None,
                                          user=request.user)
    if 'avatar' in request.FILES and upload_avatar_form.is_valid():
        avatar = Avatar(user=request.user, primary=True)
        image_file = request.FILES['avatar']
        avatar.avatar.save(image_file.name, image_file)
        avatar.save()
        avatar_updated.send(sender=Avatar, user=request.user, avatar=avatar)
        return redirect(reverse('profile'))
    context = {'upload_avatar_form': upload_avatar_form}
    return profile(request, extra_context=context)
Пример #52
0
    def update(self, instance, validated_data):
        request = self.context.get('request')

        profile = validated_data.get('profile', None)
        instance.username = validated_data.get('username', instance.username)
        instance.first_name = validated_data.get('first_name',
                                                 instance.first_name)

        if profile:
            bio = profile.get("bio")
            location = profile.get("location")
            birth_date = profile.get("birth_date")
            first_name = profile.get("first_name")
            last_name = profile.get("last_name")
            if bio and bio != instance.profile.bio:
                instance.profile.bio = bio
            if location and location != instance.profile.location:
                instance.profile.location = location
            if birth_date and birth_date != instance.profile.birth_date:
                instance.profile.birth_date = birth_date
            if first_name and first_name != instance.profile.first_name:
                instance.profile.first_name = first_name
            if last_name and last_name != instance.profile.last_name:
                instance.profile.last_name = last_name

        email = validated_data.get('email', None)
        if email and email != instance.email:
            adapter = get_adapter()
            adapter.send_mail('account/email/email_change', instance.email, {})
            email_address = EmailAddress.objects.get(user=instance,
                                                     verified=True)
            email_address.change(request, email, True)
            instance.email = email

        if 'avatar' in request.FILES:
            avatar = Avatar(user=instance, primary=True)
            image_file = request.FILES['avatar']
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            avatar_updated.send(sender=Avatar, user=instance, avatar=avatar)

        instance.save()

        # sync_sso(instance)

        return instance
    def update(self, instance, validated_data):
        profile_validated_data = validated_data.pop('profile', {})
        avatar_image = validated_data.get('avatar', None)

        instance = super(UserSerializer, self).update(instance, validated_data)
        try:
            profile = instance.profile
        except:
            profile = Profile.objects.create(user=instance)
        profile_serializer = ProfileSerializer(instance=profile, data=profile_validated_data)
        if profile_serializer.is_valid(raise_exception=False):
            profile_serializer.save()

        if avatar_image:
            avatar = Avatar(user=instance, primary=True)
            avatar.avatar.save(avatar_image.name, avatar_image)
            avatar.save()

        return instance
Пример #54
0
def add_avatar(group, image_dir, image_file_name) :
    if image_file_name == '' : 
        return

    f = ImageFile(open('mhpss_export/%s/%s'%(image_dir,image_file_name)),'rb')
    if f.size == 1357 :
        return   # image is plone default ... we don't want it
          
    path = avatar_file_path(target=group, filename=image_file_name)

    avatar = Avatar(
        target = group.get_ref(),
        primary = True,
        avatar = path,
        )

    avatar.save()
    new_file = avatar.avatar.storage.save(path, f)
    avatar.save()
Пример #55
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(user=request.user, 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)

            files_dict = {
                "files": [{
                    "name": image_file.name,
                    "size": len(image_file),
                    "url": avatar.avatar.url,
                    "thumbnailUrl": avatar.avatar.url,
                    "deleteUrl": "",
                    "deleteType": "DELETE"
                }]
            }
            return HttpResponse(json.dumps(files_dict),
                                content_type='application/json')
    context = {
        'avatar': avatar,
        'avatars': avatars,
        'upload_avatar_form': upload_avatar_form,
        'next': next_override or _get_next(request),
    }
    context.update(extra_context)
    return render(request, 'avatar/add.html', context)
Пример #56
0
    def update(self, instance, validated_data):
        request = self.context.get('request')

        profile = validated_data.get('profile', None)
        instance.username = validated_data.get('username', instance.username)
        instance.first_name = validated_data.get(
            'first_name', instance.first_name)
        if profile:
            new_track = profile.get('track')
            track = Track.objects.get(slug=new_track.slug)
            is_track_updated = instance.profile.track != new_track
            instance.profile.track = track
            instance.profile.last_opened_lesson = profile.get(
                'last_opened_lesson', instance.profile.last_opened_lesson)
            if is_track_updated:
                instance.profile.last_opened_lesson = None

        email = validated_data.get('email', None)
        if email and email != instance.email:
            adapter = get_adapter()
            adapter.send_mail('account/email/email_change', instance.email, {})
            email_address = EmailAddress.objects.get(
                user=instance, verified=True)
            email_address.change(request, email, True)
            instance.email = email

        if 'avatar' in request.FILES:
            avatar = Avatar(user=instance, primary=True)
            image_file = request.FILES['avatar']
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            avatar_updated.send(sender=Avatar, user=instance, avatar=avatar)

        instance.save()

        # sync_sso(instance)

        return instance
Пример #57
0
def add_avatar_for_user(request,
                        for_user=None,
                        extra_context=None,
                        next_override=None,
                        upload_form=UploadAvatarForm,
                        *args,
                        **kwargs):
    target_user = get_object_or_404(User, username=for_user, is_active=True)
    if not AVATAR_ADMIN_TEST(request, target_user):
        raise PermissionDenied
    if extra_context is None:
        extra_context = {}
    avatar, avatars = _get_avatars(target_user)
    upload_avatar_form = upload_form(request.POST or None,
                                     request.FILES or None,
                                     user=target_user)
    if request.method == "POST" and 'avatar' in request.FILES:
        if upload_avatar_form.is_valid():
            avatar = Avatar(
                user=target_user,
                primary=True,
            )
            image_file = request.FILES['avatar']
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            messages.add_message(request, messages.INFO,
                                 _("Successfully uploaded a new avatar"))
            avatar_updated.send(sender=Avatar, user=target_user, avatar=avatar)
            return redirect(next_override or _get_next(request))
    context = {
        'avatar': avatar,
        'avatars': avatars,
        'target_user': target_user,
        'upload_avatar_form': upload_avatar_form,
        'next': next_override or _get_next(request),
    }
    context.update(extra_context)
    return render(request, 'avatar/add_for_user.html', context)
Пример #58
0
    def save_avatar(self, instance):
        keys = self.initial_data.keys()
        if 'avatar' in keys and \
            (self.avatar is not None or self.initial_data.get('avatar') is None):
            avatar = instance.user.avatar_set.filter(primary=True).first()
            if avatar is not None:
                avatar.primary = False
                avatar.save()
                return avatar_updated.send(sender=Avatar,
                                           user=instance.user,
                                           avatar=avatar)
        elif self.avatar is None:
            return None

        if self.avatar:
            avatar = Avatar(user=instance.user, primary=True)
            image_file = self.avatar
            avatar.avatar.save(image_file.name, image_file)
            avatar.save()
            avatar_updated.send(sender=Avatar,
                                user=instance.user,
                                avatar=avatar)
            return avatar