__init__.py 7.2 KB

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