Exemplo n.º 1
0
def localised_nice_date(datetime_):
    ''' Returns a friendly localised unicode representation of a datetime. '''
    now = datetime.datetime.now()
    date_diff = now - datetime_
    days = date_diff.days
    if days < 1 and now > datetime_:
        # less than one day
        seconds = date_diff.seconds
        if seconds < 3600:
            # less than one hour
            if seconds < 60:
                return _('Just now')
            else:
                return ungettext('{mins} minute ago', '{mins} minutes ago',
                                 seconds / 60).format(mins=seconds / 60)
        else:
            return ungettext('{hours} hour ago', '{hours} hours ago',
                             seconds / 3600).format(hours=seconds / 3600)
    # more than one day
    if days < 31:
        return ungettext('{days} day ago', '{days} days ago',
                         days).format(days=days)
    # actual date
    month = datetime_.month
    day = datetime_.day
    year = datetime_.year
    month_name = _MONTH_FUNCTIONS[month - 1]()
    return _('{month} {day}, {year}').format(month=month_name, day=day,
                                             year=year)
Exemplo n.º 2
0
    def _subject(self, sections, events):
        pages = files = 0
        for section in sections:
            for event in section['events']:
                if event['type'] == 'page':
                    pages += 1
                elif event['type'] == 'file':
                    files += 1

        subject = _('Ututi news: %(changes)s')
        file_changes = ungettext('%(file_count)d new file',
                                 '%(file_count)d new files', files) % {
            'file_count': files}
        page_changes = ungettext('%(page_count)d new page',
                                 '%(page_count)d new pages', pages) % {
            'page_count': pages}

        if pages and files:
            subject = _('Ututi news: %(file_changes)s and %(page_changes)s')
            subject = subject % {'file_changes': file_changes,
                                 'page_changes': page_changes}
        elif files:
            subject = subject % {'changes': file_changes}
        elif pages:
            subject = subject % {'changes': page_changes}
        else:
            messages = len([event for event in events if event.category == 'moderation'])
            moderation_changes = ungettext('%(message_count)d new message awaiting moderation',
                                           '%(message_count)d new messages awaiting moderation', messages) % {
                'message_count': messages}
            subject = subject % {'changes': moderation_changes}

        return   subject
Exemplo n.º 3
0
def when(time):
    """Formats now() - time in human readable format."""
    import datetime
    from pylons.i18n import ungettext
    difference = datetime.datetime.utcnow() - time
    if datetime.timedelta(seconds=60) > difference:
        num = difference.seconds
        return ungettext("%(num)s second ago",
                         "%(num)s seconds ago",
                         num) % {'num': num}
    elif datetime.timedelta(seconds=3600) > difference:
        num = difference.seconds / 60
        return ungettext("%(num)s minute ago",
                         "%(num)s minutes ago",
                         num) % {'num': num}
    elif datetime.timedelta(1) > difference:
        num = difference.seconds / 3600
        return ungettext("%(num)s hour ago",
                         "%(num)s hours ago",
                         num) % {'num': num}
    elif datetime.timedelta(5) > difference:
        num = difference.days
        return ungettext("%(num)s day ago",
                         "%(num)s days ago",
                         num) % {'num': num}
    else:
        return time.strftime("%Y-%m-%d")
Exemplo n.º 4
0
def popular(type_, number, min=1, title=None):
    """ display a popular icon. """
    if type_ == "views":
        title = ungettext("{number} view", "{number} views", number)
    elif type_ == "recent views":
        title = ungettext("{number} recent view", "{number} recent views", number)
    elif not title:
        raise Exception("popular() did not recieve a valid type_ or title")
    return snippet("snippets/popular.html", title=title, number=number, min=min)
Exemplo n.º 5
0
Arquivo: helpers.py Projeto: HHS/ckan
def popular(type_, number, min=1, title=None):
    ''' display a popular icon. '''
    if type_ == 'views':
        title = ungettext('{number} view', '{number} views', number)
    elif type_ == 'recent views':
        title = ungettext('{number} recent view', '{number} recent views', number)
    elif not title:
        raise Exception('popular() did not recieve a valid type_ or title')
    return snippet('snippets/popular.html', title=title, number=number, min=min)
Exemplo n.º 6
0
 def __getattr__(self, attr):
     if attr.startswith("N_"):
         a = attr[2:]
         rval = self.string_dict[a]
         return lambda x: ungettext(rval[0], rval[1], x)
     else:
         rval = self.string_dict[attr]
         n = 1 if attr == rval[0] else 5
         return ungettext(rval[0], rval[1], n)
Exemplo n.º 7
0
    def merge_post(self):
        primary_id = int(request.params.get('primary_id'))
        primary = meta.Session.query(model.Person).get(primary_id)
        log.debug("primary: %s" % primary)

        primary_media = map(lambda x: x.medium, primary.persons_to_media)
        log.debug("primary_media: %s" % primary_media)

        person_ids = request.params.get('person_ids_str')
        person_ids = person_ids.split(',')
        person_ids = map(lambda x: int(x), person_ids)
        person_ids.remove(primary_id)
        log.debug("person_ids: %s" % person_ids)

        remap_cnt = 0
        for secondary_id in person_ids:
            secondary = meta.Session.query(model.Person).get(secondary_id)
            log.debug("secondary: %s" % secondary)
            for item in secondary.persons_to_media:
                if item.medium in primary_media:
                    log.debug("medium already exists: %s" % item.medium)
                else:
                    log.debug("medium does not exists: %s" % item.medium)
                    #~ item.person_id = primary.id
                    #~ meta.Session.update(item)
                    record = model.PersonToMedia()
                    record.type_id = item.type_id
                    item.medium.persons_to_media.append(record)
                    primary.persons_to_media.append(record)
                    
                    remap_cnt += 1

            alias = model.PersonAlias()
            alias.name = secondary.name
            primary.aliases.append(alias)
            meta.Session.delete(secondary)

        meta.Session.commit()
        #~ h.flash(_("Removed %(person_cnt)d, added %(media_cnt)d media") %\
                #~ {'person_cnt':len(person_ids), 'media_cnt':remap_cnt})

        h.flash(ungettext("Removed %d person",
                          "Removed %d persons",
                          len(person_ids)) % len(person_ids))
                          
        h.flash(ungettext("Added %(cnt)d medium to '%(person)s'",
                          "Added %(cnt)d media to '%(person)s'",
                          remap_cnt) % {'cnt':remap_cnt,
                                             'person':primary.name})
                          
        return_to = request.params.get('return_to',
                                       h.url_for(controller='person',
                                                 action='edit',
                                                 id=primary.id))
        return redirect(str(return_to))
Exemplo n.º 8
0
    def __getattr__(self, attr):
        to_func = False
        if attr.startswith("N_"):
            attr = attr[2:]
            to_func = True

        attr = attr.replace("_", " ")
        if to_func:
            rval = self.string_dict[attr]
            return lambda x: ungettext(rval[0], rval[1], x)
        else:
            rval = self.string_dict[attr]
            n = 1 if attr == rval[0] else 5
            return ungettext(rval[0], rval[1], n)
Exemplo n.º 9
0
 def _handle_personal_sms_credits(self, msg):
     if msg.sender is None:
         return _('Your phone number (+%s) is not registered in Ututi.') % msg.sender_phone_number
     credit_count = int(config.get('fortumo.personal_sms_credits.credits', 50))
     credit_price = float(config.get('fortumo.personal_sms_credits.price', 500)) / 100
     msg.sender.purchase_sms_credits(credit_count)
     msg.success = True
     return ungettext(
          'You have purchased %(count)d SMS credit for %(price).2f Lt;',
          'You have purchased %(count)d SMS credits for %(price).2f Lt;',
          credit_count) % dict(count=credit_count, price=credit_price) + \
        ungettext(
          ' You now have %(count)d credit.',
          ' You now have %(count)d credits.',
          msg.sender.sms_messages_remaining) % dict(count=msg.sender.sms_messages_remaining)
Exemplo n.º 10
0
    def invite_fb(self, group):
        # Handle POST.
        invited = request.params.get('ids[]')
        if invited:
            ids = invited.split(',')
            for facebook_id in ids:
                group.create_pending_fb_invitation(int(facebook_id), c.user)
            make_facebook_invitations(ids, c.user, group.location)
            meta.Session.commit()
            h.flash(ungettext('Invited %(num)d friend.',
                              'Invited %(num)d friends.',
                              len(ids)) % dict(num=len(ids)))
            redirect(c.group.url(action='members'))

        # Render page.
        fb_user = facebook.get_user_from_cookie(request.cookies,
                         config['facebook.appid'], config['facebook.secret'])
        c.has_facebook = fb_user is not None
        if c.has_facebook:
            try:
                graph = facebook.GraphAPI(fb_user['access_token'])
                friends = graph.get_object("me/friends")
            except facebook.GraphAPIError:
                c.has_facebook = False
        if not c.has_facebook:
            # Ask to log on to facebook.
            return render('group/invite.mako')

        friend_ids = [f['id'] for f in friends['data']]
        friend_users = meta.Session.query(User).filter(
                            User.facebook_id.in_(friend_ids)).all()
        c.exclude_ids = ','.join(str(u.facebook_id) for u in friend_users
                                 if c.group.is_member(u))
        return render('group/invite.mako')
Exemplo n.º 11
0
 def html_news(self):
     count = self.count_of_messages_in_queue()
     text = ungettext('There is %(number_of_messages)d message waiting in the <a href="%(moderation_queue_link)s">moderation queue</a>',
                      'There are %(number_of_messages)d waiting in the <a href="%(moderation_queue_link)s">moderation queue</a>', count) % {
         'number_of_messages': count,
         'moderation_queue_link': self.context.url(controller='mailinglist', action='administration', qualified=True)}
     return text
Exemplo n.º 12
0
 def text_news(self):
     count = self.count_of_messages_in_queue()
     text = ungettext('There is %(number_of_messages)d message in the moderation queue (%(moderation_queue_link)s)',
                      'There are %(number_of_messages)d messages in the moderation queue (%(moderation_queue_link)s)', count) % {
         'number_of_messages': count,
         'moderation_queue_link': self.context.url(controller='mailinglist', action='administration', qualified=True)}
     return text
Exemplo n.º 13
0
    def create(cls, link, campaigns):
        transactions = get_transactions(link, campaigns)
        live_campaigns = scheduled_campaigns_by_link(link)
        user_is_sponsor = c.user_is_sponsor
        r = []
        for camp in campaigns:
            transaction = transactions.get(camp._id)
            campaign_id36 = camp._id36
            start_date = camp.start_date.strftime("%m/%d/%Y")
            end_date = camp.end_date.strftime("%m/%d/%Y")
            ndays = (camp.end_date - camp.start_date).days
            duration = strings.time_label % dict(num=ndays,
                            time=ungettext("day", "days", ndays))
            bid = "%.2f" % camp.bid
            sr = camp.sr_name
            status = {'paid': bool(transaction),
                      'complete': False,
                      'free': camp.is_freebie(),
                      'pay_url': pay_url(link, camp),
                      'view_live_url': view_live_url(link, sr),
                      'sponsor': user_is_sponsor,
                      'live': camp._id in live_campaigns}
            if transaction:
                if transaction.is_void():
                    status['paid'] = False
                    status['free'] = False
                elif transaction.is_charged():
                    status['complete'] = True

            rc = cls(campaign_id36, start_date, end_date, duration, bid, sr,
                     status)
            r.append(rc)
        return r
Exemplo n.º 14
0
    def get_links(cls, event_id):
        link_ids = cls._get_related_link_ids(event_id)
        links = Link._byID(link_ids, data=True, return_dict=False)
        links.sort(key=lambda L: L.num_comments, reverse=True)

        sr_ids = set(L.sr_id for L in links)
        subreddits = Subreddit._byID(sr_ids, data=True)

        wrapped = []
        for link in links:
            w = Wrapped(link)

            if w._spam or w._deleted:
                continue

            if not getattr(w, "allow_liveupdate", True):
                continue

            w.subreddit = subreddits[link.sr_id]

            # ideally we'd check if the user can see the subreddit, but by
            # doing this we keep everything user unspecific which makes caching
            # easier.
            if w.subreddit.type == "private":
                continue

            comment_label = ungettext("comment", "comments", link.num_comments)
            w.comments_label = strings.number_label % dict(
                num=link.num_comments, thing=comment_label)

            wrapped.append(w)
        return wrapped
Exemplo n.º 15
0
    def invite_friends_fb(self):
        # handle facebook callback
        ids = request.params.get('ids[]')
        if ids:
            ids = map(int, ids.split(','))
            invited = make_facebook_invitations(ids, c.user, c.user.location)
            meta.Session.commit()
            if invited:
                h.flash(ungettext('Invited %(num)d friend.',
                                  'Invited %(num)d friends.',
                                  len(invited)) % dict(num=len(invited)))

            redirect(url(controller='profile', action='home'))

        # render page
        fb_user = facebook.get_user_from_cookie(request.cookies,
                      config['facebook.appid'], config['facebook.secret'])
        c.has_facebook = fb_user is not None
        if c.has_facebook:
            try:
                graph = facebook.GraphAPI(fb_user['access_token'])
                friends = graph.get_object("me/friends")
                friend_ids = [f['id'] for f in friends['data']]
                friend_users = meta.Session.query(User)\
                        .filter(User.facebook_id.in_(friend_ids))\
                        .filter(User.location == c.user.location).all()
                c.exclude_ids = ','.join(str(u.facebook_id) for u in friend_users)
            except facebook.GraphAPIError:
                c.has_facebook = False

        return render('profile/invite_friends_fb.mako')
Exemplo n.º 16
0
    def _handle_group_message(self, msg):
        parts = msg.message_text.split(None, 1)
        if len(parts) != 2:
            return _('Invalid group message: %s') % msg.message_text

        group_id, text = parts

        if not msg.sender:
            return _('The phone number %s is not associated with a Ututi user') % (msg.sender_phone_number)

        group = Group.get(group_id)
        if group is None:
            return _('Invalid group: %s') % group_id

        max_group_members = config.get('sms_max_group_members', 40)
        if len(group.recipients_sms(sender=msg.sender)) > max_group_members:
            return ungettext(
                    'More than %d recipient, cannot send message.',
                    'More than %d recipients, cannot send message.',
                    max_group_members) % max_group_members

        # Send message.
        msg = OutgoingGroupSMSMessage(sender=msg.sender, group=group,
                                      message_text=text)
        meta.Session.add(msg)
        msg.send()

        msg.success = True
        return _('SMS message sent to group %s.') % group_id
Exemplo n.º 17
0
    def __init__(self, link, campaign, transaction):
        self.campaign_id36 = campaign._id36
        self.start_date = campaign.start_date.strftime("%m/%d/%Y")
        self.end_date = campaign.end_date.strftime("%m/%d/%Y")
        ndays = (campaign.end_date - campaign.start_date).days
        self.duration = strings.time_label % dict(num=ndays,
                          time=ungettext("day", "days", ndays))
        self.bid = "%.2f" % campaign.bid
        self.sr = campaign.sr_name
        live = campaign_is_live(link, campaign._id)

        self.status = dict(
            paid=bool(transaction),
            complete=False,
            free=campaign.is_freebie(),
            pay_url=pay_url(link, campaign),
            view_live_url=view_live_url(link, campaign.sr_name),
            sponsor=c.user_is_sponsor,
            live=live,
        )

        if transaction:
            if transaction.is_void():
                self.status['paid'] = False
                self.status['free'] = False
            elif transaction.is_charged():
                self.status['complete'] = True
Exemplo n.º 18
0
 def ungettext(self, singular, plural, count):
     """
     Traduit un message en tenant compte des pluriels.
     Lisez la documentation du module C{gettext} pour plus d'information.
     """
     orig_translation = super(VigiloRumTranslator, self).ugettext(
         singular, plural, count)
     if orig_translation != singular and orig_translation != plural:
         return orig_translation
     return i18n.ungettext(singular, plural, count)
Exemplo n.º 19
0
    def clear_persons(self, id):
        item = meta.find(model.Medium, id)
        cnt = 0
        for person2media in item.persons_to_media:
            meta.Session.delete(person2media)
            cnt += 1

        meta.Session.commit()
        h.flash(ungettext("removed %d person", "removed %d persons", cnt) % cnt)
        return redirect(url(controller="medium", action="edit", id=id))
Exemplo n.º 20
0
def comment_label(num_comments=None):
    if not num_comments:
        # generates "comment" the imperative verb
        com_label = _("comment {verb}")
        com_cls = "comments empty may-blank"
    else:
        # generates "XX comments" as a noun
        com_label = ungettext("comment", "comments", num_comments)
        com_label = strings.number_label % dict(num=num_comments, thing=com_label)
        com_cls = "comments may-blank"
    return com_label, com_cls
Exemplo n.º 21
0
def make_gold_message(thing, user_gilded):
    from r2.models import Comment

    if thing.gildings == 0 or thing._spam or thing._deleted:
        return None

    author = Account._byID(thing.author_id, data=True)
    if not author._deleted:
        author_name = author.name
    else:
        author_name = _("[deleted]")

    if c.user_is_loggedin and thing.author_id == c.user._id:
        if isinstance(thing, Comment):
            gilded_message = ungettext(
                "a redditor gifted you a month of reddit gold for this " "comment.",
                "redditors have gifted you %(months)d months of reddit gold " "for this comment.",
                thing.gildings,
            )
        else:
            gilded_message = ungettext(
                "a redditor gifted you a month of reddit gold for this " "submission.",
                "redditors have gifted you %(months)d months of reddit gold " "for this submission.",
                thing.gildings,
            )
    elif user_gilded:
        if isinstance(thing, Comment):
            gilded_message = ungettext(
                "you have gifted reddit gold to %(recipient)s for this " "comment.",
                "you and other redditors have gifted %(months)d months of "
                "reddit gold to %(recipient)s for this comment.",
                thing.gildings,
            )
        else:
            gilded_message = ungettext(
                "you have gifted reddit gold to %(recipient)s for this " "submission.",
                "you and other redditors have gifted %(months)d months of "
                "reddit gold to %(recipient)s for this submission.",
                thing.gildings,
            )
    else:
        if isinstance(thing, Comment):
            gilded_message = ungettext(
                "a redditor has gifted reddit gold to %(recipient)s for this " "comment.",
                "redditors have gifted %(months)d months of reddit gold to " "%(recipient)s for this comment.",
                thing.gildings,
            )
        else:
            gilded_message = ungettext(
                "a redditor has gifted reddit gold to %(recipient)s for this " "submission.",
                "redditors have gifted %(months)d months of reddit gold to " "%(recipient)s for this submission.",
                thing.gildings,
            )

    return gilded_message % dict(recipient=author_name, months=thing.gildings)
Exemplo n.º 22
0
    def create(cls, link, campaigns):
        transactions = get_transactions(link, campaigns)
        live_campaigns = scheduled_campaigns_by_link(link)
        user_is_sponsor = c.user_is_sponsor
        today = promo_datetime_now().date()
        r = []
        for camp in campaigns:
            transaction = transactions.get(camp._id)
            campaign_id36 = camp._id36
            start_date = camp.start_date.strftime("%m/%d/%Y")
            end_date = camp.end_date.strftime("%m/%d/%Y")
            ndays = camp.ndays
            duration = strings.time_label % dict(num=ndays,
                            time=ungettext("day", "days", ndays))
            bid = camp.bid
            spent = get_spent_amount(camp)
            cpm = getattr(camp, 'cpm', g.cpm_selfserve.pennies)
            sr = camp.sr_name
            live = camp._id in live_campaigns
            pending = today < to_date(camp.start_date)
            complete = (transaction and (transaction.is_charged() or
                                         transaction.is_refund()) and
                        not (live or pending))

            status = {'paid': bool(transaction),
                      'complete': complete,
                      'free': camp.is_freebie(),
                      'pay_url': pay_url(link, camp),
                      'view_live_url': view_live_url(link, sr),
                      'sponsor': user_is_sponsor,
                      'live': live,
                      'non_cpm': not camp.priority.cpm}

            if transaction and transaction.is_void():
                status['paid'] = False
                status['free'] = False

            if complete and user_is_sponsor and not transaction.is_refund():
                if spent < bid:
                    status['refund'] = True
                    status['refund_url'] = refund_url(link, camp)

            rc = cls(campaign_id36, start_date, end_date, duration, bid, spent,
                     cpm, sr, camp.priority, status)
            r.append(rc)
        return r
Exemplo n.º 23
0
def timetext(delta, resultion = 1, bare=True):
    """
    Takes a datetime object, returns the time between then and now
    as a nicely formatted string, e.g "10 minutes"
    Adapted from django which was adapted from
    http://blog.natbat.co.uk/archive/2003/Jun/14/time_since
    """
    chunks = (
      (60 * 60 * 24 * 365, lambda n: ungettext('year', 'years', n)),
      (60 * 60 * 24 * 30, lambda n: ungettext('month', 'months', n)),
      (60 * 60 * 24, lambda n : ungettext('day', 'days', n)),
      (60 * 60, lambda n: ungettext('hour', 'hours', n)),
      (60, lambda n: ungettext('minute', 'minutes', n)),
      (1, lambda n: ungettext('second', 'seconds', n))
    )
    delta = max(delta, timedelta(0))
    since = delta.days * 24 * 60 * 60 + delta.seconds
    for i, (seconds, name) in enumerate(chunks):
        count = math.floor(since / seconds)
        if count != 0:
            break

    from r2.lib.strings import strings
    if count == 0 and delta.seconds == 0 and delta != timedelta(0):
        n = math.floor(delta.microseconds / 1000)
        s = strings.time_label % dict(num=n, 
                                      time=ungettext("millisecond", 
                                                     "milliseconds", n))
    else:
        s = strings.time_label % dict(num=count, time=name(int(count)))
        if resultion > 1:
            if i + 1 < len(chunks):
                # Now get the second item
                seconds2, name2 = chunks[i + 1]
                count2 = (since - (seconds * count)) / seconds2
                if count2 != 0:
                    s += ', %d %s' % (count2, name2(count2))
    if not bare: s += ' ' + _('ago')
    return s
Exemplo n.º 24
0
 def somethings(x, word):
     p = plurals.string_dict[word]
     f = lambda x: ungettext(p[0], p[1], x)
     return strings.number_label % dict(num=x, thing=f(x))
Exemplo n.º 25
0
    def _replace_render(style=None, display=True):
        """
        A helper function for listings to set uncachable attributes on a
        rendered thing (item) to its proper display values for the current
        context.
        """
        style = style or c.render_style or 'html'
        replacements = {}

        if hasattr(item, 'child'):
            if item.child:
                replacements['childlisting'] = item.child.render(style=style)
            else:
                # Special case for when the comment tree wasn't built which
                # occurs both in the inbox and spam page view of comments.
                replacements['childlisting'] = None
        else:
            replacements['childlisting'] = ''

        #only LinkListing has a show_nums attribute
        if listing and hasattr(listing, "show_nums"):
            if listing.show_nums and item.num > 0:
                num = str(item.num)
            else:
                num = ""
            replacements["num"] = num

        if getattr(item, "rowstyle_cls", None):
            replacements["rowstyle"] = item.rowstyle_cls

        if hasattr(item, "num_comments"):
            com_label, com_cls = comment_label(item.num_comments)
            if style == "compact":
                com_label = unicode(item.num_comments)
            replacements['numcomments'] = com_label
            replacements['commentcls'] = com_cls

        if hasattr(item, "num_children"):
            label = ungettext("child", "children", item.num_children)
            numchildren_text = strings.number_label % {
                'num': item.num_children,
                'thing': label
            }
            replacements['numchildren_text'] = numchildren_text

        replacements['display'] = "" if display else "style='display:none'"

        if hasattr(item, "render_score"):
            # replace the score stub
            (replacements['scoredislikes'], replacements['scoreunvoted'],
             replacements['scorelikes']) = item.render_score

        # compute the timesince here so we don't end up caching it
        if hasattr(item, "_date"):
            if hasattr(item, "promoted") and item.promoted is not None:
                from r2.lib import promote
                # promoted links are special in their date handling
                replacements['timesince'] = \
                    simplified_timesince(item._date - promote.timezone_offset)
            else:
                replacements['timesince'] = simplified_timesince(item._date)

        # compute the last edited time here so we don't end up caching it
        if hasattr(item, "editted") and not isinstance(item.editted, bool):
            replacements['lastedited'] = simplified_timesince(item.editted)

        renderer = render_func or item.render
        res = renderer(style=style, **replacements)

        if isinstance(res, (str, unicode)):
            rv = unsafe(res)
            if g.debug:
                for leftover in re.findall('<\$>(.+?)(?:<|$)', rv):
                    print "replace_render didn't replace %s" % leftover

            return rv

        return res
Exemplo n.º 26
0
    def _replace_render(style = None, display = True):
        """
        A helper function for listings to set uncachable attributes on a
        rendered thing (item) to its proper display values for the current
        context.
        """
        style = style or c.render_style or 'html'
        replacements = {}

        if hasattr(item, 'child'):
            if item.child:
                replacements['childlisting'] = item.child.render(style=style)
            else:
                # Special case for when the comment tree wasn't built which
                # occurs both in the inbox and spam page view of comments.
                replacements['childlisting'] = None
        else:
            replacements['childlisting'] = ''

        #only LinkListing has a show_nums attribute
        if listing and hasattr(listing, "show_nums"):
            if listing.show_nums and item.num > 0:
                num = str(item.num)
            else:
                num = ""
            replacements["num"] = num

        if getattr(item, "rowstyle_cls", None):
            replacements["rowstyle"] = item.rowstyle_cls

        if hasattr(item, "num_comments"):
            com_label, com_cls = comment_label(item.num_comments)
            if style == "compact":
                com_label = unicode(item.num_comments)
            replacements['numcomments'] = com_label
            replacements['commentcls'] = com_cls

        if hasattr(item, "num_children"):
            label = ungettext("child", "children", item.num_children)
            numchildren_text = strings.number_label % {'num': item.num_children,
                                                       'thing': label}
            replacements['numchildren_text'] = numchildren_text

        replacements['display'] =  "" if display else "style='display:none'"

        if hasattr(item, "render_score"):
            # replace the score stub
            (replacements['scoredislikes'],
             replacements['scoreunvoted'],
             replacements['scorelikes'])  = item.render_score

        # compute the timesince here so we don't end up caching it
        if hasattr(item, "_date"):
            if hasattr(item, "promoted") and item.promoted is not None:
                from r2.lib import promote
                # promoted links are special in their date handling
                replacements['timesince'] = \
                    simplified_timesince(item._date - promote.timezone_offset)
            else:
                replacements['timesince'] = simplified_timesince(item._date)

        # compute the last edited time here so we don't end up caching it
        if hasattr(item, "editted") and not isinstance(item.editted, bool):
            replacements['lastedited'] = simplified_timesince(item.editted)

        renderer = render_func or item.render
        res = renderer(style = style, **replacements)

        if isinstance(res, (str, unicode)):
            rv = unsafe(res)
            if g.debug:
                for leftover in re.findall('<\$>(.+?)(?:<|$)', rv):
                    print "replace_render didn't replace %s" % leftover

            return rv

        return res
Exemplo n.º 27
0
    def _replace_render(style = None, display = True):
        """
        A helper function for listings to set uncachable attributes on a
        rendered thing (item) to its proper display values for the current
        context.
        """
        style = style or c.render_style or 'html'
        replacements = {}

        child_txt = ( hasattr(item, "child") and item.child )\
            and item.child.render(style = style) or ""
        replacements["childlisting"] = child_txt


        #only LinkListing has a show_nums attribute
        if listing:
            if hasattr(listing, "show_nums"):
                if listing.show_nums:
                    num_str = str(item.num)
                    if hasattr(listing, "num_margin"):
                        num_margin = str(listing.num_margin)
                    else:
                        num_margin = "%.2fex" % (len(str(listing.max_num))*1.1)
                else:
                    num_str = ''
                    num_margin = "0px;display:none"

                replacements["numcolmargin"] = num_margin
                replacements["num"] = num_str

            if hasattr(listing, "max_score"):
                mid_margin = len(str(listing.max_score))
                if hasattr(listing, "mid_margin"):
                    mid_margin = str(listing.mid_margin)
                elif mid_margin == 1:
                    mid_margin = "15px"
                else:
                    mid_margin = "%dex" % (mid_margin+1)

                replacements["midcolmargin"] = mid_margin

            #$votehash is only present when voting arrows are present
            if c.user_is_loggedin:
                replacements['votehash'] = vote_hash(c.user, item,
                                                     listing.vote_hash_type)
        if hasattr(item, "num_comments"):
            if not item.num_comments:
                # generates "comment" the imperative verb
                com_label = _("comment {verb}")
                com_cls = 'comments empty'
            else:
                # generates "XX comments" as a noun
                com_label = ungettext("comment", "comments", item.num_comments)
                com_label = strings.number_label % dict(num=item.num_comments,
                                                        thing=com_label)
                com_cls = 'comments'
            if style == "compact":
                com_label = unicode(item.num_comments)
            replacements['numcomments'] = com_label
            replacements['commentcls'] = com_cls

        replacements['display'] =  "" if display else "style='display:none'"

        if hasattr(item, "render_score"):
            # replace the score stub
            (replacements['scoredislikes'],
             replacements['scoreunvoted'],
             replacements['scorelikes'])  = item.render_score

        # compute the timesince here so we don't end up caching it
        if hasattr(item, "_date"):
            if hasattr(item, "promoted") and item.promoted is not None:
                from r2.lib import promote
                # promoted links are special in their date handling
                replacements['timesince'] = timesince(item._date -
                                                      promote.timezone_offset)
            else:
                replacements['timesince'] = timesince(item._date)

            replacements['time_period'] = calc_time_period(item._date)

        # Set in front.py:GET_comments()
        replacements['previous_visits_hex'] = c.previous_visits_hex

        renderer = render_func or item.render
        res = renderer(style = style, **replacements)

        if isinstance(res, (str, unicode)):
            rv = unsafe(res)
            if g.debug:
                for leftover in re.findall('<\$>(.+?)(?:<|$)', rv):
                    print "replace_render didn't replace %s" % leftover

            return rv

        return res
Exemplo n.º 28
0
 def somethings(x, word):
     p = plurals.string_dict[word]
     f = lambda x: ungettext(p[0], p[1], x)
     return strings.number_label % dict(num=x, thing=f(x))
Exemplo n.º 29
0
def make_gold_message(thing, user_gilded):
    from r2.models import Comment

    if thing.gildings == 0 or thing._spam or thing._deleted:
        return None

    author = Account._byID(thing.author_id, data=True)
    if not author._deleted:
        author_name = author.name
    else:
        author_name = _("[deleted]")

    if c.user_is_loggedin and thing.author_id == c.user._id:
        if isinstance(thing, Comment):
            gilded_message = ungettext(
                "a redditor gifted you a month of reddit gold for this "
                "comment.",
                "redditors have gifted you %(months)d months of reddit gold "
                "for this comment.",
                thing.gildings
            )
        else:
            gilded_message = ungettext(
                "a redditor gifted you a month of reddit gold for this "
                "submission.",
                "redditors have gifted you %(months)d months of reddit gold "
                "for this submission.",
                thing.gildings
            )
    elif user_gilded:
        if isinstance(thing, Comment):
            gilded_message = ungettext(
                "you have gifted reddit gold to %(recipient)s for this "
                "comment.",
                "you and other redditors have gifted %(months)d months of "
                "reddit gold to %(recipient)s for this comment.",
                thing.gildings
            )
        else:
            gilded_message = ungettext(
                "you have gifted reddit gold to %(recipient)s for this "
                "submission.",
                "you and other redditors have gifted %(months)d months of "
                "reddit gold to %(recipient)s for this submission.",
                thing.gildings
            )
    else:
        if isinstance(thing, Comment):
            gilded_message = ungettext(
                "a redditor has gifted reddit gold to %(recipient)s for this "
                "comment.",
                "redditors have gifted %(months)d months of reddit gold to "
                "%(recipient)s for this comment.",
                thing.gildings
            )
        else:
            gilded_message = ungettext(
                "a redditor has gifted reddit gold to %(recipient)s for this "
                "submission.",
                "redditors have gifted %(months)d months of reddit gold to "
                "%(recipient)s for this submission.",
                thing.gildings
            )

    return gilded_message % dict(
        recipient=author_name,
        months=thing.gildings,
    )
Exemplo n.º 30
0
    def _replace_render(style = None, display = True):
        """
        A helper function for listings to set uncachable attributes on a
        rendered thing (item) to its proper display values for the current
        context.
        """
        style = style or c.render_style or 'html'
        replacements = {}
    
        child_txt = ( hasattr(item, "child") and item.child )\
            and item.child.render(style = style) or ""
        replacements["childlisting"] = child_txt
        
    
        #only LinkListing has a show_nums attribute
        if listing: 
            if hasattr(listing, "show_nums"):
                if listing.show_nums:
                    num_str = str(item.num) 
                    if hasattr(listing, "num_margin"):
                        num_margin = str(listing.num_margin)
                    else:
                        num_margin = "%.2fex" % (len(str(listing.max_num))*1.1)
                else:
                    num_str = ''
                    num_margin = "0px"
    
                replacements["numcolmargin"] = num_margin
                replacements["num"] = num_str
    
            if hasattr(listing, "max_score"):
                mid_margin = len(str(listing.max_score)) 
                if hasattr(listing, "mid_margin"):
                    mid_margin = str(listing.mid_margin)
                elif mid_margin == 1:
                    mid_margin = "15px"
                else:
                    mid_margin = "%dex" % (mid_margin+1)
    
                replacements["midcolmargin"] = mid_margin
    
            #$votehash is only present when voting arrows are present
            if c.user_is_loggedin:
                replacements['votehash'] = vote_hash(c.user, item,
                                                     listing.vote_hash_type)
        if hasattr(item, "num_comments"):
            if not item.num_comments:
                # generates "comment" the imperative verb
                com_label = _("comment {verb}")
                com_cls = 'comments empty'
            else:
                # generates "XX comments" as a noun
                com_label = ungettext("comment", "comments", item.num_comments)
                com_label = strings.number_label % dict(num=item.num_comments,
                                                        thing=com_label)
                com_cls = 'comments'
            replacements['numcomments'] = com_label
            replacements['commentcls'] = com_cls
    
        replacements['display'] =  "" if display else "style='display:none'"
    
        if hasattr(item, "render_score"):
            # replace the score stub
            (replacements['scoredislikes'],
             replacements['scoreunvoted'],
             replacements['scorelikes'])  = item.render_score
    
        # compute the timesince here so we don't end up caching it
        if hasattr(item, "_date"):
            replacements['timesince'] = timesince(item._date)

        renderer = render_func or item.render
        res = renderer(style = style, **replacements)
        if isinstance(res, (str, unicode)):
            return unsafe(res)
        return res
Exemplo n.º 31
0
    def mass_add_post(self):
        if not request.params.get('title'):
            h.flash(_("please specify name"))
            return redirect(url(controller='medium', action='mass_add'))

        if int(request.params.get('media_type', -1)) < 0:
            h.flash(_("please specify media type"))
            return self.mass_add()

        media_type_obj = meta.Session.query(model.MediaType).get(request.params.get('media_type', -1))
        
        
        count = 0
        new_media = []
        failed = []
        for item in request.params.get('title').split('\n'):
            if not item.strip():
                continue

            query = meta.Session\
                .query(model.Medium)\
                .filter(or_(model.Medium.title==item,
                            model.Medium.isbn==item))
            if query.first() != None:
                first_item = query.first()
                h.flash(_("medium already exists: %s") %\
                    anchor_tmpl.render_unicode(url=h.url_for(controller='medium', action='edit', id=first_item.id),
                                       text=h.html_escape(first_item.title)), escape=False)
                continue

            log.debug("!!!item: %s" % item)
            if re.match('^\d+\s*$', item):
                #~ log.info("@@@@@@@@@@@@@@@@@@ treat input as isbn: %s" % item)
                import medienverwaltungweb.lib.amazon as amazon
                result = amazon.AddMediumByISBN(item, media_type_obj.amzon_search_index)
                if not result:
                    #~ h.flash(_("I tried to use '%s' as an isbn, but amazon didn't find it.") % item)
                    h.flash(_("Amzon does not knwo what '%s' is.") % item)
                    failed.append(item)
                    continue

                elif not result['success']:
                    h.flash(_("Amazon Lookup failed with the following error: %s") % result['message'])
                    failed.append(item)
                    continue

                medium_id = result['medium_id']
                record = meta.Session.query(model.Medium).get(medium_id)
                new_media.append(record)
                continue

            record = model.Medium()
            record.title = item.strip()
            record.created_ts = datetime.now()
            record.updated_ts = datetime.now()
            record.media_type_id = request.params.get('media_type')
            meta.Session.add(record)
            count += 1
            new_media.append(record)

        if len(new_media) > 0:
            meta.Session.commit()
            log.debug("new_media: %s" % unicode(new_media[0].title))
            log.debug("type new_media: %s" % type(new_media[0].title))
            link_list = map(lambda x: anchor_tmpl.render_unicode(url=h.url_for(controller='medium', action='edit', id=x.id), text=x.title), new_media)
            link_list = ", ".join(link_list)
            msg = ungettext("added medium %(media)s",
                            "added %(num)d media: %(media)s",
                            len(new_media)) % {'num':len(new_media),
                                               'media':link_list}
            h.flash(msg, escape=False)
            #~ h.flash(UnsafeString(msg))

        if len(new_media) == 1:
            return redirect(url(controller='medium', action='edit', id=new_media[0].id))
        else:
            return redirect(url(controller='medium', action='index'))
Exemplo n.º 32
0
    def _replace_render(style=None, display=True):
        """
        A helper function for listings to set uncachable attributes on a
        rendered thing (item) to its proper display values for the current
        context.
        """
        style = style or c.render_style or 'html'
        replacements = {}

        child_txt = ( hasattr(item, "child") and item.child )\
            and item.child.render(style = style) or ""
        replacements["childlisting"] = child_txt

        #only LinkListing has a show_nums attribute
        if listing:
            if hasattr(listing, "show_nums"):
                if listing.show_nums:
                    num_str = str(item.num)
                    if hasattr(listing, "num_margin"):
                        num_margin = str(listing.num_margin)
                    else:
                        num_margin = "%.2fex" % (len(str(listing.max_num)) *
                                                 1.1)
                else:
                    num_str = ''
                    num_margin = "0px;display:none"

                replacements["numcolmargin"] = num_margin
                replacements["num"] = num_str

            if hasattr(listing, "max_score"):
                mid_margin = len(str(listing.max_score))
                if hasattr(listing, "mid_margin"):
                    mid_margin = str(listing.mid_margin)
                elif mid_margin == 1:
                    mid_margin = "15px"
                else:
                    mid_margin = "%dex" % (mid_margin + 1)

                replacements["midcolmargin"] = mid_margin

            #$votehash is only present when voting arrows are present
            if c.user_is_loggedin:
                replacements['votehash'] = vote_hash(c.user, item,
                                                     listing.vote_hash_type)
        if hasattr(item, "num_comments"):
            if not item.num_comments:
                # generates "comment" the imperative verb
                com_label = _("comment {verb}")
                com_cls = 'comments empty'
            else:
                # generates "XX comments" as a noun
                com_label = ungettext("comment", "comments", item.num_comments)
                com_label = strings.number_label % dict(num=item.num_comments,
                                                        thing=com_label)
                com_cls = 'comments'
            if style == "compact":
                com_label = unicode(item.num_comments)
            replacements['numcomments'] = com_label
            replacements['commentcls'] = com_cls

        replacements['display'] = "" if display else "style='display:none'"

        if hasattr(item, "render_score"):
            # replace the score stub
            (replacements['scoredislikes'], replacements['scoreunvoted'],
             replacements['scorelikes']) = item.render_score

        # compute the timesince here so we don't end up caching it
        if hasattr(item, "_date"):
            if hasattr(item, "promoted") and item.promoted is not None:
                from r2.lib import promote
                # promoted links are special in their date handling
                replacements['timesince'] = timesince(item._date -
                                                      promote.timezone_offset)
            else:
                replacements['timesince'] = timesince(item._date)

            replacements['time_period'] = calc_time_period(item._date)

        # Set in front.py:GET_comments()
        replacements['previous_visits_hex'] = c.previous_visits_hex

        renderer = render_func or item.render
        res = renderer(style=style, **replacements)

        if isinstance(res, (str, unicode)):
            rv = unsafe(res)
            if g.debug:
                for leftover in re.findall('<\$>(.+?)(?:<|$)', rv):
                    print "replace_render didn't replace %s" % leftover

            return rv

        return res