~sirn/fanboi2

ref: 834edf0edc5dd633c0ecea16231b6ed2d728476d fanboi2/fanboi2/services/filter_.py -rw-r--r-- 1.7 KiB
834edf0eKridsada Thanabulpong Massive cleanup in preparation for 0.30 (#25) 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
from collections import namedtuple

from ..interfaces import ISettingQueryService, IPostQueryService


FilterResult = namedtuple('FilterResult', ('rejected_by', 'filters'))


class FilterService(object):
    """Filter service provides a service for evaluating content using
    predefined sets of pre-posting filters.
    """

    def __init__(self, filters, service_query_fn):
        self.filters = filters
        self.service_query_fn = service_query_fn

    def evaluate(self, payload):
        """Evaluate the given payload with filters.

        :param payload: A filter payload to verify.
        """
        filters_chain = []
        setting_query_svc = self.service_query_fn(ISettingQueryService)

        if 'ip_address' in payload:
            post_query_svc = self.service_query_fn(IPostQueryService)
            if post_query_svc.was_recently_seen(payload['ip_address']):
                return FilterResult(rejected_by=None, filters=[])

        for name, cls in self.filters:
            services = {}
            filters_chain.append(name)
            if hasattr(cls, '__use_services__'):
                for s in cls.__use_services__:
                    services[s] = self.service_query_fn(name=s)

            settings_name = "ext.filters.%s" % (name,)
            settings_default = getattr(cls, '__default_settings__', None)
            settings = setting_query_svc.value_from_key(settings_name)
            if settings is None:
                settings = settings_default

            f = cls(settings, services)
            if f.should_reject(payload):
                return FilterResult(rejected_by=name, filters=filters_chain)

        return FilterResult(rejected_by=None, filters=filters_chain)