webapp.py 41 KB

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