online.py 7.6 KB

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