webapp.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. #!/usr/bin/env python
  2. '''
  3. searx is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. searx is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with searx. If not, see < http://www.gnu.org/licenses/ >.
  13. (C) 2013- by Adam Tauber, <asciimoo@gmail.com>
  14. '''
  15. import os
  16. import sys
  17. if __name__ == "__main__":
  18. sys.path.append(os.path.realpath(os.path.dirname(os.path.realpath(__file__))+'/../'))
  19. # first argument is for specifying settings module, used mostly by robot tests
  20. from sys import argv
  21. if len(argv) == 2:
  22. from importlib import import_module
  23. settings = import_module('searx.' + argv[1])
  24. else:
  25. from searx import settings
  26. from flask import Flask, request, render_template, url_for, Response, make_response, redirect
  27. from searx.engines import search, categories, engines, get_engines_stats
  28. import json
  29. import cStringIO
  30. from searx.utils import UnicodeWriter
  31. from flask import send_from_directory
  32. from searx.utils import highlight_content, html_to_text
  33. app = Flask(__name__)
  34. app.secret_key = settings.secret_key
  35. opensearch_xml = '''<?xml version="1.0" encoding="utf-8"?>
  36. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
  37. <ShortName>searx</ShortName>
  38. <Description>Search searx</Description>
  39. <InputEncoding>UTF-8</InputEncoding>
  40. <LongName>searx meta search engine</LongName>
  41. <Url type="text/html" method="{method}" template="{host}">
  42. <Param name="q" value="{{searchTerms}}" />
  43. </Url>
  44. </OpenSearchDescription>
  45. '''
  46. def get_base_url():
  47. if settings.base_url:
  48. hostname = settings.base_url
  49. else:
  50. scheme = 'http'
  51. if request.is_secure:
  52. scheme = 'https'
  53. hostname = url_for('index', _external=True, _scheme=scheme)
  54. return hostname
  55. def render(template_name, **kwargs):
  56. global categories
  57. kwargs['categories'] = sorted(categories.keys())
  58. if not 'selected_categories' in kwargs:
  59. kwargs['selected_categories'] = []
  60. cookie_categories = request.cookies.get('categories', '').split(',')
  61. for ccateg in cookie_categories:
  62. if ccateg in categories:
  63. kwargs['selected_categories'].append(ccateg)
  64. if not len(kwargs['selected_categories']):
  65. kwargs['selected_categories'] = ['general']
  66. return render_template(template_name, **kwargs)
  67. def parse_query(query):
  68. query_engines = []
  69. query_parts = query.split()
  70. if query_parts[0].startswith('-') and query_parts[0][1:] in engines:
  71. query_engines.append({'category': 'TODO', 'name': query_parts[0][1:]})
  72. query = query.replace(query_parts[0], '', 1).strip()
  73. return query, query_engines
  74. @app.route('/', methods=['GET', 'POST'])
  75. def index():
  76. global categories
  77. if request.method=='POST':
  78. request_data = request.form
  79. else:
  80. request_data = request.args
  81. if not request_data.get('q'):
  82. return render('index.html')
  83. selected_categories = []
  84. query, selected_engines = parse_query(request_data['q'].encode('utf-8'))
  85. if not len(selected_engines):
  86. for pd_name,pd in request_data.items():
  87. if pd_name.startswith('category_'):
  88. category = pd_name[9:]
  89. if not category in categories:
  90. continue
  91. selected_categories.append(category)
  92. if not len(selected_categories):
  93. cookie_categories = request.cookies.get('categories', '').split(',')
  94. for ccateg in cookie_categories:
  95. if ccateg in categories:
  96. selected_categories.append(ccateg)
  97. if not len(selected_categories):
  98. selected_categories = ['general']
  99. for categ in selected_categories:
  100. selected_engines.extend({'category': categ, 'name': x.name} for x in categories[categ])
  101. results, suggestions = search(query, request, selected_engines)
  102. for result in results:
  103. if request_data.get('format', 'html') == 'html':
  104. if 'content' in result:
  105. result['content'] = highlight_content(result['content'], query)
  106. result['title'] = highlight_content(result['title'], query)
  107. else:
  108. if 'content' in result:
  109. result['content'] = html_to_text(result['content']).strip()
  110. result['title'] = html_to_text(result['title']).strip()
  111. if len(result['url']) > 74:
  112. result['pretty_url'] = result['url'][:35] + '[..]' + result['url'][-35:]
  113. else:
  114. result['pretty_url'] = result['url']
  115. if request_data.get('format') == 'json':
  116. return Response(json.dumps({'query': query, 'results': results}), mimetype='application/json')
  117. elif request_data.get('format') == 'csv':
  118. csv = UnicodeWriter(cStringIO.StringIO())
  119. keys = ('title', 'url', 'content', 'host', 'engine', 'score')
  120. if len(results):
  121. csv.writerow(keys)
  122. for row in results:
  123. row['host'] = row['parsed_url'].netloc
  124. csv.writerow([row.get(key, '') for key in keys])
  125. csv.stream.seek(0)
  126. response = Response(csv.stream.read(), mimetype='application/csv')
  127. response.headers.add('Content-Disposition', 'attachment;Filename=searx_-_{0}.csv'.format('_'.join(query.split())))
  128. return response
  129. elif request_data.get('format') == 'rss':
  130. response_rss = render('opensearch_response_rss.xml'
  131. ,results=results
  132. ,q=request_data['q']
  133. ,number_of_results=len(results)
  134. ,base_url=get_base_url()
  135. )
  136. return Response(response_rss, mimetype='text/xml')
  137. return render('results.html'
  138. ,results=results
  139. ,q=request_data['q']
  140. ,selected_categories=selected_categories
  141. ,number_of_results=len(results)
  142. ,suggestions=suggestions
  143. )
  144. @app.route('/about', methods=['GET'])
  145. def about():
  146. return render('about.html')
  147. @app.route('/engines', methods=['GET'])
  148. def list_engines():
  149. global categories
  150. return render('engines.html', categs=categories.items())
  151. @app.route('/preferences', methods=['GET', 'POST'])
  152. def preferences():
  153. if request.method=='POST':
  154. selected_categories = []
  155. for pd_name,pd in request.form.items():
  156. if pd_name.startswith('category_'):
  157. category = pd_name[9:]
  158. if not category in categories:
  159. continue
  160. selected_categories.append(category)
  161. if selected_categories:
  162. resp = make_response(redirect('/'))
  163. # cookie max age: 4 weeks
  164. resp.set_cookie('categories', ','.join(selected_categories), max_age=60*60*24*7*4)
  165. return resp
  166. return render('preferences.html')
  167. @app.route('/stats', methods=['GET'])
  168. def stats():
  169. global categories
  170. stats = get_engines_stats()
  171. return render('stats.html', stats=stats)
  172. @app.route('/robots.txt', methods=['GET'])
  173. def robots():
  174. return Response("""User-agent: *
  175. Allow: /
  176. Allow: /about
  177. Disallow: /stats
  178. """, mimetype='text/plain')
  179. @app.route('/opensearch.xml', methods=['GET'])
  180. def opensearch():
  181. global opensearch_xml
  182. method = 'post'
  183. # chrome/chromium only supports HTTP GET....
  184. if request.headers.get('User-Agent', '').lower().find('webkit') >= 0:
  185. method = 'get'
  186. base_url = get_base_url()
  187. ret = opensearch_xml.format(method=method, host=base_url)
  188. resp = Response(response=ret,
  189. status=200,
  190. mimetype="application/xml")
  191. return resp
  192. @app.route('/favicon.ico')
  193. def favicon():
  194. return send_from_directory(os.path.join(app.root_path, 'static/img'),
  195. 'favicon.png', mimetype='image/vnd.microsoft.icon')
  196. def run():
  197. from gevent import monkey
  198. monkey.patch_all()
  199. app.run(debug = settings.debug
  200. ,use_debugger = settings.debug
  201. ,port = settings.port
  202. )
  203. if __name__ == "__main__":
  204. run()