webapp.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  1. #!/usr/bin/env python
  2. '''
  3. searx is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. searx is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with searx. If not, see < http://www.gnu.org/licenses/ >.
  13. (C) 2013- by Adam Tauber, <asciimoo@gmail.com>
  14. '''
  15. import sys
  16. if sys.version_info[0] < 3:
  17. print('\033[1;31m Python2 is no longer supported\033[0m')
  18. exit(1)
  19. if __name__ == '__main__':
  20. from os.path import realpath, dirname
  21. sys.path.append(realpath(dirname(realpath(__file__)) + '/../'))
  22. import hashlib
  23. import hmac
  24. import json
  25. import os
  26. import requests
  27. from searx import logger
  28. logger = logger.getChild('webapp')
  29. from datetime import datetime, timedelta
  30. from time import time
  31. from html import escape
  32. from io import StringIO
  33. import urllib
  34. from urllib.parse import urlencode, urlparse
  35. from pygments import highlight
  36. from pygments.lexers import get_lexer_by_name
  37. from pygments.formatters import HtmlFormatter # pylint: disable=no-name-in-module
  38. from werkzeug.middleware.proxy_fix import ProxyFix
  39. from flask import (
  40. Flask, request, render_template, url_for, Response, make_response,
  41. redirect, send_from_directory
  42. )
  43. from babel.support import Translations
  44. import flask_babel
  45. from flask_babel import Babel, gettext, format_date, format_decimal
  46. from flask.ctx import has_request_context
  47. from flask.json import jsonify
  48. from searx import brand, static_path
  49. from searx import settings, searx_dir, searx_debug
  50. from searx.exceptions import SearxParameterException
  51. from searx.engines import (
  52. categories, engines, engine_shortcuts, get_engines_stats
  53. )
  54. from searx.webutils import (
  55. UnicodeWriter, highlight_content, get_resources_directory,
  56. get_static_files, get_result_templates, get_themes,
  57. prettify_url, new_hmac, is_flask_run_cmdline
  58. )
  59. from searx.webadapter import get_search_query_from_webapp, get_selected_categories
  60. from searx.utils import html_to_text, gen_useragent, dict_subset, match_language
  61. from searx.version import VERSION_STRING
  62. from searx.languages import language_codes as languages
  63. from searx.search import SearchWithPlugins, initialize as search_initialize
  64. from searx.search.checker import get_result as checker_get_result
  65. from searx.query import RawTextQuery
  66. from searx.autocomplete import search_autocomplete, backends as autocomplete_backends
  67. from searx.plugins import plugins
  68. from searx.plugins.oa_doi_rewrite import get_doi_resolver
  69. from searx.preferences import Preferences, ValidationException, LANGUAGE_CODES
  70. from searx.answerers import answerers
  71. from searx.poolrequests import get_global_proxies
  72. from searx.answerers import ask
  73. from searx.metrology.error_recorder import errors_per_engines
  74. from searx.settings_loader import get_default_settings_path
  75. # serve pages with HTTP/1.1
  76. from werkzeug.serving import WSGIRequestHandler
  77. WSGIRequestHandler.protocol_version = "HTTP/{}".format(settings['server'].get('http_protocol_version', '1.0'))
  78. # check secret_key
  79. if not searx_debug and settings['server']['secret_key'] == 'ultrasecretkey':
  80. logger.error('server.secret_key is not changed. Please use something else instead of ultrasecretkey.')
  81. exit(1)
  82. # about static
  83. static_path = get_resources_directory(searx_dir, 'static', settings['ui']['static_path'])
  84. logger.debug('static directory is %s', static_path)
  85. static_files = get_static_files(static_path)
  86. # about templates
  87. default_theme = settings['ui']['default_theme']
  88. templates_path = get_resources_directory(searx_dir, 'templates', settings['ui']['templates_path'])
  89. logger.debug('templates directory is %s', templates_path)
  90. themes = get_themes(templates_path)
  91. result_templates = get_result_templates(templates_path)
  92. global_favicons = []
  93. for indice, theme in enumerate(themes):
  94. global_favicons.append([])
  95. theme_img_path = os.path.join(static_path, 'themes', theme, 'img', 'icons')
  96. for (dirpath, dirnames, filenames) in os.walk(theme_img_path):
  97. global_favicons[indice].extend(filenames)
  98. # Flask app
  99. app = Flask(
  100. __name__,
  101. static_folder=static_path,
  102. template_folder=templates_path
  103. )
  104. app.jinja_env.trim_blocks = True
  105. app.jinja_env.lstrip_blocks = True
  106. app.jinja_env.add_extension('jinja2.ext.loopcontrols') # pylint: disable=no-member
  107. app.secret_key = settings['server']['secret_key']
  108. # see https://flask.palletsprojects.com/en/1.1.x/cli/
  109. # True if "FLASK_APP=searx/webapp.py FLASK_ENV=development flask run"
  110. flask_run_development = \
  111. os.environ.get("FLASK_APP") is not None\
  112. and os.environ.get("FLASK_ENV") == 'development'\
  113. and is_flask_run_cmdline()
  114. # True if reload feature is activated of werkzeug, False otherwise (including uwsgi, etc..)
  115. # __name__ != "__main__" if searx.webapp is imported (make test, make docs, uwsgi...)
  116. # see run() at the end of this file : searx_debug activates the reload feature.
  117. werkzeug_reloader = flask_run_development or (searx_debug and __name__ == "__main__")
  118. # initialize the engines except on the first run of the werkzeug server.
  119. if not werkzeug_reloader\
  120. or (werkzeug_reloader and os.environ.get("WERKZEUG_RUN_MAIN") == "true"):
  121. search_initialize(enable_checker=True)
  122. babel = Babel(app)
  123. rtl_locales = ['ar', 'arc', 'bcc', 'bqi', 'ckb', 'dv', 'fa', 'fa_IR', 'glk', 'he',
  124. 'ku', 'mzn', 'pnb', 'ps', 'sd', 'ug', 'ur', 'yi']
  125. ui_locale_codes = [l.replace('_', '-') for l in settings['locales'].keys()]
  126. # used when translating category names
  127. _category_names = (gettext('files'),
  128. gettext('general'),
  129. gettext('music'),
  130. gettext('social media'),
  131. gettext('images'),
  132. gettext('videos'),
  133. gettext('it'),
  134. gettext('news'),
  135. gettext('map'),
  136. gettext('onions'),
  137. gettext('science'))
  138. _flask_babel_get_translations = flask_babel.get_translations
  139. # monkey patch for flask_babel.get_translations
  140. def _get_translations():
  141. if has_request_context() and request.form.get('use-translation') == 'oc':
  142. babel_ext = flask_babel.current_app.extensions['babel']
  143. return Translations.load(next(babel_ext.translation_directories), 'oc')
  144. return _flask_babel_get_translations()
  145. flask_babel.get_translations = _get_translations
  146. def _get_browser_or_settings_language(request, lang_list):
  147. for lang in request.headers.get("Accept-Language", "en").split(","):
  148. if ';' in lang:
  149. lang = lang.split(';')[0]
  150. if '-' in lang:
  151. lang_parts = lang.split('-')
  152. lang = "{}-{}".format(lang_parts[0], lang_parts[-1].upper())
  153. locale = match_language(lang, lang_list, fallback=None)
  154. if locale is not None:
  155. return locale
  156. return settings['search']['default_lang'] or 'en'
  157. @babel.localeselector
  158. def get_locale():
  159. if 'locale' in request.form\
  160. and request.form['locale'] in settings['locales']:
  161. # use locale from the form
  162. locale = request.form['locale']
  163. locale_source = 'form'
  164. elif request.preferences.get_value('locale') != '':
  165. # use locale from the preferences
  166. locale = request.preferences.get_value('locale')
  167. locale_source = 'preferences'
  168. else:
  169. # use local from the browser
  170. locale = _get_browser_or_settings_language(request, ui_locale_codes)
  171. locale = locale.replace('-', '_')
  172. locale_source = 'browser'
  173. # see _get_translations function
  174. # and https://github.com/searx/searx/pull/1863
  175. if locale == 'oc':
  176. request.form['use-translation'] = 'oc'
  177. locale = 'fr_FR'
  178. logger.debug(
  179. "%s uses locale `%s` from %s", urllib.parse.quote(request.url), locale, locale_source
  180. )
  181. return locale
  182. # code-highlighter
  183. @app.template_filter('code_highlighter')
  184. def code_highlighter(codelines, language=None):
  185. if not language:
  186. language = 'text'
  187. try:
  188. # find lexer by programming language
  189. lexer = get_lexer_by_name(language, stripall=True)
  190. except:
  191. # if lexer is not found, using default one
  192. logger.debug('highlighter cannot find lexer for {0}'.format(language))
  193. lexer = get_lexer_by_name('text', stripall=True)
  194. html_code = ''
  195. tmp_code = ''
  196. last_line = None
  197. # parse lines
  198. for line, code in codelines:
  199. if not last_line:
  200. line_code_start = line
  201. # new codeblock is detected
  202. if last_line is not None and\
  203. last_line + 1 != line:
  204. # highlight last codepart
  205. formatter = HtmlFormatter(linenos='inline',
  206. linenostart=line_code_start,
  207. cssclass="code-highlight")
  208. html_code = html_code + highlight(tmp_code, lexer, formatter)
  209. # reset conditions for next codepart
  210. tmp_code = ''
  211. line_code_start = line
  212. # add codepart
  213. tmp_code += code + '\n'
  214. # update line
  215. last_line = line
  216. # highlight last codepart
  217. formatter = HtmlFormatter(linenos='inline', linenostart=line_code_start, cssclass="code-highlight")
  218. html_code = html_code + highlight(tmp_code, lexer, formatter)
  219. return html_code
  220. # Extract domain from url
  221. @app.template_filter('extract_domain')
  222. def extract_domain(url):
  223. return urlparse(url)[1]
  224. def get_base_url():
  225. return url_for('index', _external=True)
  226. def get_current_theme_name(override=None):
  227. """Returns theme name.
  228. Checks in this order:
  229. 1. override
  230. 2. cookies
  231. 3. settings"""
  232. if override and (override in themes or override == '__common__'):
  233. return override
  234. theme_name = request.args.get('theme', request.preferences.get_value('theme'))
  235. if theme_name not in themes:
  236. theme_name = default_theme
  237. return theme_name
  238. def get_result_template(theme, template_name):
  239. themed_path = theme + '/result_templates/' + template_name
  240. if themed_path in result_templates:
  241. return themed_path
  242. return 'result_templates/' + template_name
  243. def url_for_theme(endpoint, override_theme=None, **values):
  244. if endpoint == 'static' and values.get('filename'):
  245. theme_name = get_current_theme_name(override=override_theme)
  246. filename_with_theme = "themes/{}/{}".format(theme_name, values['filename'])
  247. if filename_with_theme in static_files:
  248. values['filename'] = filename_with_theme
  249. url = url_for(endpoint, **values)
  250. return url
  251. def proxify(url):
  252. if url.startswith('//'):
  253. url = 'https:' + url
  254. if not settings.get('result_proxy'):
  255. return url
  256. url_params = dict(mortyurl=url.encode())
  257. if settings['result_proxy'].get('key'):
  258. url_params['mortyhash'] = hmac.new(settings['result_proxy']['key'],
  259. url.encode(),
  260. hashlib.sha256).hexdigest()
  261. return '{0}?{1}'.format(settings['result_proxy']['url'],
  262. urlencode(url_params))
  263. def image_proxify(url):
  264. if url.startswith('//'):
  265. url = 'https:' + url
  266. if not request.preferences.get_value('image_proxy'):
  267. return url
  268. if url.startswith('data:image/'):
  269. # 50 is an arbitrary number to get only the beginning of the image.
  270. partial_base64 = url[len('data:image/'):50].split(';')
  271. if len(partial_base64) == 2 \
  272. and partial_base64[0] in ['gif', 'png', 'jpeg', 'pjpeg', 'webp', 'tiff', 'bmp']\
  273. and partial_base64[1].startswith('base64,'):
  274. return url
  275. else:
  276. return None
  277. if settings.get('result_proxy'):
  278. return proxify(url)
  279. h = new_hmac(settings['server']['secret_key'], url.encode())
  280. return '{0}?{1}'.format(url_for('image_proxy'),
  281. urlencode(dict(url=url.encode(), h=h)))
  282. def get_translations():
  283. return {
  284. # when there is autocompletion
  285. 'no_item_found': gettext('No item found')
  286. }
  287. def render(template_name, override_theme=None, **kwargs):
  288. disabled_engines = request.preferences.engines.get_disabled()
  289. enabled_categories = set(category for engine_name in engines
  290. for category in engines[engine_name].categories
  291. if (engine_name, category) not in disabled_engines)
  292. if 'categories' not in kwargs:
  293. kwargs['categories'] = [x for x in
  294. _get_ordered_categories()
  295. if x in enabled_categories]
  296. if 'autocomplete' not in kwargs:
  297. kwargs['autocomplete'] = request.preferences.get_value('autocomplete')
  298. locale = request.preferences.get_value('locale')
  299. if locale in rtl_locales and 'rtl' not in kwargs:
  300. kwargs['rtl'] = True
  301. kwargs['searx_version'] = VERSION_STRING
  302. kwargs['method'] = request.preferences.get_value('method')
  303. kwargs['autofocus'] = request.preferences.get_value('autofocus')
  304. kwargs['archive_today'] = request.preferences.get_value('archive_today')
  305. kwargs['safesearch'] = str(request.preferences.get_value('safesearch'))
  306. kwargs['language_codes'] = languages
  307. if 'current_language' not in kwargs:
  308. kwargs['current_language'] = match_language(request.preferences.get_value('language'),
  309. LANGUAGE_CODES)
  310. # override url_for function in templates
  311. kwargs['url_for'] = url_for_theme
  312. kwargs['image_proxify'] = image_proxify
  313. kwargs['proxify'] = proxify if settings.get('result_proxy', {}).get('url') else None
  314. kwargs['opensearch_url'] = url_for('opensearch') + '?' \
  315. + urlencode({'method': kwargs['method'], 'autocomplete': kwargs['autocomplete']})
  316. kwargs['get_result_template'] = get_result_template
  317. kwargs['theme'] = get_current_theme_name(override=override_theme)
  318. kwargs['template_name'] = template_name
  319. kwargs['cookies'] = request.cookies
  320. kwargs['errors'] = request.errors
  321. kwargs['instance_name'] = settings['general']['instance_name']
  322. kwargs['results_on_new_tab'] = request.preferences.get_value('results_on_new_tab')
  323. kwargs['preferences'] = request.preferences
  324. kwargs['brand'] = brand
  325. kwargs['translations'] = json.dumps(get_translations(), separators=(',', ':'))
  326. kwargs['scripts'] = set()
  327. kwargs['endpoint'] = 'results' if 'q' in kwargs else request.endpoint
  328. for plugin in request.user_plugins:
  329. for script in plugin.js_dependencies:
  330. kwargs['scripts'].add(script)
  331. kwargs['styles'] = set()
  332. for plugin in request.user_plugins:
  333. for css in plugin.css_dependencies:
  334. kwargs['styles'].add(css)
  335. return render_template(
  336. '{}/{}'.format(kwargs['theme'], template_name), **kwargs)
  337. def _get_ordered_categories():
  338. ordered_categories = []
  339. if 'categories_order' not in settings['ui']:
  340. ordered_categories = ['general']
  341. ordered_categories.extend(x for x in sorted(categories.keys()) if x != 'general')
  342. return ordered_categories
  343. ordered_categories = settings['ui']['categories_order']
  344. ordered_categories.extend(x for x in sorted(categories.keys()) if x not in ordered_categories)
  345. return ordered_categories
  346. @app.before_request
  347. def pre_request():
  348. request.start_time = time()
  349. request.timings = []
  350. request.errors = []
  351. preferences = Preferences(themes, list(categories.keys()), engines, plugins)
  352. user_agent = request.headers.get('User-Agent', '').lower()
  353. if 'webkit' in user_agent and 'android' in user_agent:
  354. preferences.key_value_settings['method'].value = 'GET'
  355. request.preferences = preferences
  356. try:
  357. preferences.parse_dict(request.cookies)
  358. except:
  359. request.errors.append(gettext('Invalid settings, please edit your preferences'))
  360. # merge GET, POST vars
  361. # request.form
  362. request.form = dict(request.form.items())
  363. for k, v in request.args.items():
  364. if k not in request.form:
  365. request.form[k] = v
  366. if request.form.get('preferences'):
  367. preferences.parse_encoded_data(request.form['preferences'])
  368. else:
  369. try:
  370. preferences.parse_dict(request.form)
  371. except Exception:
  372. logger.exception('invalid settings')
  373. request.errors.append(gettext('Invalid settings'))
  374. # init search language and locale
  375. if not preferences.get_value("language"):
  376. preferences.parse_dict({"language": _get_browser_or_settings_language(request, LANGUAGE_CODES)})
  377. if not preferences.get_value("locale"):
  378. preferences.parse_dict({"locale": get_locale()})
  379. # request.user_plugins
  380. request.user_plugins = []
  381. allowed_plugins = preferences.plugins.get_enabled()
  382. disabled_plugins = preferences.plugins.get_disabled()
  383. for plugin in plugins:
  384. if ((plugin.default_on and plugin.id not in disabled_plugins)
  385. or plugin.id in allowed_plugins):
  386. request.user_plugins.append(plugin)
  387. @app.after_request
  388. def add_default_headers(response):
  389. # set default http headers
  390. for header, value in settings['server'].get('default_http_headers', {}).items():
  391. if header in response.headers:
  392. continue
  393. response.headers[header] = value
  394. return response
  395. @app.after_request
  396. def post_request(response):
  397. total_time = time() - request.start_time
  398. timings_all = ['total;dur=' + str(round(total_time * 1000, 3))]
  399. if len(request.timings) > 0:
  400. timings = sorted(request.timings, key=lambda v: v['total'])
  401. timings_total = ['total_' + str(i) + '_' + v['engine'] +
  402. ';dur=' + str(round(v['total'] * 1000, 3)) for i, v in enumerate(timings)]
  403. timings_load = ['load_' + str(i) + '_' + v['engine'] +
  404. ';dur=' + str(round(v['load'] * 1000, 3)) for i, v in enumerate(timings)]
  405. timings_all = timings_all + timings_total + timings_load
  406. response.headers.add('Server-Timing', ', '.join(timings_all))
  407. return response
  408. def index_error(output_format, error_message):
  409. if output_format == 'json':
  410. return Response(json.dumps({'error': error_message}),
  411. mimetype='application/json')
  412. elif output_format == 'csv':
  413. response = Response('', mimetype='application/csv')
  414. cont_disp = 'attachment;Filename=searx.csv'
  415. response.headers.add('Content-Disposition', cont_disp)
  416. return response
  417. elif output_format == 'rss':
  418. response_rss = render(
  419. 'opensearch_response_rss.xml',
  420. results=[],
  421. q=request.form['q'] if 'q' in request.form else '',
  422. number_of_results=0,
  423. base_url=get_base_url(),
  424. error_message=error_message,
  425. override_theme='__common__',
  426. )
  427. return Response(response_rss, mimetype='text/xml')
  428. else:
  429. # html
  430. request.errors.append(gettext('search error'))
  431. return render(
  432. 'index.html',
  433. selected_categories=get_selected_categories(request.preferences, request.form),
  434. )
  435. @app.route('/', methods=['GET', 'POST'])
  436. def index():
  437. """Render index page."""
  438. # UI
  439. advanced_search = request.preferences.get_value('advanced_search')
  440. # redirect to search if there's a query in the request
  441. if request.form.get('q'):
  442. query = ('?' + request.query_string.decode()) if request.query_string else ''
  443. return redirect(url_for('search') + query, 308)
  444. return render(
  445. 'index.html',
  446. selected_categories=get_selected_categories(request.preferences, request.form),
  447. advanced_search=advanced_search,
  448. )
  449. @app.route('/healthz', methods=['GET'])
  450. def health():
  451. return Response('OK', mimetype='text/plain')
  452. @app.route('/search', methods=['GET', 'POST'])
  453. def search():
  454. """Search query in q and return results.
  455. Supported outputs: html, json, csv, rss.
  456. """
  457. # output_format
  458. output_format = request.form.get('format', 'html')
  459. if output_format not in ['html', 'csv', 'json', 'rss']:
  460. output_format = 'html'
  461. # check if there is query (not None and not an empty string)
  462. if not request.form.get('q'):
  463. if output_format == 'html':
  464. return render(
  465. 'index.html',
  466. advanced_search=request.preferences.get_value('advanced_search'),
  467. selected_categories=get_selected_categories(request.preferences, request.form),
  468. )
  469. else:
  470. return index_error(output_format, 'No query'), 400
  471. # search
  472. search_query = None
  473. raw_text_query = None
  474. result_container = None
  475. try:
  476. search_query, raw_text_query, _, _ = get_search_query_from_webapp(request.preferences, request.form)
  477. # search = Search(search_query) # without plugins
  478. search = SearchWithPlugins(search_query, request.user_plugins, request)
  479. result_container = search.search()
  480. except SearxParameterException as e:
  481. logger.exception('search error: SearxParameterException')
  482. return index_error(output_format, e.message), 400
  483. except Exception as e:
  484. logger.exception('search error')
  485. return index_error(output_format, gettext('search error')), 500
  486. # results
  487. results = result_container.get_ordered_results()
  488. number_of_results = result_container.results_number()
  489. if number_of_results < result_container.results_length():
  490. number_of_results = 0
  491. # checkin for a external bang
  492. if result_container.redirect_url:
  493. return redirect(result_container.redirect_url)
  494. # Server-Timing header
  495. request.timings = result_container.get_timings()
  496. # output
  497. for result in results:
  498. if output_format == 'html':
  499. if 'content' in result and result['content']:
  500. result['content'] = highlight_content(escape(result['content'][:1024]), search_query.query)
  501. if 'title' in result and result['title']:
  502. result['title'] = highlight_content(escape(result['title'] or ''), search_query.query)
  503. else:
  504. if result.get('content'):
  505. result['content'] = html_to_text(result['content']).strip()
  506. # removing html content and whitespace duplications
  507. result['title'] = ' '.join(html_to_text(result['title']).strip().split())
  508. if 'url' in result and 'pretty_url' not in result:
  509. result['pretty_url'] = prettify_url(result['url'])
  510. # TODO, check if timezone is calculated right
  511. if result.get('publishedDate'): # do not try to get a date from an empty string or a None type
  512. try: # test if publishedDate >= 1900 (datetime module bug)
  513. result['pubdate'] = result['publishedDate'].strftime('%Y-%m-%d %H:%M:%S%z')
  514. except ValueError:
  515. result['publishedDate'] = None
  516. else:
  517. if result['publishedDate'].replace(tzinfo=None) >= datetime.now() - timedelta(days=1):
  518. timedifference = datetime.now() - result['publishedDate'].replace(tzinfo=None)
  519. minutes = int((timedifference.seconds / 60) % 60)
  520. hours = int(timedifference.seconds / 60 / 60)
  521. if hours == 0:
  522. result['publishedDate'] = gettext('{minutes} minute(s) ago').format(minutes=minutes)
  523. else:
  524. result['publishedDate'] = gettext('{hours} hour(s), {minutes} minute(s) ago').format(hours=hours, minutes=minutes) # noqa
  525. else:
  526. result['publishedDate'] = format_date(result['publishedDate'])
  527. if output_format == 'json':
  528. return Response(json.dumps({'query': search_query.query,
  529. 'number_of_results': number_of_results,
  530. 'results': results,
  531. 'answers': list(result_container.answers),
  532. 'corrections': list(result_container.corrections),
  533. 'infoboxes': result_container.infoboxes,
  534. 'suggestions': list(result_container.suggestions),
  535. 'unresponsive_engines': __get_translated_errors(result_container.unresponsive_engines)}, # noqa
  536. default=lambda item: list(item) if isinstance(item, set) else item),
  537. mimetype='application/json')
  538. elif output_format == 'csv':
  539. csv = UnicodeWriter(StringIO())
  540. keys = ('title', 'url', 'content', 'host', 'engine', 'score', 'type')
  541. csv.writerow(keys)
  542. for row in results:
  543. row['host'] = row['parsed_url'].netloc
  544. row['type'] = 'result'
  545. csv.writerow([row.get(key, '') for key in keys])
  546. for a in result_container.answers:
  547. row = {'title': a, 'type': 'answer'}
  548. csv.writerow([row.get(key, '') for key in keys])
  549. for a in result_container.suggestions:
  550. row = {'title': a, 'type': 'suggestion'}
  551. csv.writerow([row.get(key, '') for key in keys])
  552. for a in result_container.corrections:
  553. row = {'title': a, 'type': 'correction'}
  554. csv.writerow([row.get(key, '') for key in keys])
  555. csv.stream.seek(0)
  556. response = Response(csv.stream.read(), mimetype='application/csv')
  557. cont_disp = 'attachment;Filename=searx_-_{0}.csv'.format(search_query.query)
  558. response.headers.add('Content-Disposition', cont_disp)
  559. return response
  560. elif output_format == 'rss':
  561. response_rss = render(
  562. 'opensearch_response_rss.xml',
  563. results=results,
  564. answers=result_container.answers,
  565. corrections=result_container.corrections,
  566. suggestions=result_container.suggestions,
  567. q=request.form['q'],
  568. number_of_results=number_of_results,
  569. base_url=get_base_url(),
  570. override_theme='__common__',
  571. )
  572. return Response(response_rss, mimetype='text/xml')
  573. # HTML output format
  574. # suggestions: use RawTextQuery to get the suggestion URLs with the same bang
  575. suggestion_urls = list(map(lambda suggestion: {
  576. 'url': raw_text_query.changeQuery(suggestion).getFullQuery(),
  577. 'title': suggestion
  578. },
  579. result_container.suggestions))
  580. correction_urls = list(map(lambda correction: {
  581. 'url': raw_text_query.changeQuery(correction).getFullQuery(),
  582. 'title': correction
  583. },
  584. result_container.corrections))
  585. #
  586. return render(
  587. 'results.html',
  588. results=results,
  589. q=request.form['q'],
  590. selected_categories=search_query.categories,
  591. pageno=search_query.pageno,
  592. time_range=search_query.time_range,
  593. number_of_results=format_decimal(number_of_results),
  594. suggestions=suggestion_urls,
  595. answers=result_container.answers,
  596. corrections=correction_urls,
  597. infoboxes=result_container.infoboxes,
  598. engine_data=result_container.engine_data,
  599. paging=result_container.paging,
  600. unresponsive_engines=__get_translated_errors(result_container.unresponsive_engines),
  601. current_language=match_language(search_query.lang,
  602. LANGUAGE_CODES,
  603. fallback=request.preferences.get_value("language")),
  604. base_url=get_base_url(),
  605. theme=get_current_theme_name(),
  606. favicons=global_favicons[themes.index(get_current_theme_name())],
  607. timeout_limit=request.form.get('timeout_limit', None)
  608. )
  609. def __get_translated_errors(unresponsive_engines):
  610. translated_errors = set()
  611. for unresponsive_engine in unresponsive_engines:
  612. error_msg = gettext(unresponsive_engine[1])
  613. if unresponsive_engine[2]:
  614. error_msg = "{} {}".format(error_msg, unresponsive_engine[2])
  615. translated_errors.add((unresponsive_engine[0], error_msg))
  616. return translated_errors
  617. @app.route('/about', methods=['GET'])
  618. def about():
  619. """Render about page"""
  620. return render(
  621. 'about.html',
  622. )
  623. @app.route('/autocompleter', methods=['GET', 'POST'])
  624. def autocompleter():
  625. """Return autocompleter results"""
  626. # run autocompleter
  627. results = []
  628. # set blocked engines
  629. disabled_engines = request.preferences.engines.get_disabled()
  630. # parse query
  631. raw_text_query = RawTextQuery(request.form.get('q', ''), disabled_engines)
  632. sug_prefix = raw_text_query.getQuery()
  633. # normal autocompletion results only appear if no inner results returned
  634. # and there is a query part
  635. if len(raw_text_query.autocomplete_list) == 0 and len(sug_prefix) > 0:
  636. # get language from cookie
  637. language = request.preferences.get_value('language')
  638. if not language or language == 'all':
  639. language = 'en'
  640. else:
  641. language = language.split('-')[0]
  642. # run autocompletion
  643. raw_results = search_autocomplete(
  644. request.preferences.get_value('autocomplete'), sug_prefix, language
  645. )
  646. for result in raw_results:
  647. # attention: this loop will change raw_text_query object and this is
  648. # the reason why the sug_prefix was stored before (see above)
  649. results.append(raw_text_query.changeQuery(result).getFullQuery())
  650. if len(raw_text_query.autocomplete_list) > 0:
  651. for autocomplete_text in raw_text_query.autocomplete_list:
  652. results.append(raw_text_query.get_autocomplete_full_query(autocomplete_text))
  653. for answers in ask(raw_text_query):
  654. for answer in answers:
  655. results.append(str(answer['answer']))
  656. if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
  657. # the suggestion request comes from the searx search form
  658. suggestions = json.dumps(results)
  659. mimetype = 'application/json'
  660. else:
  661. # the suggestion request comes from browser's URL bar
  662. suggestions = json.dumps([sug_prefix, results])
  663. mimetype = 'application/x-suggestions+json'
  664. return Response(suggestions, mimetype=mimetype)
  665. @app.route('/preferences', methods=['GET', 'POST'])
  666. def preferences():
  667. """Render preferences page && save user preferences"""
  668. # save preferences
  669. if request.method == 'POST':
  670. resp = make_response(redirect(url_for('index', _external=True)))
  671. try:
  672. request.preferences.parse_form(request.form)
  673. except ValidationException:
  674. request.errors.append(gettext('Invalid settings, please edit your preferences'))
  675. return resp
  676. return request.preferences.save(resp)
  677. # render preferences
  678. image_proxy = request.preferences.get_value('image_proxy')
  679. disabled_engines = request.preferences.engines.get_disabled()
  680. allowed_plugins = request.preferences.plugins.get_enabled()
  681. # stats for preferences page
  682. stats = {}
  683. engines_by_category = {}
  684. for c in categories:
  685. engines_by_category[c] = []
  686. for e in categories[c]:
  687. if not request.preferences.validate_token(e):
  688. continue
  689. stats[e.name] = {'time': None,
  690. 'warn_timeout': False,
  691. 'warn_time': False}
  692. if e.timeout > settings['outgoing']['request_timeout']:
  693. stats[e.name]['warn_timeout'] = True
  694. stats[e.name]['supports_selected_language'] = _is_selected_language_supported(e, request.preferences)
  695. engines_by_category[c].append(e)
  696. # get first element [0], the engine time,
  697. # and then the second element [1] : the time (the first one is the label)
  698. for engine_stat in get_engines_stats(request.preferences)[0][1]:
  699. stats[engine_stat.get('name')]['time'] = round(engine_stat.get('avg'), 3)
  700. if engine_stat.get('avg') > settings['outgoing']['request_timeout']:
  701. stats[engine_stat.get('name')]['warn_time'] = True
  702. # end of stats
  703. locked_preferences = list()
  704. if 'preferences' in settings and 'lock' in settings['preferences']:
  705. locked_preferences = settings['preferences']['lock']
  706. return render('preferences.html',
  707. selected_categories=get_selected_categories(request.preferences, request.form),
  708. all_categories=_get_ordered_categories(),
  709. locales=settings['locales'],
  710. current_locale=request.preferences.get_value("locale"),
  711. image_proxy=image_proxy,
  712. engines_by_category=engines_by_category,
  713. stats=stats,
  714. answerers=[{'info': a.self_info(), 'keywords': a.keywords} for a in answerers],
  715. disabled_engines=disabled_engines,
  716. autocomplete_backends=autocomplete_backends,
  717. shortcuts={y: x for x, y in engine_shortcuts.items()},
  718. themes=themes,
  719. plugins=plugins,
  720. doi_resolvers=settings['doi_resolvers'],
  721. current_doi_resolver=get_doi_resolver(request.args, request.preferences.get_value('doi_resolver')),
  722. allowed_plugins=allowed_plugins,
  723. theme=get_current_theme_name(),
  724. preferences_url_params=request.preferences.get_as_url_params(),
  725. base_url=get_base_url(),
  726. locked_preferences=locked_preferences,
  727. preferences=True)
  728. def _is_selected_language_supported(engine, preferences):
  729. language = preferences.get_value('language')
  730. return (language == 'all'
  731. or match_language(language,
  732. getattr(engine, 'supported_languages', []),
  733. getattr(engine, 'language_aliases', {}), None))
  734. @app.route('/image_proxy', methods=['GET'])
  735. def image_proxy():
  736. url = request.args.get('url').encode()
  737. if not url:
  738. return '', 400
  739. h = new_hmac(settings['server']['secret_key'], url)
  740. if h != request.args.get('h'):
  741. return '', 400
  742. headers = {
  743. 'User-Agent': gen_useragent(),
  744. 'Accept': 'image/webp,*/*',
  745. 'Accept-Encoding': 'gzip, deflate',
  746. 'Sec-GPC': '1',
  747. 'DNT': '1',
  748. }
  749. headers = dict_subset(request.headers, {'If-Modified-Since', 'If-None-Match'})
  750. resp = requests.get(url,
  751. stream=True,
  752. timeout=settings['outgoing']['request_timeout'],
  753. headers=headers,
  754. proxies=get_global_proxies())
  755. if resp.status_code == 304:
  756. return '', resp.status_code
  757. if resp.status_code != 200:
  758. logger.debug('image-proxy: wrong response code: {0}'.format(resp.status_code))
  759. if resp.status_code >= 400:
  760. return '', resp.status_code
  761. return '', 400
  762. if not resp.headers.get('content-type', '').startswith('image/'):
  763. logger.debug('image-proxy: wrong content-type: {0}'.format(resp.headers.get('content-type')))
  764. return '', 400
  765. img = b''
  766. chunk_counter = 0
  767. for chunk in resp.iter_content(1024 * 1024):
  768. chunk_counter += 1
  769. if chunk_counter > 5:
  770. return '', 502 # Bad gateway - file is too big (>5M)
  771. img += chunk
  772. headers = dict_subset(resp.headers, {'Content-Length', 'Length', 'Date', 'Last-Modified', 'Expires', 'Etag'})
  773. return Response(img, mimetype=resp.headers['content-type'], headers=headers)
  774. @app.route('/stats', methods=['GET'])
  775. def stats():
  776. """Render engine statistics page."""
  777. if not settings['general'].get('enable_stats'):
  778. return page_not_found(None)
  779. stats = get_engines_stats(request.preferences)
  780. return render(
  781. 'stats.html',
  782. stats=stats,
  783. )
  784. @app.route('/stats/errors', methods=['GET'])
  785. def stats_errors():
  786. result = {}
  787. engine_names = list(errors_per_engines.keys())
  788. engine_names.sort()
  789. for engine_name in engine_names:
  790. error_stats = errors_per_engines[engine_name]
  791. sent_search_count = max(engines[engine_name].stats['sent_search_count'], 1)
  792. sorted_context_count_list = sorted(error_stats.items(), key=lambda context_count: context_count[1])
  793. r = []
  794. percentage_sum = 0
  795. for context, count in sorted_context_count_list:
  796. percentage = round(20 * count / sent_search_count) * 5
  797. percentage_sum += percentage
  798. r.append({
  799. 'filename': context.filename,
  800. 'function': context.function,
  801. 'line_no': context.line_no,
  802. 'code': context.code,
  803. 'exception_classname': context.exception_classname,
  804. 'log_message': context.log_message,
  805. 'log_parameters': context.log_parameters,
  806. 'percentage': percentage,
  807. })
  808. result[engine_name] = sorted(r, reverse=True, key=lambda d: d['percentage'])
  809. return jsonify(result)
  810. @app.route('/stats/checker', methods=['GET'])
  811. def stats_checker():
  812. result = checker_get_result()
  813. return jsonify(result)
  814. @app.route('/robots.txt', methods=['GET'])
  815. def robots():
  816. return Response("""User-agent: *
  817. Allow: /
  818. Allow: /about
  819. Disallow: /stats
  820. Disallow: /preferences
  821. Disallow: /*?*q=*
  822. """, mimetype='text/plain')
  823. @app.route('/opensearch.xml', methods=['GET'])
  824. def opensearch():
  825. method = 'post'
  826. if request.preferences.get_value('method') == 'GET':
  827. method = 'get'
  828. # chrome/chromium only supports HTTP GET....
  829. if request.headers.get('User-Agent', '').lower().find('webkit') >= 0:
  830. method = 'get'
  831. ret = render(
  832. 'opensearch.xml',
  833. opensearch_method=method,
  834. override_theme='__common__'
  835. )
  836. resp = Response(response=ret,
  837. status=200,
  838. mimetype="application/opensearchdescription+xml")
  839. return resp
  840. @app.route('/favicon.ico')
  841. def favicon():
  842. return send_from_directory(os.path.join(app.root_path,
  843. static_path,
  844. 'themes',
  845. get_current_theme_name(),
  846. 'img'),
  847. 'favicon.png',
  848. mimetype='image/vnd.microsoft.icon')
  849. @app.route('/clear_cookies')
  850. def clear_cookies():
  851. resp = make_response(redirect(url_for('index', _external=True)))
  852. for cookie_name in request.cookies:
  853. resp.delete_cookie(cookie_name)
  854. return resp
  855. @app.route('/config')
  856. def config():
  857. """Return configuration in JSON format."""
  858. _engines = []
  859. for name, engine in engines.items():
  860. if not request.preferences.validate_token(engine):
  861. continue
  862. supported_languages = engine.supported_languages
  863. if isinstance(engine.supported_languages, dict):
  864. supported_languages = list(engine.supported_languages.keys())
  865. _engines.append({
  866. 'name': name,
  867. 'categories': engine.categories,
  868. 'shortcut': engine.shortcut,
  869. 'enabled': not engine.disabled,
  870. 'paging': engine.paging,
  871. 'language_support': engine.language_support,
  872. 'supported_languages': supported_languages,
  873. 'safesearch': engine.safesearch,
  874. 'time_range_support': engine.time_range_support,
  875. 'timeout': engine.timeout
  876. })
  877. _plugins = []
  878. for _ in plugins:
  879. _plugins.append({'name': _.name, 'enabled': _.default_on})
  880. return jsonify({
  881. 'categories': list(categories.keys()),
  882. 'engines': _engines,
  883. 'plugins': _plugins,
  884. 'instance_name': settings['general']['instance_name'],
  885. 'locales': settings['locales'],
  886. 'default_locale': settings['ui']['default_locale'],
  887. 'autocomplete': settings['search']['autocomplete'],
  888. 'safe_search': settings['search']['safe_search'],
  889. 'default_theme': settings['ui']['default_theme'],
  890. 'version': VERSION_STRING,
  891. 'brand': {
  892. 'CONTACT_URL': brand.CONTACT_URL,
  893. 'GIT_URL': brand.GIT_URL,
  894. 'GIT_BRANCH': brand.GIT_BRANCH,
  895. 'DOCS_URL': brand.DOCS_URL
  896. },
  897. 'doi_resolvers': [r for r in settings['doi_resolvers']],
  898. 'default_doi_resolver': settings['default_doi_resolver'],
  899. })
  900. @app.errorhandler(404)
  901. def page_not_found(e):
  902. return render('404.html'), 404
  903. def run():
  904. logger.debug('starting webserver on %s:%s', settings['server']['bind_address'], settings['server']['port'])
  905. app.run(
  906. debug=searx_debug,
  907. use_debugger=searx_debug,
  908. port=settings['server']['port'],
  909. host=settings['server']['bind_address'],
  910. threaded=True,
  911. extra_files=[
  912. get_default_settings_path()
  913. ],
  914. )
  915. def patch_application(app):
  916. # serve pages with HTTP/1.1
  917. WSGIRequestHandler.protocol_version = "HTTP/{}".format(settings['server']['http_protocol_version'])
  918. # patch app to handle non root url-s behind proxy & wsgi
  919. app.wsgi_app = ReverseProxyPathFix(ProxyFix(app.wsgi_app))
  920. class ReverseProxyPathFix:
  921. '''Wrap the application in this middleware and configure the
  922. front-end server to add these headers, to let you quietly bind
  923. this to a URL other than / and to an HTTP scheme that is
  924. different than what is used locally.
  925. http://flask.pocoo.org/snippets/35/
  926. In nginx:
  927. location /myprefix {
  928. proxy_pass http://127.0.0.1:8000;
  929. proxy_set_header Host $host;
  930. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  931. proxy_set_header X-Scheme $scheme;
  932. proxy_set_header X-Script-Name /myprefix;
  933. }
  934. :param app: the WSGI application
  935. '''
  936. def __init__(self, app):
  937. self.app = app
  938. self.script_name = None
  939. self.scheme = None
  940. self.server = None
  941. if settings['server']['base_url']:
  942. # If base_url is specified, then these values from are given
  943. # preference over any Flask's generics.
  944. base_url = urlparse(settings['server']['base_url'])
  945. self.script_name = base_url.path
  946. if self.script_name.endswith('/'):
  947. # remove trailing slash to avoid infinite redirect on the index
  948. # see https://github.com/searx/searx/issues/2729
  949. self.script_name = self.script_name[:-1]
  950. self.scheme = base_url.scheme
  951. self.server = base_url.netloc
  952. def __call__(self, environ, start_response):
  953. script_name = self.script_name or environ.get('HTTP_X_SCRIPT_NAME', '')
  954. if script_name:
  955. environ['SCRIPT_NAME'] = script_name
  956. path_info = environ['PATH_INFO']
  957. if path_info.startswith(script_name):
  958. environ['PATH_INFO'] = path_info[len(script_name):]
  959. scheme = self.scheme or environ.get('HTTP_X_SCHEME', '')
  960. if scheme:
  961. environ['wsgi.url_scheme'] = scheme
  962. server = self.server or environ.get('HTTP_X_FORWARDED_HOST', '')
  963. if server:
  964. environ['HTTP_HOST'] = server
  965. return self.app(environ, start_response)
  966. application = app
  967. # patch app to handle non root url-s behind proxy & wsgi
  968. app.wsgi_app = ReverseProxyPathFix(ProxyFix(application.wsgi_app))
  969. if __name__ == "__main__":
  970. run()