Beispiel #1
0
    def add_props(cls, user, wrapped):
        Link.add_props(user, wrapped)
        user_is_sponsor = c.user_is_sponsor
        try:
            if user_is_sponsor:
                promoted_by_ids = set(x.promoted_by
                                      for x in wrapped
                                      if hasattr(x,'promoted_by'))
                promoted_by_accounts = Account._byID(promoted_by_ids,
                                                     data=True)
            else:
                promoted_by_accounts = {}

        except NotFound:
            # since this is just cosmetic, we can skip it altogether
            # if one isn't found or is broken
            promoted_by_accounts = {}

        for item in wrapped:
            # these are potentially paid for placement
            item.nofollow = True
            item.user_is_sponsor = user_is_sponsor
            if item.promoted_by in promoted_by_accounts:
                item.promoted_by_name = promoted_by_accounts[item.promoted_by].name
            else:
                # keep the template from trying to read it
                item.promoted_by = None
        # Run this last
        Printable.add_props(user, wrapped)
Beispiel #2
0
    def add_props(cls, user, wrapped):
        names = ('subscriber', 'moderator', 'contributor')
        rels = (SRMember._fast_query(wrapped, [user], names) if c.user_is_loggedin else {})
        defaults = Subreddit.default_subreddits()
        for item in wrapped:
            if not user or not user.has_subscribed:
                item.subscriber = item._id in defaults
            else:
                item.subscriber = bool(rels.get((item, user, 'subscriber')))
            item.moderator = bool(rels.get((item, user, 'moderator')))
            item.contributor = bool(item.type != 'public' and
                                    (item.moderator or
                                     rels.get((item, user, 'contributor'))))
            item.score = item._ups
            # override "voting" score behavior (it will override the use of
            # item.score in builder.py to be ups-downs)
            item.likes = item.subscriber or None
            base_score = item.score - (1 if item.likes else 0)
            item.voting_score = [(base_score + x - 1) for x in range(3)]
            item.score_fmt = Score.subscribers

            #will seem less horrible when add_props is in pages.py
            from r2.lib.pages import UserText
            item.usertext = UserText(item, item.description)


        Printable.add_props(user, wrapped)
Beispiel #3
0
    def add_props(cls, user, wrapped):
        names = ('subscriber', 'moderator', 'contributor')
        rels = (SRMember._fast_query(wrapped, [user], names)
                if c.user_is_loggedin else {})
        defaults = Subreddit.default_subreddits()
        target = "_top" if c.cname else None
        for item in wrapped:
            if not user or not user.has_subscribed:
                item.subscriber = item._id in defaults
            else:
                item.subscriber = bool(rels.get((item, user, 'subscriber')))
            item.moderator = bool(rels.get((item, user, 'moderator')))
            item.contributor = bool(item.type != 'public'
                                    and (item.moderator or rels.get(
                                        (item, user, 'contributor'))))

            # Don't reveal revenue information via /r/lounge's subscribers
            if (g.lounge_reddit and item.name == g.lounge_reddit
                    and not c.user_is_admin):
                item._ups = 0

            item.score = item._ups

            # override "voting" score behavior (it will override the use of
            # item.score in builder.py to be ups-downs)
            item.likes = item.subscriber or None
            base_score = item.score - (1 if item.likes else 0)
            item.voting_score = [(base_score + x - 1) for x in range(3)]
            item.score_fmt = Score.subscribers

            #will seem less horrible when add_props is in pages.py
            from r2.lib.pages import UserText
            item.usertext = UserText(item, item.description, target=target)

        Printable.add_props(user, wrapped)
Beispiel #4
0
    def add_props(cls, user, wrapped):
        names = ("subscriber", "moderator", "contributor")
        rels = SRMember._fast_query(wrapped, [user], names) if c.user_is_loggedin else {}
        defaults = Subreddit.default_subreddits()
        for item in wrapped:
            if not user or not user.has_subscribed:
                item.subscriber = item._id in defaults
            else:
                item.subscriber = bool(rels.get((item, user, "subscriber")))
            item.moderator = bool(rels.get((item, user, "moderator")))
            item.contributor = bool(item.type != "public" and (item.moderator or rels.get((item, user, "contributor"))))

            # Don't reveal revenue information via /r/lounge's subscribers
            if g.lounge_reddit and item.name == g.lounge_reddit and not c.user_is_admin:
                item._ups = 0

            item.score = item._ups

            # override "voting" score behavior (it will override the use of
            # item.score in builder.py to be ups-downs)
            item.likes = item.subscriber or None
            base_score = item.score - (1 if item.likes else 0)
            item.voting_score = [(base_score + x - 1) for x in range(3)]
            item.score_fmt = Score.subscribers

            # will seem less horrible when add_props is in pages.py
            from r2.lib.pages import UserText

            item.usertext = UserText(item, item.description)

        Printable.add_props(user, wrapped)
Beispiel #5
0
    def wrapped_cache_key(wrapped, style):
        s = Printable.wrapped_cache_key(wrapped, style)
        if wrapped.promoted is not None:
            s.extend([getattr(wrapped, "promote_status", -1),
                      getattr(wrapped, "disable_comments", False),
                      getattr(wrapped, "media_override", False),
                      wrapped._date,
                      c.user_is_sponsor,
                      wrapped.url, repr(wrapped.title)])
        if style == "htmllite":
             s.extend([request.get.has_key('twocolumn'),
                       c.link_target])
        elif style == "xml":
            s.append(request.GET.has_key("nothumbs"))
        elif style == "compact":
            s.append(c.permalink_page)
        s.append(getattr(wrapped, 'media_object', {}))
        s.append(wrapped.flair_text)
        s.append(wrapped.flair_css_class)

        # if browsing a single subreddit, incorporate link flair position
        # in the key so 'flair' buttons show up appropriately for mods
        if hasattr(c.site, '_id'):
            s.append(c.site.link_flair_position)

        return s
Beispiel #6
0
    def wrapped_cache_key(wrapped, style):
        s = Printable.wrapped_cache_key(wrapped, style)
        if wrapped.promoted is not None:
            s.extend([getattr(wrapped, "promote_status", -1),
                      getattr(wrapped, "disable_comments", False),
                      getattr(wrapped, "media_override", False),
                      wrapped._date,
                      c.user_is_sponsor,
                      wrapped.url, repr(wrapped.title)])
        if style == "htmllite":
             s.extend([request.get.has_key('twocolumn'),
                       c.link_target])
        elif style == "xml":
            s.append(request.GET.has_key("nothumbs"))
        elif style == "compact":
            s.append(c.permalink_page)
        s.append(getattr(wrapped, 'media_object', {}))
        s.append(wrapped.flair_text)
        s.append(wrapped.flair_css_class)

        # if browsing a single subreddit, incorporate link flair position
        # in the key so 'flair' buttons show up appropriately for mods
        if hasattr(c.site, '_id'):
            s.append(c.site.link_flair_position)

        return s
Beispiel #7
0
    def add_props(cls, user, wrapped):
        Link.add_props(user, wrapped)
        user_is_sponsor = c.user_is_sponsor

        status_dict = dict((v, k) for k, v in PROMOTE_STATUS.iteritems())
        for item in wrapped:
            # these are potentially paid for placement
            item.nofollow = True
            item.user_is_sponsor = user_is_sponsor
            status = getattr(item, "promote_status", -1)
            if item.is_author or c.user_is_sponsor:
                item.rowstyle = "link " + PROMOTE_STATUS.name[status].lower()
            else:
                item.rowstyle = "link promoted"
        # Run this last
        Printable.add_props(user, wrapped)
Beispiel #8
0
 def wrapped_cache_key(wrapped, style):
     s = Printable.wrapped_cache_key(wrapped, style)
     if style == "htmllite":
          s.append(request.get.has_key('twocolumn'))
     elif style == "xml":
         s.append(request.GET.has_key("nothumbs"))
     s.append(getattr(wrapped, 'media_object', {}))
     return s
Beispiel #9
0
    def add_props(cls, user, wrapped):
        #TODO global-ish functions that shouldn't be here?
        #reset msgtime after this request
        msgtime = c.have_messages
        
        #load the "to" field if required
        to_ids = set(w.to_id for w in wrapped)
        tos = Account._byID(to_ids, True) if to_ids else {}

        for item in wrapped:
            item.to = tos[item.to_id]
            if msgtime and item._date >= msgtime:
                item.new = True
            else:
                item.new = False
            item.score_fmt = Score.none
        # Run this last
        Printable.add_props(user, wrapped)
Beispiel #10
0
    def add_props(cls, user, wrapped):
        # prevents cyclic dependencies
        from r2.lib import promote
        Link.add_props(user, wrapped)
        user_is_sponsor = c.user_is_sponsor

        status_dict = dict((v, k) for k, v in promote.STATUS.iteritems())
        for item in wrapped:
            # these are potentially paid for placement
            item.nofollow = True
            item.user_is_sponsor = user_is_sponsor
            status = getattr(item, "promote_status", -1)
            if item.is_author or c.user_is_sponsor:
                item.rowstyle = "link " + promote.STATUS.name[status].lower()
            else:
                item.rowstyle = "link promoted"
        # Run this last
        Printable.add_props(user, wrapped)
Beispiel #11
0
    def add_props(cls, user, wrapped):
        names = ('subscriber', 'moderator', 'contributor')
        rels = (SRMember._fast_query(wrapped, [user], names) if c.user_is_loggedin else {})
        defaults = Subreddit.default_subreddits()
        target = "_top" if c.cname else None
        for item in wrapped:
            if not user or not user.has_subscribed:
                item.subscriber = item._id in defaults
            else:
                item.subscriber = bool(rels.get((item, user, 'subscriber')))
            item.moderator = bool(rels.get((item, user, 'moderator')))
            item.contributor = bool(item.type != 'public' and
                                    (item.moderator or
                                     rels.get((item, user, 'contributor'))))

            # Don't reveal revenue information via /r/lounge's subscribers
            if (g.lounge_reddit and item.name == g.lounge_reddit
                and not c.user_is_admin):
                item._ups = 0

            item.score = item._ups

            # override "voting" score behavior (it will override the use of
            # item.score in builder.py to be ups-downs)
            item.likes = item.subscriber or None
            base_score = item.score - (1 if item.likes else 0)
            item.voting_score = [(base_score + x - 1) for x in range(3)]
            item.score_fmt = Score.subscribers

            #will seem less horrible when add_props is in pages.py
            from r2.lib.pages import UserText
            item.description_usertext = UserText(item, item.description, target=target)
            if item.public_description or item.description:
                text = (item.public_description or
                        summarize_markdown(item.description))
                item.public_description_usertext = UserText(item,
                                                            text,
                                                            target=target)
            else:
                item.public_description_usertext = None


        Printable.add_props(user, wrapped)
Beispiel #12
0
    def add_props(cls, user, wrapped):
        #TODO global-ish functions that shouldn't be here?
        #reset msgtime after this request
        msgtime = c.have_messages
        
        #load the "to" field if required
        to_ids = set(w.to_id for w in wrapped)
        tos = Account._byID(to_ids, True) if to_ids else {}
        links = Link._byID(set(l.link_id for l in wrapped if l.was_comment),
                           data = True,
                           return_dict = True)
        subreddits = Subreddit._byID(set(l.sr_id for l in links.values()),
                                     data = True, return_dict = True)
        parents = Comment._byID(set(l.parent_id for l in wrapped
                                  if hasattr(l, "parent_id") and l.was_comment),
                                data = True, return_dict = True)

        for item in wrapped:
            item.to = tos[item.to_id]
            if msgtime and item._date >= msgtime:
                item.new = True
            else:
                item.new = False
            item.score_fmt = Score.none

            item.message_style = ""
            if item.was_comment:
                link = links[item.link_id]
                sr = subreddits[link.sr_id]
                item.link_title = link.title
                item.link_permalink = link.make_permalink(sr)
                if hasattr(item, "parent_id"):
                    item.subject = _('comment reply')
                    item.message_style = "comment-reply"
                    parent = parents[item.parent_id]
                    item.parent = parent._fullname
                    item.parent_permalink = parent.make_permalink(link, sr)
                else:
                    item.subject = _('post reply')
                    item.message_style = "post-reply"

        # Run this last
        Printable.add_props(user, wrapped)
Beispiel #13
0
 def add_props(cls, user, wrapped):
     names = ('subscriber', 'moderator', 'contributor')
     rels = (SRMember._fast_query(wrapped, [user], names) if c.user_is_loggedin else {})
     defaults = Subreddit.default_subreddits()
     for item in wrapped:
         if not user or not user.has_subscribed:
             item.subscriber = item._id in defaults
         else:
             item.subscriber = bool(rels.get((item, user, 'subscriber')))
         item.moderator = bool(rels.get((item, user, 'moderator')))
         item.contributor = bool(item.moderator or \
                                 rels.get((item, user, 'contributor')))
         item.score = item._ups
         # override "voting" score behavior (it will override the use of
         # item.score in builder.py to be ups-downs)
         item.likes = item.subscriber or None
         base_score = item.score - (1 if item.likes else 0)
         item.voting_score = [(base_score + x - 1) for x in range(3)]
         item.score_fmt = Score.subscribers
     Printable.add_props(user, wrapped)
Beispiel #14
0
 def wrapped_cache_key(wrapped, style):
     s = Printable.wrapped_cache_key(wrapped, style)
     if wrapped.promoted is not None:
         s.extend([getattr(wrapped, "promote_status", -1),
                   getattr(wrapped, "disable_comments", False),
                   wrapped._date,
                   c.user_is_sponsor,
                   wrapped.url, repr(wrapped.title)])
     if style == "htmllite":
          s.extend([request.get.has_key('twocolumn'),
                    c.link_target])
     elif style == "xml":
         s.append(request.GET.has_key("nothumbs"))
     s.append(getattr(wrapped, 'media_object', {}))
     return s
Beispiel #15
0
 def wrapped_cache_key(wrapped, style):
     s = Printable.wrapped_cache_key(wrapped, style)
     if wrapped.promoted is not None:
         s.extend([
             getattr(wrapped, "promote_status", -1),
             getattr(wrapped, "disable_comments", False), wrapped._date,
             c.user_is_sponsor, wrapped.url,
             repr(wrapped.title)
         ])
     if style == "htmllite":
         s.extend([request.get.has_key('twocolumn'), c.link_target])
     elif style == "xml":
         s.append(request.GET.has_key("nothumbs"))
     s.append(getattr(wrapped, 'media_object', {}))
     return s
Beispiel #16
0
 def wrapped_cache_key(wrapped, style):
     s = Printable.wrapped_cache_key(wrapped, style)
     s.extend([wrapped.new, wrapped.collapsed])
     return s
Beispiel #17
0
    def add_props(cls, user, wrapped):
        from r2.lib.db import queries
        #TODO global-ish functions that shouldn't be here?
        #reset msgtime after this request
        msgtime = c.have_messages

        # make sure there is a sr_id set:
        for w in wrapped:
            if not hasattr(w, "sr_id"):
                w.sr_id = None

        # load the to fields if one exists
        to_ids = set(w.to_id for w in wrapped if w.to_id is not None)
        tos = Account._byID(to_ids, True) if to_ids else {}

        # load the subreddit field if one exists:
        sr_ids = set(w.sr_id for w in wrapped if w.sr_id is not None)
        m_subreddits = Subreddit._byID(sr_ids, data=True, return_dict=True)

        # load the links and their subreddits (if comment-as-message)
        links = Link._byID(set(l.link_id for l in wrapped if l.was_comment),
                           data=True,
                           return_dict=True)
        # subreddits of the links (for comment-as-message)
        l_subreddits = Subreddit._byID(set(l.sr_id for l in links.values()),
                                       data=True,
                                       return_dict=True)

        parents = Comment._byID(set(l.parent_id for l in wrapped
                                    if l.parent_id and l.was_comment),
                                data=True,
                                return_dict=True)

        # load the inbox relations for the messages to determine new-ness
        # TODO: query cache?
        inbox = Inbox._fast_query(c.user,
                                  [item.lookups[0] for item in wrapped],
                                  ['inbox', 'selfreply'])

        # we don't care about the username or the rel name
        inbox = dict(
            (m._fullname, v) for (u, m, n), v in inbox.iteritems() if v)

        msgs = filter(lambda x: isinstance(x.lookups[0], Message), wrapped)

        modinbox = ModeratorInbox._fast_query(m_subreddits.values(), msgs,
                                              ['inbox'])

        # best to not have to eager_load the things
        def make_message_fullname(mid):
            return "t%s_%s" % (utils.to36(Message._type_id), utils.to36(mid))

        modinbox = dict((make_message_fullname(v._thing2_id), v)
                        for (u, m, n), v in modinbox.iteritems() if v)

        for item in wrapped:
            item.to = tos.get(item.to_id)
            if item.sr_id:
                item.recipient = (item.author_id != c.user._id)
            else:
                item.recipient = (item.to_id == c.user._id)

            # new-ness is stored on the relation
            if item.author_id == c.user._id:
                item.new = False
            elif item._fullname in inbox:
                item.new = getattr(inbox[item._fullname], "new", False)
                # wipe new messages if preferences say so, and this isn't a feed
                # and it is in the user's personal inbox
                if (item.new and c.user.pref_mark_messages_read
                        and c.extension not in ("rss", "xml", "api", "json")):
                    queries.set_unread(inbox[item._fullname]._thing2, c.user,
                                       False)
            elif item._fullname in modinbox:
                item.new = getattr(modinbox[item._fullname], "new", False)
            else:
                item.new = False

            item.score_fmt = Score.none

            item.message_style = ""
            # comment as message:
            if item.was_comment:
                link = links[item.link_id]
                sr = l_subreddits[link.sr_id]
                item.to_collapse = False
                item.author_collapse = False
                item.link_title = link.title
                item.link_permalink = link.make_permalink(sr)
                if item.parent_id:
                    item.subject = _('comment reply')
                    item.message_style = "comment-reply"
                    parent = parents[item.parent_id]
                    item.parent = parent._fullname
                    item.parent_permalink = parent.make_permalink(link, sr)
                else:
                    item.subject = _('post reply')
                    item.message_style = "post-reply"
            elif item.sr_id is not None:
                item.subreddit = m_subreddits[item.sr_id]

            if c.user.pref_no_profanity:
                item.subject = profanity_filter(item.subject)

            item.is_collapsed = None
            if not item.new:
                if item.recipient:
                    item.is_collapsed = item.to_collapse
                if item.author_id == c.user._id:
                    item.is_collapsed = item.author_collapse
                if c.user.pref_collapse_read_messages:
                    item.is_collapsed = (item.is_collapsed is not False)

        # Run this last
        Printable.add_props(user, wrapped)
Beispiel #18
0
    def add_props(cls, user, wrapped):
        from r2.lib.template_helpers import add_attr
        from r2.lib import promote
        from r2.lib.wrapped import CachedVariable

        # fetch parent links
        links = Link._byID(set(l.link_id for l in wrapped), data=True, return_dict=True, stale=True)

        # get srs for comments that don't have them (old comments)
        for cm in wrapped:
            if not hasattr(cm, "sr_id"):
                cm.sr_id = links[cm.link_id].sr_id

        subreddits = Subreddit._byID(set(cm.sr_id for cm in wrapped), data=True, return_dict=False, stale=True)
        cids = dict((w._id, w) for w in wrapped)
        parent_ids = set(cm.parent_id for cm in wrapped if getattr(cm, "parent_id", None) and cm.parent_id not in cids)
        parents = {}
        if parent_ids:
            parents = Comment._byID(parent_ids, data=True, stale=True)

        can_reply_srs = set(s._id for s in subreddits if s.can_comment(user)) if c.user_is_loggedin else set()
        can_reply_srs.add(promote.get_promote_srid())

        min_score = user.pref_min_comment_score

        profilepage = c.profilepage
        user_is_admin = c.user_is_admin
        user_is_loggedin = c.user_is_loggedin
        focal_comment = c.focal_comment

        for item in wrapped:
            # for caching:
            item.profilepage = c.profilepage
            item.link = links.get(item.link_id)

            if item.link._score <= 1 or item.score < 3 or item.link._spam or item._spam or item.author._spam:
                item.nofollow = True
            else:
                item.nofollow = False

            if not hasattr(item, "subreddit"):
                item.subreddit = item.subreddit_slow
            if item.author_id == item.link.author_id and not item.link._deleted:
                add_attr(item.attribs, "S", link=item.link.make_permalink(item.subreddit))
            if not hasattr(item, "target"):
                item.target = None
            if item.parent_id:
                if item.parent_id in cids:
                    item.parent_permalink = "#" + utils.to36(item.parent_id)
                else:
                    parent = parents[item.parent_id]
                    item.parent_permalink = parent.make_permalink(item.link, item.subreddit)
            else:
                item.parent_permalink = None

            item.can_reply = False
            if c.can_reply or (item.sr_id in can_reply_srs):
                age = c.start_time - item._date
                if age.days < g.REPLY_AGE_LIMIT:
                    item.can_reply = True

            # not deleted on profile pages,
            # deleted if spam and not author or admin
            item.deleted = not profilepage and (
                item._deleted or (item._spam and item.author != user and not item.show_spam)
            )

            extra_css = ""
            if item.deleted:
                extra_css += "grayed"
                if not user_is_admin:
                    item.author = DeletedUser()
                    item.body = "[deleted]"

            if focal_comment == item._id36:
                extra_css += " border"

            # don't collapse for admins, on profile pages, or if deleted
            item.collapsed = (item.score < min_score) and not (profilepage or item.deleted or user_is_admin)

            item.editted = getattr(item, "editted", False)

            item.render_css_class = "comment %s" % CachedVariable("time_period")

            # will get updated in builder
            item.num_children = 0
            item.score_fmt = Score.points
            item.permalink = item.make_permalink(item.link, item.subreddit)

            item.is_author = user == item.author
            item.is_focal = focal_comment == item._id36

            # will seem less horrible when add_props is in pages.py
            from r2.lib.pages import UserText

            item.usertext = UserText(
                item,
                item.body,
                editable=item.is_author,
                nofollow=item.nofollow,
                target=item.target,
                extra_css=extra_css,
            )
        # Run this last
        Printable.add_props(user, wrapped)
Beispiel #19
0
    def add_props(cls, user, wrapped):
        from r2.lib.pages import make_link_child
        from r2.lib.count import incr_counts
        from r2.lib.media import thumbnail_url
        from r2.lib.utils import timeago
        from r2.lib.template_helpers import get_domain
        from r2.models.subreddit import FakeSubreddit
        from r2.lib.wrapped import CachedVariable

        # referencing c's getattr is cheap, but not as cheap when it
        # is in a loop that calls it 30 times on 25-200 things.
        user_is_admin = c.user_is_admin
        user_is_loggedin = c.user_is_loggedin
        pref_media = user.pref_media
        pref_frame = user.pref_frame
        pref_newwindow = user.pref_newwindow
        cname = c.cname
        site = c.site

        saved = Link._saved(user, wrapped) if user_is_loggedin else {}
        hidden = Link._hidden(user, wrapped) if user_is_loggedin else {}
        trials = trial_info(wrapped)

        #clicked = Link._clicked(user, wrapped) if user else {}
        clicked = {}

        for item in wrapped:
            show_media = False
            if not hasattr(item, "score_fmt"):
                item.score_fmt = Score.number_only
            item.pref_compress = user.pref_compress
            if user.pref_compress and item.promoted is None:
                item.render_css_class = "compressed link"
                item.score_fmt = Score.points
            elif pref_media == 'on' and not user.pref_compress:
                show_media = True
            elif pref_media == 'subreddit' and item.subreddit.show_media:
                show_media = True
            elif item.promoted and item.has_thumbnail:
                if user_is_loggedin and item.author_id == user._id:
                    show_media = True
                elif pref_media != 'off' and not user.pref_compress:
                    show_media = True

            item.over_18 = bool(item.over_18 or item.subreddit.over_18
                                or item._nsfw.findall(item.title))
            item.nsfw = item.over_18 and user.pref_label_nsfw

            if user.pref_no_profanity and item.over_18 and not c.site.over_18:
                item.thumbnail = ""
            elif not show_media:
                item.thumbnail = ""
            elif item.has_thumbnail:
                item.thumbnail = thumbnail_url(item)
            elif item.is_self:
                item.thumbnail = g.self_thumb
            else:
                item.thumbnail = g.default_thumb

            item.score = max(0, item.score)

            item.domain = (domain(item.url) if not item.is_self else 'self.' +
                           item.subreddit.name)
            item.urlprefix = ''
            item.saved = bool(saved.get((user, item, 'save')))
            item.hidden = bool(hidden.get((user, item, 'hide')))
            item.clicked = bool(clicked.get((user, item, 'click')))
            item.num = None
            item.permalink = item.make_permalink(item.subreddit)
            if item.is_self:
                item.url = item.make_permalink(item.subreddit,
                                               force_domain=True)

            # do we hide the score?
            if user_is_admin:
                item.hide_score = False
            elif item.promoted and item.score <= 0:
                item.hide_score = True
            elif user == item.author:
                item.hide_score = False
            elif item._date > timeago("2 hours"):
                item.hide_score = True
            else:
                item.hide_score = False

            # store user preferences locally for caching
            item.pref_frame = pref_frame
            item.newwindow = pref_newwindow
            # is this link a member of a different (non-c.site) subreddit?
            item.different_sr = (isinstance(site, FakeSubreddit)
                                 or site.name != item.subreddit.name)

            if user_is_loggedin and item.author_id == user._id:
                item.nofollow = False
            elif item.score <= 1 or item._spam or item.author._spam:
                item.nofollow = True
            else:
                item.nofollow = False

            if c.user.pref_no_profanity:
                item.title = profanity_filter(item.title)

            item.subreddit_path = item.subreddit.path
            if cname:
                item.subreddit_path = ("http://" + get_domain(
                    cname=(site == item.subreddit), subreddit=False))
                if site != item.subreddit:
                    item.subreddit_path += item.subreddit.path
            item.domain_path = "/domain/%s" % item.domain
            if item.is_self:
                item.domain_path = item.subreddit_path

            # attach video or selftext as needed
            item.link_child, item.editable = make_link_child(item)

            item.tblink = "http://%s/tb/%s" % (get_domain(
                cname=cname, subreddit=False), item._id36)

            if item.is_self:
                item.href_url = item.permalink
            else:
                item.href_url = item.url

            # show the toolbar if the preference is set and the link
            # is neither a promoted link nor a self post
            if pref_frame and not item.is_self and not item.promoted:
                item.mousedown_url = item.tblink
            else:
                item.mousedown_url = None

            item.fresh = not any((item.likes != None, item.saved, item.clicked,
                                  item.hidden, item._deleted, item._spam))

            item.is_author = (user == item.author)

            # bits that we will render stubs (to make the cached
            # version more flexible)
            item.num = CachedVariable("num")
            item.numcolmargin = CachedVariable("numcolmargin")
            item.commentcls = CachedVariable("commentcls")
            item.midcolmargin = CachedVariable("midcolmargin")
            item.comment_label = CachedVariable("numcomments")

            item.as_deleted = False
            if item.deleted and not c.user_is_admin:
                item.author = DeletedUser()
                item.as_deleted = True

            item.trial_info = trials.get(item._fullname, None)

            item.approval_checkmark = None

            if item.can_ban:
                verdict = getattr(item, "verdict", None)
                if verdict in ('admin-approved', 'mod-approved'):
                    approver = None
                    if getattr(item, "ban_info", None):
                        approver = item.ban_info.get("unbanner", None)

                    if approver:
                        item.approval_checkmark = _(
                            "approved by %s") % approver
                    else:
                        item.approval_checkmark = _("approved by a moderator")

                if item.trial_info is not None:
                    item.reveal_trial_info = True
                    item.use_big_modbuttons = True

        if user_is_loggedin:
            incr_counts(wrapped)

        # Run this last
        Printable.add_props(user, wrapped)
Beispiel #20
0
    def add_props(cls, user, wrapped):
        from r2.lib.pages import make_link_child
        from r2.lib.count import incr_counts
        from r2.lib import media
        from r2.lib.utils import timeago
        from r2.lib.template_helpers import get_domain
        from r2.models.subreddit import FakeSubreddit
        from r2.lib.wrapped import CachedVariable

        # referencing c's getattr is cheap, but not as cheap when it
        # is in a loop that calls it 30 times on 25-200 things.
        user_is_admin = c.user_is_admin
        user_is_loggedin = c.user_is_loggedin
        pref_media = user.pref_media
        pref_frame = user.pref_frame
        pref_newwindow = user.pref_newwindow
        cname = c.cname
        site = c.site

        if user_is_loggedin:
            saved_lu = []
            for item in wrapped:
                if not SaveHide._can_skip_lookup(user, item):
                    saved_lu.append(item._id36)

            saved = CassandraSave._fast_query(user._id36, saved_lu)
            hidden = CassandraHide._fast_query(user._id36, saved_lu)

            clicked = {}
        else:
            saved = hidden = clicked = {}

        trials = trial_info(wrapped)

        for item in wrapped:
            show_media = False
            if not hasattr(item, "score_fmt"):
                item.score_fmt = Score.number_only
            if c.render_style == 'compact':
                item.score_fmt = Score.points
            item.pref_compress = user.pref_compress
            if user.pref_compress and item.promoted is None:
                item.render_css_class = "compressed link"
                item.score_fmt = Score.points
            elif pref_media == 'on' and not user.pref_compress:
                show_media = True
            elif pref_media == 'subreddit' and item.subreddit.show_media:
                show_media = True
            elif item.promoted and item.has_thumbnail:
                if user_is_loggedin and item.author_id == user._id:
                    show_media = True
                elif pref_media != 'off' and not user.pref_compress:
                    show_media = True

            item.nsfw_str = item._nsfw.findall(item.title)
            item.over_18 = bool(item.over_18 or item.subreddit.over_18
                                or item.nsfw_str)
            item.nsfw = item.over_18 and user.pref_label_nsfw

            item.is_author = (user == item.author)

            item.thumbnail_sprited = False
            # always show a promo author their own thumbnail
            if item.promoted and (user_is_admin
                                  or item.is_author) and item.has_thumbnail:
                item.thumbnail = media.thumbnail_url(item)
            elif user.pref_no_profanity and item.over_18 and not c.site.over_18:
                if show_media:
                    item.thumbnail = "nsfw"
                    item.thumbnail_sprited = True
                else:
                    item.thumbnail = ""
            elif not show_media:
                item.thumbnail = ""
            elif item.has_thumbnail:
                item.thumbnail = media.thumbnail_url(item)
            elif item.is_self:
                item.thumbnail = "self"
                item.thumbnail_sprited = True
            else:
                item.thumbnail = "default"
                item.thumbnail_sprited = True

            item.score = max(0, item.score)

            if getattr(item, "domain_override", None):
                item.domain = item.domain_override
            else:
                item.domain = (domain(item.url) if not item.is_self else
                               'self.' + item.subreddit.name)
            item.urlprefix = ''

            if user_is_loggedin:
                item.saved = (user._id36, item._id36) in saved
                item.hidden = (user._id36, item._id36) in hidden

                item.clicked = bool(clicked.get((user, item, 'click')))
            else:
                item.saved = item.hidden = item.clicked = False

            item.num = None
            item.permalink = item.make_permalink(item.subreddit)
            if item.is_self:
                item.url = item.make_permalink(item.subreddit,
                                               force_domain=True)

            if g.shortdomain:
                item.shortlink = g.shortdomain + '/' + item._id36

            # do we hide the score?
            if user_is_admin:
                item.hide_score = False
            elif item.promoted and item.score <= 0:
                item.hide_score = True
            elif user == item.author:
                item.hide_score = False


# TODO: uncomment to let gold users see the score of upcoming links
#            elif user.gold:
#                item.hide_score = False
            elif item._date > timeago("2 hours"):
                item.hide_score = True
            else:
                item.hide_score = False

            # store user preferences locally for caching
            item.pref_frame = pref_frame
            item.newwindow = pref_newwindow
            # is this link a member of a different (non-c.site) subreddit?
            item.different_sr = (isinstance(site, FakeSubreddit)
                                 or site.name != item.subreddit.name)

            if user_is_loggedin and item.author_id == user._id:
                item.nofollow = False
            elif item.score <= 1 or item._spam or item.author._spam:
                item.nofollow = True
            else:
                item.nofollow = False

            item.subreddit_path = item.subreddit.path
            if cname:
                item.subreddit_path = ("http://" + get_domain(
                    cname=(site == item.subreddit), subreddit=False))
                if site != item.subreddit:
                    item.subreddit_path += item.subreddit.path
            item.domain_path = "/domain/%s/" % item.domain
            if item.is_self:
                item.domain_path = item.subreddit_path

            # attach video or selftext as needed
            item.link_child, item.editable = make_link_child(item)

            item.tblink = "http://%s/tb/%s" % (get_domain(
                cname=cname, subreddit=False), item._id36)

            if item.is_self:
                item.href_url = item.permalink
            else:
                item.href_url = item.url

            # show the toolbar if the preference is set and the link
            # is neither a promoted link nor a self post
            if pref_frame and not item.is_self and not item.promoted:
                item.mousedown_url = item.tblink
            else:
                item.mousedown_url = None

            item.fresh = not any((item.likes != None, item.saved, item.clicked,
                                  item.hidden, item._deleted, item._spam))

            # bits that we will render stubs (to make the cached
            # version more flexible)
            item.num = CachedVariable("num")
            item.numcolmargin = CachedVariable("numcolmargin")
            item.commentcls = CachedVariable("commentcls")
            item.midcolmargin = CachedVariable("midcolmargin")
            item.comment_label = CachedVariable("numcomments")

            item.as_deleted = False
            if item.deleted and not c.user_is_admin:
                item.author = DeletedUser()
                item.as_deleted = True

            item.trial_info = trials.get(item._fullname, None)

            item.approval_checkmark = None

            item_age = datetime.now(g.tz) - item._date
            if item_age.days > g.VOTE_AGE_LIMIT and item.promoted is None:
                item.votable = False
            else:
                item.votable = True

            if item.can_ban:
                verdict = getattr(item, "verdict", None)
                if verdict in ('admin-approved', 'mod-approved'):
                    approver = None
                    if getattr(item, "ban_info", None):
                        approver = item.ban_info.get("unbanner", None)

                    if approver:
                        item.approval_checkmark = _(
                            "approved by %s") % approver
                    else:
                        item.approval_checkmark = _("approved by a moderator")

                if item.trial_info is not None:
                    item.reveal_trial_info = True
                    item.use_big_modbuttons = True

            item.expunged = False
            if item.is_self:
                item.expunged = Link._should_expunge_selftext(item)

        if user_is_loggedin:
            incr_counts(wrapped)

        # Run this last
        Printable.add_props(user, wrapped)
Beispiel #21
0
    def add_props(cls, user, wrapped):
        from r2.lib.template_helpers import add_attr
        from r2.lib import promote

        #fetch parent links

        links = Link._byID(set(l.link_id for l in wrapped), data = True,
                           return_dict = True)

        #get srs for comments that don't have them (old comments)
        for cm in wrapped:
            if not hasattr(cm, 'sr_id'):
                cm.sr_id = links[cm.link_id].sr_id

        subreddits = Subreddit._byID(set(cm.sr_id for cm in wrapped),
                                     data=True,return_dict=False)

        can_reply_srs = set(s._id for s in subreddits if s.can_comment(user)) \
                        if c.user_is_loggedin else set()
        can_reply_srs.add(promote.PromoteSR._id)

        min_score = user.pref_min_comment_score

        cids = dict((w._id, w) for w in wrapped)

        profilepage = c.profilepage
        user_is_admin = c.user_is_admin
        user_is_loggedin = c.user_is_loggedin
        focal_comment = c.focal_comment

        for item in wrapped:
            # for caching:
            item.profilepage = c.profilepage
            item.link = links.get(item.link_id)

            if (item.link._score <= 1 or item.score < 3 or
                item.link._spam or item._spam or item.author._spam):
                item.nofollow = True
            else:
                item.nofollow = False

            if not hasattr(item, 'subreddit'):
                item.subreddit = item.subreddit_slow
            if item.author_id == item.link.author_id:
                add_attr(item.attribs, 'S',
                         link = item.link.make_permalink(item.subreddit))
            if not hasattr(item, 'target'):
                item.target = None
            if hasattr(item, 'parent_id'):
                if cids.has_key(item.parent_id):
                    item.parent_permalink = '#' + utils.to36(item.parent_id)
                else:
                    parent = Comment._byID(item.parent_id)
                    item.parent_permalink = parent.make_permalink(item.link, item.subreddit)
            else:
                item.parent_permalink = None

            item.can_reply = (item.sr_id in can_reply_srs)


            # not deleted on profile pages,
            # deleted if spam and not author or admin
            item.deleted = (not profilepage and
                           (item._deleted or
                            (item._spam and
                             item.author != user and
                             not item.show_spam)))

            extra_css = ''
            if item.deleted:
                extra_css += "grayed"
                if not user_is_admin:
                    item.author = DeletedUser()
                    item.body = '[deleted]'


            if focal_comment == item._id36:
                extra_css += " border"


            # don't collapse for admins, on profile pages, or if deleted
            item.collapsed = ((item.score < min_score) and
                             not (profilepage or
                                  item.deleted or
                                  user_is_admin))

            item.editted = getattr(item, "editted", False)


            #will get updated in builder
            item.num_children = 0
            item.score_fmt = Score.points
            item.permalink = item.make_permalink(item.link, item.subreddit)

            item.is_author = (user == item.author)
            item.is_focal  = (focal_comment == item._id36)

            #will seem less horrible when add_props is in pages.py
            from r2.lib.pages import UserText
            item.usertext = UserText(item, item.body,
                                     editable = item.is_author,
                                     nofollow = item.nofollow,
                                     target = item.target,
                                     extra_css = extra_css)
        # Run this last
        Printable.add_props(user, wrapped)
Beispiel #22
0
    def add_props(cls, user, wrapped):
        from r2.lib.db import queries
        #TODO global-ish functions that shouldn't be here?
        #reset msgtime after this request
        msgtime = c.have_messages

        # make sure there is a sr_id set:
        for w in wrapped:
            if not hasattr(w, "sr_id"):
                w.sr_id = None

        # load the to fields if one exists
        to_ids = set(w.to_id for w in wrapped if w.to_id is not None)
        tos = Account._byID(to_ids, True) if to_ids else {}

        # load the subreddit field if one exists:
        sr_ids = set(w.sr_id for w in wrapped if w.sr_id is not None)
        m_subreddits = Subreddit._byID(sr_ids, data=True, return_dict=True)

        # load the links and their subreddits (if comment-as-message)
        links = Link._byID(
            set(l.link_id for l in wrapped if l.was_comment),
            data=True,
            return_dict=True)
        # subreddits of the links (for comment-as-message)
        l_subreddits = Subreddit._byID(
            set(l.sr_id for l in links.values()), data=True, return_dict=True)

        parents = Comment._byID(
            set(l.parent_id for l in wrapped if l.parent_id and l.was_comment),
            data=True,
            return_dict=True)

        # load the unread list to determine message newness
        unread = set(queries.get_unread_inbox(user))

        msg_srs = set(
            m_subreddits[x.sr_id] for x in wrapped
            if x.sr_id is not None and isinstance(x.lookups[0], Message))
        # load the unread mod list for the same reason
        mod_unread = set(
            queries.merge_results(
                *[queries.get_unread_subreddit_messages(sr)
                  for sr in msg_srs]))

        for item in wrapped:
            item.to = tos.get(item.to_id)
            if item.sr_id:
                item.recipient = (item.author_id != c.user._id)
            else:
                item.recipient = (item.to_id == c.user._id)

            # new-ness is stored on the relation
            if item.author_id == c.user._id:
                item.new = False
            elif item._fullname in unread:
                item.new = True
                # wipe new messages if preferences say so, and this isn't a feed
                # and it is in the user's personal inbox
                if (item.new and c.user.pref_mark_messages_read
                        and c.extension not in ("rss", "xml", "api", "json")):
                    queries.set_unread(item.lookups[0], c.user, False)
            else:
                item.new = (item._fullname in mod_unread)

            item.score_fmt = Score.none

            item.message_style = ""
            # comment as message:
            if item.was_comment:
                link = links[item.link_id]
                sr = l_subreddits[link.sr_id]
                item.to_collapse = False
                item.author_collapse = False
                item.link_title = link.title
                item.permalink = item.lookups[0].make_permalink(link, sr=sr)
                item.link_permalink = link.make_permalink(sr)
                if item.parent_id:
                    item.subject = _('comment reply')
                    item.message_style = "comment-reply"
                    parent = parents[item.parent_id]
                    item.parent = parent._fullname
                    item.parent_permalink = parent.make_permalink(link, sr)
                else:
                    item.subject = _('post reply')
                    item.message_style = "post-reply"
            elif item.sr_id is not None:
                item.subreddit = m_subreddits[item.sr_id]

            if c.user.pref_no_profanity:
                item.subject = profanity_filter(item.subject)

            item.is_collapsed = None
            if not item.new:
                if item.recipient:
                    item.is_collapsed = item.to_collapse
                if item.author_id == c.user._id:
                    item.is_collapsed = item.author_collapse
                if c.user.pref_collapse_read_messages:
                    item.is_collapsed = (item.is_collapsed is not False)

        # Run this last
        Printable.add_props(user, wrapped)
Beispiel #23
0
 def wrapped_cache_key(wrapped, style):
     s = Printable.wrapped_cache_key(wrapped, style)
     s.extend([c.msg_location])
     return s
Beispiel #24
0
    def add_props(cls, user, wrapped):
        from r2.lib.db import queries
        #TODO global-ish functions that shouldn't be here?
        #reset msgtime after this request
        msgtime = c.have_messages

        # make sure there is a sr_id set:
        for w in wrapped:
            if not hasattr(w, "sr_id"):
                w.sr_id = None

        # load the to fields if one exists
        to_ids = set(w.to_id for w in wrapped if w.to_id is not None)
        tos = Account._byID(to_ids, True) if to_ids else {}

        # load the subreddit field if one exists:
        sr_ids = set(w.sr_id for w in wrapped if w.sr_id is not None)
        m_subreddits = Subreddit._byID(sr_ids, data = True, return_dict = True)

        # load the links and their subreddits (if comment-as-message)
        links = Link._byID(set(l.link_id for l in wrapped if l.was_comment),
                           data = True,
                           return_dict = True)
        # subreddits of the links (for comment-as-message)
        l_subreddits = Subreddit._byID(set(l.sr_id for l in links.values()),
                                       data = True, return_dict = True)

        parents = Comment._byID(set(l.parent_id for l in wrapped
                                  if l.parent_id and l.was_comment),
                                data = True, return_dict = True)

        # load the unread list to determine message newness
        unread = set(queries.get_unread_inbox(user))

        msg_srs = set(m_subreddits[x.sr_id]
                      for x in wrapped if x.sr_id is not None
                      and isinstance(x.lookups[0], Message))
        # load the unread mod list for the same reason
        mod_unread = set(queries.get_unread_subreddit_messages_multi(msg_srs))

        for item in wrapped:
            item.to = tos.get(item.to_id)
            if item.sr_id:
                item.recipient = (item.author_id != c.user._id)
            else:
                item.recipient = (item.to_id == c.user._id)
            
            # new-ness is stored on the relation
            if item.author_id == c.user._id:
                item.new = False
            elif item._fullname in unread:
                item.new = True
                # wipe new messages if preferences say so, and this isn't a feed
                # and it is in the user's personal inbox
                if (item.new and c.user.pref_mark_messages_read
                    and c.extension not in ("rss", "xml", "api", "json")):
                    queries.set_unread(item.lookups[0],
                                       c.user, False)
            else:
                item.new = (item._fullname in mod_unread and not item.to_id)

            item.score_fmt = Score.none

            item.message_style = ""
            # comment as message:
            if item.was_comment:
                link = links[item.link_id]
                sr = l_subreddits[link.sr_id]
                item.to_collapse = False
                item.author_collapse = False
                item.link_title = link.title
                item.permalink = item.lookups[0].make_permalink(link, sr=sr)
                item.link_permalink = link.make_permalink(sr)
                if item.parent_id:
                    item.subject = _('comment reply')
                    item.message_style = "comment-reply"
                    parent = parents[item.parent_id]
                    item.parent = parent._fullname
                    item.parent_permalink = parent.make_permalink(link, sr)
                else:
                    item.subject = _('post reply')
                    item.message_style = "post-reply"
            elif item.sr_id is not None:
                item.subreddit = m_subreddits[item.sr_id]
            
            item.hide_author = False
            if getattr(item, "from_sr", False):
                if not (item.subreddit.is_moderator(c.user) or
                        c.user_is_admin):
                    item.author = item.subreddit
                    item.hide_author = True
            
            item.is_collapsed = None
            if not item.new:
                if item.recipient:
                    item.is_collapsed = item.to_collapse
                if item.author_id == c.user._id:
                    item.is_collapsed = item.author_collapse
                if c.user.pref_collapse_read_messages:
                    item.is_collapsed = (item.is_collapsed is not False)
            if item.author_id in c.user.enemies and not item.was_comment:
                item.is_collapsed = True
                if not c.user_is_admin:
                    item.subject = _('[message from blocked user]')
                    item.body = _('[unblock user to see this message]')
            taglinetext = ''
            if item.hide_author:
                taglinetext = _("subreddit message %(author)s sent %(when)s ago")
            elif item.author_id == c.user._id:
                taglinetext = _("to %(dest)s sent %(when)s ago")
            elif item.to_id == c.user._id or item.to_id is None:
                taglinetext = _("from %(author)s sent %(when)s ago")
            else:
                taglinetext = _("to %(dest)s from %(author)s sent %(when)s ago")
            item.taglinetext = taglinetext
            item.dest = item.to.name if item.to else ""
            if item.sr_id:
                if item.hide_author:
                    item.updated_author = _("via %(subreddit)s")
                else:
                    item.updated_author = _("%(author)s via %(subreddit)s")
            else:
                item.updated_author = ''


        # Run this last
        Printable.add_props(user, wrapped)
Beispiel #25
0
 def wrapped_cache_key(wrapped, style):
     s = Printable.wrapped_cache_key(wrapped, style)
     s.extend([wrapped._spam])
     return s
Beispiel #26
0
    def add_props(cls, user, wrapped):
        from r2.lib.template_helpers import add_attr, get_domain
        from r2.lib import promote
        from r2.lib.wrapped import CachedVariable
        from r2.lib.pages import WrappedUser

        #fetch parent links
        links = Link._byID(set(l.link_id for l in wrapped),
                           data=True,
                           return_dict=True,
                           stale=True)

        # fetch authors
        authors = Account._byID(set(l.author_id for l in links.values()),
                                data=True,
                                return_dict=True,
                                stale=True)

        #get srs for comments that don't have them (old comments)
        for cm in wrapped:
            if not hasattr(cm, 'sr_id'):
                cm.sr_id = links[cm.link_id].sr_id

        subreddits = Subreddit._byID(set(cm.sr_id for cm in wrapped),
                                     data=True,
                                     return_dict=False,
                                     stale=True)
        cids = dict((w._id, w) for w in wrapped)
        parent_ids = set(
            cm.parent_id for cm in wrapped
            if getattr(cm, 'parent_id', None) and cm.parent_id not in cids)
        parents = {}
        if parent_ids:
            parents = Comment._byID(parent_ids, data=True, stale=True)

        can_reply_srs = set(s._id for s in subreddits if s.can_comment(user)) \
                        if c.user_is_loggedin else set()
        can_reply_srs.add(promote.get_promote_srid())

        min_score = user.pref_min_comment_score

        profilepage = c.profilepage
        user_is_admin = c.user_is_admin
        user_is_loggedin = c.user_is_loggedin
        focal_comment = c.focal_comment
        cname = c.cname
        site = c.site

        for item in wrapped:
            # for caching:
            item.profilepage = c.profilepage
            item.link = links.get(item.link_id)

            if (item.link._score <= 1 or item.score < 3 or item.link._spam
                    or item._spam or item.author._spam):
                item.nofollow = True
            else:
                item.nofollow = False

            if not hasattr(item, 'subreddit'):
                item.subreddit = item.subreddit_slow
            if item.author_id == item.link.author_id and not item.link._deleted:
                add_attr(item.attribs,
                         'S',
                         link=item.link.make_permalink(item.subreddit))
            if not hasattr(item, 'target'):
                item.target = "_top" if cname else None
            if item.parent_id:
                if item.parent_id in cids:
                    item.parent_permalink = '#' + utils.to36(item.parent_id)
                else:
                    parent = parents[item.parent_id]
                    item.parent_permalink = parent.make_permalink(
                        item.link, item.subreddit)
            else:
                item.parent_permalink = None

            item.can_reply = False
            if c.can_reply or (item.sr_id in can_reply_srs):
                age = datetime.now(g.tz) - item._date
                if age.days < g.REPLY_AGE_LIMIT:
                    item.can_reply = True

            # not deleted on profile pages,
            # deleted if spam and not author or admin
            item.deleted = (
                not profilepage and
                (item._deleted or
                 (item._spam and item.author != user and not item.show_spam)))

            extra_css = ''
            if item.deleted:
                extra_css += "grayed"
                if not user_is_admin:
                    item.author = DeletedUser()
                    item.body = '[deleted]'

            if focal_comment == item._id36:
                extra_css += " border"

            if profilepage:
                item.link_author = WrappedUser(authors[item.link.author_id])

                item.subreddit_path = item.subreddit.path
                if cname:
                    item.subreddit_path = ("http://" + get_domain(
                        cname=(site == item.subreddit), subreddit=False))
                    if site != item.subreddit:
                        item.subreddit_path += item.subreddit.path

            item.full_comment_path = item.link.make_permalink(item.subreddit)

            # don't collapse for admins, on profile pages, or if deleted
            item.collapsed = False
            if ((item.score < min_score)
                    and not (profilepage or item.deleted or user_is_admin)):
                item.collapsed = True
                item.collapsed_reason = _("comment score below threshold")
            if user_is_loggedin and item.author_id in c.user.enemies:
                if "grayed" not in extra_css:
                    extra_css += " grayed"
                item.collapsed = True
                item.collapsed_reason = _("blocked user")

            item.editted = getattr(item, "editted", False)

            item.render_css_class = "comment %s" % CachedVariable(
                "time_period")

            #will get updated in builder
            item.num_children = 0
            item.score_fmt = Score.points
            item.permalink = item.make_permalink(item.link, item.subreddit)

            item.is_author = (user == item.author)
            item.is_focal = (focal_comment == item._id36)

            item_age = c.start_time - item._date
            if item_age.days > g.VOTE_AGE_LIMIT:
                item.votable = False
            else:
                item.votable = True

            #will seem less horrible when add_props is in pages.py
            from r2.lib.pages import UserText
            item.usertext = UserText(item,
                                     item.body,
                                     editable=item.is_author,
                                     nofollow=item.nofollow,
                                     target=item.target,
                                     extra_css=extra_css)
        # Run this last
        Printable.add_props(user, wrapped)
Beispiel #27
0
 def wrapped_cache_key(wrapped, style):
     s = Printable.wrapped_cache_key(wrapped, style)
     s.extend([wrapped.new, wrapped.collapsed])
     return s
Beispiel #28
0
 def add_props(cls, user, wrapped):
     Link.add_props(user, wrapped)
     for item in wrapped:
         item.rowstyle = "link ontrial"
     # Run this last
     Printable.add_props(user, wrapped)
Beispiel #29
0
    def add_props(cls, user, wrapped):
        from r2.lib.template_helpers import add_attr
        from r2.lib import promote
        #fetch parent links
        links = Link._byID(set(l.link_id for l in wrapped), data = True,
                           return_dict = True)

        #get srs for comments that don't have them (old comments)
        for cm in wrapped:
            if not hasattr(cm, 'sr_id'):
                cm.sr_id = links[cm.link_id].sr_id

        subreddits = Subreddit._byID(set(cm.sr_id for cm in wrapped),
                                     data=True,return_dict=False)
        cids = dict((w._id, w) for w in wrapped)
        parent_ids = set(cm.parent_id for cm in wrapped
                         if getattr(cm, 'parent_id', None)
                         and cm.parent_id not in cids)
        parents = {}
        if parent_ids:
            parents = Comment._byID(parent_ids, data=True)

        can_reply_srs = set(s._id for s in subreddits if s.can_comment(user)) \
                        if c.user_is_loggedin else set()
        can_reply_srs.add(promote.get_promote_srid())

        min_score = user.pref_min_comment_score

        profilepage = c.profilepage
        user_is_admin = c.user_is_admin
        user_is_loggedin = c.user_is_loggedin
        focal_comment = c.focal_comment

        for item in wrapped:
            # for caching:
            item.profilepage = c.profilepage
            item.link = links.get(item.link_id)

            if (item.link._score <= 1 or item.score < 3 or
                item.link._spam or item._spam or item.author._spam):
                item.nofollow = True
            else:
                item.nofollow = False

            if not hasattr(item, 'subreddit'):
                item.subreddit = item.subreddit_slow
            if item.author_id == item.link.author_id and not item.link._deleted:
                add_attr(item.attribs, 'S',
                         link = item.link.make_permalink(item.subreddit))
            if not hasattr(item, 'target'):
                item.target = None
            if item.parent_id:
                if item.parent_id in cids:
                    item.parent_permalink = '#' + utils.to36(item.parent_id)
                else:
                    parent = parents[item.parent_id]
                    item.parent_permalink = parent.make_permalink(item.link, item.subreddit)
            else:
                item.parent_permalink = None

            item.can_reply = False
            if c.can_reply or (item.sr_id in can_reply_srs):
                age = c.start_time - item._date
                if age.days < g.REPLY_AGE_LIMIT:
                    item.can_reply = True


            # not deleted on profile pages,
            # deleted if spam and not author or admin
            item.deleted = (not profilepage and
                           (item._deleted or
                            (item._spam and
                             item.author != user and
                             not item.show_spam)))

            extra_css = ''
            if item.deleted:
                extra_css += "grayed"
                if not user_is_admin:
                    item.author = DeletedUser()
                    item.body = '[deleted]'


            if focal_comment == item._id36:
                extra_css += " border"


            # don't collapse for admins, on profile pages, or if deleted
            item.collapsed = ((item.score < min_score) and
                             not (profilepage or
                                  item.deleted or
                                  user_is_admin))

            item.editted = getattr(item, "editted", False)


            #will get updated in builder
            item.num_children = 0
            item.score_fmt = Score.points
            item.permalink = item.make_permalink(item.link, item.subreddit)

            item.is_author = (user == item.author)
            item.is_focal  = (focal_comment == item._id36)

            #will seem less horrible when add_props is in pages.py
            from r2.lib.pages import UserText
            item.usertext = UserText(item, item.body,
                                     editable = item.is_author,
                                     nofollow = item.nofollow,
                                     target = item.target,
                                     extra_css = extra_css)
        # Run this last
        Printable.add_props(user, wrapped)
Beispiel #30
0
    def add_props(cls, user, wrapped):
        from r2.lib.pages import make_link_child
        from r2.lib.count import incr_counts
        from r2.lib.media import thumbnail_url
        from r2.lib.utils import timeago
        from r2.lib.template_helpers import get_domain
        from r2.models.subreddit import FakeSubreddit
        from r2.lib.wrapped import CachedVariable

        # referencing c's getattr is cheap, but not as cheap when it
        # is in a loop that calls it 30 times on 25-200 things.
        user_is_admin = c.user_is_admin
        user_is_loggedin = c.user_is_loggedin
        pref_media = user.pref_media
        pref_frame = user.pref_frame
        pref_newwindow = user.pref_newwindow
        cname = c.cname
        site = c.site

        if user_is_loggedin:
            saved_lu = []
            for item in wrapped:
                if not SaveHide._can_skip_lookup(user, item):
                    saved_lu.append(item._id36)

            saved = CassandraSave._fast_query(user._id36, saved_lu)
            hidden = CassandraHide._fast_query(user._id36, saved_lu)

            clicked = {}
        else:
            saved = hidden = clicked = {}

        trials = trial_info(wrapped)

        for item in wrapped:
            show_media = False
            if not hasattr(item, "score_fmt"):
                item.score_fmt = Score.number_only
            if c.render_style == 'compact':
                item.score_fmt = Score.points
            item.pref_compress = user.pref_compress
            if user.pref_compress and item.promoted is None:
                item.render_css_class = "compressed link"
                item.score_fmt = Score.points
            elif pref_media == 'on' and not user.pref_compress:
                show_media = True
            elif pref_media == 'subreddit' and item.subreddit.show_media:
                show_media = True
            elif item.promoted and item.has_thumbnail:
                if user_is_loggedin and item.author_id == user._id:
                    show_media = True
                elif pref_media != 'off' and not user.pref_compress:
                    show_media = True

            item.over_18 = bool(
                item.over_18 or item.subreddit.over_18
                or item._nsfw.findall(item.title))
            item.nsfw = item.over_18 and user.pref_label_nsfw

            item.is_author = (user == item.author)

            # always show a promo author their own thumbnail
            if item.promoted and (user_is_admin
                                  or item.is_author) and item.has_thumbnail:
                item.thumbnail = thumbnail_url(item)
            elif user.pref_no_profanity and item.over_18 and not c.site.over_18:
                if show_media:
                    item.thumbnail = "/static/nsfw2.png"
                else:
                    item.thumbnail = ""
            elif not show_media:
                item.thumbnail = ""
            elif item.has_thumbnail:
                item.thumbnail = thumbnail_url(item)
            elif item.is_self:
                item.thumbnail = g.self_thumb
            else:
                item.thumbnail = g.default_thumb

            item.score = max(0, item.score)

            if getattr(item, "domain_override", None):
                item.domain = item.domain_override
            else:
                item.domain = (domain(item.url) if not item.is_self else
                               'self.' + item.subreddit.name)
            item.urlprefix = ''

            if user_is_loggedin:
                item.saved = (user._id36, item._id36) in saved
                item.hidden = (user._id36, item._id36) in hidden

                item.clicked = bool(clicked.get((user, item, 'click')))
            else:
                item.saved = item.hidden = item.clicked = False

            item.num = None
            item.permalink = item.make_permalink(item.subreddit)
            if item.is_self:
                item.url = item.make_permalink(
                    item.subreddit, force_domain=True)

            if g.shortdomain:
                item.shortlink = g.shortdomain + '/' + item._id36

            # do we hide the score?
            if user_is_admin:
                item.hide_score = False
            elif item.promoted and item.score <= 0:
                item.hide_score = True
            elif user == item.author:
                item.hide_score = False


# TODO: uncomment to let gold users see the score of upcoming links
#            elif user.gold:
#                item.hide_score = False
            elif item._date > timeago("2 hours"):
                item.hide_score = True
            else:
                item.hide_score = False

            # store user preferences locally for caching
            item.pref_frame = pref_frame
            item.newwindow = pref_newwindow
            # is this link a member of a different (non-c.site) subreddit?
            item.different_sr = (isinstance(site, FakeSubreddit)
                                 or site.name != item.subreddit.name)

            if user_is_loggedin and item.author_id == user._id:
                item.nofollow = False
            elif item.score <= 1 or item._spam or item.author._spam:
                item.nofollow = True
            else:
                item.nofollow = False

            if c.user.pref_no_profanity:
                item.title = profanity_filter(item.title)

            item.subreddit_path = item.subreddit.path
            if cname:
                item.subreddit_path = ("http://" + get_domain(
                    cname=(site == item.subreddit), subreddit=False))
                if site != item.subreddit:
                    item.subreddit_path += item.subreddit.path
            item.domain_path = "/domain/%s/" % item.domain
            if item.is_self:
                item.domain_path = item.subreddit_path

            # attach video or selftext as needed
            item.link_child, item.editable = make_link_child(item)

            item.tblink = "http://%s/tb/%s" % (get_domain(
                cname=cname, subreddit=False), item._id36)

            if item.is_self:
                item.href_url = item.permalink
            else:
                item.href_url = item.url

            # show the toolbar if the preference is set and the link
            # is neither a promoted link nor a self post
            if pref_frame and not item.is_self and not item.promoted:
                item.mousedown_url = item.tblink
            else:
                item.mousedown_url = None

            item.fresh = not any((item.likes != None, item.saved, item.clicked,
                                  item.hidden, item._deleted, item._spam))

            # bits that we will render stubs (to make the cached
            # version more flexible)
            item.num = CachedVariable("num")
            item.numcolmargin = CachedVariable("numcolmargin")
            item.commentcls = CachedVariable("commentcls")
            item.midcolmargin = CachedVariable("midcolmargin")
            item.comment_label = CachedVariable("numcomments")

            item.as_deleted = False
            if item.deleted and not c.user_is_admin:
                item.author = DeletedUser()
                item.as_deleted = True

            item.trial_info = trials.get(item._fullname, None)

            item.approval_checkmark = None

            if item.can_ban:
                verdict = getattr(item, "verdict", None)
                if verdict in ('admin-approved', 'mod-approved'):
                    approver = None
                    if getattr(item, "ban_info", None):
                        approver = item.ban_info.get("unbanner", None)

                    if approver:
                        item.approval_checkmark = _(
                            "approved by %s") % approver
                    else:
                        item.approval_checkmark = _("approved by a moderator")

                if item.trial_info is not None:
                    item.reveal_trial_info = True
                    item.use_big_modbuttons = True

        if user_is_loggedin:
            incr_counts(wrapped)

        # Run this last
        Printable.add_props(user, wrapped)
    def add_props(cls, user, wrapped):
        names = ('subscriber', 'moderator', 'contributor')
        rels = (SRMember._fast_query(wrapped, [user], names) if c.user_is_loggedin else {})
        defaults = Subreddit.default_subreddits()
        target = "_top" if c.cname else None
        for item in wrapped:
            if not user or not user.has_subscribed:
                item.subscriber = item._id in defaults
            else:
                item.subscriber = bool(rels.get((item, user, 'subscriber')))
            item.moderator = bool(rels.get((item, user, 'moderator')))
            item.contributor = bool(item.type != 'public' and
                                    (item.moderator or
                                     rels.get((item, user, 'contributor'))))

            # Don't reveal revenue information via /space/lounge's subscribers
            if (g.lounge_reddit and item.name == g.lounge_reddit
                and not c.user_is_admin):
                item._ups = 0

            item.score = item._ups

            # override "voting" score behavior (it will override the use of
            # item.score in builder.py to be ups-downs)
            item.likes = item.subscriber or None
            base_score = item.score - (1 if item.likes else 0)
            item.voting_score = [(base_score + x - 1) for x in range(3)]
            item.score_fmt = Score.subscribers

            #will seem less horrible when add_props is in pages.py
            from r2.lib.pages import UserText
            item.description_usertext = UserText(item,
                                                 item.description,
                                                 have_form=False,
                                                 target=target,
                                                 extra_css = 'sidebar_description')
            if item.public_description or item.description:
                text = (item.public_description or
                        summarize_markdown(item.description))
                item.public_description_usertext = UserText(item,
                                                            text,
                                                            have_form=False,
                                                            target=target)
            else:
                item.public_description_usertext = None

            house_rules = '#### [](#h4-green)\n> ## [House Rules](#icon-information)\n'
            if not item.space_is_house:
                house_rules += '> (using house rules from **'
                house_rules += item.use_rules_from_space if item.use_rules_from_space else ""
                house_rules += '**)\n\n>&nbsp;\n\n>'
            house_rules += item.get_house_rules().replace('\n','\n\n>')

            item.house_rules_usertext = UserText(   item,
                                                    house_rules,
                                                    have_form=False,
                                                    target=target,
                                                    extra_css = 'sidebar_description')


        Printable.add_props(user, wrapped)
Beispiel #32
0
    def add_props(cls, user, wrapped):
        from r2.lib.count import incr_counts
        from r2.lib.media import thumbnail_url
        from r2.lib.utils import timeago
        from r2.lib.template_helpers import get_domain
        from r2.models.subreddit import FakeSubreddit
        from r2.lib.wrapped import CachedVariable

        # referencing c's getattr is cheap, but not as cheap when it
        # is in a loop that calls it 30 times on 25-200 things.
        user_is_admin = c.user_is_admin
        user_is_loggedin = c.user_is_loggedin
        pref_media = user.pref_media
        pref_frame = user.pref_frame
        pref_newwindow = user.pref_newwindow
        cname = c.cname
        site = c.site

        saved = Link._saved(user, wrapped) if user_is_loggedin else {}
        hidden = Link._hidden(user, wrapped) if user_is_loggedin else {}

        #clicked = Link._clicked(user, wrapped) if user else {}
        clicked = {}

        for item in wrapped:
            show_media = False
            if not hasattr(item, "score_fmt"):
                item.score_fmt = Score.number_only
            item.pref_compress = user.pref_compress
            if user.pref_compress and item.promoted is None:
                item.render_css_class = "compressed link"
                item.score_fmt = Score.points
            elif pref_media == 'on' and not user.pref_compress:
                show_media = True
            elif pref_media == 'subreddit' and item.subreddit.show_media:
                show_media = True
            elif item.promoted and item.has_thumbnail:
                if user_is_loggedin and item.author_id == user._id:
                    show_media = True
                elif pref_media != 'off' and not user.pref_compress:
                    show_media = True

            if not show_media:
                item.thumbnail = ""
            elif item.has_thumbnail:
                item.thumbnail = thumbnail_url(item)
            else:
                item.thumbnail = g.default_thumb

            item.score = max(0, item.score)

            item.domain = (domain(item.url) if not item.is_self
                          else 'self.' + item.subreddit.name)
            if not hasattr(item,'top_link'):
                item.top_link = False
            item.urlprefix = ''
            item.saved = bool(saved.get((user, item, 'save')))
            item.hidden = bool(hidden.get((user, item, 'hide')))
            item.clicked = bool(clicked.get((user, item, 'click')))
            item.num = None
            item.permalink = item.make_permalink(item.subreddit)
            if item.is_self:
                item.url = item.make_permalink(item.subreddit, force_domain = True)

            # do we hide the score?
            if user_is_admin:
                item.hide_score = False
            elif item.promoted:
                item.hide_score = True
            elif user == item.author:
                item.hide_score = False
            elif item._date > timeago("2 hours"):
                item.hide_score = True
            else:
                item.hide_score = False

            # store user preferences locally for caching
            item.pref_frame = pref_frame
            item.newwindow = pref_newwindow
            # is this link a member of a different (non-c.site) subreddit?
            item.different_sr = (isinstance(site, FakeSubreddit) or
                                 site.name != item.subreddit.name)

            if user_is_loggedin and item.author._id == user._id:
                item.nofollow = False
            elif item.score <= 1 or item._spam or item.author._spam:
                item.nofollow = True
            else:
                item.nofollow = False

            item.subreddit_path = item.subreddit.path
            if cname:
                item.subreddit_path = ("http://" + 
                     get_domain(cname = (site == item.subreddit),
                                subreddit = False))
                if site != item.subreddit:
                    item.subreddit_path += item.subreddit.path
            item.domain_path = "/domain/%s" % item.domain
            if item.is_self:
                item.domain_path = item.subreddit_path

            #this is wrong, but won't be so wrong when we move this
            #whole chunk of code into pages.py
            from r2.lib.pages import MediaChild, SelfTextChild
            item.link_child = None
            item.editable = False
            if item.media_object:
                item.link_child = MediaChild(item, load = True)
            elif item.selftext:
                expand = getattr(item, 'expand_children', False)
                item.link_child = SelfTextChild(item, expand = expand,
                                                nofollow = item.nofollow)
                #draw the edit button if the contents are pre-expanded
                item.editable = expand and item.author == c.user
               
            item.tblink = "http://%s/tb/%s" % (
                get_domain(cname = cname, subreddit=False),
                item._id36)

            if item.is_self:
                item.href_url = item.permalink
            else:
                item.href_url = item.url

            # show the toolbar if the preference is set and the link
            # is neither a promoted link nor a self post
            if pref_frame and not item.is_self and not item.promoted:
                item.mousedown_url = item.tblink
            else:
                item.mousedown_url = None

            item.fresh = not any((item.likes != None,
                                  item.saved,
                                  item.clicked,
                                  item.hidden,
                                  item._deleted,
                                  item._spam))

            item.is_author = (user == item.author)

            # bits that we will render stubs (to make the cached
            # version more flexible)
            item.num = CachedVariable("num")
            item.numcolmargin = CachedVariable("numcolmargin")
            item.commentcls = CachedVariable("commentcls")
            item.midcolmargin = CachedVariable("midcolmargin")
            item.comment_label = CachedVariable("numcomments")

        if user_is_loggedin:
            incr_counts(wrapped)

        # Run this last
        Printable.add_props(user, wrapped)
Beispiel #33
0
    def add_props(cls, user, wrapped):
        from r2.lib.db import queries
        #TODO global-ish functions that shouldn't be here?
        #reset msgtime after this request
        msgtime = c.have_messages

        # make sure there is a sr_id set:
        for w in wrapped:
            if not hasattr(w, "sr_id"):
                w.sr_id = None

        # load the to fields if one exists
        to_ids = set(w.to_id for w in wrapped if w.to_id is not None)
        tos = Account._byID(to_ids, True) if to_ids else {}

        # load the subreddit field if one exists:
        sr_ids = set(w.sr_id for w in wrapped if w.sr_id is not None)
        m_subreddits = Subreddit._byID(sr_ids, data=True, return_dict=True)

        # load the links and their subreddits (if comment-as-message)
        links = Link._byID(set(l.link_id for l in wrapped if l.was_comment),
                           data=True,
                           return_dict=True)
        # subreddits of the links (for comment-as-message)
        l_subreddits = Subreddit._byID(set(l.sr_id for l in links.values()),
                                       data=True,
                                       return_dict=True)

        parents = Comment._byID(set(l.parent_id for l in wrapped
                                    if l.parent_id and l.was_comment),
                                data=True,
                                return_dict=True)

        # load the unread list to determine message newness
        unread = set(queries.get_unread_inbox(user))

        msg_srs = set(
            m_subreddits[x.sr_id] for x in wrapped
            if x.sr_id is not None and isinstance(x.lookups[0], Message))
        # load the unread mod list for the same reason
        mod_unread = set(
            queries.merge_results(
                *[queries.get_unread_subreddit_messages(sr)
                  for sr in msg_srs]))

        for item in wrapped:
            item.to = tos.get(item.to_id)
            if item.sr_id:
                item.recipient = (item.author_id != c.user._id)
            else:
                item.recipient = (item.to_id == c.user._id)

            # new-ness is stored on the relation
            if item.author_id == c.user._id:
                item.new = False
            elif item._fullname in unread:
                item.new = True
                # wipe new messages if preferences say so, and this isn't a feed
                # and it is in the user's personal inbox
                if (item.new and c.user.pref_mark_messages_read
                        and c.extension not in ("rss", "xml", "api", "json")):
                    queries.set_unread(item.lookups[0], c.user, False)
            else:
                item.new = (item._fullname in mod_unread)

            item.score_fmt = Score.none

            item.message_style = ""
            # comment as message:
            if item.was_comment:
                link = links[item.link_id]
                sr = l_subreddits[link.sr_id]
                item.to_collapse = False
                item.author_collapse = False
                item.link_title = link.title
                item.permalink = item.lookups[0].make_permalink(link, sr=sr)
                item.link_permalink = link.make_permalink(sr)
                if item.parent_id:
                    item.subject = _('comment reply')
                    item.message_style = "comment-reply"
                    parent = parents[item.parent_id]
                    item.parent = parent._fullname
                    item.parent_permalink = parent.make_permalink(link, sr)
                else:
                    item.subject = _('post reply')
                    item.message_style = "post-reply"
            elif item.sr_id is not None:
                item.subreddit = m_subreddits[item.sr_id]

            item.is_collapsed = None
            if not item.new:
                if item.recipient:
                    item.is_collapsed = item.to_collapse
                if item.author_id == c.user._id:
                    item.is_collapsed = item.author_collapse
                if c.user.pref_collapse_read_messages:
                    item.is_collapsed = (item.is_collapsed is not False)
            if item.author_id in c.user.enemies and not item.was_comment:
                item.is_collapsed = True
                if not c.user_is_admin:
                    item.subject = _('[message from blocked user]')
                    item.body = _('[unblock user to see this message]')

        # Run this last
        Printable.add_props(user, wrapped)
Beispiel #34
0
    def add_props(cls, user, wrapped):
        from r2.lib.template_helpers import add_attr, get_domain
        from r2.lib import promote
        from r2.lib.wrapped import CachedVariable
        from r2.lib.pages import WrappedUser

        #fetch parent links
        links = Link._byID(set(l.link_id for l in wrapped), data = True,
                           return_dict = True, stale=True)

        # fetch authors
        authors = Account._byID(set(l.author_id for l in links.values()), data=True, 
                                return_dict=True, stale=True)

        #get srs for comments that don't have them (old comments)
        for cm in wrapped:
            if not hasattr(cm, 'sr_id'):
                cm.sr_id = links[cm.link_id].sr_id

        subreddits = Subreddit._byID(set(cm.sr_id for cm in wrapped),
                                     data=True, return_dict=False, stale=True)
        cids = dict((w._id, w) for w in wrapped)
        parent_ids = set(cm.parent_id for cm in wrapped
                         if getattr(cm, 'parent_id', None)
                         and cm.parent_id not in cids)
        parents = {}
        if parent_ids:
            parents = Comment._byID(parent_ids, data=True, stale=True)

        can_reply_srs = set(s._id for s in subreddits if s.can_comment(user)) \
                        if c.user_is_loggedin else set()
        can_reply_srs.add(promote.get_promote_srid())

        min_score = user.pref_min_comment_score

        profilepage = c.profilepage
        user_is_admin = c.user_is_admin
        user_is_loggedin = c.user_is_loggedin
        focal_comment = c.focal_comment
        cname = c.cname
        site = c.site

        for item in wrapped:
            # for caching:
            item.profilepage = c.profilepage
            item.link = links.get(item.link_id)

            if (item.link._score <= 1 or item.score < 3 or
                item.link._spam or item._spam or item.author._spam):
                item.nofollow = True
            else:
                item.nofollow = False

            if not hasattr(item, 'subreddit'):
                item.subreddit = item.subreddit_slow
            if item.author_id == item.link.author_id and not item.link._deleted:
                add_attr(item.attribs, 'S',
                         link = item.link.make_permalink(item.subreddit))
            if not hasattr(item, 'target'):
                item.target = "_top" if cname else None
            if item.parent_id:
                if item.parent_id in cids:
                    item.parent_permalink = '#' + utils.to36(item.parent_id)
                else:
                    parent = parents[item.parent_id]
                    item.parent_permalink = parent.make_permalink(item.link, item.subreddit)
            else:
                item.parent_permalink = None

            item.can_reply = False
            if c.can_reply or (item.sr_id in can_reply_srs):
                age = datetime.now(g.tz) - item._date
                if age.days < g.REPLY_AGE_LIMIT:
                    item.can_reply = True


            # not deleted on profile pages,
            # deleted if spam and not author or admin
            item.deleted = (not profilepage and
                           (item._deleted or
                            (item._spam and
                             item.author != user and
                             not item.show_spam)))

            extra_css = ''
            if item.deleted:
                extra_css += "grayed"
                if not user_is_admin:
                    item.author = DeletedUser()
                    item.body = '[deleted]'


            if focal_comment == item._id36:
                extra_css += " border"

            if profilepage:
                item.link_author = WrappedUser(authors[item.link.author_id])

                item.subreddit_path = item.subreddit.path
                if cname:
                    item.subreddit_path = ("http://" + 
                         get_domain(cname = (site == item.subreddit),
                                    subreddit = False))
                    if site != item.subreddit:
                        item.subreddit_path += item.subreddit.path

            item.full_comment_path = item.link.make_permalink(item.subreddit)

            # don't collapse for admins, on profile pages, or if deleted
            item.collapsed = False
            if ((item.score < min_score) and not (profilepage or
                item.deleted or user_is_admin)):
                item.collapsed = True
                item.collapsed_reason = _("comment score below threshold")
            if user_is_loggedin and item.author_id in c.user.enemies:
                if "grayed" not in extra_css:
                    extra_css += " grayed"
                item.collapsed = True
                item.collapsed_reason = _("blocked user")

            item.editted = getattr(item, "editted", False)

            item.render_css_class = "comment %s" % CachedVariable("time_period")

            #will get updated in builder
            item.num_children = 0
            item.score_fmt = Score.points
            item.permalink = item.make_permalink(item.link, item.subreddit)

            item.is_author = (user == item.author)
            item.is_focal  = (focal_comment == item._id36)

            item_age = c.start_time - item._date
            if item_age.days > g.VOTE_AGE_LIMIT:
                item.votable = False
            else:
                item.votable = True

            #will seem less horrible when add_props is in pages.py
            from r2.lib.pages import UserText
            item.usertext = UserText(item, item.body,
                                     editable = item.is_author,
                                     nofollow = item.nofollow,
                                     target = item.target,
                                     extra_css = extra_css)
        # Run this last
        Printable.add_props(user, wrapped)
Beispiel #35
0
 def add_props(cls, user, wrapped):
     Link.add_props(user, wrapped)
     for item in wrapped:
         item.rowstyle = "link ontrial"
     # Run this last
     Printable.add_props(user, wrapped)
Beispiel #36
0
    def add_props(cls, user, wrapped):
        from r2.lib.pages import make_link_child
        from r2.lib.count import incr_counts
        from r2.lib.media import thumbnail_url
        from r2.lib.utils import timeago
        from r2.lib.template_helpers import get_domain
        from r2.models.subreddit import FakeSubreddit
        from r2.lib.wrapped import CachedVariable

        # referencing c's getattr is cheap, but not as cheap when it
        # is in a loop that calls it 30 times on 25-200 things.
        user_is_admin = c.user_is_admin
        user_is_loggedin = c.user_is_loggedin
        pref_media = user.pref_media
        pref_frame = user.pref_frame
        pref_newwindow = user.pref_newwindow
        cname = c.cname
        site = c.site

        saved = Link._saved(user, wrapped) if user_is_loggedin else {}
        hidden = Link._hidden(user, wrapped) if user_is_loggedin else {}
        trials = trial_info(wrapped)

        # clicked = Link._clicked(user, wrapped) if user else {}
        clicked = {}

        for item in wrapped:
            show_media = False
            if not hasattr(item, "score_fmt"):
                item.score_fmt = Score.number_only
            item.pref_compress = user.pref_compress
            if user.pref_compress and item.promoted is None:
                item.render_css_class = "compressed link"
                item.score_fmt = Score.points
            elif pref_media == "on" and not user.pref_compress:
                show_media = True
            elif pref_media == "subreddit" and item.subreddit.show_media:
                show_media = True
            elif item.promoted and item.has_thumbnail:
                if user_is_loggedin and item.author_id == user._id:
                    show_media = True
                elif pref_media != "off" and not user.pref_compress:
                    show_media = True

            item.over_18 = bool(item.over_18 or item.subreddit.over_18 or item._nsfw.findall(item.title))
            item.nsfw = item.over_18 and user.pref_label_nsfw

            #            if user.pref_no_profanity and item.over_18 and not c.site.over_18:
            #                item.thumbnail = ""
            #            elif not show_media:
            #                item.thumbnail = ""
            #            elif item.has_thumbnail:
            #                item.thumbnail = thumbnail_url(item)
            #            elif item.is_self:
            #                item.thumbnail = g.self_thumb
            #            else:
            #                item.thumbnail = g.default_thumb

            if item.has_thumbnail:
                item.thumbnail = thumbnail_url(item)
            else:
                item.thumbnail = ""

            item.score = max(0, item.score)

            item.domain = domain(item.url) if not item.is_self else "self." + item.subreddit.name
            item.urlprefix = ""
            item.saved = bool(saved.get((user, item, "save")))
            item.hidden = bool(hidden.get((user, item, "hide")))
            item.clicked = bool(clicked.get((user, item, "click")))
            item.num = None
            item.permalink = item.make_permalink(item.subreddit)
            if item.is_self:
                item.url = item.make_permalink(item.subreddit, force_domain=True)

            # do we hide the score?
            if user_is_admin:
                item.hide_score = False
            elif item.promoted and item.score <= 0:
                item.hide_score = True
            elif user == item.author:
                item.hide_score = False
            elif item._date > timeago("2 hours"):
                item.hide_score = True
            else:
                item.hide_score = False

            # store user preferences locally for caching
            item.pref_frame = pref_frame
            item.newwindow = pref_newwindow
            # is this link a member of a different (non-c.site) subreddit?
            item.different_sr = isinstance(site, FakeSubreddit) or site.name != item.subreddit.name

            if user_is_loggedin and item.author_id == user._id:
                item.nofollow = False
            elif item.score <= 1 or item._spam or item.author._spam:
                item.nofollow = True
            else:
                item.nofollow = False

            if c.user.pref_no_profanity:
                item.title = profanity_filter(item.title)

            item.subreddit_path = item.subreddit.path
            if cname:
                item.subreddit_path = "http://" + get_domain(cname=(site == item.subreddit), subreddit=False)
                if site != item.subreddit:
                    item.subreddit_path += item.subreddit.path
            item.domain_path = "/domain/%s" % item.domain
            if item.is_self:
                item.domain_path = item.subreddit_path

            # attach video or selftext as needed
            item.link_child, item.editable = make_link_child(item)

            item.tblink = "http://%s/tb/%s" % (get_domain(cname=cname, subreddit=False), item._id36)

            if item.is_self:
                item.href_url = item.permalink
            else:
                item.href_url = item.url

            # show the toolbar if the preference is set and the link
            # is neither a promoted link nor a self post
            if pref_frame and not item.is_self and not item.promoted:
                item.mousedown_url = item.tblink
            else:
                item.mousedown_url = None

            item.fresh = not any((item.likes != None, item.saved, item.clicked, item.hidden, item._deleted, item._spam))

            item.is_author = user == item.author

            # bits that we will render stubs (to make the cached
            # version more flexible)
            item.num = CachedVariable("num")
            item.numcolmargin = CachedVariable("numcolmargin")
            item.commentcls = CachedVariable("commentcls")
            item.midcolmargin = CachedVariable("midcolmargin")
            item.comment_label = CachedVariable("numcomments")

            item.as_deleted = False
            if item.deleted and not c.user_is_admin:
                item.author = DeletedUser()
                item.as_deleted = True

            item.trial_info = trials.get(item._fullname, None)

            item.approval_checkmark = None

            if item.can_ban:
                verdict = getattr(item, "verdict", None)
                if verdict in ("admin-approved", "mod-approved"):
                    approver = None
                    if getattr(item, "ban_info", None):
                        approver = item.ban_info.get("unbanner", None)

                    if approver:
                        item.approval_checkmark = _("approved by %s") % approver
                    else:
                        item.approval_checkmark = _("approved by a moderator")

                if item.trial_info is not None:
                    item.reveal_trial_info = True
                    item.use_big_modbuttons = True

        if user_is_loggedin:
            incr_counts(wrapped)

        # Run this last
        Printable.add_props(user, wrapped)
Beispiel #37
0
    def add_props(cls, user, wrapped):
        from r2.lib.pages import make_link_child
        from r2.lib.count import incr_counts
        from r2.lib import media
        from r2.lib.utils import timeago
        from r2.lib.template_helpers import get_domain
        from r2.models.subreddit import FakeSubreddit
        from r2.lib.wrapped import CachedVariable

        # referencing c's getattr is cheap, but not as cheap when it
        # is in a loop that calls it 30 times on 25-200 things.
        user_is_admin = c.user_is_admin
        user_is_loggedin = c.user_is_loggedin
        pref_media = user.pref_media
        pref_frame = user.pref_frame
        pref_newwindow = user.pref_newwindow
        cname = c.cname
        site = c.site

        if user_is_loggedin:
            try:
                saved = CassandraSave._fast_query(user, wrapped)
                hidden = CassandraHide._fast_query(user, wrapped)
            except tdb_cassandra.TRANSIENT_EXCEPTIONS as e:
                g.log.warning("Cassandra save/hide lookup failed: %r", e)
                saved = hidden = {}

            clicked = {}
        else:
            saved = hidden = clicked = {}

        for item in wrapped:
            show_media = False
            if not hasattr(item, "score_fmt"):
                item.score_fmt = Score.number_only
            if c.render_style == 'compact':
                item.score_fmt = Score.points
            item.pref_compress = user.pref_compress
            if user.pref_compress and item.promoted is None:
                item.render_css_class = "compressed link"
                item.score_fmt = Score.points
            elif pref_media == 'on' and not user.pref_compress:
                show_media = True
            elif pref_media == 'subreddit' and item.subreddit.show_media:
                show_media = True
            elif item.promoted and item.has_thumbnail:
                if user_is_loggedin and item.author_id == user._id:
                    show_media = True
                elif pref_media != 'off' and not user.pref_compress:
                    show_media = True

            item.nsfw_str = item._nsfw.findall(item.title)
            item.over_18 = bool(item.over_18 or item.subreddit.over_18 or
                                item.nsfw_str)
            item.nsfw = item.over_18 and user.pref_label_nsfw

            item.is_author = (user == item.author)

            item.thumbnail_sprited = False
            # always show a promo author their own thumbnail
            if item.promoted and (user_is_admin or item.is_author) and item.has_thumbnail:
                item.thumbnail = media.thumbnail_url(item)
            elif user.pref_no_profanity and item.over_18 and not c.site.over_18:
                if show_media:
                    item.thumbnail = "nsfw"
                    item.thumbnail_sprited = True
                else:
                    item.thumbnail = ""
            elif not show_media:
                item.thumbnail = ""
            elif item.has_thumbnail:
                item.thumbnail = media.thumbnail_url(item)
            elif item.is_self:
                item.thumbnail = "self"
                item.thumbnail_sprited = True
            else:
                item.thumbnail = "default"
                item.thumbnail_sprited = True

            item.score = max(0, item.score)

            if getattr(item, "domain_override", None):
                item.domain = item.domain_override
            else:
                item.domain = (domain(item.url) if not item.is_self
                               else 'self.' + item.subreddit.name)
            item.urlprefix = ''

            if user_is_loggedin:
                item.saved = (user, item) in saved
                item.hidden = (user, item) in hidden

                item.clicked = bool(clicked.get((user, item, 'click')))
            else:
                item.saved = item.hidden = item.clicked = False

            item.num = None
            item.permalink = item.make_permalink(item.subreddit)
            if item.is_self:
                item.url = item.make_permalink(item.subreddit,
                                               force_domain=True)

            if g.shortdomain:
                item.shortlink = g.shortdomain + '/' + item._id36

            # do we hide the score?
            if user_is_admin:
                item.hide_score = False
            elif item.promoted and item.score <= 0:
                item.hide_score = True
            elif user == item.author:
                item.hide_score = False
# TODO: uncomment to let gold users see the score of upcoming links
#            elif user.gold:
#                item.hide_score = False
            elif item._date > timeago("2 hours"):
                item.hide_score = True
            else:
                item.hide_score = False

            # store user preferences locally for caching
            item.pref_frame = pref_frame
            item.newwindow = pref_newwindow
            # is this link a member of a different (non-c.site) subreddit?
            item.different_sr = (isinstance(site, FakeSubreddit) or
                                 site.name != item.subreddit.name)

            if user_is_loggedin and item.author_id == user._id:
                item.nofollow = False
            elif item.score <= 1 or item._spam or item.author._spam:
                item.nofollow = True
            else:
                item.nofollow = False

            item.subreddit_path = item.subreddit.path
            if cname:
                item.subreddit_path = ("http://" +
                     get_domain(cname=(site == item.subreddit),
                                subreddit=False))
                if site != item.subreddit:
                    item.subreddit_path += item.subreddit.path
            item.domain_path = "/domain/%s/" % item.domain
            if item.is_self:
                item.domain_path = item.subreddit_path

            # attach video or selftext as needed
            item.link_child, item.editable = make_link_child(item)

            item.tblink = "http://%s/tb/%s" % (
                get_domain(cname=cname, subreddit=False),
                item._id36)

            if item.is_self:
                item.href_url = item.permalink
            else:
                item.href_url = item.url

            # show the toolbar if the preference is set and the link
            # is neither a promoted link nor a self post
            if pref_frame and not item.is_self and not item.promoted:
                item.mousedown_url = item.tblink
            else:
                item.mousedown_url = None

            item.fresh = not any((item.likes != None,
                                  item.saved,
                                  item.clicked,
                                  item.hidden,
                                  item._deleted,
                                  item._spam))

            # bits that we will render stubs (to make the cached
            # version more flexible)
            item.num = CachedVariable("num")
            item.numcolmargin = CachedVariable("numcolmargin")
            item.commentcls = CachedVariable("commentcls")
            item.midcolmargin = CachedVariable("midcolmargin")
            item.comment_label = CachedVariable("numcomments")
            item.lastedited = CachedVariable("lastedited")

            item.as_deleted = False
            if item.deleted and not c.user_is_admin:
                item.author = DeletedUser()
                item.as_deleted = True

            item.approval_checkmark = None

            item_age = datetime.now(g.tz) - item._date
            if item_age.days > g.VOTE_AGE_LIMIT and item.promoted is None:
                item.votable = False
            else:
                item.votable = True

            if item.can_ban:
                verdict = getattr(item, "verdict", None)
                if verdict in ('admin-approved', 'mod-approved'):
                    approver = None
                    if getattr(item, "ban_info", None):
                        approver = item.ban_info.get("unbanner", None)

                    if approver:
                        item.approval_checkmark = _("approved by %s") % approver
                    else:
                        item.approval_checkmark = _("approved by a moderator")

            item.expunged = False
            if item.is_self:
                item.expunged = Link._should_expunge_selftext(item)

            item.editted = getattr(item, "editted", False)

            taglinetext = ''
            if item.different_sr:
                author_text = (" <span>" + _("by %(author)s to %(reddit)s") +
                               "</span>")
            else:
                author_text = " <span>" + _("by %(author)s") + "</span>"
            if item.editted:
                if item.score_fmt == Score.points:
                    taglinetext = ("<span>" +
                                   _("%(score)s submitted %(when)s "
                                     "ago%(lastedited)s") +
                                   "</span>")
                    taglinetext += author_text
                elif item.different_sr:
                    taglinetext = _("submitted %(when)s ago%(lastedited)s "
                                    "by %(author)s to %(reddit)s")
                else:
                    taglinetext = _("submitted %(when)s ago%(lastedited)s "
                                    "by %(author)s")
            else:
                if item.score_fmt == Score.points:
                    taglinetext = ("<span>" +
                                   _("%(score)s submitted %(when)s ago") +
                                   "</span>")
                    taglinetext += author_text
                elif item.different_sr:
                    taglinetext = _("submitted %(when)s ago by %(author)s "
                                    "to %(reddit)s")
                else:
                    taglinetext = _("submitted %(when)s ago by %(author)s")
            item.taglinetext = taglinetext

        if user_is_loggedin:
            incr_counts(wrapped)

        # Run this last
        Printable.add_props(user, wrapped)
Beispiel #38
0
 def wrapped_cache_key(wrapped, style):
     s = Printable.wrapped_cache_key(wrapped, style)
     s.extend([wrapped._spam])
     return s
Beispiel #39
0
    def add_props(cls, user, wrapped):
        from r2.lib.db import queries

        # TODO global-ish functions that shouldn't be here?
        # reset msgtime after this request
        msgtime = c.have_messages

        # make sure there is a sr_id set:
        for w in wrapped:
            if not hasattr(w, "sr_id"):
                w.sr_id = None

        # load the to fields if one exists
        to_ids = set(w.to_id for w in wrapped if w.to_id is not None)
        tos = Account._byID(to_ids, True) if to_ids else {}

        # load the subreddit field if one exists:
        sr_ids = set(w.sr_id for w in wrapped if w.sr_id is not None)
        m_subreddits = Subreddit._byID(sr_ids, data=True, return_dict=True)

        # load the links and their subreddits (if comment-as-message)
        links = Link._byID(set(l.link_id for l in wrapped if l.was_comment), data=True, return_dict=True)
        # subreddits of the links (for comment-as-message)
        l_subreddits = Subreddit._byID(set(l.sr_id for l in links.values()), data=True, return_dict=True)

        parents = Comment._byID(
            set(l.parent_id for l in wrapped if l.parent_id and l.was_comment), data=True, return_dict=True
        )

        # load the inbox relations for the messages to determine new-ness
        # TODO: query cache?
        inbox = Inbox._fast_query(c.user, [item.lookups[0] for item in wrapped], ["inbox", "selfreply"])

        # we don't care about the username or the rel name
        inbox = dict((m._fullname, v) for (u, m, n), v in inbox.iteritems() if v)

        msgs = filter(lambda x: isinstance(x.lookups[0], Message), wrapped)

        modinbox = ModeratorInbox._fast_query(m_subreddits.values(), msgs, ["inbox"])

        # best to not have to eager_load the things
        def make_message_fullname(mid):
            return "t%s_%s" % (utils.to36(Message._type_id), utils.to36(mid))

        modinbox = dict((make_message_fullname(v._thing2_id), v) for (u, m, n), v in modinbox.iteritems() if v)

        for item in wrapped:
            item.to = tos.get(item.to_id)
            if item.sr_id:
                item.recipient = item.author_id != c.user._id
            else:
                item.recipient = item.to_id == c.user._id

            # new-ness is stored on the relation
            if item.author_id == c.user._id:
                item.new = False
            elif item._fullname in inbox:
                item.new = getattr(inbox[item._fullname], "new", False)
                # wipe new messages if preferences say so, and this isn't a feed
                # and it is in the user's personal inbox
                if item.new and c.user.pref_mark_messages_read and c.extension not in ("rss", "xml", "api", "json"):
                    queries.set_unread(inbox[item._fullname]._thing2, c.user, False)
            elif item._fullname in modinbox:
                item.new = getattr(modinbox[item._fullname], "new", False)
            else:
                item.new = False

            item.score_fmt = Score.none

            item.message_style = ""
            # comment as message:
            if item.was_comment:
                link = links[item.link_id]
                sr = l_subreddits[link.sr_id]
                item.to_collapse = False
                item.author_collapse = False
                item.link_title = link.title
                item.link_permalink = link.make_permalink(sr)
                if item.parent_id:
                    item.subject = _("comment reply")
                    item.message_style = "comment-reply"
                    parent = parents[item.parent_id]
                    item.parent = parent._fullname
                    item.parent_permalink = parent.make_permalink(link, sr)
                else:
                    item.subject = _("post reply")
                    item.message_style = "post-reply"
            elif item.sr_id is not None:
                item.subreddit = m_subreddits[item.sr_id]

            if c.user.pref_no_profanity:
                item.subject = profanity_filter(item.subject)

            item.is_collapsed = None
            if not item.new:
                if item.recipient:
                    item.is_collapsed = item.to_collapse
                if item.author_id == c.user._id:
                    item.is_collapsed = item.author_collapse
                if c.user.pref_collapse_read_messages:
                    item.is_collapsed = item.is_collapsed is not False

        # Run this last
        Printable.add_props(user, wrapped)