def test_thumbnail_transpose_based_on_exif(self): upload_helper(self, "image_no_exif.jpg") avatar = get_primary_avatar(self.user) image_no_exif = Image.open(avatar.avatar.storage.open(avatar.avatar_name(settings.AVATAR_DEFAULT_SIZE), 'rb')) upload_helper(self, "image_exif_orientation.jpg") avatar = get_primary_avatar(self.user) image_with_exif = Image.open(avatar.avatar.storage.open(avatar.avatar_name(settings.AVATAR_DEFAULT_SIZE), 'rb')) self.assertLess(root_mean_square_difference(image_with_exif, image_no_exif), 1)
def test_thumbnail_transpose_based_on_exif(self): upload_helper(self, "image_no_exif.jpg") avatar = get_primary_avatar(self.user) image_no_exif = Image.open( avatar.avatar.storage.open( avatar.avatar_name(settings.AVATAR_DEFAULT_SIZE), 'rb')) upload_helper(self, "image_exif_orientation.jpg") avatar = get_primary_avatar(self.user) image_with_exif = Image.open( avatar.avatar.storage.open( avatar.avatar_name(settings.AVATAR_DEFAULT_SIZE), 'rb')) self.assertLess( root_mean_square_difference(image_with_exif, image_no_exif), 1)
def test_automatic_thumbnail_creation_CMYK(self): upload_helper(self, "django_pony_cmyk.jpg") avatar = get_primary_avatar(self.user) image = Image.open( avatar.avatar.storage.open( avatar.avatar_name(settings.AVATAR_DEFAULT_SIZE), 'rb')) self.assertEqual(image.mode, 'RGB')
def test_avatar_tag_works_with_kwargs(self): upload_helper(self, "test.png") avatar = get_primary_avatar(self.user) result = avatar_tags.avatar(self.user, title="Avatar") html = '<img src="{}" width="80" height="80" alt="test" title="Avatar" />'.format(avatar.avatar_url(80)) self.assertInHTML(html, result)
def get_user_avatar_url(user): avatar = get_primary_avatar(user, 80) if avatar: url = avatar.avatar_url(80) return { 'url': url, 'uploaded': True, 'html': ( '<img class="fw-avatar" src="' + url + '" alt="' + user.username + '">' ) } else: cl = string_to_color(user.username) return { 'url': get_default_avatar_url(), 'uploaded': False, 'html': ( '<span class="fw-string-avatar" style="background-color: ' + cl + ';"><span>' + user.username[0] + '</span></span>' ) }
def get_user_avatar_url(user): the_avatar = get_primary_avatar(user, 80) if the_avatar: the_avatar = the_avatar.avatar_url(80) else: the_avatar = get_default_avatar_url() return the_avatar
def autocomplete_usernames(request): if 'q' not in request.GET: HttpResponse(simplejson.dumps([])) q = request.GET['q'] # Replace non-breaking space with regular space q = q.replace(unichr(160), ' ') users = UserProfile.objects.filter( Q(user__username__icontains=q) | Q(real_name__icontains=q) ).distinct()[:10] results = [] for user in users: avatar = get_primary_avatar(user, 40) if avatar is None: avatar_url = get_default_avatar_url() else: avatar_url = avatar.get_absolute_url() results.append({ 'id': str(user.id), 'username': user.user.username, 'realName': user.user.userprofile.real_name, 'displayName': user.user.userprofile.real_name if user.user.userprofile.real_name else user.user.username, 'avatar': avatar_url, }) return HttpResponse(simplejson.dumps(results))
def test_avatar_tag_works_with_custom_size(self): upload_helper(self, "test.png") avatar = get_primary_avatar(self.user) result = avatar_tags.avatar(self.user, 100) self.assertIn('<img src="{}"'.format(avatar.avatar_url(100)), result) self.assertIn('width="100" height="100" alt="test" />', result)
def test_avatar_tag_works_with_user(self): upload_helper(self, "test.png") avatar = get_primary_avatar(self.user) result = avatar_tags.avatar(self.user) self.assertIn('<img src="{}"'.format(avatar.avatar_url(80)), result) self.assertIn('alt="test" width="80" height="80" />', result)
def test_avatar_tag_works_with_kwargs(self): upload_helper(self, "test.png") avatar = get_primary_avatar(self.user) result = avatar_tags.avatar(self.user, title="Avatar") html = '<img src="{}" width="80" height="80" alt="test" ' \ 'title="Avatar" />'.format(avatar.avatar_url(80)) self.assertInHTML(html, result)
def test_avatar_tag_works_with_user(self): upload_helper(self, "test.png") avatar = get_primary_avatar(self.user) result = avatar_tags.avatar(self.user) self.assertIn('<img src="{}"'.format(avatar.avatar_url(80)), result) self.assertIn('width="80" height="80" alt="test" />', result)
def test_avatar_tag_works_with_custom_size(self): upload_helper(self, "test.png") avatar = get_primary_avatar(self.user) result = avatar_tags.avatar(self.user, 100) self.assertIn('<img src="{}"'.format(avatar.avatar_url(100)), result) self.assertIn('alt="test" width="100" height="100" />', result)
def test_normal_image_upload(self): response = upload_helper(self, "test.png") self.assertEqual(response.status_code, 200) self.assertEqual(len(response.redirect_chain), 1) self.assertEqual(response.context['upload_avatar_form'].errors, {}) avatar = get_primary_avatar(self.user) self.assertIsNotNone(avatar) self.assertEqual(avatar.user, self.user) self.assertTrue(avatar.primary)
def test_delete_primary_avatar_and_new_primary(self): self.test_there_can_be_only_one_primary_avatar() primary = get_primary_avatar(self.user) oid = primary.id self.client.post(reverse('avatar_delete'), { 'choices': [oid], }) primaries = Avatar.objects.filter(user=self.user, primary=True) self.assertEqual(len(primaries), 1) self.assertNotEqual(oid, primaries[0].id) avatars = Avatar.objects.filter(user=self.user) self.assertEqual(avatars[0].id, primaries[0].id)
def get_user_avatar_url(user): avatar = get_primary_avatar(user, 80) if avatar: return { 'url': avatar.avatar_url(80), 'uploaded': True } else: return { 'url': get_default_avatar_url(), 'uploaded': False }
def render_primary(request, user=None, size=settings.AVATAR_DEFAULT_SIZE): size = int(size) avatar = get_primary_avatar(user, size=size) if avatar: # FIXME: later, add an option to render the resized avatar dynamically # instead of redirecting to an already created static file. This could # be useful in certain situations, particulary if there is a CDN and # we want to minimize the storage usage on our static server, letting # the CDN store those files instead url = avatar.avatar_url(size) else: url = get_default_avatar_url() return redirect(url)
def get_accessrights(ars): ret = [] for ar in ars: the_avatar = get_primary_avatar(ar.user, 80) if the_avatar: the_avatar = the_avatar.avatar_url(80) else: the_avatar = get_default_avatar_url() ret.append({ 'book_id': ar.book.id, 'user_id': ar.user.id, 'user_name': ar.user.readable_name, 'rights': ar.rights, 'avatar': the_avatar }) return ret
def recentCompetitionUserScoreboard(request): today = timezone.now() allPastRounds = Rounds.objects.filter( startdatetime__lte=today).order_by('startdatetime').reverse() if allPastRounds.count() > 0: mostRecentRound = allPastRounds[0] # now editing thisRoundSubmissions = RoundSubmissions.objects.filter( roundquestion__thisround__id=mostRecentRound.id, passed=True).order_by('-score', 'submitted_at') thisRoundSubmissions = getDistinctModelFields( thisRoundSubmissions, ['user', 'roundquestion']) users = {} for submission in thisRoundSubmissions: thisUser = submission.user if RoundUsers.objects.filter( user=thisUser, thisround=mostRecentRound).exists() == True: if thisUser.id not in users.keys(): if has_avatar(thisUser) == True: userAvatarUrl = get_primary_avatar( thisUser.username).get_absolute_url() elif thisUser.profile.profileImgUrl != '': userAvatarUrl = thisUser.profile.profileImgUrl else: userAvatarUrl = '' users[thisUser.id] = { 'userid': thisUser.id, 'profileImgUrl': userAvatarUrl, 'first_name': thisUser.first_name, 'last_name': thisUser.last_name, 'username': thisUser.username, } competitionUsers = list(users.values()) # editing ends return JsonResponse({'users': competitionUsers}) else: competitionUsers = None return JsonResponse({'error': 'No competitions'})
def avatar_url(user, size=settings.AVATAR_DEFAULT_SIZE): avatar = get_primary_avatar(user, size=size) if avatar: return avatar.avatar_url(size) if settings.AVATAR_GRAVATAR_BACKUP: params = {'s': str(size)} if settings.AVATAR_GRAVATAR_DEFAULT: params['d'] = settings.AVATAR_GRAVATAR_DEFAULT if settings.AVATAR_GRAVATAR_FORCEDEFAULT: params['f'] = 'y' path = "%s/?%s" % (hashlib.md5(force_bytes(getattr(user, settings.AVATAR_GRAVATAR_FIELD))).hexdigest(), urlencode(params)) return urljoin(settings.AVATAR_GRAVATAR_BASE_URL, path) if settings.AVATAR_FACEBOOK_BACKUP: fb_id = get_facebook_id(user) if fb_id: return 'https://graph.facebook.com/{fb_id}/picture?type=square&width={size}&height={size}'.format( fb_id=fb_id, size=size ) return get_default_avatar_url()
def get_avatar_url(self, user, size): avatar = get_primary_avatar(user, size) if avatar: return avatar.avatar_url(size)
def to_representation(self, obj): avatar = get_primary_avatar(obj, 40) if avatar is None: return get_default_avatar_url() return avatar.get_absolute_url()
def get_user_avatar_url(user): avatar = get_primary_avatar(user, 80) if avatar: return {'url': avatar.avatar_url(80), 'uploaded': True} else: return {'url': get_default_avatar_url(), 'uploaded': False}
def autocomplete_usernames(request): if 'q' not in request.GET: return HttpResponse(simplejson.dumps([])) if request.user.is_anonymous: if 'token' not in request.GET: return HttpResponse(simplejson.dumps([])) try: Token.objects.get(key=request.GET.get('token')) except Token.DoesNotExist: return HttpResponse(simplejson.dumps([])) q = request.GET['q'] referer_header = request.META.get('HTTP_REFERER', '') from_forums = '/forum' in referer_header from_comments = re.match(r'%s\/?([a-zA-Z0-9]{6})\/.*' % settings.BASE_URL, referer_header) users = [] results = [] limit = 10 # Replace non-breaking space with regular space q = q.replace(chr(160), ' ') if from_forums: referer = request.META.get('HTTP_REFERER') if '?' in referer: slug = os.path.basename(os.path.normpath(referer.rsplit('/', 1)[0])) else: slug = os.path.basename(os.path.normpath(referer)) users = list(UserProfile.objects.filter( Q(user__posts__topic__slug=slug) & (Q(user__username__icontains=q) | Q(real_name__icontains=q)) ).distinct()[:limit]) elif from_comments: image_id = from_comments.group(1) image = ImageService.get_object(image_id, Image.objects_including_wip.all()) users = list(UserProfile.objects.filter( Q( Q(user__image=image) | Q( Q(user__comments__object_id=image.id) & Q(user__comments__deleted=False) ) ) & Q( Q(user__username__icontains=q) | Q(real_name__icontains=q) ) ).distinct()[:limit]) users = UtilsService.unique(users + list(UserProfile.objects.filter( Q(user__username__icontains=q) | Q(real_name__icontains=q) ).distinct()[:limit]))[:limit] for user in users: avatar = get_primary_avatar(user, 40) if avatar is None: avatar_url = get_default_avatar_url() else: avatar_url = avatar.get_absolute_url() results.append({ 'id': str(user.id), 'username': user.user.username, 'realName': user.user.userprofile.real_name, 'displayName': user.user.userprofile.real_name if user.user.userprofile.real_name else user.user.username, 'avatar': avatar_url, }) return HttpResponse(simplejson.dumps(results))
def test_non_existing_user(self): a = get_primary_avatar("nonexistinguser") self.assertEqual(a, None)
def testAutomaticThumbnailCreationRGBA(self): upload_helper(self, "django.png") avatar = get_primary_avatar(self.user) image = Image.open(avatar.avatar.storage.open(avatar.avatar_name(settings.AVATAR_DEFAULT_SIZE), 'rb')) self.assertEqual(image.mode, 'RGBA')
def test_automatic_thumbnail_creation_CMYK(self): upload_helper(self, "django_pony_cmyk.jpg") avatar = get_primary_avatar(self.user) image = Image.open(avatar.avatar.storage.open(avatar.avatar_name(settings.AVATAR_DEFAULT_SIZE), 'rb')) self.assertEqual(image.mode, 'RGB')
def overallUserScoreboard(request): allsubmissions = Submissions.objects.all().order_by( '-score', 'submitted_at') allsubmissions = getDistinctModelFields(allsubmissions, ['user', 'question']) users = [] for submission in allsubmissions: score = 0 isSuccess = submission.passed gotSubscore = submission.gotSubscore if isSuccess: score = submission.question.points if gotSubscore: score = score + submission.question.subscore username = submission.user.username if not any(d.get('username', None) == username for d in users): # user avatar thisUserObj = userObjFromId(submission.user.id) if has_avatar(thisUserObj) == True: userAvatarUrl = get_primary_avatar( thisUserObj).get_absolute_url() elif thisUserObj.profile.profileImgUrl != '': userAvatarUrl = thisUserObj.profile.profileImgUrl else: userAvatarUrl = '' users.append({ 'username': username, 'score': score, 'profileImgUrl': userAvatarUrl, 'first_name': submission.user.first_name, 'last_name': submission.user.last_name, }) else: for index, item in enumerate(users): if item['username'] == username: score = score + item['score'] # user avatar thisUserObj = userObjFromId(submission.user.id) if has_avatar(thisUserObj) == True: userAvatarUrl = get_primary_avatar( thisUserObj).get_absolute_url() elif thisUserObj.profile.profileImgUrl != '': userAvatarUrl = thisUserObj.profile.profileImgUrl else: userAvatarUrl = '' users[index] = { 'username': username, 'score': score, 'profileImgUrl': userAvatarUrl, 'first_name': submission.user.first_name, 'last_name': submission.user.last_name, } if len(users) > 0: users = sorted(users, key=itemgetter('score'), reverse=True) return JsonResponse({'users': users}) else: return JsonResponse({'error': 'No submissions'})
def get_avatar(self, user): avatar = get_primary_avatar(user) return avatar.avatar_url(80) if avatar else None