__init__.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """This module implements the engine loader.
  4. Load and initialize the ``engines``, see :py:func:`load_engines` and register
  5. :py:obj:`engine_shortcuts`.
  6. usage::
  7. load_engines( settings['engines'] )
  8. """
  9. import sys
  10. import copy
  11. from typing import Dict, List, Optional
  12. from os.path import realpath, dirname
  13. from babel.localedata import locale_identifiers
  14. from searx import logger, settings
  15. from searx.data import ENGINES_LANGUAGES
  16. from searx.network import get
  17. from searx.utils import load_module, match_language, gen_useragent
  18. logger = logger.getChild('engines')
  19. ENGINE_DIR = dirname(realpath(__file__))
  20. BABEL_LANGS = [
  21. lang_parts[0] + '-' + lang_parts[-1] if len(lang_parts) > 1 else lang_parts[0]
  22. for lang_parts in (lang_code.split('_') for lang_code in locale_identifiers())
  23. ]
  24. ENGINE_DEFAULT_ARGS = {
  25. "engine_type": "online",
  26. "inactive": False,
  27. "disabled": False,
  28. "timeout": settings["outgoing"]["request_timeout"],
  29. "shortcut": "-",
  30. "categories": ["general"],
  31. "supported_languages": [],
  32. "language_aliases": {},
  33. "paging": False,
  34. "safesearch": False,
  35. "time_range_support": False,
  36. "enable_http": False,
  37. "using_tor_proxy": False,
  38. "display_error_messages": True,
  39. "tokens": [],
  40. "about": {},
  41. }
  42. # set automatically when an engine does not have any tab category
  43. OTHER_CATEGORY = 'other'
  44. class Engine: # pylint: disable=too-few-public-methods
  45. """This class is currently never initialized and only used for type hinting."""
  46. name: str
  47. engine: str
  48. shortcut: str
  49. categories: List[str]
  50. supported_languages: List[str]
  51. about: dict
  52. inactive: bool
  53. disabled: bool
  54. language_support: bool
  55. paging: bool
  56. safesearch: bool
  57. time_range_support: bool
  58. timeout: float
  59. # Defaults for the namespace of an engine module, see :py:func:`load_engine`
  60. categories = {'general': []}
  61. engines: Dict[str, Engine] = {}
  62. engine_shortcuts = {}
  63. """Simple map of registered *shortcuts* to name of the engine (or ``None``).
  64. ::
  65. engine_shortcuts[engine.shortcut] = engine.name
  66. """
  67. def load_engine(engine_data: dict) -> Optional[Engine]:
  68. """Load engine from ``engine_data``.
  69. :param dict engine_data: Attributes from YAML ``settings:engines/<engine>``
  70. :return: initialized namespace of the ``<engine>``.
  71. 1. create a namespace and load module of the ``<engine>``
  72. 2. update namespace with the defaults from :py:obj:`ENGINE_DEFAULT_ARGS`
  73. 3. update namespace with values from ``engine_data``
  74. If engine *is active*, return namespace of the engine, otherwise return
  75. ``None``.
  76. This function also returns ``None`` if initialization of the namespace fails
  77. for one of the following reasons:
  78. - engine name contains underscore
  79. - engine name is not lowercase
  80. - required attribute is not set :py:func:`is_missing_required_attributes`
  81. """
  82. engine_name = engine_data['name']
  83. if '_' in engine_name:
  84. logger.error('Engine name contains underscore: "{}"'.format(engine_name))
  85. return None
  86. if engine_name.lower() != engine_name:
  87. logger.warn('Engine name is not lowercase: "{}", converting to lowercase'.format(engine_name))
  88. engine_name = engine_name.lower()
  89. engine_data['name'] = engine_name
  90. # load_module
  91. engine_module = engine_data['engine']
  92. try:
  93. engine = load_module(engine_module + '.py', ENGINE_DIR)
  94. except (SyntaxError, KeyboardInterrupt, SystemExit, SystemError, ImportError, RuntimeError):
  95. logger.exception('Fatal exception in engine "{}"'.format(engine_module))
  96. sys.exit(1)
  97. except BaseException:
  98. logger.exception('Cannot load engine "{}"'.format(engine_module))
  99. return None
  100. update_engine_attributes(engine, engine_data)
  101. set_language_attributes(engine)
  102. update_attributes_for_tor(engine)
  103. if not is_engine_active(engine):
  104. return None
  105. if is_missing_required_attributes(engine):
  106. return None
  107. set_loggers(engine, engine_name)
  108. if not any(cat in settings['categories_as_tabs'] for cat in engine.categories):
  109. engine.categories.append(OTHER_CATEGORY)
  110. return engine
  111. def set_loggers(engine, engine_name):
  112. # set the logger for engine
  113. engine.logger = logger.getChild(engine_name)
  114. # the engine may have load some other engines
  115. # may sure the logger is initialized
  116. # use sys.modules.copy() to avoid "RuntimeError: dictionary changed size during iteration"
  117. # see https://github.com/python/cpython/issues/89516
  118. # and https://docs.python.org/3.10/library/sys.html#sys.modules
  119. modules = sys.modules.copy()
  120. for module_name, module in modules.items():
  121. if (
  122. module_name.startswith("searx.engines")
  123. and module_name != "searx.engines.__init__"
  124. and not hasattr(module, "logger")
  125. ):
  126. module_engine_name = module_name.split(".")[-1]
  127. module.logger = logger.getChild(module_engine_name)
  128. def update_engine_attributes(engine: Engine, engine_data):
  129. # set engine attributes from engine_data
  130. for param_name, param_value in engine_data.items():
  131. if param_name == 'categories':
  132. if isinstance(param_value, str):
  133. param_value = list(map(str.strip, param_value.split(',')))
  134. engine.categories = param_value
  135. elif hasattr(engine, 'about') and param_name == 'about':
  136. engine.about = {**engine.about, **engine_data['about']}
  137. else:
  138. setattr(engine, param_name, param_value)
  139. # set default attributes
  140. for arg_name, arg_value in ENGINE_DEFAULT_ARGS.items():
  141. if not hasattr(engine, arg_name):
  142. setattr(engine, arg_name, copy.deepcopy(arg_value))
  143. def set_language_attributes(engine: Engine):
  144. # assign supported languages from json file
  145. if engine.name in ENGINES_LANGUAGES:
  146. engine.supported_languages = ENGINES_LANGUAGES[engine.name]
  147. elif engine.engine in ENGINES_LANGUAGES:
  148. # The key of the dictionary ENGINES_LANGUAGES is the *engine name*
  149. # configured in settings.xml. When multiple engines are configured in
  150. # settings.yml to use the same origin engine (python module) these
  151. # additional engines can use the languages from the origin engine.
  152. # For this use the configured ``engine: ...`` from settings.yml
  153. engine.supported_languages = ENGINES_LANGUAGES[engine.engine]
  154. if hasattr(engine, 'language'):
  155. # For an engine, when there is `language: ...` in the YAML settings, the
  156. # engine supports only one language, in this case
  157. # engine.supported_languages should contains this value defined in
  158. # settings.yml
  159. if engine.language not in engine.supported_languages:
  160. raise ValueError(
  161. "settings.yml - engine: '%s' / language: '%s' not supported" % (engine.name, engine.language)
  162. )
  163. if isinstance(engine.supported_languages, dict):
  164. engine.supported_languages = {engine.language: engine.supported_languages[engine.language]}
  165. else:
  166. engine.supported_languages = [engine.language]
  167. # find custom aliases for non standard language codes
  168. for engine_lang in engine.supported_languages:
  169. iso_lang = match_language(engine_lang, BABEL_LANGS, fallback=None)
  170. if (
  171. iso_lang
  172. and iso_lang != engine_lang
  173. and not engine_lang.startswith(iso_lang)
  174. and iso_lang not in engine.supported_languages
  175. ):
  176. engine.language_aliases[iso_lang] = engine_lang
  177. # language_support
  178. engine.language_support = len(engine.supported_languages) > 0
  179. # assign language fetching method if auxiliary method exists
  180. if hasattr(engine, '_fetch_supported_languages'):
  181. headers = {
  182. 'User-Agent': gen_useragent(),
  183. 'Accept-Language': "en-US,en;q=0.5", # bing needs to set the English language
  184. }
  185. engine.fetch_supported_languages = (
  186. # pylint: disable=protected-access
  187. lambda: engine._fetch_supported_languages(get(engine.supported_languages_url, headers=headers))
  188. )
  189. def update_attributes_for_tor(engine: Engine) -> bool:
  190. if using_tor_proxy(engine) and hasattr(engine, 'onion_url'):
  191. engine.search_url = engine.onion_url + getattr(engine, 'search_path', '')
  192. engine.timeout += settings['outgoing'].get('extra_proxy_timeout', 0)
  193. def is_missing_required_attributes(engine):
  194. """An attribute is required when its name doesn't start with ``_`` (underline).
  195. Required attributes must not be ``None``.
  196. """
  197. missing = False
  198. for engine_attr in dir(engine):
  199. if not engine_attr.startswith('_') and getattr(engine, engine_attr) is None:
  200. logger.error('Missing engine config attribute: "{0}.{1}"'.format(engine.name, engine_attr))
  201. missing = True
  202. return missing
  203. def using_tor_proxy(engine: Engine):
  204. """Return True if the engine configuration declares to use Tor."""
  205. return settings['outgoing'].get('using_tor_proxy') or getattr(engine, 'using_tor_proxy', False)
  206. def is_engine_active(engine: Engine):
  207. # check if engine is inactive
  208. if engine.inactive is True:
  209. return False
  210. # exclude onion engines if not using tor
  211. if 'onions' in engine.categories and not using_tor_proxy(engine):
  212. return False
  213. return True
  214. def register_engine(engine: Engine):
  215. if engine.name in engines:
  216. logger.error('Engine config error: ambigious name: {0}'.format(engine.name))
  217. sys.exit(1)
  218. engines[engine.name] = engine
  219. if engine.shortcut in engine_shortcuts:
  220. logger.error('Engine config error: ambigious shortcut: {0}'.format(engine.shortcut))
  221. sys.exit(1)
  222. engine_shortcuts[engine.shortcut] = engine.name
  223. for category_name in engine.categories:
  224. categories.setdefault(category_name, []).append(engine)
  225. def load_engines(engine_list):
  226. """usage: ``engine_list = settings['engines']``"""
  227. engines.clear()
  228. engine_shortcuts.clear()
  229. categories.clear()
  230. categories['general'] = []
  231. for engine_data in engine_list:
  232. engine = load_engine(engine_data)
  233. if engine:
  234. register_engine(engine)
  235. return engines