online.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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 ssl
  8. import httpx
  9. import searx.network
  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. def default_request_params():
  19. """Default request parameters for ``online`` engines."""
  20. return {
  21. # fmt: off
  22. 'method': 'GET',
  23. 'headers': {},
  24. 'data': {},
  25. 'url': '',
  26. 'cookies': {},
  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(headers=params['headers'], cookies=params['cookies'], auth=params['auth'])
  64. # verify
  65. # if not None, it overrides the verify value defined in the network.
  66. # use False to accept any server certificate
  67. # use a path to file to specify a server certificate
  68. verify = params.get('verify')
  69. if verify is not None:
  70. request_args['verify'] = params['verify']
  71. # max_redirects
  72. max_redirects = params.get('max_redirects')
  73. if max_redirects:
  74. request_args['max_redirects'] = max_redirects
  75. # allow_redirects
  76. if 'allow_redirects' in params:
  77. request_args['allow_redirects'] = params['allow_redirects']
  78. # soft_max_redirects
  79. soft_max_redirects = params.get('soft_max_redirects', max_redirects or 0)
  80. # raise_for_status
  81. request_args['raise_for_httperror'] = params.get('raise_for_httperror', True)
  82. # specific type of request (GET or POST)
  83. if params['method'] == 'GET':
  84. req = searx.network.get
  85. else:
  86. req = searx.network.post
  87. request_args['data'] = params['data']
  88. # send the request
  89. response = req(params['url'], **request_args)
  90. # check soft limit of the redirect count
  91. if len(response.history) > soft_max_redirects:
  92. # unexpected redirect : record an error
  93. # but the engine might still return valid results.
  94. status_code = str(response.status_code or '')
  95. reason = response.reason_phrase or ''
  96. hostname = response.url.host
  97. count_error(
  98. self.engine_name,
  99. '{} redirects, maximum: {}'.format(len(response.history), soft_max_redirects),
  100. (status_code, reason, hostname),
  101. secondary=True,
  102. )
  103. return response
  104. def _search_basic(self, query, params):
  105. # update request parameters dependent on
  106. # search-engine (contained in engines folder)
  107. self.engine.request(query, params)
  108. # ignoring empty urls
  109. if params['url'] is None:
  110. return None
  111. if not params['url']:
  112. return None
  113. # send request
  114. response = self._send_http_request(params)
  115. # parse the response
  116. response.search_params = params
  117. return self.engine.response(response)
  118. def search(self, query, params, result_container, start_time, timeout_limit):
  119. # set timeout for all HTTP requests
  120. searx.network.set_timeout_for_thread(timeout_limit, start_time=start_time)
  121. # reset the HTTP total time
  122. searx.network.reset_time_for_thread()
  123. # set the network
  124. searx.network.set_context_network_name(self.engine_name)
  125. try:
  126. # send requests and parse the results
  127. search_results = self._search_basic(query, params)
  128. self.extend_container(result_container, start_time, search_results)
  129. except ssl.SSLError as e:
  130. # requests timeout (connect or read)
  131. self.handle_exception(result_container, e, suspend=True)
  132. self.logger.error("SSLError {}, verify={}".format(e, searx.network.get_network(self.engine_name).verify))
  133. except (httpx.TimeoutException, asyncio.TimeoutError) as e:
  134. # requests timeout (connect or read)
  135. self.handle_exception(result_container, e, suspend=True)
  136. self.logger.error(
  137. "HTTP requests timeout (search duration : {0} s, timeout: {1} s) : {2}".format(
  138. default_timer() - start_time, timeout_limit, e.__class__.__name__
  139. )
  140. )
  141. except (httpx.HTTPError, httpx.StreamError) as e:
  142. # other requests exception
  143. self.handle_exception(result_container, e, suspend=True)
  144. self.logger.exception(
  145. "requests exception (search duration : {0} s, timeout: {1} s) : {2}".format(
  146. default_timer() - start_time, timeout_limit, e
  147. )
  148. )
  149. except SearxEngineCaptchaException as e:
  150. self.handle_exception(result_container, e, suspend=True)
  151. self.logger.exception('CAPTCHA')
  152. except SearxEngineTooManyRequestsException as e:
  153. if "google" in self.engine_name:
  154. self.logger.warn(
  155. "Set to 'true' the use_mobile_ui parameter in the 'engines:'"
  156. " section of your settings.yml file if google is blocked for you."
  157. )
  158. self.handle_exception(result_container, e, suspend=True)
  159. self.logger.exception('Too many requests')
  160. except SearxEngineAccessDeniedException as e:
  161. self.handle_exception(result_container, e, suspend=True)
  162. self.logger.exception('Searx is blocked')
  163. except Exception as e: # pylint: disable=broad-except
  164. self.handle_exception(result_container, e)
  165. self.logger.exception('exception : {0}'.format(e))
  166. def get_default_tests(self):
  167. tests = {}
  168. tests['simple'] = {
  169. 'matrix': {'query': ('life', 'computer')},
  170. 'result_container': ['not_empty'],
  171. }
  172. if getattr(self.engine, 'paging', False):
  173. tests['paging'] = {
  174. 'matrix': {'query': 'time', 'pageno': (1, 2, 3)},
  175. 'result_container': ['not_empty'],
  176. 'test': ['unique_results'],
  177. }
  178. if 'general' in self.engine.categories:
  179. # avoid documentation about HTML tags (<time> and <input type="time">)
  180. tests['paging']['matrix']['query'] = 'news'
  181. if getattr(self.engine, 'time_range', False):
  182. tests['time_range'] = {
  183. 'matrix': {'query': 'news', 'time_range': (None, 'day')},
  184. 'result_container': ['not_empty'],
  185. 'test': ['unique_results'],
  186. }
  187. if getattr(self.engine, 'supported_languages', []):
  188. tests['lang_fr'] = {
  189. 'matrix': {'query': 'paris', 'lang': 'fr'},
  190. 'result_container': ['not_empty', ('has_language', 'fr')],
  191. }
  192. tests['lang_en'] = {
  193. 'matrix': {'query': 'paris', 'lang': 'en'},
  194. 'result_container': ['not_empty', ('has_language', 'en')],
  195. }
  196. if getattr(self.engine, 'safesearch', False):
  197. tests['safesearch'] = {'matrix': {'query': 'porn', 'safesearch': (0, 2)}, 'test': ['unique_results']}
  198. return tests