online.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. 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. self.logger.error(
  119. "HTTP requests timeout (search duration : {0} s, timeout: {1} s) : {2}"
  120. .format(
  121. default_timer() - start_time,
  122. timeout_limit,
  123. e.__class__.__name__
  124. )
  125. )
  126. except (httpx.HTTPError, httpx.StreamError) as e:
  127. # other requests exception
  128. self.handle_exception(result_container, e, suspend=True)
  129. self.logger.exception(
  130. "requests exception (search duration : {0} s, timeout: {1} s) : {2}"
  131. .format(
  132. default_timer() - start_time,
  133. timeout_limit,
  134. e
  135. )
  136. )
  137. except SearxEngineCaptchaException as e:
  138. self.handle_exception(result_container, e, suspend=True)
  139. self.logger.exception('CAPTCHA')
  140. except SearxEngineTooManyRequestsException as e:
  141. self.handle_exception(result_container, e, suspend=True)
  142. self.logger.exception('Too many requests')
  143. except SearxEngineAccessDeniedException as e:
  144. self.handle_exception(result_container, e, suspend=True)
  145. self.logger.exception('Searx is blocked')
  146. except Exception as e: # pylint: disable=broad-except
  147. self.handle_exception(result_container, e)
  148. self.logger.exception('exception : {0}'.format(e))
  149. def get_default_tests(self):
  150. tests = {}
  151. tests['simple'] = {
  152. 'matrix': {'query': ('life', 'computer')},
  153. 'result_container': ['not_empty'],
  154. }
  155. if getattr(self.engine, 'paging', False):
  156. tests['paging'] = {
  157. 'matrix': {'query': 'time',
  158. 'pageno': (1, 2, 3)},
  159. 'result_container': ['not_empty'],
  160. 'test': ['unique_results']
  161. }
  162. if 'general' in self.engine.categories:
  163. # avoid documentation about HTML tags (<time> and <input type="time">)
  164. tests['paging']['matrix']['query'] = 'news'
  165. if getattr(self.engine, 'time_range', False):
  166. tests['time_range'] = {
  167. 'matrix': {'query': 'news',
  168. 'time_range': (None, 'day')},
  169. 'result_container': ['not_empty'],
  170. 'test': ['unique_results']
  171. }
  172. if getattr(self.engine, 'supported_languages', []):
  173. tests['lang_fr'] = {
  174. 'matrix': {'query': 'paris', 'lang': 'fr'},
  175. 'result_container': ['not_empty', ('has_language', 'fr')],
  176. }
  177. tests['lang_en'] = {
  178. 'matrix': {'query': 'paris', 'lang': 'en'},
  179. 'result_container': ['not_empty', ('has_language', 'en')],
  180. }
  181. if getattr(self.engine, 'safesearch', False):
  182. tests['safesearch'] = {
  183. 'matrix': {'query': 'porn',
  184. 'safesearch': (0, 2)},
  185. 'test': ['unique_results']
  186. }
  187. return tests