webapp.py 8.2 KB

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