Exemple #1
0
    def wrap_items(self, items):
        from r2.lib.db import queries
        from r2.lib.template_helpers import add_attr
        user = c.user if c.user_is_loggedin else None

        #get authors
        #TODO pull the author stuff into add_props for links and
        #comments and messages?
        aids = set(l.author_id for l in items
                   if hasattr(l, 'author_id') and l.author_id is not None)

        authors = {}
        cakes = {}
        friend_rels = None
        if aids:
            authors = Account._byID(aids, data=True,
                                    stale=self.stale) if aids else {}
            now = datetime.datetime.now(g.tz)
            cakes = {
                a._id
                for a in authors.itervalues()
                if a.cake_expiration and a.cake_expiration >= now
            }
            if user and user.gold:
                friend_rels = user.friend_rels()

        subreddits = Subreddit.load_subreddits(items, stale=self.stale)

        can_ban_set = set()
        can_flair_set = set()
        can_own_flair_set = set()
        if user:
            for sr_id, sr in subreddits.iteritems():
                if sr.can_ban(user):
                    can_ban_set.add(sr_id)
                if sr.is_moderator_with_perms(user, 'flair'):
                    can_flair_set.add(sr_id)
                if sr.link_flair_self_assign_enabled:
                    can_own_flair_set.add(sr_id)

        #get likes/dislikes
        try:
            likes = queries.get_likes(user, items)
        except tdb_cassandra.TRANSIENT_EXCEPTIONS as e:
            g.log.warning("Cassandra vote lookup failed: %r", e)
            likes = {}
        uid = user._id if user else None

        types = {}
        wrapped = []

        modlink = {}
        modlabel = {}
        for s in subreddits.values():
            modlink[s._id] = '/r/%s/about/moderators' % s.name
            modlabel[s._id] = (
                _('moderator of /r/%(reddit)s, speaking officially') %
                dict(reddit=s.name))

        for item in items:
            w = self.wrap(item)
            wrapped.append(w)
            # add for caching (plus it should be bad form to use _
            # variables in templates)
            w.fullname = item._fullname
            types.setdefault(w.render_class, []).append(w)

            #TODO pull the author stuff into add_props for links and
            #comments and messages?
            w.author = None
            w.friend = False

            # List of tuples (see add_attr() for details)
            w.attribs = []

            w.distinguished = None
            if hasattr(item, "distinguished"):
                if item.distinguished == 'yes':
                    w.distinguished = 'moderator'
                elif item.distinguished in ('admin', 'special', 'gold',
                                            'gold-auto'):
                    w.distinguished = item.distinguished

            try:
                w.author = authors.get(item.author_id)
                if user and item.author_id in user.friends:
                    # deprecated old way:
                    w.friend = True

                    # new way:
                    label = None
                    if friend_rels:
                        rel = friend_rels[item.author_id]
                        note = getattr(rel, "note", None)
                        if note:
                            label = u"%s (%s)" % (_("friend"),
                                                  _force_unicode(note))
                    add_attr(w.attribs, 'F', label)

            except AttributeError:
                pass

            if (w.distinguished == 'admin' and w.author):
                add_attr(w.attribs, 'A')

            if w.distinguished == 'moderator':
                add_attr(w.attribs,
                         'M',
                         label=modlabel[item.sr_id],
                         link=modlink[item.sr_id])

            if w.distinguished == 'special':
                args = w.author.special_distinguish()
                args.pop('name')
                if not args.get('kind'):
                    args['kind'] = 'special'
                add_attr(w.attribs, **args)

            if w.author and w.author._id in cakes and not c.profilepage:
                add_attr(
                    w.attribs,
                    kind="cake",
                    label=(_("%(user)s just celebrated a reddit birthday!") % {
                        "user": w.author.name
                    }),
                    link="/user/%s" % w.author.name,
                )

            if hasattr(item, "sr_id") and item.sr_id is not None:
                w.subreddit = subreddits[item.sr_id]

            w.likes = likes.get((user, item))

            # update vote tallies
            compute_votes(w, item)

            w.score = w.upvotes - w.downvotes

            if w.likes:
                base_score = w.score - 1
            elif w.likes is None:
                base_score = w.score
            else:
                base_score = w.score + 1

            # store the set of available scores based on the vote
            # for ease of i18n when there is a label
            w.voting_score = [(base_score + x - 1) for x in range(3)]

            w.deleted = item._deleted

            w.link_notes = []

            if c.user_is_admin:
                if item._deleted:
                    w.link_notes.append("deleted link")
                if getattr(item, "verdict", None):
                    if not item.verdict.endswith("-approved"):
                        w.link_notes.append(w.verdict)

            if c.user_is_admin and getattr(item, 'ip', None):
                w.ip_span = ip_span(item.ip)
            else:
                w.ip_span = ""

            # if the user can ban things on a given subreddit, or an
            # admin, then allow them to see that the item is spam, and
            # add the other spam-related display attributes
            w.show_reports = False
            w.show_spam = False
            w.can_ban = False
            w.can_flair = False
            w.use_big_modbuttons = self.spam_listing

            if (c.user_is_admin or (user and hasattr(item, 'sr_id')
                                    and item.sr_id in can_ban_set)):
                if getattr(item, "promoted", None) is None:
                    w.can_ban = True

                ban_info = getattr(item, 'ban_info', {})
                w.unbanner = ban_info.get('unbanner')

                if item._spam:
                    w.show_spam = True
                    w.moderator_banned = ban_info.get('moderator_banned',
                                                      False)
                    w.autobanned = ban_info.get('auto', False)
                    w.banner = ban_info.get('banner')
                    if ban_info.get('note', None) and w.banner:
                        w.banner += ' (%s)' % ban_info['note']
                    w.use_big_modbuttons = True
                    if getattr(w, "author", None) and w.author._spam:
                        w.show_spam = "author"

                    if c.user == w.author and c.user._spam:
                        w.show_spam = False
                        w._spam = False
                        w.use_big_modbuttons = False

                elif (getattr(item, 'reported', 0) > 0
                      and (not getattr(item, 'ignore_reports', False)
                           or c.user_is_admin)):
                    w.show_reports = True
                    w.use_big_modbuttons = True

            if (c.user_is_admin or (user and hasattr(item, 'sr_id') and
                                    (item.sr_id in can_flair_set or
                                     (w.author and w.author._id == user._id
                                      and item.sr_id in can_own_flair_set)))):
                w.can_flair = True

            w.approval_checkmark = None
            if w.can_ban:
                verdict = getattr(w, "verdict", None)
                if verdict in ('admin-approved', 'mod-approved'):
                    approver = None
                    approval_time = None
                    baninfo = getattr(w, "ban_info", None)
                    if baninfo:
                        approver = baninfo.get("unbanner", None)
                        approval_time = baninfo.get("unbanned_at", None)

                    approver = approver or _("a moderator")

                    if approval_time:
                        text = _("approved by %(who)s %(when)s ago") % {
                            "who": approver,
                            "when": timesince(approval_time)
                        }
                    else:
                        text = _("approved by %s") % approver
                    w.approval_checkmark = text

        # recache the user object: it may be None if user is not logged in,
        # whereas now we are happy to have the UnloggedUser object
        user = c.user
        for cls in types.keys():
            cls.add_props(user, types[cls])

        return wrapped
Exemple #2
0
    def wrap_items(self, items):
        from r2.lib.db import queries
        from r2.lib.template_helpers import add_attr
        user = c.user if c.user_is_loggedin else None

        #get authors
        #TODO pull the author stuff into add_props for links and
        #comments and messages?

        aids = set(l.author_id for l in items if hasattr(l, 'author_id')
                   and l.author_id is not None)

        authors = {}
        cup_infos = {}
        friend_rels = None
        if aids:
            authors = Account._byID(aids, data=True, stale=self.stale) if aids else {}
            cup_infos = Account.cup_info_multi(aids)
            if user and user.gold:
                friend_rels = user.friend_rels()

        subreddits = Subreddit.load_subreddits(items, stale=self.stale)

        can_ban_set = set()
        can_flair_set = set()
        can_own_flair_set = set()
        if user:
            for sr_id, sr in subreddits.iteritems():
                if sr.can_ban(user):
                    can_ban_set.add(sr_id)
                if sr.is_moderator_with_perms(user, 'flair'):
                    can_flair_set.add(sr_id)
                if sr.link_flair_self_assign_enabled:
                    can_own_flair_set.add(sr_id)

        #get likes/dislikes
        try:
            likes = queries.get_likes(user, items)
        except tdb_cassandra.TRANSIENT_EXCEPTIONS as e:
            g.log.warning("Cassandra vote lookup failed: %r", e)
            likes = {}
        uid = user._id if user else None

        types = {}
        wrapped = []

        modlink = {}
        modlabel = {}
        for s in subreddits.values():
            modlink[s._id] = '/r/%s/about/moderators' % s.name
            modlabel[s._id] = (_('moderator of /r/%(reddit)s, speaking officially') %
                        dict(reddit = s.name) )


        for item in items:
            w = self.wrap(item)
            wrapped.append(w)
            # add for caching (plus it should be bad form to use _
            # variables in templates)
            w.fullname = item._fullname
            types.setdefault(w.render_class, []).append(w)

            #TODO pull the author stuff into add_props for links and
            #comments and messages?
            w.author = None
            w.friend = False

            # List of tuples (see add_attr() for details)
            w.attribs = []

            w.distinguished = None
            if hasattr(item, "distinguished"):
                if item.distinguished == 'yes':
                    w.distinguished = 'moderator'
                elif item.distinguished in ('admin', 'special', 'gold'):
                    w.distinguished = item.distinguished

            try:
                w.author = authors.get(item.author_id)
                if user and item.author_id in user.friends:
                    # deprecated old way:
                    w.friend = True

                    # new way:
                    label = None
                    if friend_rels:
                        rel = friend_rels[item.author_id]
                        note = getattr(rel, "note", None)
                        if note:
                            label = u"%s (%s)" % (_("friend"), 
                                                  _force_unicode(note))
                    add_attr(w.attribs, 'F', label)

            except AttributeError:
                pass

            if (w.distinguished == 'admin' and w.author):
                add_attr(w.attribs, 'A')

            if w.distinguished == 'moderator':
                add_attr(w.attribs, 'M', label=modlabel[item.sr_id],
                         link=modlink[item.sr_id])
            
            if w.distinguished == 'special':
                args = w.author.special_distinguish()
                args.pop('name')
                if not args.get('kind'):
                    args['kind'] = 'special'
                add_attr(w.attribs, **args)

            if w.author and w.author._id in cup_infos and not c.profilepage:
                cup_info = cup_infos[w.author._id]
                label = _(cup_info["label_template"]) % \
                        {'user':w.author.name}
                add_attr(w.attribs, 'trophy:' + cup_info["img_url"],
                         label=label,
                         link = "/user/%s" % w.author.name)

            if hasattr(item, "sr_id") and item.sr_id is not None:
                w.subreddit = subreddits[item.sr_id]

            w.likes = likes.get((user, item))

            # update vote tallies
            compute_votes(w, item)

            w.score = w.upvotes - w.downvotes

            if w.likes:
                base_score = w.score - 1
            elif w.likes is None:
                base_score = w.score
            else:
                base_score = w.score + 1

            # store the set of available scores based on the vote
            # for ease of i18n when there is a label
            w.voting_score = [(base_score + x - 1) for x in range(3)]

            w.deleted = item._deleted

            w.link_notes = []

            if c.user_is_admin:
                if item._deleted:
                    w.link_notes.append("deleted link")
                if getattr(item, "verdict", None):
                    if not item.verdict.endswith("-approved"):
                        w.link_notes.append(w.verdict)
                if hasattr(item, 'url') and is_banned_domain(item.url):
                    w.link_notes.append("banned domain")

            if c.user_is_admin and getattr(item, 'ip', None):
                w.ip_span = ip_span(item.ip)
            else:
                w.ip_span = ""

            # if the user can ban things on a given subreddit, or an
            # admin, then allow them to see that the item is spam, and
            # add the other spam-related display attributes
            w.show_reports = False
            w.show_spam    = False
            w.can_ban      = False
            w.can_flair    = False
            w.use_big_modbuttons = self.spam_listing

            if (c.user_is_admin
                or (user
                    and hasattr(item,'sr_id')
                    and item.sr_id in can_ban_set)):
                if getattr(item, "promoted", None) is None:
                    w.can_ban = True

                ban_info = getattr(item, 'ban_info', {})
                w.unbanner = ban_info.get('unbanner')

                if item._spam:
                    w.show_spam = True
                    w.moderator_banned = ban_info.get('moderator_banned', False)
                    w.autobanned = ban_info.get('auto', False)
                    w.banner = ban_info.get('banner')
                    if ban_info.get('note', None) and w.banner:
                        w.banner += ' (%s)' % ban_info['note']
                    w.use_big_modbuttons = True
                    if getattr(w, "author", None) and w.author._spam:
                        w.show_spam = "author"

                    if c.user == w.author and c.user._spam:
                        w.show_spam = False
                        w._spam = False
                        w.use_big_modbuttons = False

                elif (getattr(item, 'reported', 0) > 0
                      and (not getattr(item, 'ignore_reports', False) or c.user_is_admin)):
                    w.show_reports = True
                    w.use_big_modbuttons = True

            if (c.user_is_admin
                or (user and hasattr(item, 'sr_id')
                    and (item.sr_id in can_flair_set
                         or (w.author and w.author._id == user._id
                             and item.sr_id in can_own_flair_set)))):
                w.can_flair = True

            w.approval_checkmark = None
            if w.can_ban:
                verdict = getattr(w, "verdict", None)
                if verdict in ('admin-approved', 'mod-approved'):
                    approver = None
                    baninfo = getattr(w, "ban_info", None)
                    if baninfo:
                        approver = baninfo.get("unbanner", None)
                        approval_time = baninfo.get("unbanned_at", None)

                    approver = approver or _("a moderator")

                    if approval_time:
                        text = _("approved by %(who)s %(when)s ago") % {
                                    "who": approver,
                                    "when": timesince(approval_time)}
                    else:
                        text = _("approved by %s") % approver
                    w.approval_checkmark = text

        # recache the user object: it may be None if user is not logged in,
        # whereas now we are happy to have the UnloggedUser object
        user = c.user
        for cls in types.keys():
            cls.add_props(user, types[cls])

        return wrapped
Exemple #3
0
    def wrap_items(self, items):
        from r2.lib.db import queries
        from r2.lib.template_helpers import add_attr
        user = c.user if c.user_is_loggedin else None

        #get authors
        #TODO pull the author stuff into add_props for links and
        #comments and messages?

        aids = set(l.author_id for l in items
                   if hasattr(l, 'author_id') and l.author_id is not None)

        authors = {}
        cup_infos = {}
        email_attrses = {}
        friend_rels = None
        if aids:
            authors = Account._byID(aids, True) if aids else {}
            cup_infos = Account.cup_info_multi(aids)
            if c.user_is_admin:
                email_attrses = admintools.email_attrs(aids, return_dict=True)
            if c.user.gold:
                friend_rels = c.user.friend_rels()

        subreddits = Subreddit.load_subreddits(items)

        if not user:
            can_ban_set = set()
        else:
            can_ban_set = set(id for (id, sr) in subreddits.iteritems()
                              if sr.can_ban(user))

        #get likes/dislikes
        likes = queries.get_likes(user, items)
        uid = user._id if user else None

        types = {}
        wrapped = []
        count = 0

        modlink = {}
        modlabel = {}
        for s in subreddits.values():
            modlink[s._id] = '/r/%s/about/moderators' % s.name
            modlabel[s._id] = (
                _('moderator of /r/%(reddit)s, speaking officially') %
                dict(reddit=s.name))

        for item in items:
            w = self.wrap(item)
            wrapped.append(w)
            # add for caching (plus it should be bad form to use _
            # variables in templates)
            w.fullname = item._fullname
            types.setdefault(w.render_class, []).append(w)

            #TODO pull the author stuff into add_props for links and
            #comments and messages?
            w.author = None
            w.friend = False

            # List of tuples (see add_attr() for details)
            w.attribs = []

            w.distinguished = None
            if hasattr(item, "distinguished"):
                if item.distinguished == 'yes':
                    w.distinguished = 'moderator'
                elif item.distinguished == 'admin':
                    w.distinguished = 'admin'

            try:
                w.author = authors.get(item.author_id)
                if user and item.author_id in user.friends:
                    # deprecated old way:
                    w.friend = True

                    # new way:
                    label = None
                    if friend_rels:
                        rel = friend_rels[item.author_id]
                        note = getattr(rel, "note", None)
                        if note:
                            label = "%s (%s)" % (_("friend"), note)
                    add_attr(w.attribs, 'F', label)

            except AttributeError:
                pass

            if (w.distinguished == 'admin' and w.author
                    and w.author.name in g.admins):
                add_attr(w.attribs, 'A')

            if w.distinguished == 'moderator':
                add_attr(w.attribs,
                         'M',
                         label=modlabel[item.sr_id],
                         link=modlink[item.sr_id])

            if False and w.author and c.user_is_admin:
                for attr in email_attrses[w.author._id]:
                    add_attr(w.attribs, attr[2], label=attr[1])

            if w.author and w.author._id in cup_infos and not c.profilepage:
                cup_info = cup_infos[w.author._id]
                label = _(cup_info["label_template"]) % \
                        {'user':w.author.name}
                add_attr(w.attribs,
                         'trophy:' + cup_info["img_url"],
                         label=label,
                         link="/user/%s" % w.author.name)

            if hasattr(item, "sr_id") and item.sr_id is not None:
                w.subreddit = subreddits[item.sr_id]

            w.likes = likes.get((user, item))

            # update vote tallies
            compute_votes(w, item)

            w.score = w.upvotes - w.downvotes

            if w.likes:
                base_score = w.score - 1
            elif w.likes is None:
                base_score = w.score
            else:
                base_score = w.score + 1

            # store the set of available scores based on the vote
            # for ease of i18n when there is a label
            w.voting_score = [(base_score + x - 1) for x in range(3)]

            w.deleted = item._deleted

            w.link_notes = []

            if c.user_is_admin:
                if item._deleted:
                    w.link_notes.append("deleted link")
                if getattr(item, "verdict", None):
                    if not item.verdict.endswith("-approved"):
                        w.link_notes.append(w.verdict)

            w.rowstyle = getattr(w, 'rowstyle', "")
            w.rowstyle += ' ' + ('even' if (count % 2) else 'odd')

            count += 1

            if c.user_is_admin and getattr(item, 'ip', None):
                w.ip_span = ip_span(item.ip)
            else:
                w.ip_span = ""

            # if the user can ban things on a given subreddit, or an
            # admin, then allow them to see that the item is spam, and
            # add the other spam-related display attributes
            w.show_reports = False
            w.show_spam = False
            w.can_ban = False
            w.reveal_trial_info = False
            w.use_big_modbuttons = False

            if (c.user_is_admin or (user and hasattr(item, 'sr_id')
                                    and item.sr_id in can_ban_set)):
                if getattr(item, "promoted", None) is None:
                    w.can_ban = True

                ban_info = getattr(item, 'ban_info', {})
                w.unbanner = ban_info.get('unbanner')

                if item._spam:
                    w.show_spam = True
                    w.moderator_banned = ban_info.get('moderator_banned',
                                                      False)
                    w.autobanned = ban_info.get('auto', False)
                    w.banner = ban_info.get('banner')
                    w.use_big_modbuttons = True
                    if getattr(w, "author", None) and w.author._spam:
                        w.show_spam = "author"

                elif getattr(item, 'reported', 0) > 0:
                    w.show_reports = True
                    w.use_big_modbuttons = True

        # recache the user object: it may be None if user is not logged in,
        # whereas now we are happy to have the UnloggedUser object
        user = c.user
        for cls in types.keys():
            cls.add_props(user, types[cls])

        return wrapped
Exemple #4
0
    def wrap_items(self, items):
        from r2.lib.db import queries
        from r2.lib.template_helpers import add_attr

        user = c.user if c.user_is_loggedin else None

        # get authors
        # TODO pull the author stuff into add_props for links and
        # comments and messages?

        aids = set(l.author_id for l in items if hasattr(l, "author_id") and l.author_id is not None)

        authors = {}
        cup_infos = {}
        email_attrses = {}
        friend_rels = None
        if aids:
            authors = Account._byID(aids, data=True, stale=self.stale) if aids else {}
            cup_infos = Account.cup_info_multi(aids)
            if c.user_is_admin:
                email_attrses = admintools.email_attrs(aids, return_dict=True)
            if user and user.gold:
                friend_rels = user.friend_rels()

        subreddits = Subreddit.load_subreddits(items, stale=self.stale)

        if not user:
            can_ban_set = set()
        else:
            can_ban_set = set(id for (id, sr) in subreddits.iteritems() if sr.can_ban(user))

        # get likes/dislikes
        likes = queries.get_likes(user, items)
        uid = user._id if user else None

        types = {}
        wrapped = []
        count = 0

        modlink = {}
        modlabel = {}
        for s in subreddits.values():
            modlink[s._id] = "/r/%s/about/moderators" % s.name
            modlabel[s._id] = _("moderator of /r/%(reddit)s, speaking officially") % dict(reddit=s.name)

        for item in items:
            w = self.wrap(item)
            wrapped.append(w)
            # add for caching (plus it should be bad form to use _
            # variables in templates)
            w.fullname = item._fullname
            types.setdefault(w.render_class, []).append(w)

            # TODO pull the author stuff into add_props for links and
            # comments and messages?
            w.author = None
            w.friend = False

            # List of tuples (see add_attr() for details)
            w.attribs = []

            w.distinguished = None
            if hasattr(item, "distinguished"):
                if item.distinguished == "yes":
                    w.distinguished = "moderator"
                elif item.distinguished in ("admin", "special"):
                    w.distinguished = item.distinguished

            try:
                w.author = authors.get(item.author_id)
                if user and item.author_id in user.friends:
                    # deprecated old way:
                    w.friend = True

                    # new way:
                    label = None
                    if friend_rels:
                        rel = friend_rels[item.author_id]
                        note = getattr(rel, "note", None)
                        if note:
                            label = u"%s (%s)" % (_("friend"), _force_unicode(note))
                    add_attr(w.attribs, "F", label)

            except AttributeError:
                pass

            if w.distinguished == "admin" and w.author:
                add_attr(w.attribs, "A")

            if w.distinguished == "moderator":
                add_attr(w.attribs, "M", label=modlabel[item.sr_id], link=modlink[item.sr_id])

            if w.distinguished == "special":
                args = w.author.special_distinguish()
                args.pop("name")
                if not args.get("kind"):
                    args["kind"] = "special"
                add_attr(w.attribs, **args)

            if False and w.author and c.user_is_admin:
                for attr in email_attrses[w.author._id]:
                    add_attr(w.attribs, attr[2], label=attr[1])

            if w.author and w.author._id in cup_infos and not c.profilepage:
                cup_info = cup_infos[w.author._id]
                label = _(cup_info["label_template"]) % {"user": w.author.name}
                add_attr(w.attribs, "trophy:" + cup_info["img_url"], label=label, link="/user/%s" % w.author.name)

            if hasattr(item, "sr_id") and item.sr_id is not None:
                w.subreddit = subreddits[item.sr_id]

            w.likes = likes.get((user, item))

            # update vote tallies
            compute_votes(w, item)

            w.score = w.upvotes - w.downvotes

            if w.likes:
                base_score = w.score - 1
            elif w.likes is None:
                base_score = w.score
            else:
                base_score = w.score + 1

            # store the set of available scores based on the vote
            # for ease of i18n when there is a label
            w.voting_score = [(base_score + x - 1) for x in range(3)]

            w.deleted = item._deleted

            w.link_notes = []

            if c.user_is_admin:
                if item._deleted:
                    w.link_notes.append("deleted link")
                if getattr(item, "verdict", None):
                    if not item.verdict.endswith("-approved"):
                        w.link_notes.append(w.verdict)

            w.rowstyle = getattr(w, "rowstyle", "")
            w.rowstyle += " " + ("even" if (count % 2) else "odd")

            count += 1

            if c.user_is_admin and getattr(item, "ip", None):
                w.ip_span = ip_span(item.ip)
            else:
                w.ip_span = ""

            # if the user can ban things on a given subreddit, or an
            # admin, then allow them to see that the item is spam, and
            # add the other spam-related display attributes
            w.show_reports = False
            w.show_spam = False
            w.can_ban = False
            w.reveal_trial_info = False
            w.use_big_modbuttons = False

            if c.user_is_admin or (user and hasattr(item, "sr_id") and item.sr_id in can_ban_set):
                if getattr(item, "promoted", None) is None:
                    w.can_ban = True

                ban_info = getattr(item, "ban_info", {})
                w.unbanner = ban_info.get("unbanner")

                if item._spam:
                    w.show_spam = True
                    w.moderator_banned = ban_info.get("moderator_banned", False)
                    w.autobanned = ban_info.get("auto", False)
                    w.banner = ban_info.get("banner")
                    if ban_info.get("note", None) and w.banner:
                        w.banner += " (%s)" % ban_info["note"]
                    w.use_big_modbuttons = True
                    if getattr(w, "author", None) and w.author._spam:
                        w.show_spam = "author"

                elif getattr(item, "reported", 0) > 0:
                    w.show_reports = True
                    w.use_big_modbuttons = True

        # recache the user object: it may be None if user is not logged in,
        # whereas now we are happy to have the UnloggedUser object
        user = c.user
        for cls in types.keys():
            cls.add_props(user, types[cls])

        return wrapped
Exemple #5
0
    def wrap_items(self, items):
        from r2.lib.template_helpers import add_attr
        user = c.user if c.user_is_loggedin else None

        #get authors
        #TODO pull the author stuff into add_props for links and
        #comments and messages?

        try:
            aids = set(l.author_id for l in items)
        except AttributeError:
            aids = None

        authors = Account._byID(aids, True) if aids else {}
        # srids = set(l.sr_id for l in items if hasattr(l, "sr_id"))
        subdiggs = Subreddit.load_subreddits(items)

        if not user:
            can_ban_set = set()
        else:
            can_ban_set = set(id for (id,sr) in subdiggs.iteritems()
                              if sr.can_ban(user))

        #get likes/dislikes
        #TODO Vote.likes should accept empty lists
        likes = Vote.likes(user, items) if user and items else {}

        uid = user._id if user else None

        types = {}
        wrapped = []
        count = 0

        if isinstance(c.site, FakeSubdigg):
            mods = []
        else:
            mods = c.site.moderators
            modlink = ''
            if c.cname:
                modlink = '/about/moderators'
            else:
                modlink = '/r/%s/about/moderators' % c.site.name

            modlabel = (_('moderator of /r/%(digg)s, speaking officially') %
                        dict(digg = c.site.name) )


        for item in items:
            w = self.wrap(item)
            wrapped.append(w)
            # add for caching (plus it should be bad form to use _
            # variables in templates)
            w.fullname = item._fullname
            types.setdefault(w.render_class, []).append(w)

            #TODO pull the author stuff into add_props for links and
            #comments and messages?
            w.author = None
            w.friend = False

            # List of tuples (see add_attr() for details)
            w.attribs = []

            w.distinguished = None
            if hasattr(item, "distinguished"):
                if item.distinguished == 'yes':
                    w.distinguished = 'moderator'
                elif item.distinguished == 'admin':
                    w.distinguished = 'admin'

            try:
                w.author = authors.get(item.author_id)
                if user and item.author_id in user.friends:
                        # deprecated old way:
                        w.friend = True
                        # new way:
                        add_attr(w.attribs, 'F')

            except AttributeError:
                pass

            if (w.distinguished == 'admin' and
                w.author and w.author.name in g.admins):
                add_attr(w.attribs, 'A')

            if (w.distinguished == 'moderator' and
                getattr(item, "author_id", None) in mods):
                add_attr(w.attribs, 'M', label=modlabel, link=modlink)

            if (g.show_awards and w.author
                              and w.author.should_show_cup()):
                add_attr(w.attribs, 'trophy', label=
                    _("%(user)s recently won a trophy! click here to see it.")
                         % {'user':w.author.name},
                     link = "/user/%s" % w.author.name)

            if hasattr(item, "sr_id"):
                w.subdigg = subreddits[item.sr_id]

            vote = likes.get((user, item))
            if vote:
                w.likes = (True if vote._name == '1'
                             else False if vote._name == '-1'
                             else None)
            else:
                w.likes = None


            # update vote tallies
            compute_votes(w, item)
            
            w.score = w.upvotes - w.downvotes
            if w.likes:
                base_score = w.score - 1
            elif w.likes is None:
                base_score = w.score
            else:
                base_score = w.score + 1
            # store the set of available scores based on the vote
            # for ease of i18n when there is a label
            w.voting_score = [(base_score + x - 1) for x in range(3)]

            w.deleted = item._deleted

            w.rowstyle = getattr(w, 'rowstyle', "")
            w.rowstyle += ' ' + ('even' if (count % 2) else 'odd')

            count += 1

            if c.user_is_admin and getattr(item, 'ip', None):
                w.ip_span = ip_span(item.ip)
            else:
                w.ip_span = ""

            # if the user can ban things on a given subdigg, or an
            # admin, then allow them to see that the item is spam, and
            # add the other spam-related display attributes
            w.show_reports = False
            w.show_spam    = False
            w.can_ban      = False
            if (c.user_is_admin
                or (user
                    and hasattr(item,'sr_id')
                    and item.sr_id in can_ban_set)):
                w.can_ban = True
                if item._spam:
                    w.show_spam = True
                    ban_info = getattr(item, 'ban_info', {})
                    w.moderator_banned = ban_info.get('moderator_banned', False)
                    w.autobanned = ban_info.get('auto', False)
                    w.banner = ban_info.get('banner')

                elif getattr(item, 'reported', 0) > 0:
                    w.show_reports = True

        # recache the user object: it may be None if user is not logged in,
        # whereas now we are happy to have the UnloggedUser object
        user = c.user
        for cls in types.keys():
            cls.add_props(user, types[cls])

        return wrapped
Exemple #6
0
    def wrap_items(self, items):
        from r2.lib.db import queries
        from r2.lib.template_helpers import add_attr
        user = c.user if c.user_is_loggedin else None

        #get authors
        #TODO pull the author stuff into add_props for links and
        #comments and messages?

        aids = set(l.author_id for l in items if hasattr(l, 'author_id')
                   and l.author_id is not None)

        if aids:
            authors = Account._byID(aids, True) if aids else {}
            cup_infos = Account.cup_info_multi(aids)
            email_attrses = admintools.email_attrs(aids, return_dict=True)
        else:
            authors = {}
            cup_infos = {}
            email_attrses = {}

        # srids = set(l.sr_id for l in items if hasattr(l, "sr_id"))
        subreddits = Subreddit.load_subreddits(items)

        if not user:
            can_ban_set = set()
        else:
            can_ban_set = set(id for (id,sr) in subreddits.iteritems()
                              if sr.can_ban(user))

        #get likes/dislikes
        likes = queries.get_likes(user, items)
        uid = user._id if user else None

        types = {}
        wrapped = []
        count = 0

        modlink = {}
        modlabel = {}
        for s in subreddits.values():
            modlink[s._id] = '/r/%s/about/moderators' % s.name
            modlabel[s._id] = (_('moderator of /r/%(reddit)s, speaking officially') %
                        dict(reddit = s.name) )


        for item in items:
            w = self.wrap(item)
            wrapped.append(w)
            # add for caching (plus it should be bad form to use _
            # variables in templates)
            w.fullname = item._fullname
            types.setdefault(w.render_class, []).append(w)

            #TODO pull the author stuff into add_props for links and
            #comments and messages?
            w.author = None
            w.friend = False

            # List of tuples (see add_attr() for details)
            w.attribs = []

            w.distinguished = None
            if hasattr(item, "distinguished"):
                if item.distinguished == 'yes':
                    w.distinguished = 'moderator'
                elif item.distinguished == 'admin':
                    w.distinguished = 'admin'

            try:
                w.author = authors.get(item.author_id)
                if user and item.author_id in user.friends:
                    # deprecated old way:
                    w.friend = True
                    # new way:
                    add_attr(w.attribs, 'F')

            except AttributeError:
                pass

            if (w.distinguished == 'admin' and
                w.author and w.author.name in g.admins):
                add_attr(w.attribs, 'A')

            if w.distinguished == 'moderator':
                add_attr(w.attribs, 'M', label=modlabel[item.sr_id],
                         link=modlink[item.sr_id])

            if False and w.author and c.user_is_admin:
                for attr in email_attrses[w.author._id]:
                    add_attr(w.attribs, attr[2], label=attr[1])

            if w.author and w.author._id in cup_infos and not c.profilepage:
                cup_info = cup_infos[w.author._id]
                label = _(cup_info["label_template"]) % \
                        {'user':w.author.name}
                add_attr(w.attribs, 'trophy:' + cup_info["img_url"],
                         label=label,
                         link = "/user/%s" % w.author.name)

            if hasattr(item, "sr_id") and item.sr_id is not None:
                w.subreddit = subreddits[item.sr_id]

            w.likes = likes.get((user, item))

            # update vote tallies
            compute_votes(w, item)

            w.score = w.upvotes - w.downvotes

            if w.likes:
                base_score = w.score - 1
            elif w.likes is None:
                base_score = w.score
            else:
                base_score = w.score + 1

            # store the set of available scores based on the vote
            # for ease of i18n when there is a label
            w.voting_score = [(base_score + x - 1) for x in range(3)]

            w.deleted = item._deleted

            w.link_notes = []

            if c.user_is_admin:
                if item._deleted:
                    w.link_notes.append("deleted link")
                if getattr(item, "verdict", None):
                    if not item.verdict.endswith("-approved"):
                        w.link_notes.append(w.verdict)

            w.rowstyle = getattr(w, 'rowstyle', "")
            w.rowstyle += ' ' + ('even' if (count % 2) else 'odd')

            count += 1

            if c.user_is_admin and getattr(item, 'ip', None):
                w.ip_span = ip_span(item.ip)
            else:
                w.ip_span = ""

            # if the user can ban things on a given subreddit, or an
            # admin, then allow them to see that the item is spam, and
            # add the other spam-related display attributes
            w.show_reports = False
            w.show_spam    = False
            w.can_ban      = False
            w.reveal_trial_info = False
            w.use_big_modbuttons = False

            if (c.user_is_admin
                or (user
                    and hasattr(item,'sr_id')
                    and item.sr_id in can_ban_set)):
                if getattr(item, "promoted", None) is None:
                    w.can_ban = True

                ban_info = getattr(item, 'ban_info', {})
                w.unbanner = ban_info.get('unbanner')

                if item._spam:
                    w.show_spam = True
                    w.moderator_banned = ban_info.get('moderator_banned', False)
                    w.autobanned = ban_info.get('auto', False)
                    w.banner = ban_info.get('banner')
                    w.use_big_modbuttons = True
                    if getattr(w, "author", None) and w.author._spam:
                        w.show_spam = "author"

                elif getattr(item, 'reported', 0) > 0:
                    w.show_reports = True
                    w.use_big_modbuttons = True


        # recache the user object: it may be None if user is not logged in,
        # whereas now we are happy to have the UnloggedUser object
        user = c.user
        for cls in types.keys():
            cls.add_props(user, types[cls])

        return wrapped