コード例 #1
0
 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("&", "&amp;"),
         result["message_html"])
コード例 #2
0
ファイル: RecipeView.py プロジェクト: FloArt/pywebcooking
    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)
コード例 #3
0
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()
コード例 #4
0
ファイル: models.py プロジェクト: travisjwarren/modus
    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)
コード例 #5
0
ファイル: api.py プロジェクト: superalex/Green-Mine
    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)
コード例 #6
0
ファイル: models.py プロジェクト: fpytloun/django-xmpp
    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()
コード例 #7
0
 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("&", "&amp;"),
         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>")
コード例 #8
0
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)
コード例 #9
0
ファイル: RecipeView.py プロジェクト: FloArt/pywebcooking
 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
コード例 #10
0
ファイル: vosae_user.py プロジェクト: peicheng/vosae-app
 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
コード例 #11
0
    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!"
コード例 #12
0
ファイル: models.py プロジェクト: yagosvl/associados
 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
コード例 #13
0
 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()
コード例 #14
0
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 ''
コード例 #15
0
ファイル: views.py プロジェクト: martinjohnlopez8/board
 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',
     })
コード例 #16
0
ファイル: gravatar.py プロジェクト: DjGroup/exprolife
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 ''
コード例 #17
0
 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
コード例 #18
0
ファイル: api1_views.py プロジェクト: pizzapanther/TwoSpaces
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)
コード例 #19
0
ファイル: api1_views.py プロジェクト: mark-adams/TwoSpaces
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)
コード例 #20
0
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
コード例 #21
0
ファイル: entity.py プロジェクト: tcpr1/vosae-app
 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
コード例 #22
0
ファイル: userprofile.py プロジェクト: fergalmoran/dss.api
    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()
コード例 #23
0
    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)
コード例 #24
0
ファイル: userprofile.py プロジェクト: fergalmoran/dss.api
    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()
コード例 #25
0
ファイル: userprofile.py プロジェクト: fergalmoran/dss
 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
コード例 #26
0
ファイル: gravatar.py プロジェクト: DjGroup/exprolife
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)
コード例 #27
0
 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
コード例 #28
0
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)
コード例 #29
0
 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
コード例 #30
0
 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
コード例 #31
0
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
    })
コード例 #32
0
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
コード例 #33
0
 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("&", "&amp;"))
     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"))
コード例 #34
0
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
コード例 #35
0
ファイル: models.py プロジェクト: jzvelc/djangotest
 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
コード例 #36
0
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
コード例 #37
0
ファイル: views.py プロジェクト: ging/horizon
 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
コード例 #38
0
 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("&", "&amp;"))
     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"))
コード例 #39
0
ファイル: spa_extras.py プロジェクト: fergalmoran/dss
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"
コード例 #40
0
 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("&", "&amp;"),
         result["message_html"])
コード例 #41
0
 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
コード例 #42
0
    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
コード例 #43
0
ファイル: views.py プロジェクト: yoann01/ava-capture
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)
コード例 #44
0
ファイル: views.py プロジェクト: ging/horizon
    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
コード例 #45
0
ファイル: test_message.py プロジェクト: aisworld/hyperkitty
 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("&", "&amp;"),
         result["message_html"])
コード例 #46
0
ファイル: test_message.py プロジェクト: aisworld/hyperkitty
 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("&", "&amp;"),
         result["message_html"])
コード例 #47
0
ファイル: models.py プロジェクト: predatell/django-xmpp
    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()
コード例 #48
0
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)
コード例 #49
0
ファイル: processors.py プロジェクト: cytadela8/oioioi
 def generator():
     return six.text_type(get_gravatar_url(request.user.email,
                                           size=25)) or ''
コード例 #50
0
 def get_gravatar_url(self, obj):
     return get_gravatar_url(obj.email, size=50)
コード例 #51
0
 def get_avatar(self):
     email = self.user.email
     return get_gravatar_url(email, size=150)
コード例 #52
0
 def get_photo(self, obj):
     return get_gravatar_url(obj.email)
コード例 #53
0
ファイル: views.py プロジェクト: yoann01/ava-capture
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)
コード例 #54
0
ファイル: models.py プロジェクト: pizzapanther/TwoSpaces
    def image(self):
        if self.avatar:
            return self.avatar.url

        return get_gravatar_url(self.email, size=256)
コード例 #55
0
 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()
コード例 #56
0
ファイル: serializers.py プロジェクト: tpterovtt/ava-capture
 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