online.py 7.5 KB

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