search.py 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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 gc
  15. import sys
  16. import threading
  17. from time import time
  18. from uuid import uuid4
  19. from flask_babel import gettext
  20. import requests.exceptions
  21. import searx.poolrequests as requests_lib
  22. from searx.engines import (
  23. categories, engines, settings
  24. )
  25. from searx.answerers import ask
  26. from searx.utils import gen_useragent
  27. from searx.query import RawTextQuery, SearchQuery, VALID_LANGUAGE_CODE
  28. from searx.results import ResultContainer
  29. from searx import logger
  30. from searx.plugins import plugins
  31. from searx.exceptions import SearxParameterException
  32. try:
  33. from thread import start_new_thread
  34. except:
  35. from _thread import start_new_thread
  36. if sys.version_info[0] == 3:
  37. unicode = str
  38. logger = logger.getChild('search')
  39. number_of_searches = 0
  40. def send_http_request(engine, request_params):
  41. # create dictionary which contain all
  42. # informations about the request
  43. request_args = dict(
  44. headers=request_params['headers'],
  45. cookies=request_params['cookies'],
  46. verify=request_params['verify']
  47. )
  48. # specific type of request (GET or POST)
  49. if request_params['method'] == 'GET':
  50. req = requests_lib.get
  51. else:
  52. req = requests_lib.post
  53. request_args['data'] = request_params['data']
  54. # send the request
  55. return req(request_params['url'], **request_args)
  56. def search_one_request(engine, query, request_params):
  57. # update request parameters dependent on
  58. # search-engine (contained in engines folder)
  59. engine.request(query, request_params)
  60. # ignoring empty urls
  61. if request_params['url'] is None:
  62. return []
  63. if not request_params['url']:
  64. return []
  65. # send request
  66. response = send_http_request(engine, request_params)
  67. # parse the response
  68. response.search_params = request_params
  69. return engine.response(response)
  70. def search_one_request_safe(engine_name, query, request_params, result_container, start_time, timeout_limit):
  71. # set timeout for all HTTP requests
  72. requests_lib.set_timeout_for_thread(timeout_limit, start_time=start_time)
  73. # reset the HTTP total time
  74. requests_lib.reset_time_for_thread()
  75. #
  76. engine = engines[engine_name]
  77. # suppose everything will be alright
  78. requests_exception = False
  79. try:
  80. # send requests and parse the results
  81. search_results = search_one_request(engine, query, request_params)
  82. # add results
  83. result_container.extend(engine_name, search_results)
  84. # update engine time when there is no exception
  85. with threading.RLock():
  86. engine.stats['engine_time'] += time() - start_time
  87. engine.stats['engine_time_count'] += 1
  88. # update stats with the total HTTP time
  89. engine.stats['page_load_time'] += requests_lib.get_time_for_thread()
  90. engine.stats['page_load_count'] += 1
  91. except Exception as e:
  92. search_duration = time() - start_time
  93. with threading.RLock():
  94. engine.stats['errors'] += 1
  95. if (issubclass(e.__class__, requests.exceptions.Timeout)):
  96. result_container.add_unresponsive_engine((engine_name, gettext('timeout')))
  97. # requests timeout (connect or read)
  98. logger.error("engine {0} : HTTP requests timeout"
  99. "(search duration : {1} s, timeout: {2} s) : {3}"
  100. .format(engine_name, search_duration, timeout_limit, e.__class__.__name__))
  101. requests_exception = True
  102. elif (issubclass(e.__class__, requests.exceptions.RequestException)):
  103. result_container.add_unresponsive_engine((engine_name, gettext('request exception')))
  104. # other requests exception
  105. logger.exception("engine {0} : requests exception"
  106. "(search duration : {1} s, timeout: {2} s) : {3}"
  107. .format(engine_name, search_duration, timeout_limit, e))
  108. requests_exception = True
  109. else:
  110. result_container.add_unresponsive_engine((
  111. engine_name,
  112. u'{0}: {1}'.format(gettext('unexpected crash'), e),
  113. ))
  114. # others errors
  115. logger.exception('engine {0} : exception : {1}'.format(engine_name, e))
  116. # suspend or not the engine if there are HTTP errors
  117. with threading.RLock():
  118. if requests_exception:
  119. # update continuous_errors / suspend_end_time
  120. engine.continuous_errors += 1
  121. engine.suspend_end_time = time() + min(60, engine.continuous_errors)
  122. else:
  123. # no HTTP error (perhaps an engine error)
  124. # anyway, reset the suspend variables
  125. engine.continuous_errors = 0
  126. engine.suspend_end_time = 0
  127. def search_multiple_requests(requests, result_container, start_time, timeout_limit):
  128. search_id = uuid4().__str__()
  129. for engine_name, query, request_params in requests:
  130. th = threading.Thread(
  131. target=search_one_request_safe,
  132. args=(engine_name, query, request_params, result_container, start_time, timeout_limit),
  133. name=search_id,
  134. )
  135. th._engine_name = engine_name
  136. th.start()
  137. for th in threading.enumerate():
  138. if th.name == search_id:
  139. remaining_time = max(0.0, timeout_limit - (time() - start_time))
  140. th.join(remaining_time)
  141. if th.isAlive():
  142. result_container.add_unresponsive_engine((th._engine_name, gettext('timeout')))
  143. logger.warning('engine timeout: {0}'.format(th._engine_name))
  144. # get default reqest parameter
  145. def default_request_params():
  146. return {
  147. 'method': 'GET',
  148. 'headers': {},
  149. 'data': {},
  150. 'url': '',
  151. 'cookies': {},
  152. 'verify': True
  153. }
  154. def get_search_query_from_webapp(preferences, form):
  155. # no text for the query ?
  156. if not form.get('q'):
  157. raise SearxParameterException('q', '')
  158. # set blocked engines
  159. disabled_engines = preferences.engines.get_disabled()
  160. # parse query, if tags are set, which change
  161. # the serch engine or search-language
  162. raw_text_query = RawTextQuery(form['q'], disabled_engines)
  163. raw_text_query.parse_query()
  164. # set query
  165. query = raw_text_query.getSearchQuery()
  166. # get and check page number
  167. pageno_param = form.get('pageno', '1')
  168. if not pageno_param.isdigit() or int(pageno_param) < 1:
  169. raise SearxParameterException('pageno', pageno_param)
  170. query_pageno = int(pageno_param)
  171. # get language
  172. # set specific language if set on request, query or preferences
  173. # TODO support search with multible languages
  174. if len(raw_text_query.languages):
  175. query_lang = raw_text_query.languages[-1]
  176. elif 'language' in form:
  177. query_lang = form.get('language')
  178. else:
  179. query_lang = preferences.get_value('language')
  180. # provides backwards compatibility for requests using old language default
  181. if query_lang == 'all':
  182. query_lang = settings['search']['language']
  183. # check language
  184. if not VALID_LANGUAGE_CODE.match(query_lang):
  185. raise SearxParameterException('language', query_lang)
  186. # get safesearch
  187. if 'safesearch' in form:
  188. query_safesearch = form.get('safesearch')
  189. # first check safesearch
  190. if not query_safesearch.isdigit():
  191. raise SearxParameterException('safesearch', query_safesearch)
  192. query_safesearch = int(query_safesearch)
  193. else:
  194. query_safesearch = preferences.get_value('safesearch')
  195. # safesearch : second check
  196. if query_safesearch < 0 or query_safesearch > 2:
  197. raise SearxParameterException('safesearch', query_safesearch)
  198. # get time_range
  199. query_time_range = form.get('time_range')
  200. # check time_range
  201. if query_time_range not in ('None', None, '', 'day', 'week', 'month', 'year'):
  202. raise SearxParameterException('time_range', query_time_range)
  203. # query_engines
  204. query_engines = raw_text_query.engines
  205. # query_categories
  206. query_categories = []
  207. # if engines are calculated from query,
  208. # set categories by using that informations
  209. if query_engines and raw_text_query.specific:
  210. query_categories = list(set(engine['category']
  211. for engine in query_engines))
  212. # otherwise, using defined categories to
  213. # calculate which engines should be used
  214. else:
  215. # set categories/engines
  216. load_default_categories = True
  217. for pd_name, pd in form.items():
  218. if pd_name == 'categories':
  219. query_categories.extend(categ for categ in map(unicode.strip, pd.split(',')) if categ in categories)
  220. elif pd_name == 'engines':
  221. pd_engines = [{'category': engines[engine].categories[0],
  222. 'name': engine}
  223. for engine in map(unicode.strip, pd.split(',')) if engine in engines]
  224. if pd_engines:
  225. query_engines.extend(pd_engines)
  226. load_default_categories = False
  227. elif pd_name.startswith('category_'):
  228. category = pd_name[9:]
  229. # if category is not found in list, skip
  230. if category not in categories:
  231. continue
  232. if pd != 'off':
  233. # add category to list
  234. query_categories.append(category)
  235. elif category in query_categories:
  236. # remove category from list if property is set to 'off'
  237. query_categories.remove(category)
  238. if not load_default_categories:
  239. if not query_categories:
  240. query_categories = list(set(engine['category']
  241. for engine in query_engines))
  242. else:
  243. # if no category is specified for this search,
  244. # using user-defined default-configuration which
  245. # (is stored in cookie)
  246. if not query_categories:
  247. cookie_categories = preferences.get_value('categories')
  248. for ccateg in cookie_categories:
  249. if ccateg in categories:
  250. query_categories.append(ccateg)
  251. # if still no category is specified, using general
  252. # as default-category
  253. if not query_categories:
  254. query_categories = ['general']
  255. # using all engines for that search, which are
  256. # declared under the specific categories
  257. for categ in query_categories:
  258. query_engines.extend({'category': categ,
  259. 'name': engine.name}
  260. for engine in categories[categ]
  261. if (engine.name, categ) not in disabled_engines)
  262. return SearchQuery(query, query_engines, query_categories,
  263. query_lang, query_safesearch, query_pageno, query_time_range)
  264. class Search(object):
  265. """Search information container"""
  266. def __init__(self, search_query):
  267. # init vars
  268. super(Search, self).__init__()
  269. self.search_query = search_query
  270. self.result_container = ResultContainer()
  271. # do search-request
  272. def search(self):
  273. global number_of_searches
  274. # start time
  275. start_time = time()
  276. # answeres ?
  277. answerers_results = ask(self.search_query)
  278. if answerers_results:
  279. for results in answerers_results:
  280. self.result_container.extend('answer', results)
  281. return self.result_container
  282. # init vars
  283. requests = []
  284. # increase number of searches
  285. number_of_searches += 1
  286. # set default useragent
  287. # user_agent = request.headers.get('User-Agent', '')
  288. user_agent = gen_useragent()
  289. search_query = self.search_query
  290. # max of all selected engine timeout
  291. timeout_limit = 0
  292. # start search-reqest for all selected engines
  293. for selected_engine in search_query.engines:
  294. if selected_engine['name'] not in engines:
  295. continue
  296. engine = engines[selected_engine['name']]
  297. # skip suspended engines
  298. if engine.suspend_end_time >= time():
  299. logger.debug('Engine currently suspended: %s', selected_engine['name'])
  300. continue
  301. # if paging is not supported, skip
  302. if search_query.pageno > 1 and not engine.paging:
  303. continue
  304. # if time_range is not supported, skip
  305. if search_query.time_range and not engine.time_range_support:
  306. continue
  307. # set default request parameters
  308. request_params = default_request_params()
  309. request_params['headers']['User-Agent'] = user_agent
  310. request_params['category'] = selected_engine['category']
  311. request_params['pageno'] = search_query.pageno
  312. if hasattr(engine, 'language') and engine.language:
  313. request_params['language'] = engine.language
  314. else:
  315. request_params['language'] = search_query.lang
  316. # 0 = None, 1 = Moderate, 2 = Strict
  317. request_params['safesearch'] = search_query.safesearch
  318. request_params['time_range'] = search_query.time_range
  319. # append request to list
  320. requests.append((selected_engine['name'], search_query.query, request_params))
  321. # update timeout_limit
  322. timeout_limit = max(timeout_limit, engine.timeout)
  323. if requests:
  324. # send all search-request
  325. search_multiple_requests(requests, self.result_container, start_time, timeout_limit)
  326. start_new_thread(gc.collect, tuple())
  327. # return results, suggestions, answers and infoboxes
  328. return self.result_container
  329. class SearchWithPlugins(Search):
  330. """Similar to the Search class but call the plugins."""
  331. def __init__(self, search_query, ordered_plugin_list, request):
  332. super(SearchWithPlugins, self).__init__(search_query)
  333. self.ordered_plugin_list = ordered_plugin_list
  334. self.request = request
  335. def search(self):
  336. if plugins.call(self.ordered_plugin_list, 'pre_search', self.request, self):
  337. super(SearchWithPlugins, self).search()
  338. plugins.call(self.ordered_plugin_list, 'post_search', self.request, self)
  339. results = self.result_container.get_ordered_results()
  340. for result in results:
  341. plugins.call(self.ordered_plugin_list, 'on_result', self.request, self, result)
  342. return self.result_container