tracker_url_remover.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # pylint: disable=missing-module-docstring, unused-argument
  3. from __future__ import annotations
  4. import typing
  5. import re
  6. from urllib.parse import urlparse, urlunparse, parse_qsl, urlencode
  7. from flask_babel import gettext
  8. from searx.data import TRACKER_PATTERNS
  9. from . import Plugin, PluginInfo
  10. from ._core import log
  11. if typing.TYPE_CHECKING:
  12. from searx.search import SearchWithPlugins
  13. from searx.extended_types import SXNG_Request
  14. from searx.result_types import Result, LegacyResult
  15. from searx.plugins import PluginCfg
  16. class SXNGPlugin(Plugin):
  17. """Remove trackers arguments from the returned URL."""
  18. id = "tracker_url_remover"
  19. log = log.getChild(id)
  20. def __init__(self, plg_cfg: "PluginCfg") -> None:
  21. super().__init__(plg_cfg)
  22. self.info = PluginInfo(
  23. id=self.id,
  24. name=gettext("Tracker URL remover"),
  25. description=gettext("Remove trackers arguments from the returned URL"),
  26. preference_section="privacy",
  27. )
  28. def on_result(self, request: "SXNG_Request", search: "SearchWithPlugins", result: Result) -> bool:
  29. result.filter_urls(self.filter_url_field)
  30. return True
  31. @classmethod
  32. def filter_url_field(cls, result: "Result|LegacyResult", field_name: str, url_src: str) -> bool | str:
  33. """Returns bool ``True`` to use URL unchanged (``False`` to ignore URL).
  34. If URL should be modified, the returned string is the new URL to use."""
  35. if not url_src:
  36. cls.log.debug("missing a URL in field %s", field_name)
  37. return True
  38. new_url = url_src
  39. parsed_new_url = urlparse(url=new_url)
  40. for rule in TRACKER_PATTERNS:
  41. if not re.match(rule["urlPattern"], new_url):
  42. # no match / ignore pattern
  43. continue
  44. in_exceptions = False
  45. for exception in rule["exceptions"]:
  46. if re.match(exception, new_url):
  47. in_exceptions = True
  48. break
  49. if in_exceptions:
  50. # pattern is in the list of exceptions / ignore pattern
  51. # hint: we can't break the outer pattern loop since we have
  52. # overlapping urlPattern like ".*"
  53. continue
  54. # remove tracker arguments from the url-query part
  55. query_args: list[tuple[str, str]] = list(parse_qsl(parsed_new_url.query))
  56. for name, val in query_args.copy():
  57. for reg in rule["trackerParams"]:
  58. if re.match(reg, name):
  59. cls.log.debug("%s remove tracker arg: %s='%s'", parsed_new_url.netloc, name, val)
  60. query_args.remove((name, val))
  61. parsed_new_url = parsed_new_url._replace(query=urlencode(query_args))
  62. new_url = urlunparse(parsed_new_url)
  63. if new_url != url_src:
  64. return new_url
  65. return True