webapp.py 28KB

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