__init__.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. '''
  2. searx is free software: you can redistribute it and/or modify
  3. it under the terms of the GNU Affero General Public License as published by
  4. the Free Software Foundation, either version 3 of the License, or
  5. (at your option) any later version.
  6. searx is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. GNU Affero General Public License for more details.
  10. You should have received a copy of the GNU Affero General Public License
  11. along with searx. If not, see < http://www.gnu.org/licenses/ >.
  12. (C) 2013- by Adam Tauber, <asciimoo@gmail.com>
  13. '''
  14. import typing
  15. import gc
  16. import threading
  17. from time import time
  18. from uuid import uuid4
  19. from _thread import start_new_thread
  20. from searx import settings
  21. from searx.answerers import ask
  22. from searx.external_bang import get_bang_url
  23. from searx.results import ResultContainer
  24. from searx import logger
  25. from searx.plugins import plugins
  26. from searx.search.processors import processors, initialize as initialize_processors
  27. logger = logger.getChild('search')
  28. max_request_timeout = settings.get('outgoing', {}).get('max_request_timeout' or None)
  29. if max_request_timeout is None:
  30. logger.info('max_request_timeout={0}'.format(max_request_timeout))
  31. else:
  32. if isinstance(max_request_timeout, float):
  33. logger.info('max_request_timeout={0} second(s)'.format(max_request_timeout))
  34. else:
  35. logger.critical('outgoing.max_request_timeout if defined has to be float')
  36. import sys
  37. sys.exit(1)
  38. def initialize(settings_engines=None):
  39. settings_engines = settings_engines or settings['engines']
  40. initialize_processors(settings_engines)
  41. class EngineRef:
  42. __slots__ = 'name', 'category', 'from_bang'
  43. def __init__(self, name: str, category: str, from_bang: bool=False):
  44. self.name = name
  45. self.category = category
  46. self.from_bang = from_bang
  47. def __repr__(self):
  48. return "EngineRef({!r}, {!r}, {!r})".format(self.name, self.category, self.from_bang)
  49. def __eq__(self, other):
  50. return self.name == other.name and self.category == other.category and self.from_bang == other.from_bang
  51. class SearchQuery:
  52. """container for all the search parameters (query, language, etc...)"""
  53. __slots__ = 'query', 'engineref_list', 'categories', 'lang', 'safesearch', 'pageno', 'time_range',\
  54. 'timeout_limit', 'external_bang'
  55. def __init__(self,
  56. query: str,
  57. engineref_list: typing.List[EngineRef],
  58. categories: typing.List[str],
  59. lang: str,
  60. safesearch: int,
  61. pageno: int,
  62. time_range: typing.Optional[str],
  63. timeout_limit: typing.Optional[float]=None,
  64. external_bang: typing.Optional[str]=None):
  65. self.query = query
  66. self.engineref_list = engineref_list
  67. self.categories = categories
  68. self.lang = lang
  69. self.safesearch = safesearch
  70. self.pageno = pageno
  71. self.time_range = time_range
  72. self.timeout_limit = timeout_limit
  73. self.external_bang = external_bang
  74. def __repr__(self):
  75. return "SearchQuery({!r}, {!r}, {!r}, {!r}, {!r}, {!r}, {!r}, {!r}, {!r})".\
  76. format(self.query, self.engineref_list, self.categories, self.lang, self.safesearch,
  77. self.pageno, self.time_range, self.timeout_limit, self.external_bang)
  78. def __eq__(self, other):
  79. return self.query == other.query\
  80. and self.engineref_list == other.engineref_list\
  81. and self.categories == self.categories\
  82. and self.lang == other.lang\
  83. and self.safesearch == other.safesearch\
  84. and self.pageno == other.pageno\
  85. and self.time_range == other.time_range\
  86. and self.timeout_limit == other.timeout_limit\
  87. and self.external_bang == other.external_bang
  88. class Search:
  89. """Search information container"""
  90. __slots__ = "search_query", "result_container", "start_time", "actual_timeout"
  91. def __init__(self, search_query):
  92. # init vars
  93. super().__init__()
  94. self.search_query = search_query
  95. self.result_container = ResultContainer()
  96. self.start_time = None
  97. self.actual_timeout = None
  98. def search_external_bang(self):
  99. """
  100. Check if there is a external bang.
  101. If yes, update self.result_container and return True
  102. """
  103. if self.search_query.external_bang:
  104. self.result_container.redirect_url = get_bang_url(self.search_query)
  105. # This means there was a valid bang and the
  106. # rest of the search does not need to be continued
  107. if isinstance(self.result_container.redirect_url, str):
  108. return True
  109. return False
  110. def search_answerers(self):
  111. """
  112. Check if an answer return a result.
  113. If yes, update self.result_container and return True
  114. """
  115. answerers_results = ask(self.search_query)
  116. if answerers_results:
  117. for results in answerers_results:
  118. self.result_container.extend('answer', results)
  119. return True
  120. return False
  121. # do search-request
  122. def _get_requests(self):
  123. # init vars
  124. requests = []
  125. # max of all selected engine timeout
  126. default_timeout = 0
  127. # start search-reqest for all selected engines
  128. for engineref in self.search_query.engineref_list:
  129. processor = processors[engineref.name]
  130. # set default request parameters
  131. request_params = processor.get_params(self.search_query, engineref.category)
  132. if request_params is None:
  133. continue
  134. with threading.RLock():
  135. processor.engine.stats['sent_search_count'] += 1
  136. # append request to list
  137. requests.append((engineref.name, self.search_query.query, request_params))
  138. # update default_timeout
  139. default_timeout = max(default_timeout, processor.engine.timeout)
  140. # adjust timeout
  141. actual_timeout = default_timeout
  142. query_timeout = self.search_query.timeout_limit
  143. if max_request_timeout is None and query_timeout is None:
  144. # No max, no user query: default_timeout
  145. pass
  146. elif max_request_timeout is None and query_timeout is not None:
  147. # No max, but user query: From user query except if above default
  148. actual_timeout = min(default_timeout, query_timeout)
  149. elif max_request_timeout is not None and query_timeout is None:
  150. # Max, no user query: Default except if above max
  151. actual_timeout = min(default_timeout, max_request_timeout)
  152. elif max_request_timeout is not None and query_timeout is not None:
  153. # Max & user query: From user query except if above max
  154. actual_timeout = min(query_timeout, max_request_timeout)
  155. logger.debug("actual_timeout={0} (default_timeout={1}, ?timeout_limit={2}, max_request_timeout={3})"
  156. .format(actual_timeout, default_timeout, query_timeout, max_request_timeout))
  157. return requests, actual_timeout
  158. def search_multiple_requests(self, requests):
  159. search_id = uuid4().__str__()
  160. for engine_name, query, request_params in requests:
  161. th = threading.Thread(
  162. target=processors[engine_name].search,
  163. args=(query, request_params, self.result_container, self.start_time, self.actual_timeout),
  164. name=search_id,
  165. )
  166. th._timeout = False
  167. th._engine_name = engine_name
  168. th.start()
  169. for th in threading.enumerate():
  170. if th.name == search_id:
  171. remaining_time = max(0.0, self.actual_timeout - (time() - self.start_time))
  172. th.join(remaining_time)
  173. if th.is_alive():
  174. th._timeout = True
  175. self.result_container.add_unresponsive_engine(th._engine_name, 'timeout')
  176. logger.warning('engine timeout: {0}'.format(th._engine_name))
  177. def search_standard(self):
  178. """
  179. Update self.result_container, self.actual_timeout
  180. """
  181. requests, self.actual_timeout = self._get_requests()
  182. # send all search-request
  183. if requests:
  184. self.search_multiple_requests(requests)
  185. start_new_thread(gc.collect, tuple())
  186. # return results, suggestions, answers and infoboxes
  187. return True
  188. # do search-request
  189. def search(self):
  190. self.start_time = time()
  191. if not self.search_external_bang():
  192. if not self.search_answerers():
  193. self.search_standard()
  194. return self.result_container
  195. class SearchWithPlugins(Search):
  196. """Similar to the Search class but call the plugins."""
  197. __slots__ = 'ordered_plugin_list', 'request'
  198. def __init__(self, search_query, ordered_plugin_list, request):
  199. super().__init__(search_query)
  200. self.ordered_plugin_list = ordered_plugin_list
  201. self.request = request
  202. def search(self):
  203. if plugins.call(self.ordered_plugin_list, 'pre_search', self.request, self):
  204. super().search()
  205. plugins.call(self.ordered_plugin_list, 'post_search', self.request, self)
  206. results = self.result_container.get_ordered_results()
  207. for result in results:
  208. plugins.call(self.ordered_plugin_list, 'on_result', self.request, self, result)
  209. return self.result_container