def test_reply_different_sender(self): self.user.first_name = "Django" self.user.last_name = "User" self.user.save() mm_user = Mock() self.mailman_client.get_user.side_effect = lambda name: mm_user mm_user.user_id = uuid.uuid1().int mm_user.addresses = ["*****@*****.**", "*****@*****.**"] mm_user.subscriptions = [] mlist = MailingList.objects.get(name="*****@*****.**") url = reverse('hk_message_reply', args=("*****@*****.**", get_message_id_hash("msg"))) with patch("hyperkitty.views.message.post_to_list") as posting_fn: response = self.client.post(url, { "message": "dummy reply content", "sender": "*****@*****.**", }) self.assertEqual(response.status_code, 200) self.assertEqual(posting_fn.call_count, 1) self.assertEqual(posting_fn.call_args[0][1:], (mlist, 'Re: Dummy Subject', 'dummy reply content', {'From': '*****@*****.**', 'In-Reply-To': '<msg>', 'References': '<msg>'})) result = json.loads(response.content) #print(result["message_html"]) self.assertIn("Django User", result["message_html"]) self.assertIn("dummy reply content", result["message_html"]) self.assertIn( get_gravatar_url("*****@*****.**", 120).replace("&", "&"), result["message_html"])
def get(self, request, slug): if not self.request.user.is_authenticated: return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) recipe = Recipe.objects.get(slug=slug) r_cats = [] for cat in recipe.category.all(): r_cats.append(cat.url) form = RecipeForm({"title": recipe, "slug": recipe.slug, "categories": [cat.id for cat in recipe.category.all()], "tps_prep_hr": int(recipe.tps_prep / 60), "tps_prep_min": recipe.tps_prep % 60, "tps_break_j": int(recipe.tps_rep / 1440), "tps_break_hr": int((recipe.tps_rep % 1440) / 60), "tps_break_min": recipe.tps_rep % 60, "tps_cook_hr": int(recipe.tps_cuis / 60), "tps_cook_min": recipe.tps_cuis % 60, "description": recipe.description, "pub_date": recipe.pub_date.strftime("%d/%m/%y %H:%M"), "status": int(recipe.published)}) context = { "recipe": recipe, "categories": self.categories(), "staff": request.user.is_staff, "user_name": request.user.first_name + " " + request.user.last_name, "avatar": get_gravatar_url(request.user.email, size=160), "page": "recipe", "lang": settings.LANGUAGE_CODE, "title": _("Edit") + " \"" + recipe.title + "\" | " + settings.SITE_NAME, "form": form } return render(request, 'panel/recipe.html', context)
def create_user_profile(sender, instance, created, **kwargs): """Create the UserProfile when a new User is saved""" if created: profile = UserProfile() profile.user = instance profile.gravatar_img = get_gravatar_url(profile.user.email) profile.save()
def profile_image_url(self): fb_uid = SocialAccount.objects.filter(user_id=self.user.id, provider='facebook') if len(fb_uid): return "http://graph.facebook.com/{}/picture?width=40&height=40".format(fb_uid[0].uid) return get_gravatar_url(self.user.email, 80)
def get(self, request): if "term" not in request.GET: return self.render_to_ok({'list':[]}) term = request.GET['term'] users = models.User.objects.filter( Q(username__istartswith=term) | Q(first_name__istartswith=term) | Q(last_name__istartswith=term) ) users_list = [] for user in users: users_list_item = {} users_list_item['id'] = user.id full_name = user.get_full_name() if full_name: users_list_item['label'] = full_name users_list_item['value'] = full_name else: users_list_item['label'] = user.username users_list_item['value'] = user.username if user.get_profile().photo: users_list_item['gravatar'] = user.get_profile().photo.url else: users_list_item['gravatar'] = get_gravatar_url(user.email, size=30) users_list.append(users_list_item) context = {'list': users_list} return self.render_to_ok(context)
def update_vcard(self, force=False): """ Update vcard if not updated within `XMPP_UPDATE_VCARD_HOURS` (default False) or if XMPP_UPDATE_VCARD is not False """ if not getattr(settings, 'XMPP_UPDATE_VCARD', True): # Never ever update vCard return False update_delta = getattr(settings, 'XMPP_UPDATE_VCARD_HOURS', False) if not update_delta: return False if not force: if self.updated and self.updated > timezone.now()-datetime.timedelta(hours=update_delta): return False lg.info("Updating vCard for %s" % self.jid) try: con = self.get_connection() con.set_vcard(self.user.get_full_name() or self.user.username) if gravatar_available and has_gravatar(self.user.email): try: avatar_data = urllib.urlopen(get_gravatar_url(self.user.email)).read() con.set_avatar(avatar_data, mime_type='image/jpeg') except Exception as e: lg.exception("Failed to set XMPP avatar for %s" % self.jid, e) con.disconnect() except Exception as e: lg.exception("Failed to update vCard for %s" % self.jid, e) self.updated = timezone.now() self.save()
def test_reply(self): self.user.first_name = "Django" self.user.last_name = "User" self.user.save() url = reverse('hk_message_reply', args=("*****@*****.**", get_message_id_hash("msg"))) with patch("hyperkitty.lib.posting.mailman.subscribe") as sub_fn: response = self.client.post(url, {"message": "dummy reply content"}) self.assertEqual(response.status_code, 200) self.assertTrue(sub_fn.called) result = json.loads(response.content) #print(result["message_html"]) self.assertIn("Django User", result["message_html"]) self.assertIn("dummy reply content", result["message_html"]) self.assertIn( get_gravatar_url("*****@*****.**", 120).replace("&", "&"), result["message_html"]) self.assertEqual(len(mail.outbox), 1) #print(mail.outbox[0].message()) self.assertEqual(mail.outbox[0].recipients(), ["*****@*****.**"]) self.assertEqual(mail.outbox[0].from_email, '"Django User" <*****@*****.**>') self.assertEqual(mail.outbox[0].subject, 'Re: Dummy Subject') self.assertEqual(mail.outbox[0].body, "dummy reply content") self.assertEqual(mail.outbox[0].message().get("references"), "<msg>") self.assertEqual(mail.outbox[0].message().get("in-reply-to"), "<msg>")
def person(request, pk=None, search=None, order=None): if request.method == 'GET' and pk==None: """ Returns a JSON response with a listing of person objects """ search = request.query_params.get('search') order = request.query_params.get('order') if (search==None): search = ''; if (order == None or order == ''): order = 'name' people = Person.objects.filter(name__istartswith=search).order_by(order).all() paginator = PageNumberPagination() # From the docs: # The paginate_queryset method is passed the initial queryset # and should return an iterable object that contains only the # data in the requested page. result_page = paginator.paginate_queryset(people, request) # Now we just have to serialize the data serializer = PersonSerializer(result_page, many=True) # From the docs: # The get_paginated_response method is passed the serialized page # data and should return a Response instance. return paginator.get_paginated_response(serializer.data) elif request.method == 'POST': serializer = PersonSerializer(data=request.data) if serializer.is_valid(): serializer.save(photo = get_gravatar_url(serializer.data['email'], size=150)) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) try: person = Person.objects.get(pk=pk) except Person.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = PersonSerializer(person) return Response(serializer.data) elif request.method == 'PUT': serializer = PersonSerializer(person, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serilizer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': person.delete() serializer = PersonSerializer(person) return Response(serializer.data)
def load_data(self): categories = GenericView.categories() config = GenericView.config dat = {"categories": categories, "config": config, "user": self.user if self.user.is_authenticated else None} if self.user.is_authenticated: dat["avatar"] = get_gravatar_url(self.user.email, size=160) dat["user_name"] = self.user.first_name return dat
def photo_uri(self): """ Return the photo URI (if available). """ if self.settings.gravatar_email: return get_gravatar_url(self.settings.gravatar_email) else: return None
def handle(self, *args, **options): for user_det in UserProfile.objects.all(): if has_gravatar(user_det.user.email): user_det.gravatar_img = get_gravatar_url(user_det.user.email, size=200) else: user_det.gravatar_img = "http://dummyimage.com/200x200/fff/000.png&text=" + str(user_det.user.username[0:2]) user_det.save() print "Updated gravatars!"
def update_thumbnail(self): try: g = self.github if g: self.thumb_image = g["avatar_url"] else: self.thumb_image = get_gravatar_url(self.user.email, size=150) self.save() except Exception, e: raise e
def handle(self, *args, **options): for user in Account.objects.all(): if has_gravatar(user.email): user.gravatar_url = get_gravatar_url(user.email, size=25) user.has_gravatar = True else: user.gravatar_url = user.first_name[:1].upper( ) + user.last_name[:1].upper() user.has_gravatar = False user.save()
def gravatar_url(user_or_email, size=GRAVATAR_DEFAULT_SIZE): """ Builds a gravatar url from an user or email """ if hasattr(user_or_email, 'email'): email = user_or_email.email else: email = user_or_email try: return escape(get_gravatar_url(email=email, size=size)) except: return ''
def post(self, request, *args, **kwargs): email = request.POST.get('email', None) if email: gravatar_exists = has_gravatar(email) if gravatar_exists: return Response({ 'url': get_gravatar_url(email), }) return Response({ 'message': 'Gravatar does not exist', })
def get_image_small(self): """ Returns small image for meal """ if self.icon: return self.icon.url else: from django_gravatar.helpers import get_gravatar_url # , has_gravatar url = get_gravatar_url(self.host.email, size=50) #gravatar_exists = has_gravatar('*****@*****.**') return url
def profile_image(request): if request.JSON(): if request.JSON().get('gravatar', ''): request.user.avatar = None request.user.save() images = {'gravatar': get_gravatar_url(request.user.email, size=256)} if request.user.avatar: images['image'] = request.user.avatar.url return Response(images, status=200)
def to_json(message): data = { 'id': message.id, 'message': message.message, 'timestamp': time.mktime(message.timestamp.timetuple()), } if message.sender: data.update({ 'name': message.sender.first_name, 'username': message.sender.username, 'avatar': get_gravatar_url(message.sender.email), 'id': message.sender.id, }) else: data.update({ 'name': None, 'username': None, 'avatar': get_gravatar_url(''), 'id': None, }) return data
def photo_uri(self): """Return the photo URI or the default *empty* picture.""" if self.photo_source: if self.photo_source == "LOCAL": try: return self.photo.stream_link except: return None if self.photo_source == "GRAVATAR": return get_gravatar_url(self.gravatar_mail) else: return None
def get_avatar_image(self): avatar_type = self.avatar_type if avatar_type == 'gravatar': gravatar_exists = has_gravatar(self.email) if gravatar_exists: return get_gravatar_url(self.email) else: if os.path.exists(self.avatar_image.file.name): return self.avatar_image else: return self.get_default_avatar_image() return UserProfile.get_default_avatar_image()
def get(self, request, **kwargs): queryString = request.GET.get('q') if not queryString: raise PermissionDenied() out = [] users = User.objects.filter(username__icontains=queryString).order_by('username')[:10] for user in users: out.append({ 'value': user.username, 'avatar_url': get_gravatar_url(user.email, size=25) }) return JsonResponse(out, safe=False)
def get_avatar_image(self): avatar_type = self.avatar_type if avatar_type == 'gravatar': gravatar_exists = has_gravatar(self.email) if gravatar_exists: return get_gravatar_url(self.email) elif avatar_type == 'social' or avatar_type == '': try: social_account = SocialAccount.objects.filter(user=self.user)[0] if social_account: provider = social_account.get_provider_account() return provider.get_avatar_url() except Exception, ex: pass
def gravatar(user_or_email, size=GRAVATAR_DEFAULT_SIZE, alt_text='', css_class='gravatar'): """ Builds an gravatar <img> tag from an user or email """ if hasattr(user_or_email, 'email'): email = user_or_email.email else: email = user_or_email try: url = escape(get_gravatar_url(email=email, size=size)) except: return '' return '<img class="{css_class}" src="{src}" width="{width}" height="{height}" alt="{alt}" />'.format(\ css_class=css_class, src=url, width=size, height=size, alt=alt_text)
def last_modification(self): """ returns the avatar last_modification """ try: if has_gravatar(self.user.email): info = urlopen(get_gravatar_url(email=self.user.email, size=self.size)).info() return datetime.strptime(info['Last-Modified'], "%a, %d %b %Y %H:%M:%S GMT") except NameError: pass if AVATAR_STORAGE_BACKEND.exists(self.path()): try: return AVATAR_STORAGE_BACKEND.modified_time(self.path()) except AttributeError: return timezone.now() else: return None
def get_avatar_url(self): """ returns the url of the avatar on the storage backed """ try: if has_gravatar(self.user.email): self.css_class = "gravatar" self.url = escape(get_gravatar_url(email=self.user.email, size=self.size)) return self.url except NameError: pass self.css_class = "initial-avatar" if AVATAR_STORAGE_BACKEND.exists(self.path()): self.url = AVATAR_STORAGE_BACKEND.url(self.path()) else: self.url = self.genavatar() return self.url
def add_public_registrations_table(sender, **kwargs): if not sender.settings.get('public_registrations_items') and not ( sender.settings.get('public_registrations_questions') and sender.settings.get('public_registrations_show_item_name') and sender.settings.get('public_registrations_show_attendee_name')): return "" public_questions = sender.questions.filter( pk__in=sender.settings.get('public_registrations_questions')) headers = ([_("Product")] if sender.settings.get('public_registrations_show_item_name') else []) + ([_("Name")] if sender.settings.get( 'public_registrations_show_attendee_name') else []) + [q.question for q in public_questions] order_positions = OrderPosition.objects.filter( order__event=sender, item__pk__in=sender.settings.get('public_registrations_items'), order__testmode=(sender.testmode)).exclude( order__status=Order.STATUS_CANCELED).order_by('order__datetime') public_order_positions = [ op for op in order_positions if op.meta_info_data.get('question_form_data', {}).get( 'public_registrations_public_registration') ] answers = QuestionAnswer.objects.filter( orderposition__in=public_order_positions, question__in=public_questions) public_answers = {(a.orderposition_id, a.question_id): a for a in answers} public_registrations = [{ 'gr_url': get_gravatar_url(pop.attendee_email or pop.order.code, size=24, default="wavatar"), 'fields': ([pop.item.name] if sender.settings.get('public_registrations_show_item_name') else []) + ([pop.attendee_name_cached] if sender.settings.get( 'public_registrations_show_attendee_name') else []) + [ public_answers[(pop.pk, pq.pk)].answer if public_answers.get( (pop.pk, pq.pk)) else '' for pq in public_questions ] } for pop in public_order_positions] template = get_template('pretix_public_registrations/front_page.html') return template.render({ 'headers': headers, 'public_registrations': public_registrations })
def get_avatar(obj, avatar_type, default_avatar): """Gets the object avatar or a default one.""" if type(obj) == dict: use_gravatar = obj.get('use_gravatar', None) email = obj.get('name', None) avatar = obj.get(avatar_type, None) else: use_gravatar = getattr(obj, 'use_gravatar', None) email = getattr(obj, 'name', None) avatar = getattr(obj, avatar_type, None) if use_gravatar and has_gravatar(email): return get_gravatar_url(email, size=AVATAR_SIZE[avatar_type]) if avatar and avatar != '': return settings.MEDIA_URL + avatar else: return settings.STATIC_URL + default_avatar
def test_message_page(self): url = reverse('hk_message_index', args=("*****@*****.**", get_message_id_hash("msg"))) with self.settings(USE_L10N=False, DATETIME_FORMAT='Y-m-d H:i:s', TIME_FORMAT="H:i:s"): with timezone.override(timezone.utc): response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertContains(response, "Dummy message") self.assertContains(response, "Dummy Sender", count=1) self.assertContains(response, "Dummy Subject", count=3) self.assertNotContains(response, "*****@*****.**") self.assertContains(response, get_gravatar_url("*****@*****.**", 120).replace("&", "&")) self.assertContains(response, "*****@*****.**") self.assertContains(response, url) sender_time = '<span title="Sender\'s time: 2015-02-02 13:00:00">10:00:00</span>' self.assertIn(sender_time, response.content.decode("utf-8"))
def user_link(user, size=20, region=None, show_username=True, ip=None): if user and user.is_authenticated(): # Get twice as big for high-DPI / retina gravatar_url = get_gravatar_url(user.userprofile.gravatar_email, size=(size*2)) user_path = user.get_absolute_url() link = """<a href="%(user_path)s" class="user_link" title="%(username)s"><img class="gravatar" src="%(gravatar_url)s" width="%(width)s" height="%(height)s" /><span>%(name)s</span></a>""" % { 'user_path': user_path, 'gravatar_url': gravatar_url, 'name': (" %s" % user.username) if show_username else "", 'username': user.username, 'width': size, 'height': size, } elif ip: link = ip else: link = _("Unknown") return link
def get_avatar(self, size=None): sizes = { 'xl': 200, 'lg': 160, 'md': 80, 'sm': 40, 'xs': 20 } if size and type(size) is str: size = sizes.get(size, 80) if not size: size = sizes.get('sm') if self.avatar: url = get_thumbnail(self.avatar, '%dx%d' % (size, size), crop='center', quality=99).url else: url = get_gravatar_url(self.email, size=size) return url
def user_link(user, size=20, region=None, show_username=True, ip=None): if user and user.is_authenticated(): # Get twice as big for high-DPI / retina gravatar_url = get_gravatar_url(user.userprofile.gravatar_email, size=(size * 2)) user_path = user.get_absolute_url() link = """<a href="%(user_path)s" class="user_link" title="%(username)s"><img class="gravatar" src="%(gravatar_url)s" width="%(width)s" height="%(height)s" /><span>%(name)s</span></a>""" % { 'user_path': user_path, 'gravatar_url': gravatar_url, 'name': (" %s" % user.username) if show_username else "", 'username': user.username, 'width': size, 'height': size, } elif ip: link = ip else: link = _("Unknown") return link
def get_context_data(self, **kwargs): context = super(DetailUserView, self).get_context_data(**kwargs) user_id = self.kwargs['user_id'] user = fiware_api.keystone.user_get(self.request, user_id) user_email = getattr(user, 'name', None) context['user'] = user if getattr(user, 'use_gravatar', None) and has_gravatar(user_email): image = get_gravatar_url(user_email, size=idm_utils.AVATAR_SIZE['img_original']) elif hasattr(user, 'img_original') and getattr(user, 'img_original') != '': image = getattr(user, 'img_original') image = settings.MEDIA_URL + image else: image = settings.STATIC_URL + 'dashboard/img/logos/original/user.png' context['image'] = image context['index_app'] = self.request.GET.get('index_app', 0) context['index_org'] = self.request.GET.get('index_org', 0) if self._can_edit(): context['edit'] = True return context
def test_message_page(self): url = reverse('hk_message_index', args=("*****@*****.**", get_message_id_hash("msg"))) with self.settings(USE_L10N=False, DATETIME_FORMAT='Y-m-d H:i:s', TIME_FORMAT="H:i:s"): with timezone.override(timezone.utc): response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertContains(response, "Dummy message") self.assertContains(response, "Dummy Sender", count=1) self.assertContains(response, "Dummy Subject", count=3) self.assertNotContains(response, "*****@*****.**") self.assertContains( response, get_gravatar_url("*****@*****.**", 120).replace("&", "&")) self.assertContains(response, "*****@*****.**") self.assertContains(response, url) sender_time = '<span title="Sender\'s time: 2015-02-02 13:00:00">10:00:00</span>' self.assertIn(sender_time, response.content.decode("utf-8"))
def avatar_image(user, size=150): profile = user.get_profile() avatar_type = profile.avatar_type if avatar_type == 'gravatar': gravatar_exists = has_gravatar(user.email) if gravatar_exists: return get_gravatar_url(user.email, size) elif avatar_type == 'social' or avatar_type == '': try: social_account = SocialAccount.objects.filter(user = user)[0] if social_account: provider = social_account.get_provider_account() return provider.get_avatar_url() except: return urlparse.urljoin(settings.STATIC_URL, "img/default-avatar-32.png") elif avatar_type == 'custom': return profile.avatar_image.url return settings.STATIC_URL + "/images/default-avatar-32.png"
def test_reply(self): self.user.first_name = "Django" self.user.last_name = "User" self.user.save() mlist = MailingList.objects.get(name="*****@*****.**") url = reverse('hk_message_reply', args=("*****@*****.**", get_message_id_hash("msg"))) with patch("hyperkitty.views.message.post_to_list") as posting_fn: response = self.client.post(url, {"message": "dummy reply content"}) self.assertEqual(response.status_code, 200) self.assertEqual(posting_fn.call_count, 1) self.assertEqual(posting_fn.call_args[0][1:], (mlist, 'Re: Dummy Subject', 'dummy reply content', {'References': '<msg>', 'In-Reply-To': '<msg>'})) result = json.loads(response.content) #print(result["message_html"]) self.assertIn("Django User", result["message_html"]) self.assertIn("dummy reply content", result["message_html"]) self.assertIn( get_gravatar_url("*****@*****.**", 120).replace("&", "&"), result["message_html"])
def get_context_data(self, **kwargs): context = super(DetailUserView, self).get_context_data(**kwargs) user_id = self.kwargs['user_id'] user = fiware_api.keystone.user_get(self.request, user_id) user_email = getattr(user, 'name', None) context['user'] = user if getattr(user, 'use_gravatar', None) and has_gravatar(user_email): image = get_gravatar_url( user_email, size=idm_utils.AVATAR_SIZE['img_original']) elif hasattr(user, 'img_original') and getattr(user, 'img_original') != '': image = getattr(user, 'img_original') image = settings.MEDIA_URL + image else: image = settings.STATIC_URL + 'dashboard/img/logos/original/user.png' context['image'] = image context['index_app'] = self.request.GET.get('index_app', 0) context['index_org'] = self.request.GET.get('index_org', 0) if self._can_edit(): context['edit'] = True return context
def get_avatar_url(self): """ returns the url of the avatar on the storage backed """ try: if has_gravatar(self.user.email): self.css_class = "gravatar" self.url = escape(get_gravatar_url(email=self.user.email, size=self.size)) return self.url except NameError: pass self.css_class = "initial-avatar" if AVATAR_STORAGE_BACKEND.exists(self.path()): self.url = AVATAR_STORAGE_BACKEND.url(self.path()) else: self.url = self.genavatar() if AVATAR_HIGH_RESOLUTION: self.high_res_url = AVATAR_STORAGE_BACKEND.url(self.path(high_res=True)) return self.url, self.high_res_url return self.url
def all_users(request): queryset = User.objects.all().order_by('-last_login') serializer = UserSerializer(queryset, many=True, context={'request': request}) data = serializer.data for u in data: u['gravatar'] = get_gravatar_url(u['email'], size=150) u['lastMessage'] = naturaltime(u['last_login']) u['messages'] = [] # [{ # // text: 'Hey! What\'s up?' # // }, { # // text: 'Are you there?' # // }, { # // text: 'Let me know when you come back.' # // }, { # // text: 'I am here!', # // fromMe: true # // }] return JSONResponse(data)
def get_context_data(self, **kwargs): context = super(BaseUsersMultiFormView, self).get_context_data(**kwargs) user_id = self.kwargs['user_id'] context['user_id'] = user_id if getattr(self.object, 'use_gravatar', None): context['using_gravatar'] = True if has_gravatar(getattr(self.object, 'name', None)): gravatar_image = get_gravatar_url(getattr(self.object, 'name', None), size=idm_utils.AVATAR_SIZE['img_original']) context['gravatar_image'] = gravatar_image if hasattr(self.object, 'img_original') and getattr(self.object, 'img_original') != '': uploaded_image = getattr(self.object, 'img_original') uploaded_image = settings.MEDIA_URL + uploaded_image else: uploaded_image = (settings.STATIC_URL + 'dashboard/img/logos/original/user.png') context['no_uploaded_image'] = True context['uploaded_image'] = uploaded_image return context
def test_reply_different_sender(self): self.user.first_name = "Django" self.user.last_name = "User" self.user.save() EmailAddress.objects.create(user=self.user, verified=True, email="*****@*****.**") EmailAddress.objects.create(user=self.user, verified=True, email="*****@*****.**") mm_user = Mock() self.mailman_client.get_user.side_effect = lambda name: mm_user mm_user.user_id = uuid.uuid1().int mm_user.subscriptions = [] mlist = MailingList.objects.get(name="*****@*****.**") url = reverse('hk_message_reply', args=("*****@*****.**", get_message_id_hash("msg"))) with patch("hyperkitty.views.message.post_to_list") as posting_fn: response = self.client.post( url, { "message": "dummy reply content", "sender": "*****@*****.**", }) self.assertEqual(response.status_code, 200) self.assertEqual(posting_fn.call_count, 1) self.assertEqual( posting_fn.call_args[0][1:], (mlist, 'Re: Dummy Subject', 'dummy reply content', { 'From': '*****@*****.**', 'In-Reply-To': '<msg>', 'References': '<msg>' })) result = json.loads(response.content) self.assertIn("Django User", result["message_html"]) self.assertIn("dummy reply content", result["message_html"]) self.assertIn( get_gravatar_url("*****@*****.**", 120).replace("&", "&"), result["message_html"])
def test_reply(self): self.user.first_name = "Django" self.user.last_name = "User" self.user.save() mlist = MailingList.objects.get(name="*****@*****.**") url = reverse('hk_message_reply', args=("*****@*****.**", get_message_id_hash("msg"))) with patch("hyperkitty.views.message.post_to_list") as posting_fn: response = self.client.post(url, {"message": "dummy reply content"}) self.assertEqual(response.status_code, 200) self.assertEqual(posting_fn.call_count, 1) self.assertEqual( posting_fn.call_args[0][1:], (mlist, 'Re: Dummy Subject', 'dummy reply content', { 'References': '<msg>', 'In-Reply-To': '<msg>' })) result = json.loads(response.content) self.assertIn("Django User", result["message_html"]) self.assertIn("dummy reply content", result["message_html"]) self.assertIn( get_gravatar_url("*****@*****.**", 120).replace("&", "&"), result["message_html"])
def update_vcard(self, force=False): """ Update vcard if not updated within `XMPP_UPDATE_VCARD_HOURS` (default False) or if XMPP_UPDATE_VCARD is not False """ if not getattr(settings, 'XMPP_UPDATE_VCARD', True): # Never ever update vCard return False update_delta = getattr(settings, 'XMPP_UPDATE_VCARD_HOURS', False) if not update_delta: return False if not force: if self.updated and self.updated > timezone.now( ) - datetime.timedelta(hours=update_delta): return False lg.info("Updating vCard for %s" % self.jid) try: con = self.get_connection() con.set_vcard(self.user.get_full_name() or self.user.username) if gravatar_available and has_gravatar(self.user.email): try: avatar_data = urllib.urlopen( get_gravatar_url(self.user.email)).read() con.set_avatar(avatar_data, mime_type='image/jpeg') except Exception as e: lg.exception("Failed to set XMPP avatar for %s" % self.jid, e) con.disconnect() except Exception as e: lg.exception("Failed to update vCard for %s" % self.jid, e) self.updated = timezone.now() self.save()
def save_gravatar_url(sender, instance, *args, **kwargs): # if has_gravatar(instance.user.email): if not instance.gravatar_url: # FIXME avatar is not will be refreshed instance.gravatar_url = get_gravatar_url(instance.user.email, default='identicon', size=150)
def generator(): return six.text_type(get_gravatar_url(request.user.email, size=25)) or ''
def get_gravatar_url(self, obj): return get_gravatar_url(obj.email, size=50)
def get_avatar(self): email = self.user.email return get_gravatar_url(email, size=150)
def get_photo(self, obj): return get_gravatar_url(obj.email)
def current_user(request): serializer = UserSerializer(request.user, context={'request': request}) data = serializer.data data['gravatar'] = get_gravatar_url(data['email'], size=150) return JSONResponse(data)
def image(self): if self.avatar: return self.avatar.url return get_gravatar_url(self.email, size=256)
def handle(self, *args, **options): for user in User.objects.all(): # can't bulk update profile, created = Profile.objects.get_or_create(user=user) # if has_gravatar(profile.user.email): profile.gravatar_url = get_gravatar_url(profile.user.email) profile.save()
def get_gravatar(self, obj): user = User.objects.all().filter(username=obj.created_by) if user: return get_gravatar_url(user[0].email, size=50) return None