tracker_patterns.py 4.8 KB

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