online.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Processores for engine-type: ``online``
  4. """
  5. from timeit import default_timer
  6. import asyncio
  7. import httpx
  8. import searx.network
  9. from searx.utils import gen_useragent
  10. from searx.exceptions import (
  11. SearxEngineAccessDeniedException,
  12. SearxEngineCaptchaException,
  13. SearxEngineTooManyRequestsException,
  14. )
  15. from searx.metrics.error_recorder import count_error
  16. from .abstract import EngineProcessor
  17. def default_request_params():
  18. """Default request parameters for ``online`` engines."""
  19. return {
  20. # fmt: off
  21. 'method': 'GET',
  22. 'headers': {},
  23. 'data': {},
  24. 'url': '',
  25. 'cookies': {},
  26. 'verify': True,
  27. 'auth': None
  28. # fmt: on
  29. }
  30. class OnlineProcessor(EngineProcessor):
  31. """Processor class for ``online`` engines."""
  32. engine_type = 'online'
  33. def initialize(self):
  34. # set timeout for all HTTP requests
  35. searx.network.set_timeout_for_thread(self.engine.timeout, start_time=default_timer())
  36. # reset the HTTP total time
  37. searx.network.reset_time_for_thread()
  38. # set the network
  39. searx.network.set_context_network_name(self.engine_name)
  40. super().initialize()
  41. def get_params(self, search_query, engine_category):
  42. params = super().get_params(search_query, engine_category)
  43. if params is None:
  44. return None
  45. # add default params
  46. params.update(default_request_params())
  47. # add an user agent
  48. params['headers']['User-Agent'] = gen_useragent()
  49. # add Accept-Language header
  50. if self.engine.send_accept_language_header and search_query.locale:
  51. ac_lang = search_query.locale.language
  52. if search_query.locale.territory:
  53. ac_lang = "%s-%s,%s;q=0.9,*;q=0.5" % (
  54. search_query.locale.language,
  55. search_query.locale.territory,
  56. search_query.locale.language,
  57. )
  58. params['headers']['Accept-Language'] = ac_lang
  59. return params
  60. def _send_http_request(self, params):
  61. # create dictionary which contain all
  62. # information about the request
  63. request_args = dict(
  64. headers=params['headers'], cookies=params['cookies'], verify=params['verify'], auth=params['auth']
  65. )
  66. # max_redirects
  67. max_redirects = params.get('max_redirects')
  68. if max_redirects:
  69. request_args['max_redirects'] = max_redirects
  70. # allow_redirects
  71. if 'allow_redirects' in params:
  72. request_args['allow_redirects'] = params['allow_redirects']
  73. # soft_max_redirects
  74. soft_max_redirects = params.get('soft_max_redirects', max_redirects or 0)
  75. # raise_for_status
  76. request_args['raise_for_httperror'] = params.get('raise_for_httperror', True)
  77. # specific type of request (GET or POST)
  78. if params['method'] == 'GET':
  79. req = searx.network.get
  80. else:
  81. req = searx.network.post
  82. request_args['data'] = params['data']
  83. # send the request
  84. response = req(params['url'], **request_args)
  85. # check soft limit of the redirect count
  86. if len(response.history) > soft_max_redirects:
  87. # unexpected redirect : record an error
  88. # but the engine might still return valid results.
  89. status_code = str(response.status_code or '')
  90. reason = response.reason_phrase or ''
  91. hostname = response.url.host
  92. count_error(
  93. self.engine_name,
  94. '{} redirects, maximum: {}'.format(len(response.history), soft_max_redirects),
  95. (status_code, reason, hostname),
  96. secondary=True,
  97. )
  98. return response
  99. def _search_basic(self, query, params):
  100. # update request parameters dependent on
  101. # search-engine (contained in engines folder)
  102. self.engine.request(query, params)
  103. # ignoring empty urls
  104. if params['url'] is None:
  105. return None
  106. if not params['url']:
  107. return None
  108. # send request
  109. response = self._send_http_request(params)
  110. # parse the response
  111. response.search_params = params
  112. return self.engine.response(response)
  113. def search(self, query, params, result_container, start_time, timeout_limit):
  114. # set timeout for all HTTP requests
  115. searx.network.set_timeout_for_thread(timeout_limit, start_time=start_time)
  116. # reset the HTTP total time
  117. searx.network.reset_time_for_thread()
  118. # set the network
  119. searx.network.set_context_network_name(self.engine_name)
  120. try:
  121. # send requests and parse the results
  122. search_results = self._search_basic(query, params)
  123. self.extend_container(result_container, start_time, search_results)
  124. except (httpx.TimeoutException, asyncio.TimeoutError) as e:
  125. # requests timeout (connect or read)
  126. self.handle_exception(result_container, e, suspend=True)
  127. self.logger.error(
  128. "HTTP requests timeout (search duration : {0} s, timeout: {1} s) : {2}".format(
  129. default_timer() - start_time, timeout_limit, e.__class__.__name__
  130. )
  131. )
  132. except (httpx.HTTPError, httpx.StreamError) as e:
  133. # other requests exception
  134. self.handle_exception(result_container, e, suspend=True)
  135. self.logger.exception(
  136. "requests exception (search duration : {0} s, timeout: {1} s) : {2}".format(
  137. default_timer() - start_time, timeout_limit, e
  138. )
  139. )
  140. except SearxEngineCaptchaException as e:
  141. self.handle_exception(result_container, e, suspend=True)
  142. self.logger.exception('CAPTCHA')
  143. except SearxEngineTooManyRequestsException as e:
  144. if "google" in self.engine_name:
  145. self.logger.warn(
  146. "Set to 'true' the use_mobile_ui parameter in the 'engines:'"
  147. " section of your settings.yml file if google is blocked for you."
  148. )
  149. self.handle_exception(result_container, e, suspend=True)
  150. self.logger.exception('Too many requests')
  151. except SearxEngineAccessDeniedException as e:
  152. self.handle_exception(result_container, e, suspend=True)
  153. self.logger.exception('Searx is blocked')
  154. except Exception as e: # pylint: disable=broad-except
  155. self.handle_exception(result_container, e)
  156. self.logger.exception('exception : {0}'.format(e))
  157. def get_default_tests(self):
  158. tests = {}
  159. tests['simple'] = {
  160. 'matrix': {'query': ('life', 'computer')},
  161. 'result_container': ['not_empty'],
  162. }
  163. if getattr(self.engine, 'paging', False):
  164. tests['paging'] = {
  165. 'matrix': {'query': 'time', 'pageno': (1, 2, 3)},
  166. 'result_container': ['not_empty'],
  167. 'test': ['unique_results'],
  168. }
  169. if 'general' in self.engine.categories:
  170. # avoid documentation about HTML tags (<time> and <input type="time">)
  171. tests['paging']['matrix']['query'] = 'news'
  172. if getattr(self.engine, 'time_range', False):
  173. tests['time_range'] = {
  174. 'matrix': {'query': 'news', 'time_range': (None, 'day')},
  175. 'result_container': ['not_empty'],
  176. 'test': ['unique_results'],
  177. }
  178. if getattr(self.engine, 'supported_languages', []):
  179. tests['lang_fr'] = {
  180. 'matrix': {'query': 'paris', 'lang': 'fr'},
  181. 'result_container': ['not_empty', ('has_language', 'fr')],
  182. }
  183. tests['lang_en'] = {
  184. 'matrix': {'query': 'paris', 'lang': 'en'},
  185. 'result_container': ['not_empty', ('has_language', 'en')],
  186. }
  187. if getattr(self.engine, 'safesearch', False):
  188. tests['safesearch'] = {'matrix': {'query': 'porn', 'safesearch': (0, 2)}, 'test': ['unique_results']}
  189. return tests