Esempio n. 1
0
def get_avatar_url(user, size=50):
    """Get a url pointing to user's avatar.

    The libravatar network is used for avatars. Return cached value if
    its last update was less than 24 hours before. Optional argument
    size can be provided to set the avatar size.

    """
    if not user:
        return None

    default_img_url = reduce(
        lambda u, x: urlparse.urljoin(u, x), [settings.SITE_URL, settings.STATIC_URL, "base/img/remo/remo_avatar.png"]
    )

    user_avatar, created = UserAvatar.objects.get_or_create(user=user)
    now = timezone.now()

    if (user_avatar.last_update < now - timedelta(days=7)) or created:
        user_avatar.avatar_url = libravatar_url(email=user.email, https=True)
        user_avatar.save()

    avatar_url = urlparams(user_avatar.avatar_url, default=default_img_url)
    if size != -1:
        avatar_url = urlparams(avatar_url, size=size)

    return avatar_url
Esempio n. 2
0
    def _avatar_function(email, size):
        absolute_default = 'https://fedoraproject.org/static/images/' + \
            'fedora_infinity_140x140.png'

        query = {
            's': size,
            'd': absolute_default,
        }

        if size == 'responsive':
            # Make it big so we can downscale it as we please
            query['s'] = 312

        query = urllib.urlencode(query)

        # Use md5 for emails, and sha256 for openids.
        # We're really using openids, so...
        #hash = md5(email).hexdigest()
        hash = sha256(email).hexdigest()

        # TODO This next line is temporary and can be removed.  We do
        # libravatar ourselves here by hand to avoid pyDNS issues on epel6.
        # Once those are resolved we can use pylibravatar again.
        return "http://cdn.libravatar.org/avatar/%s?%s" % (hash, query)

        gravatar_url = "http://www.gravatar.com/avatar/%s?%s" % (hash, query)

        if libravatar:
            return libravatar.libravatar_url(
                email=email,
                size=size,
                default=gravatar_url,
            )
        else:
            return gravatar_url
Esempio n. 3
0
def singleday(year, month, day):
    d = date(year, month, day)
    dateformatted = d.strftime('%b %d %Y');
    dayname = d.weekday()
    mboxlist = mbox(d, dayname)

    yesterday = d - timedelta(1)
    yesterday = yesterday.strftime("%Y/%m/%d")
    tomorrow = d + timedelta(1)
    tomorrow = tomorrow.strftime("%Y/%m/%d")
    d = d.strftime("%A, %B %d, %Y")

    if mboxlist == False:
        return '<table><tr><th><h1>This date does not appear to be in the mail archive. It either pre-dates it, or has not happened yet</th></tr></h1> '

    v = []
    a = v.append
    a('<table class="singleday">')
    a('<tr><th colspan="2"><a class="nounder" href="/%s"><</a>&nbsp;%s&nbsp;<a class="nounder" href="/%s">></a></th></tr>' % (yesterday, d, tomorrow))

    for mboxmail in mboxlist:
        avatar_url = libravatar_url(mboxmail['From'])
        a('<tr><td class="headers"><p class="subject">%s</p><p>%s</p><img src="%s"><p>%s</p></td><td class="what">%s</td></tr>' % (mboxmail['Subject'], mboxmail['From'], avatar_url, mboxmail['Date'], mboxmail['Body']))

    a('</table>')

    return '\n'.join(v)
Esempio n. 4
0
def avatar_for_email(email, size=80):
    """
    Generates url for avatar.
    """

    # Safely handle blank email
    if email == "":
        email = "*****@*****.**"

    # Retrieve from cache
    cache_key = "avatar-{0}-{1}".format(email.encode("base64").strip(), size)
    cache = caches["default"]
    url = cache.get(cache_key)
    if url is not None:
        return url

    if HAS_LIBRAVATAR:
        # Use libravatar library if available
        url = libravatar.libravatar_url(email=email, https=True, default=appsettings.AVATAR_DEFAULT_IMAGE, size=size)

    else:
        # Fallback to standard method
        mail_hash = hashlib.md5(email.lower()).hexdigest()

        url = "{0}avatar/{1}?{2}".format(
            appsettings.AVATAR_URL_PREFIX,
            mail_hash,
            urllib.urlencode({"s": str(size), "d": appsettings.AVATAR_DEFAULT_IMAGE}),
        )

    # Store result in cache
    cache.set(cache_key, url, 3600 * 24)

    return url
Esempio n. 5
0
def profile(openid):

    if (not flask.g.auth.logged_in or (
        flask.g.auth.openid != openid and
            not admin(flask.g.auth.openid))):

        flask.abort(403)

    user = fmn.lib.models.User.get_or_create(
        SESSION,
        openid=flask.g.auth.openid,
        openid_url=flask.g.auth.openid_url,
    )
    avatar = libravatar.libravatar_url(
        openid=user.openid_url,
        https=app.config.get('FMN_SSL', False),
        size=140)

    prefs = fmn.lib.models.Preference.by_user(SESSION, openid)

    icons = {}
    for context in fmn.lib.models.Context.all(SESSION):
        icons[context.name] = context.icon

    return flask.render_template(
        'profile.html',
        current='profile',
        avatar=avatar,
        prefs=prefs,
        icons=icons,
        api_key=user.api_key,
        fedora_mobile=flask.request.args.get('fedora_mobile') == 'true',
        openid_url=flask.g.auth.openid)
Esempio n. 6
0
    def get_avatar_url(self, size=128):
        default_img_url = reduce(lambda u, x: urlparse.urljoin(u, x),
                                 [settings.SITE_URL,
                                  settings.MEDIA_URL,
                                  'img/remo/remo_avatar.png'])

        return libravatar_url(email=self.user.email,
                              default=default_img_url,
                              size=size)
Esempio n. 7
0
    def gravatar_url(self):
        """
        Return url to libravatar image.
        """

        try:
            return libravatar_url(email=self.mail, https=True)
        except IOError:
            return ""
Esempio n. 8
0
def list_user(request, username, **kwargs):
    User = get_user_model()
    user = get_object_or_404(User, **{User.USERNAME_FIELD: username})
    try:
        gravatar = libravatar_url(email=user.email, https=True)
    except IOError:
        gravatar = ""
    queryset = user.softwarecollection_set.filter(has_content=True)
    dictionary = {'user': user, "gravatar": gravatar}
    return _list(request, 'scls/list_user.html', queryset, dictionary, **kwargs)
Esempio n. 9
0
def avatar_url_from_openid(openid, size=64, default='retro', dns=False):
    if dns:
        import libravatar
        return libravatar.libravatar_url(
            openid=openid,
            size=size,
            default=default,)
    else:
        query = urllib.urlencode({'s': size, 'd': default})
        hash = hashlib.sha256(openid).hexdigest()
        return "https://seccdn.libravatar.org/avatar/%s?/%s" % (hash, query)
Esempio n. 10
0
def avatar_url_from_openid(openid, size=64, default="retro", dns=False):
    """
    Our own implementation since fas doesn't support this nicely yet.
    """

    if dns:  # pragma: no cover
        # This makes an extra DNS SRV query, which can slow down our webapps.
        # It is necessary for libravatar federation, though.
        import libravatar

        return libravatar.libravatar_url(openid=openid, size=size, default=default)
    else:
        query = urllib.urlencode({"s": size, "d": default})
        hash = hashlib.sha256(openid).hexdigest()
        return "https://seccdn.libravatar.org/avatar/%s?%s" % (hash, query)
Esempio n. 11
0
    def get_avatar_url(self, size=50):
        """Get a url pointing to user's avatar.

        The libravatar network is used for avatars. Optional argument
        size can be provided to set the avatar size.

        """
        default_img_url = reduce(lambda u, x: urlparse.urljoin(u, x),
                                 [settings.SITE_URL,
                                  settings.MEDIA_URL,
                                  'img/remo/remo_avatar.png'])

        return libravatar_url(email=self.user.email,
                              default=default_img_url,
                              size=size)
Esempio n. 12
0
def avatar_for_email(email, size=80):
    """
    Generates url for avatar.
    """

    # Safely handle blank email
    if email == '':
        email = '*****@*****.**'

    mail_hash = hashlib.md5(email.lower().encode('utf-8')).hexdigest()

    # Retrieve from cache
    cache_key = '-'.join((
        'avatar',
        mail_hash,
        str(size)
    ))
    cache = caches['default']
    url = cache.get(cache_key)
    if url is not None:
        return url

    if HAS_LIBRAVATAR:
        # Use libravatar library if available
        url = libravatar.libravatar_url(
            email=email,
            https=True,
            default=appsettings.AVATAR_DEFAULT_IMAGE,
            size=size
        )

    else:
        # Fallback to standard method
        url = "{0}avatar/{1}?{2}".format(
            appsettings.AVATAR_URL_PREFIX,
            mail_hash,
            urlencode({
                's': str(size),
                'd': appsettings.AVATAR_DEFAULT_IMAGE
            })
        )

    # Store result in cache
    cache.set(cache_key, url, 3600 * 24)

    return url
Esempio n. 13
0
def profile(openid):

    if (not flask.g.auth.logged_in or (
        flask.g.auth.openid != openid and
            not admin(flask.g.auth.openid))):
        flask.abort(403)

    user = fmn.lib.models.User.get(SESSION, openid=openid)

    # Does this user exist, or is it a first visit?
    if not user:

        # If this is an admin looking at a user that doesn't exist, bail.
        if flask.g.auth.openid != openid:
            flask.abort(404)

        # Otherwise, if you are looking at your own profile, and it doesn't
        # exist, then create it.
        user = fmn.lib.models.User.get_or_create(
            SESSION,
            openid=flask.g.auth.openid,
            openid_url=flask.g.auth.openid_url,
        )

    avatar = libravatar.libravatar_url(
        openid=user.openid_url,
        https=app.config.get('FMN_SSL', False),
        size=140)

    prefs = fmn.lib.models.Preference.by_user(SESSION, openid)

    icons = {}
    for context in fmn.lib.models.Context.all(SESSION):
        icons[context.name] = context.icon

    return flask.render_template(
        'profile.html',
        current='profile',
        avatar=avatar,
        prefs=prefs,
        icons=icons,
        api_key=user.api_key,
        fedora_mobile=flask.request.args.get('fedora_mobile') == 'true',
        openid=user.openid,
        openid_url=user.openid_url,
    )
Esempio n. 14
0
    def work(username, size):
        openid = "http://%s.id.fedoraproject.org/" % username
        if asbool(config.get('libravatar_enabled', True)):
            if asbool(config.get('libravatar_dns', False)):
                return libravatar.libravatar_url(
                    openid=openid,
                    https=https,
                    size=size,
                    default='retro',
                )
            else:
                query = urllib.urlencode({'s': size, 'd': 'retro'})
                hash = hashlib.sha256(openid).hexdigest()
                template = "https://seccdn.libravatar.org/avatar/%s?%s"
                return template % (hash, query)

        return 'libravatar.org'
Esempio n. 15
0
def libravatar(context, email, size=None):
    https = context['request'].is_secure()
    default = LIBRAVATAR_DEFAULT_HTTPS if https else LIBRAVATAR_DEFAULT
    if hasattr(default, '__call__'):
        default = default(size)
    if not email:
        return default
    cache_key = "%s:%d:%d" % (email, size, https)
    print cache_key
    url = cache.get(cache_key)
    if url is None:
        print 'fetching...'
        url = libravatar_url(email,
            https=https,
            default=default,
            size=size)
        cache.set(cache_key, url, 60 * 60)
    return url
def avatar_url_from_email(email, size=64, default='retro', dns=False):
    """
    Our own implementation since fas doesn't support this nicely yet.
    """

    if dns:
        # This makes an extra DNS SRV query, which can slow down our webapps.
        # It is necessary for libravatar federation, though.
        import libravatar
        return libravatar.libravatar_url(
            email=email,
            size=size,
            default=default,
        )
    else:
        query = urllib.urlencode({'s': size, 'd': default})
        hash = md5(email).hexdigest()
        return "https://seccdn.libravatar.org/avatar/%s?%s" % (hash, query)
def _kernel(email, size, default, service='gravatar'):
    """ Copy-and-paste of some code from python-fedora. """

    if service == 'libravatar':
        import libravatar
        return libravatar.libravatar_url(
            email=email,
            size=size,
            default=default,
        )
    else:
        query_string = urllib.urlencode({
            's': size,
            'd': default,
        })

        hash = md5(email).hexdigest()

        return "http://www.gravatar.com/avatar/%s?%s" % (hash, query_string)
def avatar_url_from_email(email, size=64, default='retro', dns=False):
    """
    Our own implementation since fas doesn't support this nicely yet.
    """

    if dns:
        # This makes an extra DNS SRV query, which can slow down our webapps.
        # It is necessary for libravatar federation, though.
        import libravatar
        return libravatar.libravatar_url(
            email=email,
            size=size,
            default=default,
        )
    else:
        params = _ordered_query_params([('s', size), ('d', default)])
        query = parse.urlencode(params)
        hash = md5(email.encode('utf-8')).hexdigest()
        return "https://seccdn.libravatar.org/avatar/%s?%s" % (hash, query)
Esempio n. 19
0
def avatar_for_email(email, size=80):
    '''
    Generates url for avatar.
    '''

    # Safely handle blank email
    if email == '':
        email = '*****@*****.**'

    # Retrieve from cache
    cache_key = 'avatar-%s-%s' % (email, size)
    url = cache.get(cache_key)
    if url is not None:
        return url

    if HAS_LIBRAVATAR:
        # Use libravatar library if available
        url = libravatar.libravatar_url(
            email=email,
            https=True,
            default=AVATAR_DEFAULT_IMAGE,
            size=size
        )

    else:
        # Fallback to standard method
        mail_hash = hashlib.md5(email.lower()).hexdigest()

        url = "%savatar/%s?" % (AVATAR_URL_PREFIX, mail_hash)

        url += urllib.urlencode({
            's': str(size),
            'd': AVATAR_DEFAULT_IMAGE
        })

    # Store result in cache
    cache.set(cache_key, url, 3600 * 24)

    return escape(url)
Esempio n. 20
0
File: utils.py Progetto: tyll/tahrir
    def _avatar_function(email, size):
        request = pyramid.threadlocal.get_current_request()
        absolute_default = request.registry.settings.get(
            'tahrir.default_avatar',
            'https://badges.fedoraproject.org/static/img/badger_avatar.png')

        query = {
            's': size,
            'd': absolute_default,
        }

        if size == 'responsive':
            # Make it big so we can downscale it as we please
            query['s'] = 312

        query = urllib.urlencode(query)

        # Use md5 for emails, and sha256 for openids.
        # We're really using openids, so...
        #hash = md5(email).hexdigest()
        hash = sha256(email).hexdigest()

        # TODO This next line is temporary and can be removed.  We do
        # libravatar ourselves here by hand to avoid pyDNS issues on epel6.
        # Once those are resolved we can use pylibravatar again.
        return "https://seccdn.libravatar.org/avatar/%s?%s" % (hash, query)

        gravatar_url = "https://secure.gravatar.com/avatar/%s?%s" % (hash, query)

        if libravatar:
            return libravatar.libravatar_url(
                email=email,
                size=size,
                default=gravatar_url,
            )
        else:
            return gravatar_url
Esempio n. 21
0
 def avatar_url(self, size=96, https=True, default='mm'):
     if not self.user.email:
         return None
     return libravatar_url(self.user.email, size=size, https=https,
                           default=default)
Esempio n. 22
0
    def avatar_url(self,
                   username,
                   size=64,
                   default=None,
                   lookup_email=True,
                   service=None):
        ''' Returns a URL to an avatar for a given username.

        Avatars are drawn from third party services.

        :arg username: FAS username to construct a avatar url for
        :kwarg size: size of the avatar.  Allowed sizes are 32, 64, 140.
            Default: 64
        :kwarg default: If the service does not have a avatar image for the
            email address, this url is returned instead.  Default:
            the fedora logo at the specified size.
        :kwarg lookup_email:  If true, use the email from FAS for gravatar.com
            lookups, otherwise just append @fedoraproject.org to the username.
            For libravatar.org lookups, this is ignored.  The openid identifier
            of the user is used instead.
            Note that gravatar.com lookups will be much slower if lookup_email
            is set to True since we'd have to make a query against FAS itself.
        :kwarg service: One of 'libravatar' or 'gravatar'.
            Default: 'libravatar'.
        :raises ValueError: if the size parameter is not allowed or if the
            service is not one of 'libravatar' or 'gravatar'
        :rtype: :obj:`str`
        :returns: url of a avatar for the user

        If that user has no avatar entry, instruct the remote service to
        redirect us to the Fedora logo.

        If that user has no email attribute, then make a fake request to
        the third party service.

        .. versionadded:: 0.3.26
        .. versionchanged: 0.3.30
            Add lookup_email parameter to control whether we generate avatar
            urls with the email in fas or [email protected]
        .. versionchanged: 0.3.33
            Renamed from `gravatar_url` to `avatar_url`
        .. versionchanged: 0.3.34
            Updated libravatar to use the user's openid identifier.
        '''

        if size not in self._valid_avatar_sizes:
            raise ValueError(
                'Size %(size)i disallowed.  Must be in %(valid_sizes)r' % {
                    'size': size,
                    'valid_sizes': self._valid_avatar_sizes
                })

        # If our caller explicitly requested libravatar but they don't have
        # it installed, then we need to raise a nice error and let them know.
        if service == 'libravatar' and not libravatar:
            raise ValueError("Install python-pylibravatar if you want to "
                             "use libravatar as an avatar provider.")

        # If our caller didn't specify a service, let's pick a one for them.
        # If they have pylibravatar installed, then by all means let freedom
        # ring!  Otherwise, we'll use gravatar.com if we have to.
        if not service:
            if libravatar:
                service = 'libravatar'
            else:
                service = 'gravatar'

        # Just double check to make sure they didn't pass us a bogus service.
        if service not in self._valid_avatar_services:
            raise ValueError('Service %(service)r disallowed. '
                             'Must be in %(valid_services)r' % {
                                 'service': service,
                                 'valid_services': self._valid_avatar_services
                             })

        if not default:
            default = "http://fedoraproject.org/static/images/" + \
                      "fedora_infinity_%ix%i.png" % (size, size)

        if service == 'libravatar':
            openid = 'http://%s.id.fedoraproject.org/' % username
            return libravatar.libravatar_url(
                openid=openid,
                size=size,
                default=default,
            )
        else:
            if lookup_email:
                person = self.person_by_username(username)
                email = person.get('email', 'no_email')
            else:
                email = "*****@*****.**" % username

            query_string = urllib.urlencode({
                's': size,
                'd': default,
            })

            hash = md5(email).hexdigest()

            return "http://www.gravatar.com/avatar/%s?%s" % (hash,
                                                             query_string)
Esempio n. 23
0
 def avatar_url(self):
     return libravatar_url(email=self.email_address, https=True, default='mm')
Esempio n. 24
0
    def avatar_url(self, username, size=64,
                   default=None, lookup_email=True,
                   service=None):
        ''' Returns a URL to an avatar for a given username.

        Avatars are drawn from third party services.

        :arg username: FAS username to construct a avatar url for
        :kwarg size: size of the avatar.  Allowed sizes are 32, 64, 140.
            Default: 64
        :kwarg default: If the service does not have a avatar image for the
            email address, this url is returned instead.  Default:
            the fedora logo at the specified size.
        :kwarg lookup_email:  If true, use the email from FAS for gravatar.com
            lookups, otherwise just append @fedoraproject.org to the username.
            For libravatar.org lookups, this is ignored.  The openid identifier
            of the user is used instead.
            Note that gravatar.com lookups will be much slower if lookup_email
            is set to True since we'd have to make a query against FAS itself.
        :kwarg service: One of 'libravatar' or 'gravatar'.
            Default: 'libravatar'.
        :raises ValueError: if the size parameter is not allowed or if the
            service is not one of 'libravatar' or 'gravatar'
        :rtype: :obj:`str`
        :returns: url of a avatar for the user

        If that user has no avatar entry, instruct the remote service to
        redirect us to the Fedora logo.

        If that user has no email attribute, then make a fake request to
        the third party service.

        .. versionadded:: 0.3.26
        .. versionchanged: 0.3.30
            Add lookup_email parameter to control whether we generate avatar
            urls with the email in fas or [email protected]
        .. versionchanged: 0.3.33
            Renamed from `gravatar_url` to `avatar_url`
        .. versionchanged: 0.3.34
            Updated libravatar to use the user's openid identifier.
        '''

        if size not in self._valid_avatar_sizes:
            raise ValueError(
                'Size %(size)i disallowed.  Must be in %(valid_sizes)r' % {
                    'size': size,
                    'valid_sizes': self._valid_avatar_sizes
                }
            )

        # If our caller explicitly requested libravatar but they don't have
        # it installed, then we need to raise a nice error and let them know.
        if service == 'libravatar' and not libravatar:
            raise ValueError("Install python-pylibravatar if you want to "
                             "use libravatar as an avatar provider.")

        # If our caller didn't specify a service, let's pick a one for them.
        # If they have pylibravatar installed, then by all means let freedom
        # ring!  Otherwise, we'll use gravatar.com if we have to.
        if not service:
            if libravatar:
                service = 'libravatar'
            else:
                service = 'gravatar'

        # Just double check to make sure they didn't pass us a bogus service.
        if service not in self._valid_avatar_services:
            raise ValueError(
                'Service %(service)r disallowed. '
                'Must be in %(valid_services)r' % {
                    'service': service,
                    'valid_services': self._valid_avatar_services
                }
            )

        if not default:
            default = "http://fedoraproject.org/static/images/" + \
                      "fedora_infinity_%ix%i.png" % (size, size)

        if service == 'libravatar':
            openid = 'http://%s.id.fedoraproject.org/' % username
            return libravatar.libravatar_url(
                openid=openid,
                size=size,
                default=default,
            )
        else:
            if lookup_email:
                person = self.person_by_username(username)
                email = person.get('email', 'no_email')
            else:
                email = "*****@*****.**" % username

            query_string = urllib.urlencode({
                's': size,
                'd': default,
            })

            hash = md5(email).hexdigest()

            return "http://www.gravatar.com/avatar/%s?%s" % (
                hash, query_string)
Esempio n. 25
0
def mboxperson(person, format=False, limit=0):

    mboxquery = Archive.objects.filter(Q(sender=person) | Q(others__contains=person)).order_by("-date")

    if limit > 0:
        mboxquery = mboxquery[:limit]

    mboxdata = serializers.serialize("json", mboxquery)

    rows = simplejson.loads(mboxdata)
    mboxlist = []
    m = mboxlist.append

    for l in rows:
        m(l["fields"])

    if format == "json":
        return mboxlist

    if format == "rss2":
        feed = feedgenerator.Rss201rev2Feed(
            language="en",
            author_name="Was Where When",
            link=u"%s" % settings.MAILMAN_BASEURL,
            title=u"Whereis Mailing List",
            description=u"Telling the whole company how crappy we feel",
        )

        for mboxmail in mboxlist:
            feed.add_item(
                pubDate="%s" % mboxmail["date"],
                link=u"%s" % settings.MAILMAN_BASEURL,
                title=u"%s" % mboxmail["subject"],
                author_email="%s" % mboxmail["sender"],
                description=u"%s" % taghilight(mboxmail["body"]),
            )

        return feed.writeString("utf8")

    v = []
    a = v.append
    a('<table class="singleday">')
    a('<tr><th colspan="2">%s</th></tr>' % (person))

    if len(mboxlist) < 1:
        a("<tr><th><h1>Nothing in the whereis archives for this person</h1></th></tr>")

    for mboxmail in mboxlist:
        avatar_url = libravatar_url(email=mboxmail["sender"], size=150)

        if settings.DIRECTORY_JSON:

            try:
                tagstring = gettags(mboxmail["sender"], mboxmail["body"])
                tagstring = " | ".join(tagstring)
            except:
                tagstring = ""

            try:
                others = getothers(mboxmail["subject"], mboxmail["sender"])
            except:
                others = ""
        else:
            tagstring = others = ""

        if len(others) > 0:
            others = "Possible mentions:<br/>%s" % others

        a(
            '<tr><td class="headers"><p class="subject">%s</p><img src="%s"><p class="hilight">%s</p><p>%s</p></td><td class="what">%s<br/><br/>%s</td></tr>'
            % (mboxmail["subject"], avatar_url, others, mboxmail["date"], taghilight(mboxmail["body"]), tagstring)
        )

    a("</table>")

    return "\n".join(v)
Esempio n. 26
0
def singleday(year, month, day):
    d = date(year, month, day)
    dateformatted = d.strftime("%b %d %Y")
    dayname = d.weekday()
    yesterday = d - timedelta(1)
    yesterday = yesterday.strftime("%Y/%m/%d")
    tomorrow = d + timedelta(1)
    nextday = tomorrow
    tomorrow = tomorrow.strftime("%Y/%m/%d")
    lastweek = datetime.now() - timedelta(7)
    now = date.today()

    if d == now:
        mbox(d, dayname, False)

    mboxquerycount = Archive.objects.filter(date__contains=d).count()

    if mboxquerycount < 1:
        mboxlist = mbox(d, dayname)
    else:
        mboxquery = Archive.objects.filter(date__contains=d).order_by("date")
        jsondata = serializers.serialize("json", mboxquery)
        rows = simplejson.loads(jsondata)
        mboxlist = []
        m = mboxlist.append

        for l in rows:
            m(l["fields"])

    v = []
    a = v.append
    a('<table class="singleday">')
    a(
        '<tr><th colspan="2"><a class="nounder" href="/%s"><</a>&nbsp;%s&nbsp;<a class="nounder" href="/%s">></a></th></tr>'
        % (yesterday, d, tomorrow)
    )

    if d > now:
        a("<tr><th><h1>This date has not happened yet</h1><p>Time machines do not exist yet!</p></th></tr>")
        mboxlist = []
    elif mboxlist == False:
        mboxlist = []
        a("<tr><th><h1>This date predates the archive</h1><p>Time machines do not exist yet!</p></th></tr>")
    elif len(mboxlist) < 1:
        a("<tr><th><h1>Either this is a weekend day, or nobody mailed whereis</h1></th></tr>")

    d = d.strftime("%A, %B %d, %Y")

    for mboxmail in mboxlist:
        avatar_url = libravatar_url(email=mboxmail["sender"], size=150)

        if settings.DIRECTORY_JSON:

            try:
                tagstring = gettags(mboxmail["sender"], mboxmail["body"])
                tagstring = " | ".join(tagstring)
            except:
                tagstring = ""

            try:
                others = getothers(mboxmail["subject"], mboxmail["sender"])
            except:
                others = ""
        else:
            tagstring = others = ""

        if len(others) > 0:
            others = "Possible mentions:<br/>%s" % others

        a(
            '<tr><td class="headers"><p class="subject">%s</p><img src="%s"><p class="hilight">%s</p><p>%s</p></td><td class="what">%s<br/><br/>%s</td></tr>'
            % (mboxmail["subject"], avatar_url, others, mboxmail["date"], taghilight(mboxmail["body"]), tagstring)
        )

    a("</table>")

    return "\n".join(v)
Esempio n. 27
0
 def avatar_url(self):
     return libravatar_url(email=self.email_address, https=True, default='mm')