~sirn/fanboi2

ref: 98796226802a26b82c888365ad5b9cd331006792 fanboi2/fanboi2/tasks.py -rw-r--r-- 6.4 KiB
98796226Kridsada Thanabulpong Bump copyright year. 3 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import transaction
from celery import Celery, states
from sqlalchemy.exc import IntegrityError
from fanboi2.errors import serialize_error
from fanboi2.models import DBSession, Post, Topic, Board, \
    RuleBan, RuleOverride, serialize_model
from fanboi2.utils import akismet, dnsbl, proxy_detector, geoip, checklist

celery = Celery()


def configure_celery(settings):  # pragma: no cover
    """Returns a Celery configuration object.

    :param settings: A settings :type:`dict`.

    :type settings: dict
    :rtype: dict
    """
    return {
        'BROKER_URL': settings['celery.broker'],
        'CELERY_RESULT_BACKEND': settings['celery.broker'],
        'CELERY_ACCEPT_CONTENT': ['json'],
        'CELERY_TASK_SERIALIZER': 'json',
        'CELERY_RESULT_SERIALIZER': 'json',
        'CELERY_EVENT_SERIALIZER': 'json',
        'CELERY_TIMEZONE': settings['app.timezone'],
    }


class ResultProxy(object):
    """A proxy class for :class:`celery.result.AsyncResult` that provide
    results serialization using :func:`fanboi2.errors.serialize_error` and
    :func:`fanboi2.models.serialize_model`.

    :param result: A result of :class:`celery.AsyncResult`.
    :type result: celery.result.AsyncResult
    """

    def __init__(self, result):
        self._result = result
        self._object = None

    @property
    def object(self):
        """Serializing the result into Python object.

        :rtype: object
        """
        if self._object is None:
            obj, id_, *args = self._result.get()
            if obj == 'failure':
                self._object = serialize_error(id_, *args)
            else:
                class_ = serialize_model(obj)
                if class_ is not None:
                    self._object = DBSession.query(class_).\
                        filter_by(id=id_).\
                        one()
        return self._object

    def success(self):
        """Returns true if result was successfully processed.

        :rtype: bool
        """
        return self._result.state == states.SUCCESS

    def __getattr__(self, name):
        return self._result.__getattribute__(name)


@celery.task()
def add_topic(request, board_id, title, body):
    """Insert a topic to the database.

    :param request: A serialized request :type:`dict` returned from
                    :meth:`fanboi2.utils.serialize_request`.
    :param board_id: An :type:`int` referencing board ID.
    :param title: A :type:`str` topic title.
    :param body: A :type:`str` topic body.

    :type request: dict
    :type board_id: int
    :type title: str
    :type body: str
    :rtype: tuple
    """
    ip_address = request['remote_addr']
    country_code = geoip.country_code(ip_address)
    country_scope = 'country:%s' % (str(country_code).lower())

    with transaction.manager:
        board = DBSession.query(Board).get(board_id)
        board_scope = 'board:%s' % (board.slug,)

        if DBSession.query(RuleBan).\
           filter(RuleBan.listed(ip_address, scopes=(board_scope,))).\
           count() > 0:
            return 'failure', 'ban_rejected'

        override = {}
        rule_override = DBSession.query(RuleOverride).filter(
            RuleOverride.listed(ip_address, scopes=(board_scope,))).\
            first()

        if rule_override is not None:
            override = rule_override.override

        board_status = override.get('status', board.status)
        if board_status != 'open':
            return 'failure', 'status_rejected', board_status

        if checklist.enabled(country_scope, 'akismet') and \
           akismet.spam(request, body):
            return 'failure', 'spam_rejected'

        if checklist.enabled(country_scope, 'dnsbl') and \
           dnsbl.listed(ip_address):
            return 'failure', 'dnsbl_rejected'

        if checklist.enabled(country_scope, 'proxy_detect') and \
           proxy_detector.detect(ip_address):
            return 'failure', 'proxy_rejected'

        post = Post(body=body, ip_address=ip_address)
        post.topic = Topic(board=board, title=title)
        DBSession.add(post)
        DBSession.flush()
        return 'topic', post.topic_id


@celery.task(bind=True, max_retries=4)  # 5 total.
def add_post(self, request, topic_id, body, bumped):
    """Insert a post to a topic.

    :param self: A :class:`celery.Task` object.
    :param request: A serialized request :type:`dict` returned from
                    :meth:`fanboi2.utils.serialize_request`.
    :param topic_id: An :type:`int` referencing topic ID.
    :param body: A :type:`str` post body.
    :param bumped: A :type:`bool` specifying bump status.

    :type self: celery.Task
    :type request: dict
    :type topic_id: int
    :type body: str
    :type bumped: bool
    :rtype: tuple
    """
    ip_address = request['remote_addr']
    country_code = geoip.country_code(ip_address)
    country_scope = 'country:%s' % (str(country_code).lower())

    with transaction.manager:
        topic = DBSession.query(Topic).get(topic_id)
        board = topic.board
        board_scope = 'board:%s' % (board.slug,)

        if DBSession.query(RuleBan).\
           filter(RuleBan.listed(ip_address, scopes=(board_scope,))).\
           count() > 0:
            return 'failure', 'ban_rejected'

        if topic.status != 'open':
            return 'failure', 'status_rejected', topic.status

        override = {}
        rule_override = DBSession.query(RuleOverride).filter(
            RuleOverride.listed(ip_address, scopes=(board_scope,))).\
            first()

        if rule_override is not None:
            override = rule_override.override

        board_status = override.get('status', board.status)
        if not board_status in ('open', 'restricted'):
            return 'failure', 'status_rejected', board_status

        if checklist.enabled(country_scope, 'akismet') and \
           akismet.spam(request, body):
            return 'failure', 'spam_rejected'

        if checklist.enabled(country_scope, 'dnsbl') and \
           dnsbl.listed(ip_address):
            return 'failure', 'dnsbl_rejected'

        if checklist.enabled(country_scope, 'proxy_detect') and \
           proxy_detector.detect(ip_address):
            return 'failure', 'proxy_rejected'

        post = Post(
            topic=topic,
            body=body,
            bumped=bumped,
            ip_address=ip_address)

        try:
            DBSession.add(post)
            DBSession.flush()
        except IntegrityError as e:
            raise self.retry(exc=e)

        return 'post', post.id