Beispiel #1
0
    def __init__(self, ups = 0, downs = 0, date = None, deleted = False,
                 spam = False, id = None, descendant_karma = 0, **attrs):

        Thing.__init__(self, ups, downs, date, deleted, spam, id, **attrs)

        with self.safe_set_attr:
            self._descendant_karma = descendant_karma
Beispiel #2
0
    def _commit(self, *a, **kw):
        """Detect when we need to invalidate the sidebar recent posts.

        Whenever a post is created we need to invalidate.  Also invalidate when
        various post attributes are changed (such as moving to a different
        subreddit). If the post cache is invalidated the comment one is too.
        This is primarily for when a post is banned so that its comments
        dissapear from the sidebar too.
        """

        should_invalidate = (not self._created or
                             frozenset(('title', 'sr_id', '_deleted', '_spam')) & frozenset(self._dirties.keys()))

        Thing._commit(self, *a, **kw)

        if should_invalidate:
            g.rendercache.delete('side-posts' + '-' + c.site.name)
            g.rendercache.delete('side-comments' + '-' + c.site.name)
            tags = self.tag_names()
            if 'open_thread' in tags:
                g.rendercache.delete('side-open' + '-' + c.site.name)
            if 'quotes' in tags:
                g.rendercache.delete('side-quote' + '-' + c.site.name)
            if 'group_rationality_diary' in tags:
                g.rendercache.delete('side-diary' + '-' + c.site.name)
Beispiel #3
0
    def _commit(self, *a, **kw):
        """Detect when we need to invalidate the sidebar recent comments.

        Whenever a comment is created we need to invalidate.  Also
        invalidate when various comment attributes are changed.
        """

        should_invalidate = (not self._created or
                             frozenset(('body', '_deleted', '_spam')) & frozenset(self._dirties.keys()))

        Thing._commit(self, *a, **kw)

        if should_invalidate:
            g.rendercache.delete('side-comments' + '-' + c.site.name)
Beispiel #4
0
    def _commit(self, *a, **kw):
        """Detect when we need to invalidate the sidebar recent posts.

        Whenever a post is created we need to invalidate.  Also
        invalidate when various post attributes are changed (such as
        moving to a different subreddit).
        """

        should_invalidate = (not self._created or
                             frozenset(('title', 'sr_id', '_deleted', '_spam')) & frozenset(self._dirties.keys()))

        Thing._commit(self, *a, **kw)

        if should_invalidate:
            g.rendercache.delete('side-posts')
Beispiel #5
0
    def _handle_vote(msgs, chan):
        comments = []

        for msg in msgs:
            tag = msg.delivery_tag
            r = pickle.loads(msg.body)

            uid, tid, dir, ip, organic, cheater = r
            voter = Account._byID(uid, data=True)
            votee = Thing._by_fullname(tid, data = True)
            if isinstance(votee, Comment):
                comments.append(votee)

            if not isinstance(votee, (Link, Comment)):
                # I don't know how, but somebody is sneaking in votes
                # for subreddits
                continue

            print (voter, votee, dir, ip, organic, cheater)
            try:
                handle_vote(voter, votee, dir, ip, organic,
                            cheater=cheater, foreground=False)
            except Exception, e:
                print 'Rejecting %r:%r because of %r' % (msg.delivery_tag, r,e)
                chan.basic_reject(msg.delivery_tag, requeue=True)
Beispiel #6
0
 def __getattr__(self, attr):
     val = Thing.__getattr__(self, attr)
     if attr in ('start_date', 'end_date'):
         val = to_datetime(val)
         if not val.tzinfo:
             val = val.replace(tzinfo=g.tz)
     return val
Beispiel #7
0
    def _handle_vote(msg):
        r = pickle.loads(msg.body)

        uid, tid, dir, ip, organic, cheater = r
        voter = Account._byID(uid, data=True)
        votee = Thing._by_fullname(tid, data = True)

        print (voter, votee, dir, ip, organic, cheater)
        handle_vote(voter, votee, dir, ip, organic,
                    cheater = cheater)
Beispiel #8
0
    def _commit(self, *a, **kw):
        """Detect when we need to invalidate the sidebar recent comments.

        Whenever a comment is created we need to invalidate.  Also
        invalidate when various comment attributes are changed.
        """

        should_invalidate = (not self._created or
                             frozenset(('body', '_deleted', '_spam')) & frozenset(self._dirties.keys()))

        Thing._commit(self, *a, **kw)

        if should_invalidate:
            g.rendercache.delete('side-comments' + '-' + c.site.name)
            tags = Link._byID(self.link_id, data = True).tag_names()
            if 'open_thread' in tags:
                g.rendercache.delete('side-open' + '-' + c.site.name)
            if 'quotes' in tags:
                g.rendercache.delete('side-quote' + '-' + c.site.name)
            if 'group_rationality_diary' in tags:
                g.rendercache.delete('side-diary' + '-' + c.site.name)
Beispiel #9
0
    def _handle_vote(msgs, chan):
        assert(len(msgs) == 1)
        msg = msgs[0]

        r = pickle.loads(msg.body)

        uid, tid, dir, ip, organic, cheater = r
        voter = Account._byID(uid, data=True)
        votee = Thing._by_fullname(tid, data = True)

        print (voter, votee, dir, ip, organic, cheater)
        handle_vote(voter, votee, dir, ip, organic,
                    cheater = cheater)
Beispiel #10
0
    def _handle_vote(msg):
        # assert(len(msgs) == 1)
        r = pickle.loads(msg.body)

        uid, tid, dir, ip, organic, cheater = r
        voter = Account._byID(uid, data=True)
        votee = Thing._by_fullname(tid, data=True)
        if isinstance(votee, Comment):
            update_comment_votes([votee])

        # I don't know how, but somebody is sneaking in votes
        # for subreddits
        if isinstance(votee, (Link, Comment)):
            print (voter, votee, dir, ip, organic, cheater)
            handle_vote(voter, votee, dir, ip, organic, cheater=cheater, foreground=True)
Beispiel #11
0
    def from_queue(self, max_date, batch_limit=50, kind=None):
        from r2.models import is_banned_IP, Account, Thing
        keep_trying = True
        min_id = None
        s = self.queue_table
        while keep_trying:
            where = [s.c.date < max_date]
            if min_id:
                where.append(s.c.uid > min_id)
            if kind:
                where.append(s.c.kind == kind)

            res = sa.select([
                s.c.to_addr, s.c.account_id, s.c.from_name, s.c.fullname,
                s.c.body, s.c.kind, s.c.ip, s.c.date, s.c.uid, s.c.msg_hash,
                s.c.fr_addr, s.c.reply_to
            ],
                            sa.and_(*where),
                            order_by=s.c.uid,
                            limit=batch_limit).execute()
            res = res.fetchall()

            if not res: break

            # batch load user accounts
            aids = [x[1] for x in res if x[1] > 0]
            accts = Account._byID(aids, data=True,
                                  return_dict=True) if aids else {}

            # batch load things
            tids = [x[3] for x in res if x[3]]
            things = Thing._by_fullname(tids, data=True,
                                        return_dict=True) if tids else {}

            # make sure no IPs have been banned in the mean time
            ips = set(x[6] for x in res)
            ips = dict((ip, is_banned_IP(ip)) for ip in ips)

            # get the lower bound date for next iteration
            min_id = max(x[8] for x in res)

            # did we not fetch them all?
            keep_trying = (len(res) == batch_limit)

            for (addr, acct, fname, fulln, body, kind, ip, date, uid, msg_hash,
                 fr_addr, reply_to) in res:
                yield (accts.get(acct), things.get(fulln), addr, fname, date,
                       ip, ips[ip], kind, msg_hash, body, fr_addr, reply_to)
Beispiel #12
0
    def _handle_vote(msg):
        #assert(len(msgs) == 1)
        r = pickle.loads(msg.body)

        uid, tid, dir, ip, organic, cheater = r
        voter = Account._byID(uid, data=True)
        votee = Thing._by_fullname(tid, data = True)
        if isinstance(votee, Comment):
            update_comment_votes([votee])

        # I don't know how, but somebody is sneaking in votes
        # for subreddits
        if isinstance(votee, (Link, Comment)):
            print (voter, votee, dir, ip, organic, cheater)
            handle_vote(voter, votee, dir, ip, organic,
                        cheater = cheater, foreground=True)
Beispiel #13
0
    def _handle_vote(msgs, chan):
        # assert(len(msgs) == 1)
        comments = []
        for msg in msgs:
            r = pickle.loads(msg.body)

            uid, tid, dir, ip, organic, cheater = r
            voter = Account._byID(uid, data=True)
            votee = Thing._by_fullname(tid, data=True)
            if isinstance(votee, Comment):
                comments.append(votee)

            print (voter, votee, dir, ip, organic, cheater)
            handle_vote(voter, votee, dir, ip, organic, cheater=cheater)

        update_comment_votes(comments)
Beispiel #14
0
    def _handle_vote(msgs, chan):
        #assert(len(msgs) == 1)
        comments = []
        for msg in msgs:
            r = pickle.loads(msg.body)

            uid, tid, dir, ip, organic, cheater = r
            voter = Account._byID(uid, data=True)
            votee = Thing._by_fullname(tid, data=True)
            if isinstance(votee, Comment):
                comments.append(votee)

            print(voter, votee, dir, ip, organic, cheater)
            handle_vote(voter, votee, dir, ip, organic, cheater=cheater)

        update_comment_votes(comments)
Beispiel #15
0
    def from_queue(self, max_date, batch_limit = 50, kind = None):
        from r2.models import is_banned_IP, Account, Thing
        keep_trying = True
        min_id = None
        s = self.queue_table
        while keep_trying:
            where = [s.c.date < max_date]
            if min_id:
                where.append(s.c.uid > min_id)
            if kind:
                where.append(s.c.kind == kind)
                
            res = sa.select([s.c.to_addr, s.c.account_id,
                             s.c.from_name, s.c.fullname, s.c.body, 
                             s.c.kind, s.c.ip, s.c.date, s.c.uid,
                             s.c.msg_hash, s.c.fr_addr, s.c.reply_to],
                            sa.and_(*where),
                            order_by = s.c.uid, limit = batch_limit).execute()
            res = res.fetchall()

            if not res: break

            # batch load user accounts
            aids = [x[1] for x in res if x[1] > 0]
            accts = Account._byID(aids, data = True,
                                  return_dict = True) if aids else {}

            # batch load things
            tids = [x[3] for x in res if x[3]]
            things = Thing._by_fullname(tids, data = True,
                                        return_dict = True) if tids else {}

            # make sure no IPs have been banned in the mean time
            ips = set(x[6] for x in res)
            ips = dict((ip, is_banned_IP(ip)) for ip in ips)

            # get the lower bound date for next iteration
            min_id = max(x[8] for x in res)

            # did we not fetch them all?
            keep_trying = (len(res) == batch_limit)
        
            for (addr, acct, fname, fulln, body, kind, ip, date, uid, 
                 msg_hash, fr_addr, reply_to) in res:
                yield (accts.get(acct), things.get(fulln), addr,
                       fname, date, ip, ips[ip], kind, msg_hash, body,
                       fr_addr, reply_to)
Beispiel #16
0
    def _handle_votes(msgs, chan):
        to_do = []
        uids = set()
        tids = set()
        for x in msgs:
            r = pickle.loads(x.body)
            uid, tid, dir, ip, organic, cheater = r

            print (uid, tid, dir, ip, organic, cheater)

            uids.add(uid)
            tids.add(tid)
            to_do.append((uid, tid, dir, ip, organic, cheater))

        users = Account._byID(uids, data=True, return_dict=True)
        things = Thing._by_fullname(tids, data=True, return_dict=True)

        for uid, tid, dir, ip, organic, cheater in to_do:
            handle_vote(users[uid], things[tid], dir, ip, organic, cheater=cheater)
Beispiel #17
0
    def quota_baskets(self, kind):
        from r2.models.admintools import filter_quotas
        key = self.quota_key(kind)
        fnames = g.hardcache.get(key)

        if not fnames:
            return None

        unfiltered = Thing._by_fullname(fnames, data=True, return_dict=False)

        baskets, new_quotas = filter_quotas(unfiltered)

        if new_quotas is None:
            pass
        elif new_quotas == []:
            g.hardcache.delete(key)
        else:
            g.hardcache.set(key, new_quotas, 86400 * 30)

        return baskets
Beispiel #18
0
    def quota_baskets(self, kind):
        from r2.models.admintools import filter_quotas
        key = self.quota_key(kind)
        fnames = g.hardcache.get(key)

        if not fnames:
            return None

        unfiltered = Thing._by_fullname(fnames, data=True, return_dict=False)

        baskets, new_quotas = filter_quotas(unfiltered)

        if new_quotas is None:
            pass
        elif new_quotas == []:
            g.hardcache.delete(key)
        else:
            g.hardcache.set(key, new_quotas, 86400 * 30)

        return baskets
Beispiel #19
0
    def _handle_vote(msg):
        timer = stats.get_timer("service_time." + qname)
        timer.start()

        # assert(len(msgs) == 1)
        r = pickle.loads(msg.body)

        uid, tid, dir, ip, organic, cheater = r
        voter = Account._byID(uid, data=True)
        votee = Thing._by_fullname(tid, data=True)
        timer.intermediate("preamble")

        if isinstance(votee, Comment):
            update_comment_votes([votee])
            timer.intermediate("update_comment_votes")

        # I don't know how, but somebody is sneaking in votes
        # for subreddits
        if isinstance(votee, (Link, Comment)):
            print (voter, votee, dir, ip, organic, cheater)
            handle_vote(voter, votee, dir, ip, organic, cheater=cheater, foreground=True, timer=timer)
Beispiel #20
0
def update_flairs(msg):
    """Add non presser flair to posters/commenters in thebutton SR"""
    fullname = msg.body

    thing = Thing._by_fullname(fullname)
    if (not isinstance(thing, (Comment, Link))
            or thing.sr_id != g.live_config["thebutton_srid"]):
        return

    author = thing.author_slow
    sr = thing.subreddit_slow

    if not author.flair_css_class(sr._id):
        if author._date < ACCOUNT_CREATION_CUTOFF:
            flair_class = g.live_config["thebutton_nopress_flair_class"]
            flair_text = g.live_config["thebutton_nopress_flair_text"]
        else:
            flair_class = g.live_config["thebutton_cantpress_flair_class"]
            flair_text = g.live_config["thebutton_cantpress_flair_text"]

        if flair_class:
            author.set_flair(sr, css_class=flair_class, text=flair_text)
Beispiel #21
0
def update_flairs(msg):
    """Add non presser flair to posters/commenters in thebutton SR"""
    fullname = msg.body

    thing = Thing._by_fullname(fullname)
    if (not isinstance(thing, (Comment, Link)) or
            thing.sr_id != g.live_config["thebutton_srid"]):
        return

    author = thing.author_slow
    sr = thing.subreddit_slow

    if not author.flair_css_class(sr._id):
        if author._date < ACCOUNT_CREATION_CUTOFF:
            flair_class = g.live_config["thebutton_nopress_flair_class"]
            flair_text = g.live_config["thebutton_nopress_flair_text"]
        else:
            flair_class = g.live_config["thebutton_cantpress_flair_class"]
            flair_text = g.live_config["thebutton_cantpress_flair_text"]

        if flair_class:
            author.set_flair(sr, css_class=flair_class, text=flair_text)
Beispiel #22
0
    def _handle_votes(msgs, chan):
        to_do = []
        uids = set()
        tids = set()
        for x in msgs:
            r = pickle.loads(x.body)
            uid, tid, dir, ip, organic, cheater = r

            print(uid, tid, dir, ip, organic, cheater)

            uids.add(uid)
            tids.add(tid)
            to_do.append((uid, tid, dir, ip, organic, cheater))

        users = Account._byID(uids, data=True, return_dict=True)
        things = Thing._by_fullname(tids, data=True, return_dict=True)

        for uid, tid, dir, ip, organic, cheater in to_do:
            handle_vote(users[uid],
                        things[tid],
                        dir,
                        ip,
                        organic,
                        cheater=cheater)
Beispiel #23
0
    def add_props(cls, user, wrapped):

        from r2.lib.menus import NavButton
        from r2.lib.db.thing import Thing
        from r2.lib.pages import WrappedUser
        from r2.lib.filters import _force_unicode

        TITLE_MAX_WIDTH = 50

        request_path = request.path

        target_fullnames = [item.target_fullname for item in wrapped if hasattr(item, "target_fullname")]
        targets = Thing._by_fullname(target_fullnames, data=True)
        authors = Account._byID([t.author_id for t in targets.values() if hasattr(t, "author_id")], data=True)
        links = Link._byID([t.link_id for t in targets.values() if hasattr(t, "link_id")], data=True)
        subreddits = Subreddit._byID([item.sr_id for item in wrapped], data=True)

        # Assemble target links
        target_links = {}
        target_accounts = {}
        for fullname, target in targets.iteritems():
            if isinstance(target, Link):
                author = authors[target.author_id]
                title = _force_unicode(target.title)
                if len(title) > TITLE_MAX_WIDTH:
                    short_title = title[:TITLE_MAX_WIDTH] + "..."
                else:
                    short_title = title
                text = '%(link)s "%(title)s" %(by)s %(author)s' % {
                    "link": _("link"),
                    "title": short_title,
                    "by": _("by"),
                    "author": author.name,
                }
                path = target.make_permalink(subreddits[target.sr_id])
                target_links[fullname] = (text, path, title)
            elif isinstance(target, Comment):
                author = authors[target.author_id]
                link = links[target.link_id]
                title = _force_unicode(link.title)
                if len(title) > TITLE_MAX_WIDTH:
                    short_title = title[:TITLE_MAX_WIDTH] + "..."
                else:
                    short_title = title
                text = '%(comment)s %(by)s %(author)s %(on)s "%(title)s"' % {
                    "comment": _("comment"),
                    "by": _("by"),
                    "author": author.name,
                    "on": _("on"),
                    "title": short_title,
                }
                path = target.make_permalink(link, subreddits[link.sr_id])
                target_links[fullname] = (text, path, title)
            elif isinstance(target, Account):
                target_accounts[fullname] = WrappedUser(target)

        for item in wrapped:
            # Can I move these buttons somewhere else? Not great to have request stuff in here
            css_class = "modactions %s" % item.action
            item.button = NavButton("", item.action, opt="type", css_class=css_class)
            item.button.build(base_path=request_path)

            mod_name = item.author.name
            item.mod = NavButton(mod_name, mod_name, opt="mod")
            item.mod.build(base_path=request_path)
            item.text = ModAction._text.get(item.action, "")
            item.details = item.get_extra_text()

            if hasattr(item, "target_fullname") and item.target_fullname:
                target = targets[item.target_fullname]
                if isinstance(target, Account):
                    item.target_wrapped_user = target_accounts[item.target_fullname]
                elif isinstance(target, Link) or isinstance(target, Comment):
                    item.target_text, item.target_path, item.target_title = target_links[item.target_fullname]

            item.bgcolor = ModAction.get_rgb(item.sr_id)
            item.sr_name = subreddits[item.sr_id].name
            item.sr_path = subreddits[item.sr_id].path

        Printable.add_props(user, wrapped)
Beispiel #24
0
 def __init__(self, *a, **kw):
     Thing.__init__(self, *a, **kw)
Beispiel #25
0
    def add_props(cls, user, wrapped):

        from r2.lib.menus import NavButton
        from r2.lib.db.thing import Thing
        from r2.lib.pages import WrappedUser
        from r2.lib.filters import _force_unicode

        TITLE_MAX_WIDTH = 50

        request_path = request.path

        target_fullnames = [item.target_fullname for item in wrapped if hasattr(item, 'target_fullname')]
        targets = Thing._by_fullname(target_fullnames, data=True)
        authors = Account._byID([t.author_id for t in targets.values() if hasattr(t, 'author_id')], data=True)
        links = Link._byID([t.link_id for t in targets.values() if hasattr(t, 'link_id')], data=True)
        subreddits = Subreddit._byID([t.sr_id for t in targets.values() if hasattr(t, 'sr_id')])

        # Assemble target links
        target_links = {}
        target_accounts = {}
        for fullname, target in targets.iteritems():
            if isinstance(target, Link):
                author = authors[target.author_id]
                title = _force_unicode(target.title)
                if len(title) > TITLE_MAX_WIDTH:
                    short_title = title[:TITLE_MAX_WIDTH] + '...'
                else:
                    short_title = title
                text = '"%(title)s" %(by)s %(author)s' % {'title': short_title, 
                                                          'by': _('by'),
                                                          'author': author.name}
                path = target.make_permalink(subreddits[target.sr_id])
                target_links[fullname] = (text, path, title)
            elif isinstance(target, Comment):
                author = authors[target.author_id]
                link = links[target.link_id]
                title = _force_unicode(link.title)
                if len(title) > TITLE_MAX_WIDTH:
                    short_title = title[:TITLE_MAX_WIDTH] + '...'
                else:
                    short_title = title
                text = '%(by)s %(author)s %(on)s "%(title)s"' % {'by': _('by'),
                                                         'author': author.name,
                                                         'on': _('on'),
                                                         'title': short_title}
                path = target.make_permalink(link, subreddits[target.sr_id])
                target_links[fullname] = (text, path, title)
            elif isinstance(target, Account):
                target_accounts[fullname] = WrappedUser(target)

        for item in wrapped:
            # Can I move these buttons somewhere else? Not great to have request stuff in here
            css_class = 'modactions %s' % item.action
            item.button = NavButton('', item.action, opt='type', css_class=css_class)
            item.button.build(base_path=request_path)

            mod_name = item.author.name
            item.mod = NavButton(mod_name, mod_name, opt='mod')
            item.mod.build(base_path=request_path)
            item.text = ModAction._text.get(item.action, '')
            item.details = item.get_extra_text()

            if hasattr(item, 'target_fullname') and item.target_fullname:
                target = targets[item.target_fullname]
                if isinstance(target, Account):
                    item.target_wrapped_user = target_accounts[item.target_fullname]
                elif isinstance(target, Link) or isinstance(target, Comment):
                    item.target_text, item.target_path, item.target_title = target_links[item.target_fullname]

        Printable.add_props(user, wrapped)
 def __init__(self, config):
     Thing.__init__(self)
     Printable.__init__(self)
     self.config = config
     self.wikipage = WikiPageCached(config)
Beispiel #27
0
    def add_props(cls, user, wrapped):
        from r2.lib.db.thing import Thing
        from r2.lib.menus import QueryButton
        from r2.lib.pages import WrappedUser
        from r2.models import (
            Account,
            Link,
            ModSR,
            MultiReddit,
            Subreddit,
        )

        target_names = {item.target_fullname for item in wrapped
                            if hasattr(item, "target_fullname")}
        targets = Thing._by_fullname(target_names, data=True)

        # get moderators
        moderators = Account._byID36({item.mod_id36 for item in wrapped},
                                     data=True)

        # get authors for targets that are Links or Comments
        target_author_names = {target.author_id for target in targets.values()
                                    if hasattr(target, "author_id")}
        target_authors = Account._byID(target_author_names, data=True)

        # get parent links for targets that are Comments
        parent_link_names = {target.link_id for target in targets.values()
                                    if hasattr(target, "link_id")}
        parent_links = Link._byID(parent_link_names, data=True)

        # get subreddits
        srs = Subreddit._byID36({item.sr_id36 for item in wrapped}, data=True)

        for item in wrapped:
            item.moderator = moderators[item.mod_id36]
            item.subreddit = srs[item.sr_id36]
            item.text = cls._text.get(item.action, '')
            item.target = None
            item.target_author = None

            if hasattr(item, "target_fullname") and item.target_fullname:
                item.target = targets[item.target_fullname]

                if hasattr(item.target, "author_id"):
                    author_name = item.target.author_id
                    item.target_author = target_authors[author_name]

                if hasattr(item.target, "link_id"):
                    parent_link_name = item.target.link_id
                    item.parent_link = parent_links[parent_link_name]

                if isinstance(item.target, Account):
                    item.target_author = item.target

        if c.render_style == "html":
            request_path = request.path

            # make wrapped users for targets that are accounts
            user_targets = filter(lambda target: isinstance(target, Account),
                                  targets.values())
            wrapped_user_targets = {user._fullname: WrappedUser(user)
                                    for user in user_targets}

            for item in wrapped:
                if isinstance(item.target, Account):
                    user_name = item.target._fullname
                    item.wrapped_user_target = wrapped_user_targets[user_name]

                css_class = 'modactions %s' % item.action
                action_button = QueryButton(
                    '', item.action, query_param='type', css_class=css_class)
                action_button.build(base_path=request_path)
                item.action_button = action_button

                mod_button = QueryButton(
                    item.moderator.name, item.moderator.name, query_param='mod')
                mod_button.build(base_path=request_path)
                item.mod_button = mod_button

                if isinstance(c.site, ModSR) or isinstance(c.site, MultiReddit):
                    rgb = item.subreddit.get_rgb()
                    item.bgcolor = 'rgb(%s,%s,%s)' % rgb
                    item.is_multi = True
                else:
                    item.bgcolor = "rgb(255,255,255)"
                    item.is_multi = False
Beispiel #28
0
    def add_props(cls, user, wrapped):

        from r2.lib.menus import NavButton
        from r2.lib.db.thing import Thing
        from r2.lib.pages import WrappedUser
        from r2.lib.filters import _force_unicode

        TITLE_MAX_WIDTH = 50

        request_path = request.path

        target_fullnames = [item.target_fullname for item in wrapped if hasattr(item, 'target_fullname')]
        targets = Thing._by_fullname(target_fullnames, data=True)
        authors = Account._byID([t.author_id for t in targets.values() if hasattr(t, 'author_id')], data=True)
        links = Link._byID([t.link_id for t in targets.values() if hasattr(t, 'link_id')], data=True)

        sr_ids = set([t.sr_id for t in targets.itervalues() if hasattr(t, 'sr_id')] +
                     [w.sr_id for w in wrapped])
        subreddits = Subreddit._byID(sr_ids, data=True)

        # Assemble target links
        target_links = {}
        target_accounts = {}
        for fullname, target in targets.iteritems():
            if isinstance(target, Link):
                author = authors[target.author_id]
                title = _force_unicode(target.title)
                if len(title) > TITLE_MAX_WIDTH:
                    short_title = title[:TITLE_MAX_WIDTH] + '...'
                else:
                    short_title = title
                text = '%(link)s "%(title)s" %(by)s %(author)s' % {
                        'link': _('link'),
                        'title': short_title, 
                        'by': _('by'),
                        'author': author.name}
                path = target.make_permalink(subreddits[target.sr_id])
                target_links[fullname] = (text, path, title)
            elif isinstance(target, Comment):
                author = authors[target.author_id]
                link = links[target.link_id]
                title = _force_unicode(link.title)
                if len(title) > TITLE_MAX_WIDTH:
                    short_title = title[:TITLE_MAX_WIDTH] + '...'
                else:
                    short_title = title
                text = '%(comment)s %(by)s %(author)s %(on)s "%(title)s"' % {
                        'comment': _('comment'),
                        'by': _('by'),
                        'author': author.name,
                        'on': _('on'),
                        'title': short_title}
                path = target.make_permalink(link, subreddits[link.sr_id])
                target_links[fullname] = (text, path, title)
            elif isinstance(target, Account):
                target_accounts[fullname] = WrappedUser(target)

        for item in wrapped:
            # Can I move these buttons somewhere else? Not great to have request stuff in here
            css_class = 'modactions %s' % item.action
            item.button = NavButton('', item.action, opt='type', css_class=css_class)
            item.button.build(base_path=request_path)

            mod_name = item.author.name
            item.mod = NavButton(mod_name, mod_name, opt='mod')
            item.mod.build(base_path=request_path)
            item.text = ModAction._text.get(item.action, '')
            item.details = item.get_extra_text()

            if hasattr(item, 'target_fullname') and item.target_fullname:
                target = targets[item.target_fullname]
                if isinstance(target, Account):
                    item.target_wrapped_user = target_accounts[item.target_fullname]
                elif isinstance(target, Link) or isinstance(target, Comment):
                    item.target_text, item.target_path, item.target_title = target_links[item.target_fullname]

            item.bgcolor = ModAction.get_rgb(item.sr_id)
            item.sr_name = subreddits[item.sr_id].name
            item.sr_path = subreddits[item.sr_id].path

        Printable.add_props(user, wrapped)
 def __init__(self, config):
     Thing.__init__(self)
     Printable.__init__(self)
     self.config = config
     self.wikipage = WikiPageCached(config)
Beispiel #30
0
 def __setattr__(self, attr, val, make_dirty=True):
     if attr in self._derived_attrs:
         object.__setattr__(self, attr, val)
     else:
         Thing.__setattr__(self, attr, val, make_dirty=make_dirty)
Beispiel #31
0
 def __init__(self, *a, **kw):
     Thing.__init__(self, *a, **kw)
Beispiel #32
0
    def _commit(self, *a, **kw):

        Thing._commit(self, *a, **kw)
Beispiel #33
0
    def add_props(cls, user, wrapped):
        from r2.lib.db.thing import Thing
        from r2.lib.menus import QueryButton
        from r2.lib.pages import WrappedUser
        from r2.models import (
            Account,
            Link,
            ModSR,
            MultiReddit,
            Subreddit,
        )

        target_names = {
            item.target_fullname
            for item in wrapped if hasattr(item, "target_fullname")
        }
        targets = Thing._by_fullname(target_names, data=True)

        # get moderators
        moderators = Account._byID36({item.mod_id36
                                      for item in wrapped},
                                     data=True)

        # get authors for targets that are Links or Comments
        target_author_names = {
            target.author_id
            for target in targets.values() if hasattr(target, "author_id")
        }
        target_authors = Account._byID(target_author_names, data=True)

        # get parent links for targets that are Comments
        parent_link_names = {
            target.link_id
            for target in targets.values() if hasattr(target, "link_id")
        }
        parent_links = Link._byID(parent_link_names, data=True)

        # get subreddits
        srs = Subreddit._byID36({item.sr_id36 for item in wrapped}, data=True)

        for item in wrapped:
            item.moderator = moderators[item.mod_id36]
            item.subreddit = srs[item.sr_id36]
            item.text = cls._text.get(item.action, '')
            item.details = item.get_extra_text()
            item.target = None
            item.target_author = None

            if hasattr(item, "target_fullname") and item.target_fullname:
                item.target = targets[item.target_fullname]

                if hasattr(item.target, "author_id"):
                    author_name = item.target.author_id
                    item.target_author = target_authors[author_name]

                if hasattr(item.target, "link_id"):
                    parent_link_name = item.target.link_id
                    item.parent_link = parent_links[parent_link_name]

                if isinstance(item.target, Account):
                    item.target_author = item.target

        if c.render_style == "html":
            request_path = request.path

            # make wrapped users for targets that are accounts
            user_targets = filter(lambda target: isinstance(target, Account),
                                  targets.values())
            wrapped_user_targets = {
                user._fullname: WrappedUser(user)
                for user in user_targets
            }

            for item in wrapped:
                if isinstance(item.target, Account):
                    user_name = item.target._fullname
                    item.wrapped_user_target = wrapped_user_targets[user_name]

                css_class = 'modactions %s' % item.action
                action_button = QueryButton('',
                                            item.action,
                                            query_param='type',
                                            css_class=css_class)
                action_button.build(base_path=request_path)
                item.action_button = action_button

                mod_button = QueryButton(item.moderator.name,
                                         item.moderator.name,
                                         query_param='mod')
                mod_button.build(base_path=request_path)
                item.mod_button = mod_button

                if isinstance(c.site, ModSR) or isinstance(
                        c.site, MultiReddit):
                    item.bgcolor = 'rgb(%s,%s,%s)' % cls.get_rgb(item)
                    item.is_multi = True
                else:
                    item.bgcolor = "rgb(255,255,255)"
                    item.is_multi = False