From 817f8d66c251e263d52eeebb952858219e870eb5 Mon Sep 17 00:00:00 2001 From: Neil Williams Date: Mon, 4 Nov 2013 11:30:41 -0800 Subject: [PATCH] Add hooks into comment/vote endpoints. This stuff is needed for the server naming subreddit overrides. Would love to see it replaced with custom Thing subclasses in the future. --- r2/r2/controllers/api.py | 5 +++++ r2/r2/lib/hooks.py | 13 +++++++++++++ r2/r2/models/subreddit.py | 7 +++++++ 3 files changed, 25 insertions(+) diff --git a/r2/r2/controllers/api.py b/r2/r2/controllers/api.py index e951d4a75..19997ed01 100755 --- a/r2/r2/controllers/api.py +++ b/r2/r2/controllers/api.py @@ -1355,6 +1355,9 @@ class ApiController(RedditController, OAuth2ResourceController): if not link.promoted and parent_age.days > g.REPLY_AGE_LIMIT: c.errors.add(errors.TOO_OLD, field = "parent") + hooks.get_hook("comment.validate").call(sr=sr, link=link, + parent_comment=parent_comment) + #remove the ratelimit error if the user's karma is high if not should_ratelimit: c.errors.remove((errors.RATELIMIT, 'ratelimit')) @@ -1550,6 +1553,8 @@ class ApiController(RedditController, OAuth2ResourceController): if not thing or thing._deleted: return + hooks.get_hook("vote.validate").call(thing=thing) + if vote_info == 'rejected': reject_vote(thing) store = False diff --git a/r2/r2/lib/hooks.py b/r2/r2/lib/hooks.py index 0cb07f7a1..856fc0fb3 100644 --- a/r2/r2/lib/hooks.py +++ b/r2/r2/lib/hooks.py @@ -43,6 +43,19 @@ class Hook(object): """ return [handler(**kwargs) for handler in self.handlers] + def call_until_return(self, **kwargs): + """Call handlers until one returns a non-None value. + + As with call, handlers are called in the same order they are + registered. Only the return value of the first non-None handler is + returned. + + """ + for handler in self.handlers: + ret = handler(**kwargs) + if ret is not None: + return ret + def get_hook(name): """Return the named hook `name` creating it if necessary.""" diff --git a/r2/r2/models/subreddit.py b/r2/r2/models/subreddit.py index 0e72cf901..9ddbbbbb0 100644 --- a/r2/r2/models/subreddit.py +++ b/r2/r2/models/subreddit.py @@ -50,6 +50,7 @@ from r2.models.wiki import WikiPage from r2.lib.merge import ConflictException from r2.lib.cache import CL_ONE from r2.lib.contrib.rcssmin import cssmin +from r2.lib import hooks from r2.models.query_cache import MergedCachedQuery import pycassa @@ -423,6 +424,12 @@ class Subreddit(Thing, Printable, BaseSite): def can_comment(self, user): if c.user_is_admin: return True + + override = hooks.get_hook("subreddit.can_comment").call_until_return( + sr=self, user=user) + + if override is not None: + return override elif self.is_banned(user): return False elif self.type == 'gold_restricted' and user.gold: