webapp.py 27 KB

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