online.py 8.7 KB

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