online.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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 import logger
  10. from searx.utils import gen_useragent
  11. from searx.exceptions import (
  12. SearxEngineAccessDeniedException,
  13. SearxEngineCaptchaException,
  14. SearxEngineTooManyRequestsException,
  15. )
  16. from searx.metrics.error_recorder import count_error
  17. from .abstract import EngineProcessor
  18. logger = logger.getChild('searx.search.processor.online')
  19. def default_request_params():
  20. """Default request parameters for ``online`` engines."""
  21. return {
  22. 'method': 'GET',
  23. 'headers': {},
  24. 'data': {},
  25. 'url': '',
  26. 'cookies': {},
  27. 'verify': True,
  28. 'auth': None
  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. return params
  50. def _send_http_request(self, params):
  51. # create dictionary which contain all
  52. # informations about the request
  53. request_args = dict(
  54. headers=params['headers'],
  55. cookies=params['cookies'],
  56. verify=params['verify'],
  57. auth=params['auth']
  58. )
  59. # max_redirects
  60. max_redirects = params.get('max_redirects')
  61. if max_redirects:
  62. request_args['max_redirects'] = max_redirects
  63. # allow_redirects
  64. if 'allow_redirects' in params:
  65. request_args['allow_redirects'] = params['allow_redirects']
  66. # soft_max_redirects
  67. soft_max_redirects = params.get('soft_max_redirects', max_redirects or 0)
  68. # raise_for_status
  69. request_args['raise_for_httperror'] = params.get('raise_for_httperror', True)
  70. # specific type of request (GET or POST)
  71. if params['method'] == 'GET':
  72. req = searx.network.get
  73. else:
  74. req = searx.network.post
  75. request_args['data'] = params['data']
  76. # send the request
  77. response = req(params['url'], **request_args)
  78. # check soft limit of the redirect count
  79. if len(response.history) > soft_max_redirects:
  80. # unexpected redirect : record an error
  81. # but the engine might still return valid results.
  82. status_code = str(response.status_code or '')
  83. reason = response.reason_phrase or ''
  84. hostname = response.url.host
  85. count_error(self.engine_name,
  86. '{} redirects, maximum: {}'.format(len(response.history), soft_max_redirects),
  87. (status_code, reason, hostname),
  88. secondary=True)
  89. return response
  90. def _search_basic(self, query, params):
  91. # update request parameters dependent on
  92. # search-engine (contained in engines folder)
  93. self.engine.request(query, params)
  94. # ignoring empty urls
  95. if params['url'] is None:
  96. return None
  97. if not params['url']:
  98. return None
  99. # send request
  100. response = self._send_http_request(params)
  101. # parse the response
  102. response.search_params = params
  103. return self.engine.response(response)
  104. def search(self, query, params, result_container, start_time, timeout_limit):
  105. # set timeout for all HTTP requests
  106. searx.network.set_timeout_for_thread(timeout_limit, start_time=start_time)
  107. # reset the HTTP total time
  108. searx.network.reset_time_for_thread()
  109. # set the network
  110. searx.network.set_context_network_name(self.engine_name)
  111. try:
  112. # send requests and parse the results
  113. search_results = self._search_basic(query, params)
  114. self.extend_container(result_container, start_time, search_results)
  115. except (httpx.TimeoutException, asyncio.TimeoutError) as e:
  116. # requests timeout (connect or read)
  117. self.handle_exception(result_container, e, suspend=True)
  118. logger.error("engine {0} : HTTP requests timeout"
  119. "(search duration : {1} s, timeout: {2} s) : {3}"
  120. .format(self.engine_name, default_timer() - start_time,
  121. timeout_limit,
  122. e.__class__.__name__))
  123. except (httpx.HTTPError, httpx.StreamError) as e:
  124. # other requests exception
  125. self.handle_exception(result_container, e, suspend=True)
  126. logger.exception("engine {0} : requests exception"
  127. "(search duration : {1} s, timeout: {2} s) : {3}"
  128. .format(self.engine_name, default_timer() - start_time,
  129. timeout_limit,
  130. e))
  131. except SearxEngineCaptchaException as e:
  132. self.handle_exception(result_container, e, suspend=True)
  133. logger.exception('engine {0} : CAPTCHA'.format(self.engine_name))
  134. except SearxEngineTooManyRequestsException as e:
  135. self.handle_exception(result_container, e, suspend=True)
  136. logger.exception('engine {0} : Too many requests'.format(self.engine_name))
  137. except SearxEngineAccessDeniedException as e:
  138. self.handle_exception(result_container, e, suspend=True)
  139. logger.exception('engine {0} : Searx is blocked'.format(self.engine_name))
  140. except Exception as e: # pylint: disable=broad-except
  141. self.handle_exception(result_container, e)
  142. logger.exception('engine {0} : exception : {1}'.format(self.engine_name, e))
  143. def get_default_tests(self):
  144. tests = {}
  145. tests['simple'] = {
  146. 'matrix': {'query': ('life', 'computer')},
  147. 'result_container': ['not_empty'],
  148. }
  149. if getattr(self.engine, 'paging', False):
  150. tests['paging'] = {
  151. 'matrix': {'query': 'time',
  152. 'pageno': (1, 2, 3)},
  153. 'result_container': ['not_empty'],
  154. 'test': ['unique_results']
  155. }
  156. if 'general' in self.engine.categories:
  157. # avoid documentation about HTML tags (<time> and <input type="time">)
  158. tests['paging']['matrix']['query'] = 'news'
  159. if getattr(self.engine, 'time_range', False):
  160. tests['time_range'] = {
  161. 'matrix': {'query': 'news',
  162. 'time_range': (None, 'day')},
  163. 'result_container': ['not_empty'],
  164. 'test': ['unique_results']
  165. }
  166. if getattr(self.engine, 'supported_languages', []):
  167. tests['lang_fr'] = {
  168. 'matrix': {'query': 'paris', 'lang': 'fr'},
  169. 'result_container': ['not_empty', ('has_language', 'fr')],
  170. }
  171. tests['lang_en'] = {
  172. 'matrix': {'query': 'paris', 'lang': 'en'},
  173. 'result_container': ['not_empty', ('has_language', 'en')],
  174. }
  175. if getattr(self.engine, 'safesearch', False):
  176. tests['safesearch'] = {
  177. 'matrix': {'query': 'porn',
  178. 'safesearch': (0, 2)},
  179. 'test': ['unique_results']
  180. }
  181. return tests