.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
tracker_patterns.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""Simple implementation to store TrackerPatterns data in a SQL database."""
3
4import typing
5
6__all__ = ["TrackerPatternsDB"]
7
8import re
9from collections.abc import Iterator
10from urllib.parse import urlparse, urlunparse, parse_qsl, urlencode
11
12from httpx import HTTPError
13
14from searx.data.core import get_cache, log
15from searx.network import get as http_get
16
17RuleType = tuple[str, list[str], list[str]]
18
19
21 # pylint: disable=missing-class-docstring
22
23 ctx_name = "data_tracker_patterns"
24
25 CLEAR_LIST_URL = [
26 # ClearURL rule lists, the first one that responds HTTP 200 is used
27 "https://rules1.clearurls.xyz/data.minify.json",
28 "https://rules2.clearurls.xyz/data.minify.json",
29 "https://raw.githubusercontent.com/ClearURLs/Rules/refs/heads/master/data.min.json",
30 ]
31
32 class Fields:
33 # pylint: disable=too-few-public-methods, invalid-name
34 url_regexp: typing.Final = 0 # URL (regular expression) match condition of the link
35 url_ignore: typing.Final = 1 # URL (regular expression) to ignore
36 del_args: typing.Final = 2 # list of URL arguments (regular expression) to delete
37
38 def __init__(self):
39 self.cache = get_cache()
40
41 def init(self):
42 if self.cache.properties("tracker_patterns loaded") != "OK":
43 # To avoid parallel initializations, the property is set first
44 self.cache.properties.set("tracker_patterns loaded", "OK")
45 self.load()
46 # F I X M E:
47 # do we need a maintenance .. remember: database is stored
48 # in /tmp and will be rebuild during the reboot anyway
49
50 def load(self):
51 log.debug("init searx.data.TRACKER_PATTERNS")
52 for rule in self.iter_clear_list():
53 self.add(rule)
54
55 def add(self, rule: RuleType):
56 self.cache.set(
57 key=rule[self.Fields.url_regexp],
58 value=(
59 rule[self.Fields.url_ignore],
60 rule[self.Fields.del_args],
61 ),
62 ctx=self.ctx_name,
63 expire=None,
64 )
65
66 def rules(self) -> Iterator[RuleType]:
67 self.init()
68 for key, value in self.cache.pairs(ctx=self.ctx_name):
69 yield key, value[0], value[1]
70
71 def iter_clear_list(self) -> Iterator[RuleType]:
72 resp = None
73 for url in self.CLEAR_LIST_URL:
74 log.debug("TRACKER_PATTERNS: Trying to fetch %s...", url)
75 try:
76 resp = http_get(url, timeout=3)
77
78 except HTTPError as exc:
79 log.warning("TRACKER_PATTERNS: HTTPError (%s) occured while fetching %s", url, exc)
80 continue
81
82 if resp.status_code != 200:
83 log.warning(f"TRACKER_PATTERNS: ClearURL ignore HTTP {resp.status_code} {url}")
84 continue
85
86 break
87
88 if resp is None:
89 log.error("TRACKER_PATTERNS: failed fetching ClearURL rule lists")
90 return
91
92 for rule in resp.json()["providers"].values():
93 yield (
94 rule["urlPattern"].replace("\\\\", "\\"), # fix javascript regex syntax
95 [exc.replace("\\\\", "\\") for exc in rule.get("exceptions", [])],
96 rule.get("rules", []),
97 )
98
99 def clean_url(self, url: str) -> bool | str:
100 """The URL arguments are normalized and cleaned of tracker parameters.
101
102 Returns bool ``True`` to use URL unchanged (``False`` to ignore URL).
103 If URL should be modified, the returned string is the new URL to use.
104 """
105
106 new_url = url
107 parsed_new_url = urlparse(url=new_url)
108
109 for rule in self.rules():
110
111 if not re.match(rule[self.Fields.url_regexp], new_url):
112 # no match / ignore pattern
113 continue
114
115 do_ignore = False
116 for pattern in rule[self.Fields.url_ignore]:
117 if re.match(pattern, new_url):
118 do_ignore = True
119 break
120
121 if do_ignore:
122 # pattern is in the list of exceptions / ignore pattern
123 # HINT:
124 # we can't break the outer pattern loop since we have
125 # overlapping urlPattern like ".*"
126 continue
127
128 # remove tracker arguments from the url-query part
129 query_args: list[tuple[str, str]] = list(parse_qsl(parsed_new_url.query))
130
131 for name, val in query_args.copy():
132 # remove URL arguments
133 for pattern in rule[self.Fields.del_args]:
134 if re.match(pattern, name):
135 log.debug("TRACKER_PATTERNS: %s remove tracker arg: %s='%s'", parsed_new_url.netloc, name, val)
136 query_args.remove((name, val))
137
138 parsed_new_url = parsed_new_url._replace(query=urlencode(query_args))
139 new_url = urlunparse(parsed_new_url)
140
141 if new_url != url:
142 return new_url
143
144 return True
145
146
147if __name__ == "__main__":
149 for r in db.rules():
150 print(r)