online.py 7.3 KB

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