__init__.py 9.7 KB

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