views.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. # -*- coding: utf-8 -*-
  2. from flask import request, redirect, url_for, abort, \
  3. render_template, flash, json, session, Response, Markup, \
  4. current_app, Blueprint
  5. from flask.ext.babel import gettext as _, get_locale
  6. from flask.ext.mail import Message
  7. from sqlalchemy.sql import func, asc
  8. import itsdangerous
  9. import docutils.core
  10. import ispformat.specs
  11. from datetime import datetime
  12. import locale
  13. locale.setlocale(locale.LC_ALL, '')
  14. from time import time
  15. import os.path
  16. from . import forms, utils
  17. from .constants import STEPS, STEPS_LABELS, LOCALES_FLAGS
  18. from . import db, cache, mail
  19. from .models import ISP, ISPWhoosh, CoveredArea, RegisteredOffice
  20. from .crawler import WebValidator, PrettyValidator
  21. ispdb = Blueprint('ispdb', __name__)
  22. @ispdb.route('/')
  23. def home():
  24. return render_template('index.html', active_button="home")
  25. @ispdb.route('/embed_map_cube/')
  26. def embed_map_cube():
  27. return render_template('embed_map.html')
  28. @ispdb.route('/isp/')
  29. def project_list():
  30. return render_template('project_list.html', projects=ISP.query.filter_by(is_disabled=False).order_by(asc(func.lower(ISP.name))))
  31. @ispdb.app_errorhandler(404)
  32. def page_not_found(e):
  33. return render_template('404.html'), 404
  34. @ispdb.app_errorhandler(500)
  35. def internal_error(e):
  36. return render_template('500.html'), 500
  37. # this needs to be cached
  38. @ispdb.route('/isp/map_data.json', methods=['GET'])
  39. def isp_map_data():
  40. isps = ISP.query.filter_by(is_disabled=False)
  41. data = []
  42. for isp in isps:
  43. d = dict(isp.json)
  44. for k in d.keys():
  45. if k not in ('name', 'shortname', 'coordinates'):
  46. del d[k]
  47. d['id'] = isp.id
  48. d['ffdn_member'] = isp.is_ffdn_member
  49. d['popup'] = render_template('map_popup.html', isp=isp)
  50. data.append(d)
  51. return Response(json.dumps(data), mimetype='application/json')
  52. # this needs to be cached
  53. @ispdb.route('/isp/map_data_cube.json', methods=['GET'])
  54. def isp_map_data_cube():
  55. isps = ISP.query.filter_by(is_disabled=False)
  56. data = []
  57. for isp in isps:
  58. d = dict(isp.json)
  59. for k in d.keys():
  60. if k not in ('name', 'shortname', 'coordinates'):
  61. del d[k]
  62. d['id'] = isp.id
  63. d['ffdn_member'] = isp.is_ffdn_member
  64. d['has_vpn'] = isp.has_technology("vpn")
  65. d['distribute_cube'] = isp.has_technology("cube")
  66. d['url'] = isp.json.get("website", "")
  67. d['popup'] = render_template('map_popup.html', isp=isp)
  68. data.append(d)
  69. return Response(json.dumps(data), mimetype='application/json')
  70. @ispdb.route('/isp/find_near.json', methods=['GET'])
  71. def isp_find_near():
  72. lat = request.args.get('lat')
  73. lon = request.args.get('lon')
  74. try:
  75. lat = float(lat)
  76. lon = float(lon)
  77. except (ValueError, TypeError):
  78. abort(400)
  79. q = CoveredArea.containing((lat, lon))\
  80. .options(db.joinedload('isp'))
  81. res = [[{
  82. 'isp_id': ca.isp_id,
  83. 'area': {
  84. 'id': ca.id,
  85. 'name': ca.name,
  86. }
  87. } for ca in q]]
  88. dst = RegisteredOffice.point.distance(db.func.MakePoint(lon, lat), 1).label('distance')
  89. q = db.session.query(RegisteredOffice, dst)\
  90. .options(db.joinedload('isp'))\
  91. .order_by('distance ASC')\
  92. .limit(2)
  93. res.append([{
  94. 'distance': d,
  95. 'isp_id': r.isp.id,
  96. } for r, d in q])
  97. return Response(json.dumps(res))
  98. @ispdb.route('/isp/<projectid>/covered_areas.json', methods=['GET'])
  99. def isp_covered_areas(projectid):
  100. p = ISP.query.filter_by(id=projectid, is_disabled=False)\
  101. .options(db.joinedload('covered_areas'),
  102. db.defer('covered_areas.area'),
  103. db.undefer('covered_areas.area_geojson'))\
  104. .scalar()
  105. if not p:
  106. abort(404)
  107. cas = []
  108. for ca in p.covered_areas:
  109. cas.append({
  110. 'id': ca.id,
  111. 'name': ca.name,
  112. 'area': json.loads(ca.area_geojson) if ca.area_geojson else None
  113. })
  114. return Response(json.dumps(cas), mimetype='application/json')
  115. @ispdb.route('/isp/<projectid>/')
  116. def project(projectid):
  117. p = ISP.query.filter_by(id=projectid, is_disabled=False).first()
  118. if not p:
  119. abort(404)
  120. return render_template('project_detail.html', project_row=p, project=p.json)
  121. @ispdb.route('/isp/<projectid>/edit', methods=['GET', 'POST'])
  122. def edit_project(projectid):
  123. MAX_TOKEN_AGE = 3600
  124. isp = ISP.query.filter_by(id=projectid, is_disabled=False).first_or_404()
  125. sess_token = session.get('edit_tokens', {}).get(isp.id)
  126. if 'token' in request.args:
  127. s = itsdangerous.URLSafeTimedSerializer(current_app.secret_key, salt='edit')
  128. try:
  129. r = s.loads(request.args['token'], max_age=MAX_TOKEN_AGE,
  130. return_timestamp=True)
  131. except:
  132. abort(403)
  133. if r[0] != isp.id:
  134. abort(403)
  135. tokens = session.setdefault('edit_tokens', {})
  136. session.modified = True # ITS A TARP
  137. tokens[r[0]] = r[1]
  138. # refresh page, without the token in the url
  139. return redirect(url_for('.edit_project', projectid=r[0]))
  140. elif (sess_token is None or (datetime.utcnow() - sess_token).total_seconds() > MAX_TOKEN_AGE):
  141. return redirect(url_for('.gen_edit_token', projectid=isp.id))
  142. form = forms.ProjectForm.edit_json(isp)
  143. if form.validate_on_submit():
  144. isp.name = form.name.data
  145. isp.shortname = form.shortname.data or None
  146. isp.json = form.to_json(isp.json)
  147. isp.tech_email = form.tech_email.data
  148. isp.json_url = None
  149. db.session.add(isp)
  150. db.session.commit()
  151. flash(_(u'Project modified'), 'info')
  152. return redirect(url_for('.project', projectid=isp.id))
  153. return render_template('edit_project_form.html', form=form, isp=isp)
  154. @ispdb.route('/isp/<projectid>/edit_json_url', methods=['GET', 'POST'])
  155. def edit_project_auto_update(projectid):
  156. MAX_TOKEN_AGE = 3600
  157. isp = ISP.query.filter_by(id=projectid, is_disabled=False).first_or_404()
  158. sess_token = session.get('edit_tokens', {}).get(isp.id)
  159. if 'token' in request.args:
  160. s = itsdangerous.URLSafeTimedSerializer(current_app.secret_key, salt='edit')
  161. try:
  162. r = s.loads(request.args['token'], max_age=MAX_TOKEN_AGE,
  163. return_timestamp=True)
  164. except:
  165. abort(403)
  166. if r[0] != isp.id:
  167. abort(403)
  168. tokens = session.setdefault('edit_tokens', {})
  169. session.modified = True # ITS A TARP
  170. tokens[r[0]] = r[1]
  171. # refresh page, without the token in the url
  172. return redirect(url_for('.edit_project', projectid=r[0]))
  173. elif (sess_token is None or (datetime.utcnow() - sess_token).total_seconds() > MAX_TOKEN_AGE):
  174. return redirect(url_for('.gen_edit_token', projectid=isp.id))
  175. form = forms.ProjectJSONForm(obj=isp)
  176. if form.validate_on_submit():
  177. isp.tech_email = form.tech_email.data
  178. url = utils.make_ispjson_url(form.json_url.data)
  179. isp.json_url = url
  180. db.session.add(isp)
  181. db.session.commit()
  182. flash(_(u'Project modified'), 'info')
  183. return redirect(url_for('.project', projectid=isp.id))
  184. return render_template('edit_project_json_form.html', form=form, isp=isp)
  185. @ispdb.route('/isp/<projectid>/gen_edit_token', methods=['GET', 'POST'])
  186. def gen_edit_token(projectid):
  187. isp = ISP.query.filter_by(id=projectid, is_disabled=False).first_or_404()
  188. form = forms.RequestEditToken()
  189. if form.validate_on_submit(): # validated
  190. if form.tech_email.data == isp.tech_email:
  191. s = itsdangerous.URLSafeTimedSerializer(current_app.secret_key, salt='edit')
  192. token = s.dumps(isp.id)
  193. msg = Message("Edit request of your ISP", sender=current_app.config['EMAIL_SENDER'])
  194. msg.body = """
  195. Hello,
  196. You are receiving this message because your are listed as technical contact for "%s" on the FFDN ISP database.
  197. Someone asked to edit your ISP's data in our database. If it's not you, please ignore this message.
  198. To proceed to the editing form, please click on the following link:
  199. %s?token=%s
  200. Note: the link is only valid for one hour from the moment we send you this email.
  201. Thanks,
  202. The FFDN ISP Database team
  203. https://db.ffdn.org
  204. """.strip() % (isp.complete_name,
  205. url_for('.edit_project', projectid=isp.id, _external=True),
  206. token)
  207. msg.add_recipient(isp.tech_email)
  208. mail.send(msg)
  209. # if the email provided is not the correct one, we still redirect
  210. flash(_(u'If you provided the correct email adress, '
  211. 'you must will receive a message shortly (check your spam folder)'), 'info')
  212. return redirect(url_for('.project', projectid=isp.id))
  213. return render_template('gen_edit_token.html', form=form)
  214. @ispdb.route('/add-a-project', methods=['GET'])
  215. def add_project():
  216. return render_template('add_project.html')
  217. @ispdb.route('/isp/create/form', methods=['GET', 'POST'])
  218. def create_project_form():
  219. form = forms.ProjectForm()
  220. if form.validate_on_submit():
  221. isp = ISP()
  222. isp.name = form.name.data
  223. isp.shortname = form.shortname.data or None
  224. isp.tech_email = form.tech_email.data
  225. isp.json = form.to_json(isp.json)
  226. db.session.add(isp)
  227. db.session.commit()
  228. flash(_(u'Project created'), 'info')
  229. return redirect(url_for('.project', projectid=isp.id))
  230. return render_template('add_project_form.html', form=form)
  231. @ispdb.route('/isp/create/validator', methods=['GET'])
  232. def json_url_validator():
  233. if 'form_json' not in session or \
  234. session['form_json'].get('validated', False):
  235. abort(403)
  236. v = session['form_json'].get('validator')
  237. if v is not None:
  238. if v > time() - 5:
  239. abort(429)
  240. else:
  241. session['form_json']['validator'] = time()
  242. validator = WebValidator(session._get_current_object(), 'form_json')
  243. return Response(utils.stream_with_ctx_and_exc(
  244. validator(session['form_json']['url'])
  245. ), mimetype="text/event-stream")
  246. @ispdb.route('/isp/create', methods=['GET', 'POST'])
  247. def create_project_json():
  248. form = forms.ProjectJSONForm()
  249. if form.validate_on_submit():
  250. url = utils.make_ispjson_url(form.json_url.data)
  251. session['form_json'] = {'url': url, 'tech_email': form.tech_email.data}
  252. return render_template('project_json_validator.html')
  253. return render_template('add_project_json_form.html', form=form)
  254. @ispdb.route('/isp/create/confirm', methods=['POST'])
  255. def create_project_json_confirm():
  256. if 'form_json' in session and session['form_json'].get('validated', False):
  257. if not forms.is_url_unique(session['form_json']['url']):
  258. abort(409)
  259. jdict = session['form_json']['jdict']
  260. isp = ISP()
  261. isp.name = jdict['name']
  262. if 'shortname' in jdict:
  263. isp.shortname = jdict['shortname']
  264. isp.json_url = session['form_json']['url']
  265. isp.json = jdict
  266. isp.tech_email = session['form_json']['tech_email']
  267. isp.last_update_attempt = session['form_json']['last_update']
  268. isp.last_update_success = session['form_json']['last_update']
  269. isp.next_update = session['form_json']['next_update']
  270. isp.cache_info = session['form_json']['cache_info']
  271. del session['form_json']
  272. db.session.add(isp)
  273. db.session.commit()
  274. flash(_(u'Project created'), 'info')
  275. return redirect(url_for('.project', projectid=isp.id))
  276. else:
  277. return redirect(url_for('.create_project_json'))
  278. @ispdb.route('/isp/reactivate-validator', methods=['GET'])
  279. def reactivate_validator():
  280. if 'form_reactivate' not in session or \
  281. session['form_reactivate'].get('validated', False):
  282. abort(403)
  283. p = ISP.query.get(session['form_reactivate']['isp_id'])
  284. if not p:
  285. abort(403)
  286. v = session['form_reactivate'].get('validator')
  287. if v is not None:
  288. if v > time() - 5:
  289. abort(429)
  290. else:
  291. session['form_reactivate']['validator'] = time()
  292. validator = PrettyValidator(session._get_current_object(), 'form_reactivate')
  293. return Response(utils.stream_with_ctx_and_exc(
  294. validator(p.json_url, p.cache_info or {})
  295. ), mimetype="text/event-stream")
  296. @ispdb.route('/isp/<projectid>/reactivate', methods=['GET', 'POST'])
  297. def reactivate_isp(projectid):
  298. """
  299. Allow to reactivate an ISP after it has been disabled
  300. because of problems with the JSON file.
  301. """
  302. p = ISP.query.filter(ISP.id == projectid, ISP.is_disabled == False,
  303. ISP.update_error_strike >= 3).first_or_404()
  304. if request.method == 'GET':
  305. key = request.args.get('key')
  306. try:
  307. s = itsdangerous.URLSafeSerializer(current_app.secret_key,
  308. salt='reactivate')
  309. d = s.loads(key)
  310. except Exception:
  311. abort(403)
  312. if (len(d) != 2 or d[0] != p.id or d[1] != str(p.last_update_attempt)):
  313. abort(403)
  314. session['form_reactivate'] = {'isp_id': p.id}
  315. return render_template('reactivate_validator.html', isp=p)
  316. else:
  317. if 'form_reactivate' not in session or \
  318. not session['form_reactivate'].get('validated', False):
  319. abort(409)
  320. p = ISP.query.get(session['form_reactivate']['isp_id'])
  321. p.json = session['form_reactivate']['jdict']
  322. p.cache_info = session['form_reactivate']['cache_info']
  323. p.last_update_attempt = session['form_reactivate']['last_update']
  324. p.last_update_success = p.last_update_attempt
  325. p.update_error_strike = 0
  326. db.session.add(p)
  327. db.session.commit()
  328. flash(_(u'Automatic updates activated'), 'info')
  329. return redirect(url_for('.project', projectid=p.id))
  330. @ispdb.route('/search', methods=['GET', 'POST'])
  331. def search():
  332. terms = request.args.get('q')
  333. if not terms:
  334. return redirect(url_for('.home'))
  335. res = ISPWhoosh.search(terms)
  336. return render_template('search_results.html', results=res, search_terms=terms)
  337. @ispdb.route('/format', methods=['GET'])
  338. def format():
  339. parts = cache.get('format-spec')
  340. if parts is None:
  341. spec = open(ispformat.specs.versions[0.1]).read()
  342. overrides = {
  343. 'initial_header_level': 3,
  344. }
  345. parts = docutils.core.publish_parts(
  346. spec,
  347. source_path=os.path.dirname(ispformat.specs.versions[0.1]),
  348. destination_path=None, writer_name='html',
  349. settings_overrides=overrides
  350. )
  351. cache.set('format-spec', parts, timeout=60 * 60 * 24)
  352. return render_template('format_spec.html', spec=Markup(parts['html_body']))
  353. @ispdb.route('/api/v1/', methods=['GET'])
  354. def api():
  355. return render_template('api.html')
  356. @ispdb.route('/humans.txt', methods=['GET'])
  357. def humans():
  358. import os.path
  359. authors_file = os.path.join(os.path.dirname(__file__), '../AUTHORS')
  360. return Response(open(authors_file), mimetype='text/plain; charset=utf-8')
  361. @ispdb.route('/site.js', methods=['GET'])
  362. def site_js():
  363. l = get_locale()
  364. js_i18n = cache.get('site_js_%s' % (l,))
  365. if not js_i18n:
  366. js_i18n = render_template('site.js')
  367. cache.set('site_js_%s' % (l,), js_i18n, timeout=60 * 60)
  368. r = Response(js_i18n, headers={
  369. 'Content-type': 'application/javascript',
  370. 'Cache-control': 'private, max-age=3600'
  371. })
  372. r.add_etag()
  373. r.make_conditional(request)
  374. return r
  375. @ispdb.route('/site_embed.js', methods=['GET'])
  376. def site_embed_js():
  377. l = get_locale()
  378. js_i18n = cache.get('site_embed_js_%s' % (l,))
  379. if not js_i18n:
  380. js_i18n = render_template('site_embed.js')
  381. cache.set('site_embed_js_%s' % (l,), js_i18n, timeout=60 * 60)
  382. r = Response(js_i18n, headers={
  383. 'Content-type': 'application/javascript',
  384. 'Cache-control': 'private, max-age=3600'
  385. })
  386. r.add_etag()
  387. r.make_conditional(request)
  388. return r
  389. @ispdb.route('/locale_selector', methods=['GET', 'POST'])
  390. def locale_selector():
  391. l = current_app.config['LANGUAGES']
  392. if request.method == 'POST' and request.form.get('locale') in l:
  393. resp = redirect(url_for('.home'))
  394. resp.set_cookie('locale', request.form['locale'])
  395. return resp
  396. return render_template('locale_selector.html', locales=(
  397. (code, LOCALES_FLAGS[code], name) for code, name in l.iteritems()
  398. ))
  399. #------
  400. # Filters
  401. @ispdb.app_template_filter('step_to_label')
  402. def step_to_label(step):
  403. if step:
  404. return u"<a href='#' data-toggle='tooltip' data-placement='right' title='" + STEPS[step] + "'><span class='badge badge-" + STEPS_LABELS[step] + "'>" + str(step) + "</span></a>"
  405. else:
  406. return u'-'
  407. @ispdb.app_template_filter('stepname')
  408. def stepname(step):
  409. return STEPS[step]
  410. @ispdb.app_template_filter('js_str')
  411. def json_filter(v):
  412. return Markup(json.dumps(unicode(v)))
  413. @ispdb.app_template_filter('locale_flag')
  414. def locale_flag(l):
  415. return LOCALES_FLAGS.get(str(l), '_unknown')
  416. @ispdb.app_template_global('current_locale')
  417. def current_locale():
  418. return get_locale()