webapp.py 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  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, match_language
  53. )
  54. from searx.version import VERSION_STRING
  55. from searx.languages import language_codes as languages
  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, LANGUAGE_CODES
  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'] = languages
  275. if 'current_language' not in kwargs:
  276. kwargs['current_language'] = match_language(request.preferences.get_value('language'),
  277. LANGUAGE_CODES,
  278. fallback=settings['search']['language'])
  279. # override url_for function in templates
  280. kwargs['url_for'] = url_for_theme
  281. kwargs['image_proxify'] = image_proxify
  282. kwargs['proxify'] = proxify if settings.get('result_proxy', {}).get('url') else None
  283. kwargs['get_result_template'] = get_result_template
  284. kwargs['theme'] = get_current_theme_name(override=override_theme)
  285. kwargs['template_name'] = template_name
  286. kwargs['cookies'] = request.cookies
  287. kwargs['errors'] = request.errors
  288. kwargs['instance_name'] = settings['general']['instance_name']
  289. kwargs['results_on_new_tab'] = request.preferences.get_value('results_on_new_tab')
  290. kwargs['unicode'] = unicode
  291. kwargs['preferences'] = request.preferences
  292. kwargs['scripts'] = set()
  293. for plugin in request.user_plugins:
  294. for script in plugin.js_dependencies:
  295. kwargs['scripts'].add(script)
  296. kwargs['styles'] = set()
  297. for plugin in request.user_plugins:
  298. for css in plugin.css_dependencies:
  299. kwargs['styles'].add(css)
  300. return render_template(
  301. '{}/{}'.format(kwargs['theme'], template_name), **kwargs)
  302. @app.before_request
  303. def pre_request():
  304. request.errors = []
  305. preferences = Preferences(themes, list(categories.keys()), engines, plugins)
  306. request.preferences = preferences
  307. try:
  308. preferences.parse_dict(request.cookies)
  309. except:
  310. request.errors.append(gettext('Invalid settings, please edit your preferences'))
  311. # merge GET, POST vars
  312. # request.form
  313. request.form = dict(request.form.items())
  314. for k, v in request.args.items():
  315. if k not in request.form:
  316. request.form[k] = v
  317. if request.form.get('preferences'):
  318. preferences.parse_encoded_data(request.form['preferences'])
  319. else:
  320. try:
  321. preferences.parse_dict(request.form)
  322. except Exception as e:
  323. logger.exception('invalid settings')
  324. request.errors.append(gettext('Invalid settings'))
  325. # request.user_plugins
  326. request.user_plugins = []
  327. allowed_plugins = preferences.plugins.get_enabled()
  328. disabled_plugins = preferences.plugins.get_disabled()
  329. for plugin in plugins:
  330. if ((plugin.default_on and plugin.id not in disabled_plugins)
  331. or plugin.id in allowed_plugins):
  332. request.user_plugins.append(plugin)
  333. def index_error(output_format, error_message):
  334. if output_format == 'json':
  335. return Response(json.dumps({'error': error_message}),
  336. mimetype='application/json')
  337. elif output_format == 'csv':
  338. response = Response('', mimetype='application/csv')
  339. cont_disp = 'attachment;Filename=searx.csv'
  340. response.headers.add('Content-Disposition', cont_disp)
  341. return response
  342. elif output_format == 'rss':
  343. response_rss = render(
  344. 'opensearch_response_rss.xml',
  345. results=[],
  346. q=request.form['q'] if 'q' in request.form else '',
  347. number_of_results=0,
  348. base_url=get_base_url(),
  349. error_message=error_message,
  350. override_theme='__common__',
  351. )
  352. return Response(response_rss, mimetype='text/xml')
  353. else:
  354. # html
  355. request.errors.append(gettext('search error'))
  356. return render(
  357. 'index.html',
  358. )
  359. @app.route('/search', methods=['GET', 'POST'])
  360. @app.route('/', methods=['GET', 'POST'])
  361. def index():
  362. """Render index page.
  363. Supported outputs: html, json, csv, rss.
  364. """
  365. # output_format
  366. output_format = request.form.get('format', 'html')
  367. if output_format not in ['html', 'csv', 'json', 'rss']:
  368. output_format = 'html'
  369. # check if there is query
  370. if request.form.get('q') is None:
  371. if output_format == 'html':
  372. return render(
  373. 'index.html',
  374. )
  375. else:
  376. return index_error(output_format, 'No query'), 400
  377. # search
  378. search_query = None
  379. result_container = None
  380. try:
  381. search_query = get_search_query_from_webapp(request.preferences, request.form)
  382. # search = Search(search_query) # without plugins
  383. search = SearchWithPlugins(search_query, request.user_plugins, request)
  384. result_container = search.search()
  385. except Exception as e:
  386. # log exception
  387. logger.exception('search error')
  388. # is it an invalid input parameter or something else ?
  389. if (issubclass(e.__class__, SearxParameterException)):
  390. return index_error(output_format, e.message), 400
  391. else:
  392. return index_error(output_format, gettext('search error')), 500
  393. # results
  394. results = result_container.get_ordered_results()
  395. number_of_results = result_container.results_number()
  396. if number_of_results < result_container.results_length():
  397. number_of_results = 0
  398. # UI
  399. advanced_search = request.form.get('advanced_search', None)
  400. # output
  401. for result in results:
  402. if output_format == 'html':
  403. if 'content' in result and result['content']:
  404. result['content'] = highlight_content(escape(result['content'][:1024]), search_query.query)
  405. result['title'] = highlight_content(escape(result['title'] or u''), search_query.query)
  406. else:
  407. if result.get('content'):
  408. result['content'] = html_to_text(result['content']).strip()
  409. # removing html content and whitespace duplications
  410. result['title'] = ' '.join(html_to_text(result['title']).strip().split())
  411. result['pretty_url'] = prettify_url(result['url'])
  412. # TODO, check if timezone is calculated right
  413. if 'publishedDate' in result:
  414. try: # test if publishedDate >= 1900 (datetime module bug)
  415. result['pubdate'] = result['publishedDate'].strftime('%Y-%m-%d %H:%M:%S%z')
  416. except ValueError:
  417. result['publishedDate'] = None
  418. else:
  419. if result['publishedDate'].replace(tzinfo=None) >= datetime.now() - timedelta(days=1):
  420. timedifference = datetime.now() - result['publishedDate'].replace(tzinfo=None)
  421. minutes = int((timedifference.seconds / 60) % 60)
  422. hours = int(timedifference.seconds / 60 / 60)
  423. if hours == 0:
  424. result['publishedDate'] = gettext(u'{minutes} minute(s) ago').format(minutes=minutes)
  425. else:
  426. result['publishedDate'] = gettext(u'{hours} hour(s), {minutes} minute(s) ago').format(hours=hours, minutes=minutes) # noqa
  427. else:
  428. result['publishedDate'] = format_date(result['publishedDate'])
  429. if output_format == 'json':
  430. return Response(json.dumps({'query': search_query.query.decode('utf-8'),
  431. 'number_of_results': number_of_results,
  432. 'results': results,
  433. 'answers': list(result_container.answers),
  434. 'corrections': list(result_container.corrections),
  435. 'infoboxes': result_container.infoboxes,
  436. 'suggestions': list(result_container.suggestions),
  437. 'unresponsive_engines': list(result_container.unresponsive_engines)},
  438. default=lambda item: list(item) if isinstance(item, set) else item),
  439. mimetype='application/json')
  440. elif output_format == 'csv':
  441. csv = UnicodeWriter(StringIO())
  442. keys = ('title', 'url', 'content', 'host', 'engine', 'score')
  443. csv.writerow(keys)
  444. for row in results:
  445. row['host'] = row['parsed_url'].netloc
  446. csv.writerow([row.get(key, '') for key in keys])
  447. csv.stream.seek(0)
  448. response = Response(csv.stream.read(), mimetype='application/csv')
  449. cont_disp = 'attachment;Filename=searx_-_{0}.csv'.format(search_query.query)
  450. response.headers.add('Content-Disposition', cont_disp)
  451. return response
  452. elif output_format == 'rss':
  453. response_rss = render(
  454. 'opensearch_response_rss.xml',
  455. results=results,
  456. q=request.form['q'],
  457. number_of_results=number_of_results,
  458. base_url=get_base_url(),
  459. override_theme='__common__',
  460. )
  461. return Response(response_rss, mimetype='text/xml')
  462. return render(
  463. 'results.html',
  464. results=results,
  465. q=request.form['q'],
  466. selected_categories=search_query.categories,
  467. pageno=search_query.pageno,
  468. time_range=search_query.time_range,
  469. number_of_results=format_decimal(number_of_results),
  470. advanced_search=advanced_search,
  471. suggestions=result_container.suggestions,
  472. answers=result_container.answers,
  473. corrections=result_container.corrections,
  474. infoboxes=result_container.infoboxes,
  475. paging=result_container.paging,
  476. unresponsive_engines=result_container.unresponsive_engines,
  477. current_language=match_language(search_query.lang,
  478. LANGUAGE_CODES,
  479. fallback=settings['search']['language']),
  480. base_url=get_base_url(),
  481. theme=get_current_theme_name(),
  482. favicons=global_favicons[themes.index(get_current_theme_name())]
  483. )
  484. @app.route('/about', methods=['GET'])
  485. def about():
  486. """Render about page"""
  487. return render(
  488. 'about.html',
  489. )
  490. @app.route('/autocompleter', methods=['GET', 'POST'])
  491. def autocompleter():
  492. """Return autocompleter results"""
  493. # set blocked engines
  494. disabled_engines = request.preferences.engines.get_disabled()
  495. # parse query
  496. if PY3:
  497. raw_text_query = RawTextQuery(request.form.get('q', b''), disabled_engines)
  498. else:
  499. raw_text_query = RawTextQuery(request.form.get('q', u'').encode('utf-8'), disabled_engines)
  500. raw_text_query.parse_query()
  501. # check if search query is set
  502. if not raw_text_query.getSearchQuery():
  503. return '', 400
  504. # run autocompleter
  505. completer = autocomplete_backends.get(request.preferences.get_value('autocomplete'))
  506. # parse searx specific autocompleter results like !bang
  507. raw_results = searx_bang(raw_text_query)
  508. # normal autocompletion results only appear if max 3 inner results returned
  509. if len(raw_results) <= 3 and completer:
  510. # get language from cookie
  511. language = request.preferences.get_value('language')
  512. if not language:
  513. language = settings['search']['language']
  514. else:
  515. language = language.split('-')[0]
  516. # run autocompletion
  517. raw_results.extend(completer(raw_text_query.getSearchQuery(), language))
  518. # parse results (write :language and !engine back to result string)
  519. results = []
  520. for result in raw_results:
  521. raw_text_query.changeSearchQuery(result)
  522. # add parsed result
  523. results.append(raw_text_query.getFullQuery())
  524. # return autocompleter results
  525. if request.form.get('format') == 'x-suggestions':
  526. return Response(json.dumps([raw_text_query.query, results]),
  527. mimetype='application/json')
  528. return Response(json.dumps(results),
  529. mimetype='application/json')
  530. @app.route('/preferences', methods=['GET', 'POST'])
  531. def preferences():
  532. """Render preferences page && save user preferences"""
  533. # save preferences
  534. if request.method == 'POST':
  535. resp = make_response(redirect(urljoin(settings['server']['base_url'], url_for('index'))))
  536. try:
  537. request.preferences.parse_form(request.form)
  538. except ValidationException:
  539. request.errors.append(gettext('Invalid settings, please edit your preferences'))
  540. return resp
  541. return request.preferences.save(resp)
  542. # render preferences
  543. image_proxy = request.preferences.get_value('image_proxy')
  544. lang = request.preferences.get_value('language')
  545. disabled_engines = request.preferences.engines.get_disabled()
  546. allowed_plugins = request.preferences.plugins.get_enabled()
  547. # stats for preferences page
  548. stats = {}
  549. for c in categories:
  550. for e in categories[c]:
  551. stats[e.name] = {'time': None,
  552. 'warn_timeout': False,
  553. 'warn_time': False}
  554. if e.timeout > settings['outgoing']['request_timeout']:
  555. stats[e.name]['warn_timeout'] = True
  556. if match_language(request.preferences.get_value('language'),
  557. getattr(e, 'supported_languages', []),
  558. getattr(e, 'language_aliases', {}), None):
  559. stats[e.name]['supports_selected_language'] = True
  560. # get first element [0], the engine time,
  561. # and then the second element [1] : the time (the first one is the label)
  562. for engine_stat in get_engines_stats()[0][1]:
  563. stats[engine_stat.get('name')]['time'] = round(engine_stat.get('avg'), 3)
  564. if engine_stat.get('avg') > settings['outgoing']['request_timeout']:
  565. stats[engine_stat.get('name')]['warn_time'] = True
  566. # end of stats
  567. return render('preferences.html',
  568. locales=settings['locales'],
  569. current_locale=get_locale(),
  570. image_proxy=image_proxy,
  571. engines_by_category=categories,
  572. stats=stats,
  573. answerers=[{'info': a.self_info(), 'keywords': a.keywords} for a in answerers],
  574. disabled_engines=disabled_engines,
  575. autocomplete_backends=autocomplete_backends,
  576. shortcuts={y: x for x, y in engine_shortcuts.items()},
  577. themes=themes,
  578. plugins=plugins,
  579. doi_resolvers=settings['doi_resolvers'],
  580. current_doi_resolver=get_doi_resolver(request.args, request.preferences.get_value('doi_resolver')),
  581. allowed_plugins=allowed_plugins,
  582. theme=get_current_theme_name(),
  583. preferences_url_params=request.preferences.get_as_url_params(),
  584. base_url=get_base_url(),
  585. preferences=True)
  586. @app.route('/image_proxy', methods=['GET'])
  587. def image_proxy():
  588. url = request.args.get('url').encode('utf-8')
  589. if not url:
  590. return '', 400
  591. h = new_hmac(settings['server']['secret_key'], url)
  592. if h != request.args.get('h'):
  593. return '', 400
  594. headers = dict_subset(request.headers, {'If-Modified-Since', 'If-None-Match'})
  595. headers['User-Agent'] = gen_useragent()
  596. resp = requests.get(url,
  597. stream=True,
  598. timeout=settings['outgoing']['request_timeout'],
  599. headers=headers,
  600. proxies=outgoing_proxies)
  601. if resp.status_code == 304:
  602. return '', resp.status_code
  603. if resp.status_code != 200:
  604. logger.debug('image-proxy: wrong response code: {0}'.format(resp.status_code))
  605. if resp.status_code >= 400:
  606. return '', resp.status_code
  607. return '', 400
  608. if not resp.headers.get('content-type', '').startswith('image/'):
  609. logger.debug('image-proxy: wrong content-type: {0}'.format(resp.headers.get('content-type')))
  610. return '', 400
  611. img = b''
  612. chunk_counter = 0
  613. for chunk in resp.iter_content(1024 * 1024):
  614. chunk_counter += 1
  615. if chunk_counter > 5:
  616. return '', 502 # Bad gateway - file is too big (>5M)
  617. img += chunk
  618. headers = dict_subset(resp.headers, {'Content-Length', 'Length', 'Date', 'Last-Modified', 'Expires', 'Etag'})
  619. return Response(img, mimetype=resp.headers['content-type'], headers=headers)
  620. @app.route('/stats', methods=['GET'])
  621. def stats():
  622. """Render engine statistics page."""
  623. stats = get_engines_stats()
  624. return render(
  625. 'stats.html',
  626. stats=stats,
  627. )
  628. @app.route('/robots.txt', methods=['GET'])
  629. def robots():
  630. return Response("""User-agent: *
  631. Allow: /
  632. Allow: /about
  633. Disallow: /stats
  634. Disallow: /preferences
  635. Disallow: /*?*q=*
  636. """, mimetype='text/plain')
  637. @app.route('/opensearch.xml', methods=['GET'])
  638. def opensearch():
  639. method = 'post'
  640. if request.preferences.get_value('method') == 'GET':
  641. method = 'get'
  642. # chrome/chromium only supports HTTP GET....
  643. if request.headers.get('User-Agent', '').lower().find('webkit') >= 0:
  644. method = 'get'
  645. ret = render('opensearch.xml',
  646. opensearch_method=method,
  647. host=get_base_url(),
  648. urljoin=urljoin,
  649. override_theme='__common__')
  650. resp = Response(response=ret,
  651. status=200,
  652. mimetype="text/xml")
  653. return resp
  654. @app.route('/favicon.ico')
  655. def favicon():
  656. return send_from_directory(os.path.join(app.root_path,
  657. static_path,
  658. 'themes',
  659. get_current_theme_name(),
  660. 'img'),
  661. 'favicon.png',
  662. mimetype='image/vnd.microsoft.icon')
  663. @app.route('/clear_cookies')
  664. def clear_cookies():
  665. resp = make_response(redirect(urljoin(settings['server']['base_url'], url_for('index'))))
  666. for cookie_name in request.cookies:
  667. resp.delete_cookie(cookie_name)
  668. return resp
  669. @app.route('/config')
  670. def config():
  671. return jsonify({'categories': categories.keys(),
  672. 'engines': [{'name': engine_name,
  673. 'categories': engine.categories,
  674. 'shortcut': engine.shortcut,
  675. 'enabled': not engine.disabled,
  676. 'paging': engine.paging,
  677. 'language_support': engine.language_support,
  678. 'supported_languages':
  679. engine.supported_languages.keys()
  680. if isinstance(engine.supported_languages, dict)
  681. else engine.supported_languages,
  682. 'safesearch': engine.safesearch,
  683. 'time_range_support': engine.time_range_support,
  684. 'timeout': engine.timeout}
  685. for engine_name, engine in engines.items()],
  686. 'plugins': [{'name': plugin.name,
  687. 'enabled': plugin.default_on}
  688. for plugin in plugins],
  689. 'instance_name': settings['general']['instance_name'],
  690. 'locales': settings['locales'],
  691. 'default_locale': settings['ui']['default_locale'],
  692. 'autocomplete': settings['search']['autocomplete'],
  693. 'safe_search': settings['search']['safe_search'],
  694. 'default_theme': settings['ui']['default_theme'],
  695. 'version': VERSION_STRING,
  696. 'doi_resolvers': [r for r in settings['doi_resolvers']],
  697. 'default_doi_resolver': settings['default_doi_resolver'],
  698. })
  699. @app.errorhandler(404)
  700. def page_not_found(e):
  701. return render('404.html'), 404
  702. def run():
  703. logger.debug('starting webserver on %s:%s', settings['server']['port'], settings['server']['bind_address'])
  704. app.run(
  705. debug=searx_debug,
  706. use_debugger=searx_debug,
  707. port=settings['server']['port'],
  708. host=settings['server']['bind_address'],
  709. threaded=True
  710. )
  711. class ReverseProxyPathFix(object):
  712. '''Wrap the application in this middleware and configure the
  713. front-end server to add these headers, to let you quietly bind
  714. this to a URL other than / and to an HTTP scheme that is
  715. different than what is used locally.
  716. http://flask.pocoo.org/snippets/35/
  717. In nginx:
  718. location /myprefix {
  719. proxy_pass http://127.0.0.1:8000;
  720. proxy_set_header Host $host;
  721. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  722. proxy_set_header X-Scheme $scheme;
  723. proxy_set_header X-Script-Name /myprefix;
  724. }
  725. :param app: the WSGI application
  726. '''
  727. def __init__(self, app):
  728. self.app = app
  729. def __call__(self, environ, start_response):
  730. script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
  731. if script_name:
  732. environ['SCRIPT_NAME'] = script_name
  733. path_info = environ['PATH_INFO']
  734. if path_info.startswith(script_name):
  735. environ['PATH_INFO'] = path_info[len(script_name):]
  736. scheme = environ.get('HTTP_X_SCHEME', '')
  737. if scheme:
  738. environ['wsgi.url_scheme'] = scheme
  739. return self.app(environ, start_response)
  740. application = app
  741. # patch app to handle non root url-s behind proxy & wsgi
  742. app.wsgi_app = ReverseProxyPathFix(ProxyFix(application.wsgi_app))
  743. if __name__ == "__main__":
  744. run()