__init__.py 9.1 KB

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