__init__.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. # pylint: disable=missing-function-docstring
  4. """This module implements the engine loader.
  5. Load and initialize the ``engines``, see :py:func:`load_engines` and register
  6. :py:obj:`engine_shortcuts`.
  7. usage::
  8. load_engines( settings['engines'] )
  9. """
  10. import sys
  11. import copy
  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. }
  40. """Defaults for the namespace of an engine module, see :py:func:`load_engine`"""
  41. categories = {'general': []}
  42. engines = {}
  43. engine_shortcuts = {}
  44. """Simple map of registered *shortcuts* to name of the engine (or ``None``).
  45. ::
  46. engine_shortcuts[engine.shortcut] = engine.name
  47. """
  48. def load_engine(engine_data):
  49. """Load engine from ``engine_data``.
  50. :param dict engine_data: Attributes from YAML ``settings:engines/<engine>``
  51. :return: initialized namespace of the ``<engine>``.
  52. 1. create a namespace and load module of the ``<engine>``
  53. 2. update namespace with the defaults from :py:obj:`ENGINE_DEFAULT_ARGS`
  54. 3. update namespace with values from ``engine_data``
  55. If engine *is active*, return namespace of the engine, otherwise return
  56. ``None``.
  57. This function also returns ``None`` if initialization of the namespace fails
  58. for one of the following reasons:
  59. - engine name contains underscore
  60. - engine name is not lowercase
  61. - required attribute is not set :py:func:`is_missing_required_attributes`
  62. """
  63. engine_name = engine_data['name']
  64. if '_' in engine_name:
  65. logger.error('Engine name contains underscore: "{}"'.format(engine_name))
  66. return None
  67. if engine_name.lower() != engine_name:
  68. logger.warn('Engine name is not lowercase: "{}", converting to lowercase'.format(engine_name))
  69. engine_name = engine_name.lower()
  70. engine_data['name'] = engine_name
  71. # load_module
  72. engine_module = engine_data['engine']
  73. try:
  74. engine = load_module(engine_module + '.py', ENGINE_DIR)
  75. except (SyntaxError, KeyboardInterrupt, SystemExit, SystemError, ImportError, RuntimeError):
  76. logger.exception('Fatal exception in engine "{}"'.format(engine_module))
  77. sys.exit(1)
  78. except BaseException:
  79. logger.exception('Cannot load engine "{}"'.format(engine_module))
  80. return None
  81. update_engine_attributes(engine, engine_data)
  82. set_language_attributes(engine)
  83. update_attributes_for_tor(engine)
  84. if not is_engine_active(engine):
  85. return None
  86. if is_missing_required_attributes(engine):
  87. return None
  88. engine.logger = logger.getChild(engine_name)
  89. return engine
  90. def update_engine_attributes(engine, engine_data):
  91. # set engine attributes from engine_data
  92. for param_name, param_value in engine_data.items():
  93. if param_name == 'categories':
  94. if isinstance(param_value, str):
  95. param_value = list(map(str.strip, param_value.split(',')))
  96. engine.categories = param_value
  97. elif param_name != 'engine':
  98. setattr(engine, param_name, param_value)
  99. # set default attributes
  100. for arg_name, arg_value in ENGINE_DEFAULT_ARGS.items():
  101. if not hasattr(engine, arg_name):
  102. setattr(engine, arg_name, copy.deepcopy(arg_value))
  103. def set_language_attributes(engine):
  104. # pylint: disable=protected-access
  105. # assign supported languages from json file
  106. if engine.name in ENGINES_LANGUAGES:
  107. engine.supported_languages = ENGINES_LANGUAGES[engine.name]
  108. # find custom aliases for non standard language codes
  109. for engine_lang in engine.supported_languages:
  110. iso_lang = match_language(engine_lang, BABEL_LANGS, fallback=None)
  111. if (iso_lang
  112. and iso_lang != engine_lang
  113. and not engine_lang.startswith(iso_lang)
  114. and iso_lang not in engine.supported_languages
  115. ):
  116. engine.language_aliases[iso_lang] = engine_lang
  117. # language_support
  118. engine.language_support = len(engine.supported_languages) > 0
  119. # assign language fetching method if auxiliary method exists
  120. if hasattr(engine, '_fetch_supported_languages'):
  121. headers = {
  122. 'User-Agent': gen_useragent(),
  123. 'Accept-Language': 'ja-JP,ja;q=0.8,en-US;q=0.5,en;q=0.3', # bing needs a non-English language
  124. }
  125. engine.fetch_supported_languages = (
  126. lambda: engine._fetch_supported_languages(
  127. get(engine.supported_languages_url, headers=headers))
  128. )
  129. def update_attributes_for_tor(engine):
  130. if (settings['outgoing'].get('using_tor_proxy')
  131. and hasattr(engine, 'onion_url') ):
  132. engine.search_url = engine.onion_url + getattr(engine, 'search_path', '')
  133. engine.timeout += settings['outgoing'].get('extra_proxy_timeout', 0)
  134. def is_missing_required_attributes(engine):
  135. """An attribute is required when its name doesn't start with ``_`` (underline).
  136. Required attributes must not be ``None``.
  137. """
  138. missing = False
  139. for engine_attr in dir(engine):
  140. if not engine_attr.startswith('_') and getattr(engine, engine_attr) is None:
  141. logger.error(
  142. 'Missing engine config attribute: "{0}.{1}"'
  143. .format(engine.name, engine_attr))
  144. missing = True
  145. return missing
  146. def is_engine_active(engine):
  147. # check if engine is inactive
  148. if engine.inactive is True:
  149. return False
  150. # exclude onion engines if not using tor
  151. if ('onions' in engine.categories
  152. and not settings['outgoing'].get('using_tor_proxy') ):
  153. return False
  154. return True
  155. def register_engine(engine):
  156. if engine.name in engines:
  157. logger.error('Engine config error: ambigious name: {0}'.format(engine.name))
  158. sys.exit(1)
  159. engines[engine.name] = engine
  160. if engine.shortcut in engine_shortcuts:
  161. logger.error('Engine config error: ambigious shortcut: {0}'.format(engine.shortcut))
  162. sys.exit(1)
  163. engine_shortcuts[engine.shortcut] = engine.name
  164. for category_name in engine.categories:
  165. categories.setdefault(category_name, []).append(engine)
  166. def load_engines(engine_list):
  167. """usage: ``engine_list = settings['engines']``
  168. """
  169. engines.clear()
  170. engine_shortcuts.clear()
  171. categories.clear()
  172. categories['general'] = []
  173. for engine_data in engine_list:
  174. engine = load_engine(engine_data)
  175. if engine:
  176. register_engine(engine)
  177. return engines