webapp.py 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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. if __name__ == "__main__":
  17. from sys import path
  18. path.append(os.path.realpath(os.path.dirname(os.path.realpath(__file__))+'/../'))
  19. from flask import Flask, request, render_template, url_for, Response, make_response, redirect
  20. from searx.engines import search, categories, engines, get_engines_stats
  21. from searx import settings
  22. import json
  23. import cStringIO
  24. from searx.utils import UnicodeWriter
  25. from flask import send_from_directory
  26. from searx.utils import highlight_content, html_to_text
  27. app = Flask(__name__)
  28. app.secret_key = settings.secret_key
  29. opensearch_xml = '''<?xml version="1.0" encoding="utf-8"?>
  30. <OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
  31. <ShortName>searx</ShortName>
  32. <Description>Search searx</Description>
  33. <InputEncoding>UTF-8</InputEncoding>
  34. <LongName>searx meta search engine</LongName>
  35. <Url type="text/html" method="{method}" template="{host}">
  36. <Param name="q" value="{{searchTerms}}" />
  37. </Url>
  38. </OpenSearchDescription>
  39. '''
  40. def render(template_name, **kwargs):
  41. global categories
  42. kwargs['categories'] = sorted(categories.keys())
  43. if not 'selected_categories' in kwargs:
  44. kwargs['selected_categories'] = []
  45. cookie_categories = request.cookies.get('categories', '').split(',')
  46. for ccateg in cookie_categories:
  47. if ccateg in categories:
  48. kwargs['selected_categories'].append(ccateg)
  49. if not len(kwargs['selected_categories']):
  50. kwargs['selected_categories'] = ['general']
  51. return render_template(template_name, **kwargs)
  52. def parse_query(query):
  53. query_engines = []
  54. query_parts = query.split()
  55. if query_parts[0].startswith('-') and query_parts[0][1:] in engines:
  56. query_engines.append({'category': 'TODO', 'name': query_parts[0][1:]})
  57. query = query.replace(query_parts[0], '', 1).strip()
  58. return query, query_engines
  59. @app.route('/', methods=['GET', 'POST'])
  60. def index():
  61. global categories
  62. if request.method=='POST':
  63. request_data = request.form
  64. else:
  65. request_data = request.args
  66. if not request_data.get('q'):
  67. return render('index.html')
  68. selected_categories = []
  69. query, selected_engines = parse_query(request_data['q'].encode('utf-8'))
  70. if not len(selected_engines):
  71. for pd_name,pd in request_data.items():
  72. if pd_name.startswith('category_'):
  73. category = pd_name[9:]
  74. if not category in categories:
  75. continue
  76. selected_categories.append(category)
  77. if not len(selected_categories):
  78. cookie_categories = request.cookies.get('categories', '').split(',')
  79. for ccateg in cookie_categories:
  80. if ccateg in categories:
  81. selected_categories.append(ccateg)
  82. if not len(selected_categories):
  83. selected_categories = ['general']
  84. for categ in selected_categories:
  85. selected_engines.extend({'category': categ, 'name': x.name} for x in categories[categ])
  86. results, suggestions = search(query, request, selected_engines)
  87. for result in results:
  88. if request_data.get('format', 'html') == 'html':
  89. if 'content' in result:
  90. result['content'] = highlight_content(result['content'], query)
  91. result['title'] = highlight_content(result['title'], query)
  92. else:
  93. if 'content' in result:
  94. result['content'] = html_to_text(result['content']).strip()
  95. result['title'] = html_to_text(result['title']).strip()
  96. if len(result['url']) > 74:
  97. result['pretty_url'] = result['url'][:35] + '[..]' + result['url'][-35:]
  98. else:
  99. result['pretty_url'] = result['url']
  100. if request_data.get('format') == 'json':
  101. return Response(json.dumps({'query': query, 'results': results}), mimetype='application/json')
  102. elif request_data.get('format') == 'csv':
  103. csv = UnicodeWriter(cStringIO.StringIO())
  104. keys = ('title', 'url', 'content', 'host', 'engine', 'score')
  105. if len(results):
  106. csv.writerow(keys)
  107. for row in results:
  108. row['host'] = row['parsed_url'].netloc
  109. csv.writerow([row.get(key, '') for key in keys])
  110. csv.stream.seek(0)
  111. response = Response(csv.stream.read(), mimetype='application/csv')
  112. response.headers.add('Content-Disposition', 'attachment;Filename=searx_-_{0}.csv'.format('_'.join(query.split())))
  113. return response
  114. return render('results.html'
  115. ,results=results
  116. ,q=request_data['q']
  117. ,selected_categories=selected_categories
  118. ,number_of_results=len(results)
  119. ,suggestions=suggestions
  120. )
  121. @app.route('/about', methods=['GET'])
  122. def about():
  123. global categories
  124. return render('about.html', categs=categories.items())
  125. @app.route('/preferences', methods=['GET', 'POST'])
  126. def preferences():
  127. if request.method=='POST':
  128. selected_categories = []
  129. for pd_name,pd in request.form.items():
  130. if pd_name.startswith('category_'):
  131. category = pd_name[9:]
  132. if not category in categories:
  133. continue
  134. selected_categories.append(category)
  135. if selected_categories:
  136. resp = make_response(redirect('/'))
  137. # cookie max age: 4 weeks
  138. resp.set_cookie('categories', ','.join(selected_categories), max_age=60*60*24*7*4)
  139. return resp
  140. return render('preferences.html')
  141. @app.route('/stats', methods=['GET'])
  142. def stats():
  143. global categories
  144. stats = get_engines_stats()
  145. return render('stats.html', stats=stats)
  146. @app.route('/robots.txt', methods=['GET'])
  147. def robots():
  148. return Response("""User-agent: *
  149. Allow: /
  150. Allow: /about
  151. Disallow: /stats
  152. """, mimetype='text/plain')
  153. @app.route('/opensearch.xml', methods=['GET'])
  154. def opensearch():
  155. global opensearch_xml
  156. method = 'post'
  157. scheme = 'http'
  158. # chrome/chromium only supports HTTP GET....
  159. if request.headers.get('User-Agent', '').lower().find('webkit') >= 0:
  160. method = 'get'
  161. if request.is_secure:
  162. scheme = 'https'
  163. if settings.base_url:
  164. hostname = settings.base_url
  165. else:
  166. hostname = url_for('index', _external=True, _scheme=scheme)
  167. ret = opensearch_xml.format(method=method, host=hostname)
  168. resp = Response(response=ret,
  169. status=200,
  170. mimetype="application/xml")
  171. return resp
  172. @app.route('/favicon.ico')
  173. def favicon():
  174. return send_from_directory(os.path.join(app.root_path, 'static/img'),
  175. 'favicon.png', mimetype='image/vnd.microsoft.icon')
  176. if __name__ == "__main__":
  177. from gevent import monkey
  178. monkey.patch_all()
  179. app.run(debug = settings.debug
  180. ,use_debugger = settings.debug
  181. ,port = settings.port
  182. )