~sirn/fanboi2

ref: a68873a108d20a6a49a1b6caf374bfb2cf6a94fe fanboi2/fanboi2/services/filter_.py -rw-r--r-- 1.5 KiB
a68873a1Kridsada Thanabulpong Coding style cleanups and setup pre-commit hooks (#42) 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
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 = setting_query_svc.value_from_key(settings_name)

            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)