webapp.py 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  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. if __name__ == '__main__':
  16. from sys import path
  17. from os.path import realpath, dirname
  18. path.append(realpath(dirname(realpath(__file__)) + '/../'))
  19. import hashlib
  20. import hmac
  21. import json
  22. import os
  23. import sys
  24. import requests
  25. from searx import logger
  26. logger = logger.getChild('webapp')
  27. try:
  28. from pygments import highlight
  29. from pygments.lexers import get_lexer_by_name
  30. from pygments.formatters import HtmlFormatter
  31. except:
  32. logger.critical("cannot import dependency: pygments")
  33. from sys import exit
  34. exit(1)
  35. from cgi import escape
  36. from datetime import datetime, timedelta
  37. from werkzeug.contrib.fixers import ProxyFix
  38. from flask import (
  39. Flask, request, render_template, url_for, Response, make_response,
  40. redirect, send_from_directory
  41. )
  42. from flask_babel import Babel, gettext, format_date, format_decimal
  43. from flask.json import jsonify
  44. from searx import settings, searx_dir, searx_debug
  45. from searx.exceptions import SearxParameterException
  46. from searx.engines import (
  47. categories, engines, engine_shortcuts, get_engines_stats, initialize_engines
  48. )
  49. from searx.utils import (
  50. UnicodeWriter, highlight_content, html_to_text, get_resources_directory,
  51. get_static_files, get_result_templates, get_themes, gen_useragent,
  52. dict_subset, prettify_url
  53. )
  54. from searx.version import VERSION_STRING
  55. from searx.languages import language_codes
  56. from searx.search import SearchWithPlugins, get_search_query_from_webapp
  57. from searx.query import RawTextQuery
  58. from searx.autocomplete import searx_bang, backends as autocomplete_backends
  59. from searx.plugins import plugins
  60. from searx.plugins.oa_doi_rewrite import get_doi_resolver
  61. from searx.preferences import Preferences, ValidationException
  62. from searx.answerers import answerers
  63. from searx.url_utils import urlencode, urlparse, urljoin
  64. from searx.utils import new_hmac
  65. # check if the pyopenssl package is installed.
  66. # It is needed for SSL connection without trouble, see #298
  67. try:
  68. import OpenSSL.SSL # NOQA
  69. except ImportError:
  70. logger.critical("The pyopenssl package has to be installed.\n"
  71. "Some HTTPS connections will fail")
  72. try:
  73. from cStringIO import StringIO
  74. except:
  75. from io import StringIO
  76. if sys.version_info[0] == 3:
  77. unicode = str
  78. PY3 = True
  79. else:
  80. PY3 = False
  81. # serve pages with HTTP/1.1
  82. from werkzeug.serving import WSGIRequestHandler
  83. WSGIRequestHandler.protocol_version = "HTTP/{}".format(settings['server'].get('http_protocol_version', '1.0'))
  84. # about static
  85. static_path = get_resources_directory(searx_dir, 'static', settings['ui']['static_path'])
  86. logger.debug('static directory is %s', static_path)
  87. static_files = get_static_files(static_path)
  88. # about templates
  89. default_theme = settings['ui']['default_theme']
  90. templates_path = get_resources_directory(searx_dir, 'templates', settings['ui']['templates_path'])
  91. logger.debug('templates directory is %s', templates_path)
  92. themes = get_themes(templates_path)
  93. result_templates = get_result_templates(templates_path)
  94. global_favicons = []
  95. for indice, theme in enumerate(themes):
  96. global_favicons.append([])
  97. theme_img_path = os.path.join(static_path, 'themes', theme, 'img', 'icons')
  98. for (dirpath, dirnames, filenames) in os.walk(theme_img_path):
  99. global_favicons[indice].extend(filenames)
  100. # Flask app
  101. app = Flask(
  102. __name__,
  103. static_folder=static_path,
  104. template_folder=templates_path
  105. )
  106. app.jinja_env.trim_blocks = True
  107. app.jinja_env.lstrip_blocks = True
  108. app.secret_key = settings['server']['secret_key']
  109. if not searx_debug \
  110. or os.environ.get("WERKZEUG_RUN_MAIN") == "true" \
  111. or os.environ.get('UWSGI_ORIGINAL_PROC_NAME') is not None:
  112. initialize_engines(settings['engines'])
  113. babel = Babel(app)
  114. rtl_locales = ['ar', 'arc', 'bcc', 'bqi', 'ckb', 'dv', 'fa', 'glk', 'he',
  115. 'ku', 'mzn', 'pnb'', ''ps', 'sd', 'ug', 'ur', 'yi']
  116. # used when translating category names
  117. _category_names = (gettext('files'),
  118. gettext('general'),
  119. gettext('music'),
  120. gettext('social media'),
  121. gettext('images'),
  122. gettext('videos'),
  123. gettext('it'),
  124. gettext('news'),
  125. gettext('map'),
  126. gettext('science'))
  127. outgoing_proxies = settings['outgoing'].get('proxies') or None
  128. @babel.localeselector
  129. def get_locale():
  130. locale = request.accept_languages.best_match(settings['locales'].keys())
  131. if request.preferences.get_value('locale') != '':
  132. locale = request.preferences.get_value('locale')
  133. if 'locale' in request.args\
  134. and request.args['locale'] in settings['locales']:
  135. locale = request.args['locale']
  136. if 'locale' in request.form\
  137. and request.form['locale'] in settings['locales']:
  138. locale = request.form['locale']
  139. if locale == 'zh_TW':
  140. locale = 'zh_Hant_TW'
  141. return locale
  142. # code-highlighter
  143. @app.template_filter('code_highlighter')
  144. def code_highlighter(codelines, language=None):
  145. if not language:
  146. language = 'text'
  147. try:
  148. # find lexer by programing language
  149. lexer = get_lexer_by_name(language, stripall=True)
  150. except:
  151. # if lexer is not found, using default one
  152. logger.debug('highlighter cannot find lexer for {0}'.format(language))
  153. lexer = get_lexer_by_name('text', stripall=True)
  154. html_code = ''
  155. tmp_code = ''
  156. last_line = None
  157. # parse lines
  158. for line, code in codelines:
  159. if not last_line:
  160. line_code_start = line
  161. # new codeblock is detected
  162. if last_line is not None and\
  163. last_line + 1 != line:
  164. # highlight last codepart
  165. formatter = HtmlFormatter(linenos='inline',
  166. linenostart=line_code_start)
  167. html_code = html_code + highlight(tmp_code, lexer, formatter)
  168. # reset conditions for next codepart
  169. tmp_code = ''
  170. line_code_start = line
  171. # add codepart
  172. tmp_code += code + '\n'
  173. # update line
  174. last_line = line
  175. # highlight last codepart
  176. formatter = HtmlFormatter(linenos='inline', linenostart=line_code_start)
  177. html_code = html_code + highlight(tmp_code, lexer, formatter)
  178. return html_code
  179. # Extract domain from url
  180. @app.template_filter('extract_domain')
  181. def extract_domain(url):
  182. return urlparse(url)[1]
  183. def get_base_url():
  184. if settings['server']['base_url']:
  185. hostname = settings['server']['base_url']
  186. else:
  187. scheme = 'http'
  188. if request.is_secure:
  189. scheme = 'https'
  190. hostname = url_for('index', _external=True, _scheme=scheme)
  191. return hostname
  192. def get_current_theme_name(override=None):
  193. """Returns theme name.
  194. Checks in this order:
  195. 1. override
  196. 2. cookies
  197. 3. settings"""
  198. if override and (override in themes or override == '__common__'):
  199. return override
  200. theme_name = request.args.get('theme', request.preferences.get_value('theme'))
  201. if theme_name not in themes:
  202. theme_name = default_theme
  203. return theme_name
  204. def get_result_template(theme, template_name):
  205. themed_path = theme + '/result_templates/' + template_name
  206. if themed_path in result_templates:
  207. return themed_path
  208. return 'result_templates/' + template_name
  209. def url_for_theme(endpoint, override_theme=None, **values):
  210. if endpoint == 'static' and values.get('filename'):
  211. theme_name = get_current_theme_name(override=override_theme)
  212. filename_with_theme = "themes/{}/{}".format(theme_name, values['filename'])
  213. if filename_with_theme in static_files:
  214. values['filename'] = filename_with_theme
  215. return url_for(endpoint, **values)
  216. def proxify(url):
  217. if url.startswith('//'):
  218. url = 'https:' + url
  219. if not settings.get('result_proxy'):
  220. return url
  221. url_params = dict(mortyurl=url.encode('utf-8'))
  222. if settings['result_proxy'].get('key'):
  223. url_params['mortyhash'] = hmac.new(settings['result_proxy']['key'],
  224. url.encode('utf-8'),
  225. hashlib.sha256).hexdigest()
  226. return '{0}?{1}'.format(settings['result_proxy']['url'],
  227. urlencode(url_params))
  228. def image_proxify(url):
  229. if url.startswith('//'):
  230. url = 'https:' + url
  231. if not request.preferences.get_value('image_proxy'):
  232. return url
  233. if settings.get('result_proxy'):
  234. return proxify(url)
  235. h = new_hmac(settings['server']['secret_key'], url.encode('utf-8'))
  236. return '{0}?{1}'.format(url_for('image_proxy'),
  237. urlencode(dict(url=url.encode('utf-8'), h=h)))
  238. def render(template_name, override_theme=None, **kwargs):
  239. disabled_engines = request.preferences.engines.get_disabled()
  240. enabled_categories = set(category for engine_name in engines
  241. for category in engines[engine_name].categories
  242. if (engine_name, category) not in disabled_engines)
  243. if 'categories' not in kwargs:
  244. kwargs['categories'] = ['general']
  245. kwargs['categories'].extend(x for x in
  246. sorted(categories.keys())
  247. if x != 'general'
  248. and x in enabled_categories)
  249. if 'all_categories' not in kwargs:
  250. kwargs['all_categories'] = ['general']
  251. kwargs['all_categories'].extend(x for x in
  252. sorted(categories.keys())
  253. if x != 'general')
  254. if 'selected_categories' not in kwargs:
  255. kwargs['selected_categories'] = []
  256. for arg in request.args:
  257. if arg.startswith('category_'):
  258. c = arg.split('_', 1)[1]
  259. if c in categories:
  260. kwargs['selected_categories'].append(c)
  261. if not kwargs['selected_categories']:
  262. cookie_categories = request.preferences.get_value('categories')
  263. for ccateg in cookie_categories:
  264. kwargs['selected_categories'].append(ccateg)
  265. if not kwargs['selected_categories']:
  266. kwargs['selected_categories'] = ['general']
  267. if 'autocomplete' not in kwargs:
  268. kwargs['autocomplete'] = request.preferences.get_value('autocomplete')
  269. if get_locale() in rtl_locales and 'rtl' not in kwargs:
  270. kwargs['rtl'] = True
  271. kwargs['searx_version'] = VERSION_STRING
  272. kwargs['method'] = request.preferences.get_value('method')
  273. kwargs['safesearch'] = str(request.preferences.get_value('safesearch'))
  274. kwargs['language_codes'] = language_codes
  275. if 'current_language' not in kwargs:
  276. kwargs['current_language'] = request.preferences.get_value('language')
  277. # override url_for function in templates
  278. kwargs['url_for'] = url_for_theme
  279. kwargs['image_proxify'] = image_proxify
  280. kwargs['proxify'] = proxify if settings.get('result_proxy', {}).get('url') else None
  281. kwargs['get_result_template'] = get_result_template
  282. kwargs['theme'] = get_current_theme_name(override=override_theme)
  283. kwargs['template_name'] = template_name
  284. kwargs['cookies'] = request.cookies
  285. kwargs['errors'] = request.errors
  286. kwargs['instance_name'] = settings['general']['instance_name']
  287. kwargs['results_on_new_tab'] = request.preferences.get_value('results_on_new_tab')
  288. kwargs['unicode'] = unicode
  289. kwargs['preferences'] = request.preferences
  290. kwargs['scripts'] = set()
  291. for plugin in request.user_plugins:
  292. for script in plugin.js_dependencies:
  293. kwargs['scripts'].add(script)
  294. kwargs['styles'] = set()
  295. for plugin in request.user_plugins:
  296. for css in plugin.css_dependencies:
  297. kwargs['styles'].add(css)
  298. return render_template(
  299. '{}/{}'.format(kwargs['theme'], template_name), **kwargs)
  300. @app.before_request
  301. def pre_request():
  302. request.errors = []
  303. preferences = Preferences(themes, list(categories.keys()), engines, plugins)
  304. request.preferences = preferences
  305. try:
  306. preferences.parse_dict(request.cookies)
  307. except:
  308. request.errors.append(gettext('Invalid settings, please edit your preferences'))
  309. # merge GET, POST vars
  310. # request.form
  311. request.form = dict(request.form.items())
  312. for k, v in request.args.items():
  313. if k not in request.form:
  314. request.form[k] = v
  315. if request.form.get('preferences'):
  316. preferences.parse_encoded_data(request.form['preferences'])
  317. else:
  318. try:
  319. preferences.parse_dict(request.form)
  320. except Exception as e:
  321. logger.exception('invalid settings')
  322. request.errors.append(gettext('Invalid settings'))
  323. # request.user_plugins
  324. request.user_plugins = []
  325. allowed_plugins = preferences.plugins.get_enabled()
  326. disabled_plugins = preferences.plugins.get_disabled()
  327. for plugin in plugins:
  328. if ((plugin.default_on and plugin.id not in disabled_plugins)
  329. or plugin.id in allowed_plugins):
  330. request.user_plugins.append(plugin)
  331. def index_error(output_format, error_message):
  332. if output_format == 'json':
  333. return Response(json.dumps({'error': error_message}),
  334. mimetype='application/json')
  335. elif output_format == 'csv':
  336. response = Response('', mimetype='application/csv')
  337. cont_disp = 'attachment;Filename=searx.csv'
  338. response.headers.add('Content-Disposition', cont_disp)
  339. return response
  340. elif output_format == 'rss':
  341. response_rss = render(
  342. 'opensearch_response_rss.xml',
  343. results=[],
  344. q=request.form['q'] if 'q' in request.form else '',
  345. number_of_results=0,
  346. base_url=get_base_url(),
  347. error_message=error_message,
  348. override_theme='__common__',
  349. )
  350. return Response(response_rss, mimetype='text/xml')
  351. else:
  352. # html
  353. request.errors.append(gettext('search error'))
  354. return render(
  355. 'index.html',
  356. )
  357. @app.route('/search', methods=['GET', 'POST'])
  358. @app.route('/', methods=['GET', 'POST'])
  359. def index():
  360. """Render index page.
  361. Supported outputs: html, json, csv, rss.
  362. """
  363. # output_format
  364. output_format = request.form.get('format', 'html')
  365. if output_format not in ['html', 'csv', 'json', 'rss']:
  366. output_format = 'html'
  367. # check if there is query
  368. if request.form.get('q') is None:
  369. if output_format == 'html':
  370. return render(
  371. 'index.html',
  372. )
  373. else:
  374. return index_error(output_format, 'No query'), 400
  375. # search
  376. search_query = None
  377. result_container = None
  378. try:
  379. search_query = get_search_query_from_webapp(request.preferences, request.form)
  380. # search = Search(search_query) # without plugins
  381. search = SearchWithPlugins(search_query, request.user_plugins, request)
  382. result_container = search.search()
  383. except Exception as e:
  384. # log exception
  385. logger.exception('search error')
  386. # is it an invalid input parameter or something else ?
  387. if (issubclass(e.__class__, SearxParameterException)):
  388. return index_error(output_format, e.message), 400
  389. else:
  390. return index_error(output_format, gettext('search error')), 500
  391. # results
  392. results = result_container.get_ordered_results()
  393. number_of_results = result_container.results_number()
  394. if number_of_results < result_container.results_length():
  395. number_of_results = 0
  396. # UI
  397. advanced_search = request.form.get('advanced_search', None)
  398. # output
  399. for result in results:
  400. if output_format == 'html':
  401. if 'content' in result and result['content']:
  402. result['content'] = highlight_content(escape(result['content'][:1024]), search_query.query)
  403. result['title'] = highlight_content(escape(result['title'] or u''), search_query.query)
  404. else:
  405. if result.get('content'):
  406. result['content'] = html_to_text(result['content']).strip()
  407. # removing html content and whitespace duplications
  408. result['title'] = ' '.join(html_to_text(result['title']).strip().split())
  409. result['pretty_url'] = prettify_url(result['url'])
  410. # TODO, check if timezone is calculated right
  411. if 'publishedDate' in result:
  412. try: # test if publishedDate >= 1900 (datetime module bug)
  413. result['pubdate'] = result['publishedDate'].strftime('%Y-%m-%d %H:%M:%S%z')
  414. except ValueError:
  415. result['publishedDate'] = None
  416. else:
  417. if result['publishedDate'].replace(tzinfo=None) >= datetime.now() - timedelta(days=1):
  418. timedifference = datetime.now() - result['publishedDate'].replace(tzinfo=None)
  419. minutes = int((timedifference.seconds / 60) % 60)
  420. hours = int(timedifference.seconds / 60 / 60)
  421. if hours == 0:
  422. result['publishedDate'] = gettext(u'{minutes} minute(s) ago').format(minutes=minutes)
  423. else:
  424. result['publishedDate'] = gettext(u'{hours} hour(s), {minutes} minute(s) ago').format(hours=hours, minutes=minutes) # noqa
  425. else:
  426. result['publishedDate'] = format_date(result['publishedDate'])
  427. if output_format == 'json':
  428. return Response(json.dumps({'query': search_query.query.decode('utf-8'),
  429. 'number_of_results': number_of_results,
  430. 'results': results,
  431. 'answers': list(result_container.answers),
  432. 'corrections': list(result_container.corrections),
  433. 'infoboxes': result_container.infoboxes,
  434. 'suggestions': list(result_container.suggestions),
  435. 'unresponsive_engines': list(result_container.unresponsive_engines)},
  436. default=lambda item: list(item) if isinstance(item, set) else item),
  437. mimetype='application/json')
  438. elif output_format == 'csv':
  439. csv = UnicodeWriter(StringIO())
  440. keys = ('title', 'url', 'content', 'host', 'engine', 'score')
  441. csv.writerow(keys)
  442. for row in results:
  443. row['host'] = row['parsed_url'].netloc
  444. csv.writerow([row.get(key, '') for key in keys])
  445. csv.stream.seek(0)
  446. response = Response(csv.stream.read(), mimetype='application/csv')
  447. cont_disp = 'attachment;Filename=searx_-_{0}.csv'.format(search_query.query)
  448. response.headers.add('Content-Disposition', cont_disp)
  449. return response
  450. elif output_format == 'rss':
  451. response_rss = render(
  452. 'opensearch_response_rss.xml',
  453. results=results,
  454. q=request.form['q'],
  455. number_of_results=number_of_results,
  456. base_url=get_base_url(),
  457. override_theme='__common__',
  458. )
  459. return Response(response_rss, mimetype='text/xml')
  460. return render(
  461. 'results.html',
  462. results=results,
  463. q=request.form['q'],
  464. selected_categories=search_query.categories,
  465. pageno=search_query.pageno,
  466. time_range=search_query.time_range,
  467. number_of_results=format_decimal(number_of_results),
  468. advanced_search=advanced_search,
  469. suggestions=result_container.suggestions,
  470. answers=result_container.answers,
  471. corrections=result_container.corrections,
  472. infoboxes=result_container.infoboxes,
  473. paging=result_container.paging,
  474. unresponsive_engines=result_container.unresponsive_engines,
  475. current_language=search_query.lang,
  476. base_url=get_base_url(),
  477. theme=get_current_theme_name(),
  478. favicons=global_favicons[themes.index(get_current_theme_name())]
  479. )
  480. @app.route('/about', methods=['GET'])
  481. def about():
  482. """Render about page"""
  483. return render(
  484. 'about.html',
  485. )
  486. @app.route('/autocompleter', methods=['GET', 'POST'])
  487. def autocompleter():
  488. """Return autocompleter results"""
  489. # set blocked engines
  490. disabled_engines = request.preferences.engines.get_disabled()
  491. # parse query
  492. if PY3:
  493. raw_text_query = RawTextQuery(request.form.get('q', b''), disabled_engines)
  494. else:
  495. raw_text_query = RawTextQuery(request.form.get('q', u'').encode('utf-8'), disabled_engines)
  496. raw_text_query.parse_query()
  497. # check if search query is set
  498. if not raw_text_query.getSearchQuery():
  499. return '', 400
  500. # run autocompleter
  501. completer = autocomplete_backends.get(request.preferences.get_value('autocomplete'))
  502. # parse searx specific autocompleter results like !bang
  503. raw_results = searx_bang(raw_text_query)
  504. # normal autocompletion results only appear if max 3 inner results returned
  505. if len(raw_results) <= 3 and completer:
  506. # get language from cookie
  507. language = request.preferences.get_value('language')
  508. if not language:
  509. language = settings['search']['language']
  510. else:
  511. language = language.split('-')[0]
  512. # run autocompletion
  513. raw_results.extend(completer(raw_text_query.getSearchQuery(), language))
  514. # parse results (write :language and !engine back to result string)
  515. results = []
  516. for result in raw_results:
  517. raw_text_query.changeSearchQuery(result)
  518. # add parsed result
  519. results.append(raw_text_query.getFullQuery())
  520. # return autocompleter results
  521. if request.form.get('format') == 'x-suggestions':
  522. return Response(json.dumps([raw_text_query.query, results]),
  523. mimetype='application/json')
  524. return Response(json.dumps(results),
  525. mimetype='application/json')
  526. @app.route('/preferences', methods=['GET', 'POST'])
  527. def preferences():
  528. """Render preferences page && save user preferences"""
  529. # save preferences
  530. if request.method == 'POST':
  531. resp = make_response(redirect(urljoin(settings['server']['base_url'], url_for('index'))))
  532. try:
  533. request.preferences.parse_form(request.form)
  534. except ValidationException:
  535. request.errors.append(gettext('Invalid settings, please edit your preferences'))
  536. return resp
  537. return request.preferences.save(resp)
  538. # render preferences
  539. image_proxy = request.preferences.get_value('image_proxy')
  540. lang = request.preferences.get_value('language')
  541. disabled_engines = request.preferences.engines.get_disabled()
  542. allowed_plugins = request.preferences.plugins.get_enabled()
  543. # stats for preferences page
  544. stats = {}
  545. for c in categories:
  546. for e in categories[c]:
  547. stats[e.name] = {'time': None,
  548. 'warn_timeout': False,
  549. 'warn_time': False}
  550. if e.timeout > settings['outgoing']['request_timeout']:
  551. stats[e.name]['warn_timeout'] = True
  552. # get first element [0], the engine time,
  553. # and then the second element [1] : the time (the first one is the label)
  554. for engine_stat in get_engines_stats()[0][1]:
  555. stats[engine_stat.get('name')]['time'] = round(engine_stat.get('avg'), 3)
  556. if engine_stat.get('avg') > settings['outgoing']['request_timeout']:
  557. stats[engine_stat.get('name')]['warn_time'] = True
  558. # end of stats
  559. return render('preferences.html',
  560. locales=settings['locales'],
  561. current_locale=get_locale(),
  562. image_proxy=image_proxy,
  563. engines_by_category=categories,
  564. stats=stats,
  565. answerers=[{'info': a.self_info(), 'keywords': a.keywords} for a in answerers],
  566. disabled_engines=disabled_engines,
  567. autocomplete_backends=autocomplete_backends,
  568. shortcuts={y: x for x, y in engine_shortcuts.items()},
  569. themes=themes,
  570. plugins=plugins,
  571. doi_resolvers=settings['doi_resolvers'],
  572. current_doi_resolver=get_doi_resolver(request.args, request.preferences.get_value('doi_resolver')),
  573. allowed_plugins=allowed_plugins,
  574. theme=get_current_theme_name(),
  575. preferences_url_params=request.preferences.get_as_url_params(),
  576. base_url=get_base_url(),
  577. preferences=True)
  578. @app.route('/image_proxy', methods=['GET'])
  579. def image_proxy():
  580. url = request.args.get('url').encode('utf-8')
  581. if not url:
  582. return '', 400
  583. h = new_hmac(settings['server']['secret_key'], url)
  584. if h != request.args.get('h'):
  585. return '', 400
  586. headers = dict_subset(request.headers, {'If-Modified-Since', 'If-None-Match'})
  587. headers['User-Agent'] = gen_useragent()
  588. resp = requests.get(url,
  589. stream=True,
  590. timeout=settings['outgoing']['request_timeout'],
  591. headers=headers,
  592. proxies=outgoing_proxies)
  593. if resp.status_code == 304:
  594. return '', resp.status_code
  595. if resp.status_code != 200:
  596. logger.debug('image-proxy: wrong response code: {0}'.format(resp.status_code))
  597. if resp.status_code >= 400:
  598. return '', resp.status_code
  599. return '', 400
  600. if not resp.headers.get('content-type', '').startswith('image/'):
  601. logger.debug('image-proxy: wrong content-type: {0}'.format(resp.headers.get('content-type')))
  602. return '', 400
  603. img = b''
  604. chunk_counter = 0
  605. for chunk in resp.iter_content(1024 * 1024):
  606. chunk_counter += 1
  607. if chunk_counter > 5:
  608. return '', 502 # Bad gateway - file is too big (>5M)
  609. img += chunk
  610. headers = dict_subset(resp.headers, {'Content-Length', 'Length', 'Date', 'Last-Modified', 'Expires', 'Etag'})
  611. return Response(img, mimetype=resp.headers['content-type'], headers=headers)
  612. @app.route('/stats', methods=['GET'])
  613. def stats():
  614. """Render engine statistics page."""
  615. stats = get_engines_stats()
  616. return render(
  617. 'stats.html',
  618. stats=stats,
  619. )
  620. @app.route('/robots.txt', methods=['GET'])
  621. def robots():
  622. return Response("""User-agent: *
  623. Allow: /
  624. Allow: /about
  625. Disallow: /stats
  626. Disallow: /preferences
  627. Disallow: /*?*q=*
  628. """, mimetype='text/plain')
  629. @app.route('/opensearch.xml', methods=['GET'])
  630. def opensearch():
  631. method = 'post'
  632. if request.preferences.get_value('method') == 'GET':
  633. method = 'get'
  634. # chrome/chromium only supports HTTP GET....
  635. if request.headers.get('User-Agent', '').lower().find('webkit') >= 0:
  636. method = 'get'
  637. ret = render('opensearch.xml',
  638. opensearch_method=method,
  639. host=get_base_url(),
  640. urljoin=urljoin,
  641. override_theme='__common__')
  642. resp = Response(response=ret,
  643. status=200,
  644. mimetype="text/xml")
  645. return resp
  646. @app.route('/favicon.ico')
  647. def favicon():
  648. return send_from_directory(os.path.join(app.root_path,
  649. static_path,
  650. 'themes',
  651. get_current_theme_name(),
  652. 'img'),
  653. 'favicon.png',
  654. mimetype='image/vnd.microsoft.icon')
  655. @app.route('/clear_cookies')
  656. def clear_cookies():
  657. resp = make_response(redirect(urljoin(settings['server']['base_url'], url_for('index'))))
  658. for cookie_name in request.cookies:
  659. resp.delete_cookie(cookie_name)
  660. return resp
  661. @app.route('/config')
  662. def config():
  663. return jsonify({'categories': categories.keys(),
  664. 'engines': [{'name': engine_name,
  665. 'categories': engine.categories,
  666. 'shortcut': engine.shortcut,
  667. 'enabled': not engine.disabled,
  668. 'paging': engine.paging,
  669. 'language_support': engine.language_support,
  670. 'supported_languages':
  671. engine.supported_languages.keys()
  672. if isinstance(engine.supported_languages, dict)
  673. else engine.supported_languages,
  674. 'safesearch': engine.safesearch,
  675. 'time_range_support': engine.time_range_support,
  676. 'timeout': engine.timeout}
  677. for engine_name, engine in engines.items()],
  678. 'plugins': [{'name': plugin.name,
  679. 'enabled': plugin.default_on}
  680. for plugin in plugins],
  681. 'instance_name': settings['general']['instance_name'],
  682. 'locales': settings['locales'],
  683. 'default_locale': settings['ui']['default_locale'],
  684. 'autocomplete': settings['search']['autocomplete'],
  685. 'safe_search': settings['search']['safe_search'],
  686. 'default_theme': settings['ui']['default_theme'],
  687. 'version': VERSION_STRING,
  688. 'doi_resolvers': [r for r in settings['doi_resolvers']],
  689. 'default_doi_resolver': settings['default_doi_resolver'],
  690. })
  691. @app.errorhandler(404)
  692. def page_not_found(e):
  693. return render('404.html'), 404
  694. def run():
  695. logger.debug('starting webserver on %s:%s', settings['server']['port'], settings['server']['bind_address'])
  696. app.run(
  697. debug=searx_debug,
  698. use_debugger=searx_debug,
  699. port=settings['server']['port'],
  700. host=settings['server']['bind_address'],
  701. threaded=True
  702. )
  703. class ReverseProxyPathFix(object):
  704. '''Wrap the application in this middleware and configure the
  705. front-end server to add these headers, to let you quietly bind
  706. this to a URL other than / and to an HTTP scheme that is
  707. different than what is used locally.
  708. http://flask.pocoo.org/snippets/35/
  709. In nginx:
  710. location /myprefix {
  711. proxy_pass http://127.0.0.1:8000;
  712. proxy_set_header Host $host;
  713. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  714. proxy_set_header X-Scheme $scheme;
  715. proxy_set_header X-Script-Name /myprefix;
  716. }
  717. :param app: the WSGI application
  718. '''
  719. def __init__(self, app):
  720. self.app = app
  721. def __call__(self, environ, start_response):
  722. script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
  723. if script_name:
  724. environ['SCRIPT_NAME'] = script_name
  725. path_info = environ['PATH_INFO']
  726. if path_info.startswith(script_name):
  727. environ['PATH_INFO'] = path_info[len(script_name):]
  728. scheme = environ.get('HTTP_X_SCHEME', '')
  729. if scheme:
  730. environ['wsgi.url_scheme'] = scheme
  731. return self.app(environ, start_response)
  732. application = app
  733. # patch app to handle non root url-s behind proxy & wsgi
  734. app.wsgi_app = ReverseProxyPathFix(ProxyFix(application.wsgi_app))
  735. if __name__ == "__main__":
  736. run()