tracker_patterns.py 4.7 KB

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