def srids_from_site(user, site): if not isinstance(site, FakeSubreddit): srids = {site._id} elif isinstance(site, MultiReddit): srids = set(site.sr_ids) elif user and not isinstance(user, FakeAccount): srids = set(Subreddit.user_subreddits(user, ids=True) + [""]) else: srids = set(Subreddit.user_subreddits(None, ids=True) + [""]) return srids
def srids_from_site(user, site): if not isinstance(site, FakeSubreddit): srids = {site._id} elif isinstance(site, MultiReddit): srids = set(site.sr_ids) elif user and not isinstance(user, FakeAccount): srids = set(Subreddit.user_subreddits(user, ids=True) + [""]) else: srids = set(Subreddit.user_subreddits(None, ids=True) + [""]) return srids
def srnames_from_site(user, site): if not isinstance(site, FakeSubreddit): srnames = {site.name} elif isinstance(site, MultiReddit): srnames = {sr.name for sr in site.srs} elif user and not isinstance(user, FakeAccount): srnames = {sr.name for sr in Subreddit.user_subreddits(user, ids=False)} srnames.add(Frontpage.name) else: srnames = {sr.name for sr in Subreddit.user_subreddits(None, ids=False)} srnames.add(Frontpage.name) return srnames
def srnames_from_site(user, site): if not isinstance(site, FakeSubreddit): srnames = {site.name} elif isinstance(site, MultiReddit): srnames = {sr.name for sr in site.srs} elif user and not isinstance(user, FakeAccount): srnames = {sr.name for sr in Subreddit.user_subreddits(user, ids=False)} srnames.add(Frontpage.name) else: srnames = {sr.name for sr in Subreddit.user_subreddits(None, ids=False)} srnames.add(Frontpage.name) return srnames
def filter_links(links, filter_spam = False, multiple = True): # run the list through a builder to remove any that the user # isn't allowed to see from pylons import c from r2.models import IDBuilder, Link, Subreddit, NotFound links = IDBuilder([link._fullname for link in links], skip = False).get_items()[0] if not links: return if filter_spam: # first, try to remove any spam links_nonspam = [ link for link in links if not link._spam ] if links_nonspam: links = links_nonspam # if it occurs in one or more of their subscriptions, show them # that one first subs = set(Subreddit.user_subreddits(c.user, limit = None)) def cmp_links(a, b): if a.sr_id in subs and b.sr_id not in subs: return -1 elif a.sr_id not in subs and b.sr_id in subs: return 1 else: return cmp(b._hot, a._hot) links = sorted(links, cmp = cmp_links) # among those, show them the hottest one return links if multiple else links[0]
def can_create_subreddit(self): hook = hooks.get_hook("account.can_create_subreddit") can_create = hook.call_until_return(account=self) if can_create is not None: return can_create min_age = timedelta(days=g.live_config["create_sr_account_age_days"]) if self._age < min_age: return False if (self.link_karma < g.live_config["create_sr_link_karma"] and self.comment_karma < g.live_config["create_sr_comment_karma"]): return False # CUSTOM - allow subreddit creation once every X days # To avoid checking all subs, we get a list of user's contributed to subs, # and then check the sub author and sub creation date. Works even if they # create a sub then quit as moderator. # NOTE: user_subreddits() safely covers subs returned by special_reddits() with "contributor" and "moderator" # TODO: Use the can_create_subreddit hook to do this stuff elsewhere if g.live_config["create_sr_ratelimit_once_per_days"] > 0: from r2.models import Subreddit user_sr_ids = Subreddit.user_subreddits(self) if user_sr_ids: min_last_created = datetime.today() - timedelta(days=int(g.live_config["create_sr_ratelimit_once_per_days"])) srs = Subreddit._byID(user_sr_ids) for sr in srs.itervalues(): if sr.author_id == self._id and sr._date > min_last_created.replace(tzinfo=g.tz) and not c.user_is_admin and not self.employee: # g.log.warning("!!! dbg: user %s cannot create sub, created %s at %s, once every %s days max" % (self.name, sr.name, sr._date, g.live_config["create_sr_ratelimit_once_per_days"])) return False if self.is_global_banned: return True return True
def srnames_from_site(user, site, include_subscriptions=True): is_logged_in = user and not isinstance(user, FakeAccount) over_18 = is_site_over18(site) srnames = set() if not isinstance(site, FakeSubreddit): srnames.add(site.name) elif isinstance(site, MultiReddit): srnames = srnames | {sr.name for sr in site.srs} else: srnames.add(Frontpage.name) if is_logged_in and include_subscriptions: subscriptions = Subreddit.user_subreddits(user, ids=False) # only use subreddits that aren't quarantined and have the same # age gate as the subreddit being viewed. subscriptions = filter(lambda sr: not sr.quarantine and sr.over_18 == over_18, subscriptions) subscription_srnames = {sr.name for sr in subscriptions} # remove any subscriptions that may have nsfw ads targeting # them because they're apart of a nsfw collection. nsfw_collection_srnames = get_nsfw_collections_srnames() if not over_18: subscription_srnames = subscription_srnames - nsfw_collection_srnames srnames = srnames | subscription_srnames return srnames
def filter_links(links, filter_spam=False, multiple=True): # run the list through a builder to remove any that the user # isn't allowed to see from pylons import c from r2.models import IDBuilder, Link, Subreddit, NotFound links = IDBuilder([link._fullname for link in links], skip=False).get_items()[0] if not links: return if filter_spam: # first, try to remove any spam links_nonspam = [link for link in links if not link._spam] if links_nonspam: links = links_nonspam # if it occurs in one or more of their subscriptions, show them # that one first subs = set(Subreddit.user_subreddits(c.user, limit=None)) def cmp_links(a, b): if a.sr_id in subs and b.sr_id not in subs: return -1 elif a.sr_id not in subs and b.sr_id in subs: return 1 else: return cmp(b._hot, a._hot) links = sorted(links, cmp=cmp_links) # among those, show them the hottest one return links if multiple else links[0]
def __init__(self): Wrapped.__init__(self) my_reddits = [] sr_ids = Subreddit.user_subreddits(c.user if c.user_is_loggedin else None) if sr_ids: my_reddits = Subreddit._byID(sr_ids, True, return_dict = False) my_reddits.sort(key = lambda sr: sr.name.lower()) drop_down_buttons = [] for sr in my_reddits: drop_down_buttons.append(SubredditButton(sr)) #leaving the 'home' option out for now #drop_down_buttons.insert(0, NamedButton('home', sr_path = False, # css_class = 'top-option', # dest = '/')) drop_down_buttons.append(NamedButton('edit', sr_path = False, css_class = 'bottom-option', dest = '/reddits/')) self.sr_dropdown = SubredditMenu(drop_down_buttons, title = _('my reddits'), type = 'srdrop') pop_reddits = Subreddit.default_srs(c.content_langs, limit = 30) buttons = [SubredditButton(sr) for sr in c.recent_reddits] for sr in pop_reddits: if sr not in c.recent_reddits: buttons.append(SubredditButton(sr)) self.sr_bar = NavMenu(buttons, type='flatlist', separator = '-', _id = 'sr-bar')
def set_prefs(user, prefs): for k, v in prefs.iteritems(): if k == 'pref_beta' and v and not getattr(user, 'pref_beta', False): # If a user newly opted into beta, we want to subscribe them # to the beta subreddit. try: sr = Subreddit._by_name(g.beta_sr) if not sr.is_subscriber(user): sr.add_subscriber(user) except NotFound: g.log.warning("Could not find beta subreddit '%s'. It may " "need to be created." % g.beta_sr) # CUSTOM: reset subscriptions elif k == 'pref_subscriptions_unsubscribe' and v == 'subs_reset_subscriptions': # unsubscribe from all subscriber_srs = Subreddit.user_subreddits(user, ids=False, limit=None) for sub in subscriber_srs: sub.remove_subscriber(user) # resubscribe to the default srs default_srs = Subreddit.user_subreddits(user=None, ids=False, limit=None) Subreddit.subscribe_multiple(user, default_srs) # don't want to setattr() continue # CUSTOM: refuse empty IRC nick # elif k == 'pref_chat_user' and v is None: # continue # # CUSTOM: Nick change: force generate new chat client credentials, avoids user having to change their # # nick in the chat client. Forces new chat client session and account. # elif k == 'pref_chat_user' and v != user.pref_chat_user: # setattr(user, 'pref_chat_client_user', None) # setattr(user, 'pref_chat_client_password', None) # # CUSTOM: "update caches" (from account.py, for delete user case). Clears comment cache (sidebar block is not cached/always updates) # # TODO - Post cache does not clear, chat posts are wonky on IRC nick change. only known way is reddit-flush. asking for too much liveness? # blah = Account._by_name(user.name, allow_deleted = True, _update = True) # elif k == 'pref_chat_client_user' and v is None: # continue # elif k == 'pref_chat_client_password' and v is None: # continue setattr(user, k, v)
def nav(self): sr_ids = Subreddit.user_subreddits(c.user) if c.default_sr else [c.site._id] cloud = Tag.tag_cloud_for_subreddits(sr_ids) buttons =[] for tag, weight in cloud: buttons.append(NavButton(tag.name, tag.name, css_class=self.numbers[weight - 1])) return NavMenu(buttons, type="flatlist", separator=' ', base_path='/tag/')
def init_builder(self): user = c.user if c.user_is_loggedin else None sr_ids = Subreddit.user_subreddits(user) return UnbannedCommentBuilder( self.query(), sr_ids, num = 5, wrap = RecentItems.wrap_thing, skip = True )
def get_promotion_list(user, site): if not isinstance(site, FakeSubreddit): srids = set([site._id]) elif isinstance(site, MultiReddit): srids = set(site.sr_ids) elif user and not isinstance(user, FakeAccount): srids = set(Subreddit.reverse_subscriber_ids(user) + [""]) else: srids = set(Subreddit.user_subreddits(None, ids=True) + [""]) tuples = get_promotion_list_cached(srids) return [PromoTuple(*t) for t in tuples]
def get_promotion_list(user, site): if not isinstance(site, FakeSubreddit): srids = set([site._id]) elif isinstance(site, MultiReddit): srids = set(site.sr_ids) elif user and not isinstance(user, FakeAccount): srids = set(Subreddit.reverse_subscriber_ids(user) + [""]) else: srids = set(Subreddit.user_subreddits(None, ids=True) + [""]) tuples = get_promotion_list_cached(srids) return [PromoTuple(*t) for t in tuples]
def assign_trial(account, ip, slash16): from r2.models import Jury, Subreddit, Trial from r2.lib.db import queries defendants_voted_upon = [] defendants_assigned_to = [] for jury in Jury.by_account(account): defendants_assigned_to.append(jury._thing2_id) if jury._name != '0': defendants_voted_upon.append(jury._thing2_id) subscribed_sr_ids = Subreddit.user_subreddits(account, ids=True, limit=None) # Pull defendants, except ones which already have lots of juryvotes defs = Trial.all_defendants(quench=True) # Filter out defendants outside this user's subscribed SRs defs = filter(lambda d: d.sr_id in subscribed_sr_ids, defs) # Dictionary of sr_id => SR for all defendants' SRs srs = Subreddit._byID(set([d.sr_id for d in defs])) # Dictionary of sr_id => eligibility bool submit_srs = {} for sr_id, sr in srs.iteritems(): submit_srs[sr_id] = sr.can_submit(account) and not sr._spam # Filter out defendants with ineligible SRs defs = filter(lambda d: submit_srs.get(d.sr_id), defs) likes = queries.get_likes(account, defs) if not g.debug: # Filter out things that the user has upvoted or downvoted defs = filter(lambda d: likes.get((account, d)) is None, defs) # Prefer oldest trials defs.sort(key=lambda x: x._date) for defendant in defs: sr = srs[defendant.sr_id] if voir_dire(account, ip, slash16, defendants_voted_upon, defendant, sr): if defendant._id not in defendants_assigned_to: j = Jury._new(account, defendant) return defendant return None
def get_promotion_list(user, site): # site is specified, pick an ad from that site if not isinstance(site, FakeSubreddit): srids = set([site._id]) elif isinstance(site, MultiReddit): srids = set(site.sr_ids) # site is Fake, user is not. Pick based on their subscriptions. elif user and not isinstance(user, FakeAccount): srids = set(Subreddit.reverse_subscriber_ids(user) + [""]) # both site and user are "fake" -- get the default subscription list else: srids = set(Subreddit.user_subreddits(None, True) + [""]) return get_promotions_cached(srids)
def get_promotion_list(user, site): # site is specified, pick an ad from that site if not isinstance(site, FakeSubreddit): srids = set([site._id]) elif isinstance(site, MultiReddit): srids = set(site.sr_ids) # site is Fake, user is not. Pick based on their subscriptions. elif user and not isinstance(user, FakeAccount): srids = set(Subreddit.reverse_subscriber_ids(user) + [""]) # both site and user are "fake" -- get the default subscription list else: srids = set(Subreddit.user_subreddits(None, True) + [""]) return get_promotions_cached(srids)
def assign_trial(account, ip, slash16): from r2.models import Jury, Subreddit, Trial from r2.lib.db import queries defendants_voted_upon = [] defendants_assigned_to = [] for jury in Jury.by_account(account): defendants_assigned_to.append(jury._thing2_id) if jury._name != '0': defendants_voted_upon.append(jury._thing2_id) subscribed_sr_ids = Subreddit.user_subreddits(account, ids=True, limit=None) # Pull defendants, except ones which already have lots of juryvotes defs = Trial.all_defendants(quench=True) # Filter out defendants outside this user's subscribed SRs defs = filter (lambda d: d.sr_id in subscribed_sr_ids, defs) # Dictionary of sr_id => SR for all defendants' SRs srs = Subreddit._byID(set([ d.sr_id for d in defs ])) # Dictionary of sr_id => eligibility bool submit_srs = {} for sr_id, sr in srs.iteritems(): submit_srs[sr_id] = sr.can_submit(account) and not sr._spam # Filter out defendants with ineligible SRs defs = filter (lambda d: submit_srs.get(d.sr_id), defs) likes = queries.get_likes(account, defs) if not g.debug: # Filter out things that the user has upvoted or downvoted defs = filter (lambda d: likes.get((account, d)) is None, defs) # Prefer oldest trials defs.sort(key=lambda x: x._date) for defendant in defs: sr = srs[defendant.sr_id] if voir_dire(account, ip, slash16, defendants_voted_upon, defendant, sr): if defendant._id not in defendants_assigned_to: j = Jury._new(account, defendant) return defendant return None
def default_queries(): from r2.models import Link, Subreddit from r2.lib.db.operators import desc from copy import deepcopy queries = [] q = Link._query(Link.c.sr_id == Subreddit.user_subreddits(None), sort=desc("_hot"), limit=37) queries.append(q) # add a higher limit one too q = deepcopy(q) q._limit = 75 queries.append(q) return queries
def __init__(self, checkboxes = True): Wrapped.__init__(self) self.checkboxes = checkboxes if checkboxes: self.title = _('Customize your reddit') self.subtitle = _('Select which communities you want to see') else: self.title = _('Other reddit communities') self.subtitle = 'Visit your subscribed reddits (in bold) or explore new ones' self.create_link = ('/reddits/', menu.more) self.more_link = ('/reddits/create', _('create')) my_reddits = [] sr_ids = Subreddit.user_subreddits(c.user if c.user_is_loggedin else None) if sr_ids: my_reddits = Subreddit._byID(sr_ids, True, return_dict = False) my_reddits.sort(key = lambda sr: sr._downs, reverse = True) display_reddits = my_reddits[:g.num_side_reddits] #remove the current reddit display_reddits = filter(lambda x: x != c.site, display_reddits) pop_reddits = Subreddit.default_srs(c.content_langs, limit = g.num_side_reddits) #add english reddits to the list if c.content_langs != 'all' and 'en' not in c.content_langs: en_reddits = Subreddit.default_srs(['en']) pop_reddits += [sr for sr in en_reddits if sr not in pop_reddits] for sr in pop_reddits: if len(display_reddits) >= g.num_side_reddits: break if sr != c.site and sr not in display_reddits: display_reddits.append(sr) col1, col2 = [], [] cur_col, other = col1, col2 for sr in display_reddits: cur_col.append((sr, sr in my_reddits)) cur_col, other = other, cur_col self.cols = ((col1, col2)) self.mine = my_reddits
def default_queries(): from r2.models import Link, Subreddit from r2.lib.db.operators import desc from copy import deepcopy queries = [] q = Link._query(Link.c.sr_id == Subreddit.user_subreddits(None), sort=desc('_hot'), limit=37) queries.append(q) #add a higher limit one too q = deepcopy(q) q._limit = 75 queries.append(q) return queries
def for_user(cls, account): """Return a new AccountSRPrefs obj populated with user's data.""" prefs = cls() multis = LabeledMulti.by_owner(account) multi_srs = set(chain.from_iterable(multi.srs for multi in multis)) feedback = AccountSRFeedback.for_user(account) # subscriptions and srs in the user's multis become likes subscriptions = Subreddit.user_subreddits(account, limit=None) prefs.likes.update(utils.to36(sr_id) for sr_id in subscriptions) prefs.likes.update(sr._id36 for sr in multi_srs) # recent clicks on explore tab items are also treated as likes prefs.likes.update(feedback[CLICK]) # dismissed recommendations become dislikes prefs.dislikes.update(feedback[DISMISS]) # dislikes take precedence over likes prefs.likes = prefs.likes.difference(prefs.dislikes) # recently recommended items won't be shown again right away prefs.recent_views.update(feedback[VIEW]) return prefs
def for_user(cls, account): """Return a new AccountSRPrefs obj populated with user's data.""" prefs = cls() multis = LabeledMulti.by_owner(account) multi_srs = set(chain.from_iterable(multi.srs for multi in multis)) feedback = AccountSRFeedback.for_user(account) # subscriptions and srs in the user's multis become likes subscriptions = Subreddit.user_subreddits(account, limit=None) prefs.likes.update(utils.to36(sr_id) for sr_id in subscriptions) prefs.likes.update(sr._id36 for sr in multi_srs) # recent clicks on explore tab items are also treated as likes prefs.likes.update(feedback[CLICK]) # dismissed recommendations become dislikes prefs.dislikes.update(feedback[DISMISS]) # dislikes take precedence over likes prefs.likes = prefs.likes.difference(prefs.dislikes) # recently recommended items won't be shown again right away prefs.recent_views.update(feedback[VIEW]) return prefs
def __init__(self): Wrapped.__init__(self) self.title = _('Other reddit communities') self.subtitle = 'Visit your subscribed categories (in bold) or explore new ones' self.create_link = ('/categories/', menu.more) self.more_link = ('/categories/create', _('Create')) my_reddits = [] sr_ids = Subreddit.user_subreddits(c.user if c.user_is_loggedin else None) if sr_ids: my_reddits = Subreddit._byID(sr_ids, True, return_dict = False) my_reddits.sort(key = lambda sr: sr._downs, reverse = True) display_reddits = my_reddits[:g.num_side_reddits] #remove the current reddit display_reddits = filter(lambda x: x != c.site, display_reddits) pop_reddits = Subreddit.default_srs(c.content_langs, limit = g.num_side_reddits) #add english reddits to the list if c.content_langs != 'all' and 'en' not in c.content_langs: en_reddits = Subreddit.default_srs(['en']) pop_reddits += [sr for sr in en_reddits if sr not in pop_reddits] for sr in pop_reddits: if len(display_reddits) >= g.num_side_reddits: break if sr != c.site and sr not in display_reddits: display_reddits.append(sr) col1, col2 = [], [] cur_col, other = col1, col2 for sr in display_reddits: cur_col.append((sr, sr in my_reddits)) cur_col, other = other, cur_col self.cols = ((col1, col2)) self.mine = my_reddits
def __init__(self): Wrapped.__init__(self) my_reddits = [] sr_ids = Subreddit.user_subreddits(c.user if c.user_is_loggedin else None) if sr_ids: my_reddits = Subreddit._byID(sr_ids, True, return_dict = False) my_reddits.sort(key = lambda sr: sr.name.lower()) drop_down_buttons = [] for sr in my_reddits: drop_down_buttons.append(SubredditButton(sr)) #leaving the 'home' option out for now #drop_down_buttons.insert(0, NamedButton('home', sr_path = False, # css_class = 'top-option', # dest = '/')) drop_down_buttons.append(NamedButton('edit', sr_path = False, css_class = 'bottom-option', dest = '/categories/')) self.sr_dropdown = SubredditMenu(drop_down_buttons, title = _('My categories'), type = 'srdrop') pop_reddits = Subreddit.default_srs(c.content_langs, limit = 30) buttons = [] for sr in c.recent_reddits: # Extra guarding for Issue #50 if hasattr(sr, 'name'): buttons.append(SubredditButton(sr)) for sr in pop_reddits: if sr not in c.recent_reddits: buttons.append(SubredditButton(sr)) self.sr_bar = NavMenu(buttons, type='flatlist', separator = '-', _id = 'sr-bar')
def srnames_from_site(user, site, include_subscriptions=True): is_logged_in = user and not isinstance(user, FakeAccount) over_18 = is_site_over18(site) srnames = set() if not isinstance(site, FakeSubreddit): srnames.add(site.name) elif isinstance(site, MultiReddit): srnames = srnames | {sr.name for sr in site.srs} else: srnames.add(Frontpage.name) if is_logged_in and include_subscriptions: subscriptions = Subreddit.user_subreddits( user, ids=False, ) # only use subreddits that aren't quarantined and have the same # age gate as the subreddit being viewed. subscriptions = filter( lambda sr: not sr.quarantine and sr.over_18 == over_18, subscriptions, ) subscription_srnames = {sr.name for sr in subscriptions} # remove any subscriptions that may have nsfw ads targeting # them because they're apart of a nsfw collection. nsfw_collection_srnames = get_nsfw_collections_srnames() if not over_18: subscription_srnames = (subscription_srnames - nsfw_collection_srnames) srnames = srnames | subscription_srnames return srnames
def __init__(self): sr_ids = Subreddit.user_subreddits(c.user if c.user_is_loggedin else None) srs = Subreddit._byID(sr_ids, True, return_dict = False) srs.sort(key = lambda sr: sr.name.lower()) b = IDBuilder([sr._fullname for sr in srs]) self.reddits = LinkListing(b).listing().things
def subreddits(self): from subreddit import Subreddit return Subreddit.user_subreddits(self)
def __init__(self): sr_ids = Subreddit.user_subreddits(c.user if c.user_is_loggedin else None) srs = Subreddit._byID(sr_ids, True, return_dict = False) srs.sort(key = lambda sr: sr.name.lower()) b = IDBuilder([sr._fullname for sr in srs]) self.reddits = LinkListing(b).listing().things