hostnames.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # pylint: disable=too-many-branches, unused-argument
  3. """
  4. During the initialization phase, the plugin checks whether a ``hostnames:``
  5. configuration exists. If this is not the case, the plugin is not included
  6. in the PluginStorage (it is not available for selection).
  7. - ``hostnames.replace``: A **mapping** of regular expressions to hostnames to be
  8. replaced by other hostnames.
  9. .. code:: yaml
  10. hostnames:
  11. replace:
  12. '(.*\\.)?youtube\\.com$': 'invidious.example.com'
  13. '(.*\\.)?youtu\\.be$': 'invidious.example.com'
  14. ...
  15. - ``hostnames.remove``: A **list** of regular expressions of the hostnames whose
  16. results should be taken from the results list.
  17. .. code:: yaml
  18. hostnames:
  19. remove:
  20. - '(.*\\.)?facebook.com$'
  21. - ...
  22. - ``hostnames.high_priority``: A **list** of regular expressions for hostnames
  23. whose result should be given higher priority. The results from these hosts are
  24. arranged higher in the results list.
  25. .. code:: yaml
  26. hostnames:
  27. high_priority:
  28. - '(.*\\.)?wikipedia.org$'
  29. - ...
  30. - ``hostnames.lower_priority``: A **list** of regular expressions for hostnames
  31. whose result should be given lower priority. The results from these hosts are
  32. arranged lower in the results list.
  33. .. code:: yaml
  34. hostnames:
  35. low_priority:
  36. - '(.*\\.)?google(\\..*)?$'
  37. - ...
  38. If the URL matches the pattern of ``high_priority`` AND ``low_priority``, the
  39. higher priority wins over the lower priority.
  40. Alternatively, you can also specify a file name for the **mappings** or
  41. **lists** to load these from an external file:
  42. .. code:: yaml
  43. hostnames:
  44. replace: 'rewrite-hosts.yml'
  45. remove:
  46. - '(.*\\.)?facebook.com$'
  47. - ...
  48. low_priority:
  49. - '(.*\\.)?google(\\..*)?$'
  50. - ...
  51. high_priority:
  52. - '(.*\\.)?wikipedia.org$'
  53. - ...
  54. The ``rewrite-hosts.yml`` from the example above must be in the folder in which
  55. the ``settings.yml`` file is already located (``/etc/searxng``). The file then
  56. only contains the lists or the mapping tables without further information on the
  57. namespaces. In the example above, this would be a mapping table that looks
  58. something like this:
  59. .. code:: yaml
  60. '(.*\\.)?youtube\\.com$': 'invidious.example.com'
  61. '(.*\\.)?youtu\\.be$': 'invidious.example.com'
  62. """
  63. from __future__ import annotations
  64. import typing
  65. import re
  66. from urllib.parse import urlunparse, urlparse
  67. from flask_babel import gettext
  68. from searx import settings
  69. from searx.result_types._base import MainResult, LegacyResult
  70. from searx.settings_loader import get_yaml_cfg
  71. from searx.plugins import Plugin, PluginInfo
  72. from ._core import log
  73. if typing.TYPE_CHECKING:
  74. import flask
  75. from searx.search import SearchWithPlugins
  76. from searx.extended_types import SXNG_Request
  77. from searx.result_types import Result
  78. from searx.plugins import PluginCfg
  79. REPLACE: dict[re.Pattern, str] = {}
  80. REMOVE: set = set()
  81. HIGH: set = set()
  82. LOW: set = set()
  83. class SXNGPlugin(Plugin):
  84. """Rewrite hostnames, remove results or prioritize them."""
  85. id = "hostnames"
  86. def __init__(self, plg_cfg: "PluginCfg") -> None:
  87. super().__init__(plg_cfg)
  88. self.info = PluginInfo(
  89. id=self.id,
  90. name=gettext("Hostnames plugin"),
  91. description=gettext("Rewrite hostnames, remove results or prioritize them based on the hostname"),
  92. preference_section="general",
  93. )
  94. def on_result(self, request: "SXNG_Request", search: "SearchWithPlugins", result: Result) -> bool:
  95. for pattern in REMOVE:
  96. if result.parsed_url and pattern.search(result.parsed_url.netloc):
  97. # if the link (parsed_url) of the result match, then remove the
  98. # result from the result list, in any other case, the result
  99. # remains in the list / see final "return True" below.
  100. # log.debug("FIXME: remove [url/parsed_url] %s %s", pattern.pattern, result.url)
  101. return False
  102. result.filter_urls(filter_url_field)
  103. if isinstance(result, (MainResult, LegacyResult)):
  104. for pattern in LOW:
  105. if result.parsed_url and pattern.search(result.parsed_url.netloc):
  106. result.priority = "low"
  107. for pattern in HIGH:
  108. if result.parsed_url and pattern.search(result.parsed_url.netloc):
  109. result.priority = "high"
  110. return True
  111. def init(self, app: "flask.Flask") -> bool: # pylint: disable=unused-argument
  112. global REPLACE, REMOVE, HIGH, LOW # pylint: disable=global-statement
  113. if not settings.get(self.id):
  114. # Remove plugin, if there isn't a "hostnames:" setting
  115. return False
  116. REPLACE = self._load_regular_expressions("replace") or {} # type: ignore
  117. REMOVE = self._load_regular_expressions("remove") or set() # type: ignore
  118. HIGH = self._load_regular_expressions("high_priority") or set() # type: ignore
  119. LOW = self._load_regular_expressions("low_priority") or set() # type: ignore
  120. return True
  121. def _load_regular_expressions(self, settings_key) -> dict[re.Pattern, str] | set | None:
  122. setting_value = settings.get(self.id, {}).get(settings_key)
  123. if not setting_value:
  124. return None
  125. # load external file with configuration
  126. if isinstance(setting_value, str):
  127. setting_value = get_yaml_cfg(setting_value)
  128. if isinstance(setting_value, list):
  129. return {re.compile(r) for r in setting_value}
  130. if isinstance(setting_value, dict):
  131. return {re.compile(p): r for (p, r) in setting_value.items()}
  132. return None
  133. def filter_url_field(result: "Result|LegacyResult", field_name: str, url_src: str) -> bool | str:
  134. """Returns bool ``True`` to use URL unchanged (``False`` to ignore URL).
  135. If URL should be modified, the returned string is the new URL to use."""
  136. if not url_src:
  137. log.debug("missing a URL in field %s", field_name)
  138. return True
  139. url_src_parsed = urlparse(url=url_src)
  140. for pattern in REMOVE:
  141. if pattern.search(url_src_parsed.netloc):
  142. return False
  143. for pattern, replacement in REPLACE.items():
  144. if pattern.search(url_src_parsed.netloc):
  145. new_url = url_src_parsed._replace(netloc=pattern.sub(replacement, url_src_parsed.netloc))
  146. new_url = urlunparse(new_url)
  147. return new_url
  148. return True