Ejemplo n.º 1
0
    def listing(self, next_suggestions=None):
        self.things, prev, next, bcount, acount = self.get_items()

        self.next_suggestions = next_suggestions
        self._max_num = max(acount, bcount)
        self.after = None
        self.before = None

        if self.nextprev and self.prev_link and prev and bcount > 1:
            p = self.params.copy()
            p.update({'after':None, 'before':prev._fullname, 'count':bcount})
            self.before = prev._fullname
            self.prev = (request.path + utils.query_string(p))
            p_first = self.params.copy()
            p_first.update({'after':None, 'before':None, 'count':None})
            self.first = (request.path + utils.query_string(p_first))
        if self.nextprev and self.next_link and next:
            p = self.params.copy()
            p.update({'after':next._fullname, 'before':None, 'count':acount})
            self.after = next._fullname
            self.next = (request.path + utils.query_string(p))

        for count, thing in enumerate(self.things):
            thing.rowstyle_cls = getattr(thing, 'rowstyle_cls', "")
            thing.rowstyle_cls += ' ' + ('even' if (count % 2) else 'odd')
            thing.rowstyle = CachedVariable("rowstyle")

        #TODO: need name for template -- must be better way
        return Wrapped(self)
Ejemplo n.º 2
0
    def add_props(cls, user, wrapped):
        from r2.lib.wrapped import CachedVariable
        for item in wrapped:
            # insert replacement variable for timesince to allow for
            # caching of thing templates
            item.display = CachedVariable("display")
            item.timesince = CachedVariable("timesince")
            item.votehash = CachedVariable("votehash")
            item.childlisting = CachedVariable("childlisting")

            score_fmt = getattr(item, "score_fmt", Score.number_only)
            item.display_score = map(score_fmt, item.voting_score)

            if item.cachable:
                item.render_score = item.display_score
                item.display_score = map(
                    CachedVariable,
                    ["scoredislikes", "scoreunvoted", "scorelikes"])
Ejemplo n.º 3
0
    def __init__(self, link, depth, parent_id=None):
        from r2.lib.wrapped import CachedVariable

        if parent_id is not None:
            id36 = utils.to36(parent_id)
            self.parent_id = parent_id
            self.parent_name = "t%s_%s" % (utils.to36(Comment._type_id), id36)
            self.parent_permalink = link.make_permalink_slow() + id36
        self.link_name = link._fullname
        self.link_id = link._id
        self.depth = depth
        self.children = []
        self.count = 0
        self.previous_visits_hex = CachedVariable("previous_visits_hex")
Ejemplo n.º 4
0
    def add_props(cls, user, wrapped):
        from r2.lib.wrapped import CachedVariable
        for item in wrapped:
            # insert replacement variable for timesince to allow for
            # caching of thing templates
            item.display = CachedVariable("display")
            item.timesince = CachedVariable("timesince")
            item.childlisting = CachedVariable("childlisting")

            score_fmt = getattr(item, "score_fmt", Score.number_only)

            # CUSTOM: voting model
            if score_fmt == Score.points_dual:
                item.display_score = map(score_fmt, item.voting_score_ups, item.voting_score_downs)
            else:
                item.display_score = map(score_fmt, item.voting_score)

            if item.cachable:
                item.render_score  = item.display_score
                item.display_score = map(CachedVariable,
                                         ["scoredislikes", "scoreunvoted",
                                          "scorelikes", "scorelikesdislikes"])

        hooks.get_hook("add_props").call(items=wrapped)
Ejemplo n.º 5
0
    def listing(self, next_suggestions=None):
        self.things, prev, next, bcount, acount = self.get_items()

        self.next_suggestions = next_suggestions
        self._max_num = max(acount, bcount)
        self.after = None
        self.before = None

        if self.nextprev and self.prev_link and prev and bcount > 1:
            p = self.params.copy()
            p.update({
                'after': None,
                'before': prev._fullname,
                'count': bcount
            })
            self.before = prev._fullname
            self.prev = (request.path + utils.query_string(p))
            p_first = self.params.copy()
            p_first.update({'after': None, 'before': None, 'count': None})
            self.first = (request.path + utils.query_string(p_first))
        if self.nextprev and self.next_link and next:
            p = self.params.copy()
            p.update({
                'after': next._fullname,
                'before': None,
                'count': acount
            })
            self.after = next._fullname
            self.next = (request.path + utils.query_string(p))

        for count, thing in enumerate(self.things):
            thing.rowstyle_cls = getattr(thing, 'rowstyle_cls', "")
            thing.rowstyle_cls += ' ' + ('even' if (count % 2) else 'odd')
            thing.rowstyle = CachedVariable("rowstyle")

        survey_action = c.cookies.get('survey_action')
        if (feature.is_enabled('show_survey') and not survey_action
                and g.live_config['survey_info']):
            self.survey = ast.literal_eval(g.live_config['survey_info'])
            self.show_survey = True

        #TODO: need name for template -- must be better way
        return Wrapped(self)
Ejemplo n.º 6
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)
Ejemplo n.º 7
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)
Ejemplo n.º 8
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)