backend.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import os
  4. import sys
  5. import sqlite3
  6. import urlparse
  7. import datetime
  8. import json
  9. from email import utils
  10. from os.path import join, dirname
  11. from bottle import route, run, static_file, request, template, FormsDict, redirect, response
  12. ORIENTATIONS = (
  13. ('N', 'Nord'),
  14. ('NO', 'Nord-Ouest'),
  15. ('O', 'Ouest'),
  16. ('SO', 'Sud-Ouest'),
  17. ('S', 'Sud'),
  18. ('SE', 'Sud-Est'),
  19. ('E', 'Est'),
  20. ('NE', 'Nord-Est'),
  21. )
  22. TABLE_NAME = 'contribs'
  23. DB_FILENAME = join(dirname(__file__), 'db.sqlite3')
  24. DB = sqlite3.connect(DB_FILENAME)
  25. DB_COLS = (
  26. ('id', 'INTEGER PRIMARY KEY'),
  27. ('name', 'TEXT'),
  28. ('contrib_type', 'TEXT'),
  29. ('latitude', 'REAL'),
  30. ('longitude', 'REAL'),
  31. ('phone', 'TEXT'),
  32. ('email', 'TEXT'),
  33. ('access_type', 'TEXT'),
  34. ('bandwidth', 'REAL'),
  35. ('share_part', 'REAL'),
  36. ('floor', 'INTEGER'),
  37. ('floor_total', 'INTEGER'),
  38. ('orientations', 'TEXT'),
  39. ('roof', 'INTEGER'),
  40. ('comment', 'TEXT'),
  41. ('privacy_name', 'INTEGER'),
  42. ('privacy_email', 'INTEGER'),
  43. ('privacy_coordinates', 'INTEGER'),
  44. ('privacy_place_details', 'INTEGER'),
  45. ('privacy_comment', 'INTEGER'),
  46. ('date', 'TEXT'),
  47. )
  48. @route('/')
  49. def home():
  50. redirect("/wifi-form")
  51. @route('/wifi-form')
  52. def show_wifi_form():
  53. return template('wifi-form', errors=None, data = FormsDict(),
  54. orientations=ORIENTATIONS)
  55. def create_tabble(db, name, columns):
  56. col_defs = ','.join(['{} {}'.format(*i) for i in columns])
  57. db.execute('CREATE TABLE {} ({})'.format(name, col_defs))
  58. def save_to_db(db, dic):
  59. tosave = dic.copy()
  60. tosave['date'] = utils.formatdate()
  61. return db.execute("""
  62. INSERT INTO {}
  63. (name, contrib_type, latitude, longitude, phone, email, access_type, bandwidth, share_part, floor, floor_total, orientations, roof, comment,
  64. privacy_name, privacy_email, privacy_place_details, privacy_coordinates, privacy_comment, date)
  65. VALUES (:name, :contrib_type, :latitude, :longitude, :phone, :email, :access_type, :bandwidth, :share_part, :floor, :floor_total, :orientations, :roof, :comment,
  66. :privacy_name, :privacy_email, :privacy_place_details, :privacy_coordinates, :privacy_comment, :date)
  67. """.format(TABLE_NAME), tosave)
  68. @route('/wifi-form', method='POST')
  69. def submit_wifi_form():
  70. required = ('name', 'contrib-type',
  71. 'latitude', 'longitude')
  72. required_or = (('email', 'phone'),)
  73. required_if = (
  74. ('contrib-type', 'share',('access-type', 'bandwidth',
  75. 'share-part')),
  76. )
  77. field_names = {
  78. 'name' : 'Nom/Pseudo',
  79. 'contrib-type': 'Type de participation',
  80. 'latitude' : 'Localisation',
  81. 'longitude' : 'Localisation',
  82. 'phone' : 'Téléphone',
  83. 'email' : 'Email',
  84. 'access-type' : 'Type de connexion',
  85. 'bandwidth' : 'Bande passante',
  86. 'share-part' : 'Débit partagé',
  87. 'floor' : 'Étage',
  88. 'floor_total' : 'Nombre d\'étages total'
  89. }
  90. errors = []
  91. for name in required:
  92. if (not request.forms.get(name)):
  93. errors.append((field_names[name], 'ce champ est requis'))
  94. for name_list in required_or:
  95. filleds = [True for name in name_list if request.forms.get(name)]
  96. if len(filleds) <= 0:
  97. errors.append((
  98. ' ou '.join([field_names[i] for i in name_list]),
  99. 'au moins un des de ces champs est requis'))
  100. for key, value, fields in required_if:
  101. if request.forms.get('key') == value:
  102. for name in fields:
  103. if not request.forms.get(name):
  104. errors.append(
  105. (field_names[name], 'ce champ est requis'))
  106. if request.forms.get('floor') and not request.forms.get('floor_total'):
  107. errors.append((field_names['floor_total'], "ce champ est requis"))
  108. elif not request.forms.get('floor') and request.forms.get('floor_total'):
  109. errors.append((field_names['floor'], "ce champ est requis"))
  110. elif request.forms.get('floor') and request.forms.get('floor_total') and (request.forms.get('floor') > request.forms.get('floor_total')):
  111. errors.append((field_names['floor'], "Étage supérieur au nombre total"))
  112. if errors:
  113. return template('wifi-form', errors=errors, data=request.forms,
  114. orientations=ORIENTATIONS)
  115. else:
  116. d = request.forms
  117. save_to_db(DB, {
  118. 'name' : d.get('name'),
  119. 'contrib_type' : d.get('contrib-type'),
  120. 'latitude' : d.get('latitude'),
  121. 'longitude' : d.get('longitude'),
  122. 'phone' : d.get('phone'),
  123. 'email' : d.get('email'),
  124. 'phone' : d.get('phone'),
  125. 'access_type' : d.get('access-type'),
  126. 'bandwidth' : d.get('bandwidth'),
  127. 'share_part' : d.get('share-part'),
  128. 'floor' : d.get('floor'),
  129. 'floor_total' : d.get('floor_total'),
  130. 'orientations' : ','.join(d.getall('orientation')),
  131. 'roof' : d.get('roof'),
  132. 'comment' : d.get('comment'),
  133. 'privacy_name' : 'name' in d.getall('privacy'),
  134. 'privacy_email' : 'email' in d.getall('privacy'),
  135. 'privacy_place_details': 'details' in d.getall('privacy'),
  136. 'privacy_coordinates' : 'coordinates' in d.getall('privacy'),
  137. 'privacy_comment' : 'comment' in d.getall('privacy'),
  138. })
  139. DB.commit()
  140. # Rebuild GeoJSON
  141. build_geojson()
  142. return redirect(urlparse.urljoin(request.path,'thanks'))
  143. @route('/thanks')
  144. def wifi_form_thanks():
  145. return template('thanks')
  146. @route('/assets/<filename:path>')
  147. def send_asset(filename):
  148. return static_file(filename, root=join(dirname(__file__), 'assets'))
  149. @route('/legal')
  150. def legal():
  151. return template('legal')
  152. """
  153. Results Map
  154. """
  155. @route('/map')
  156. def public_map():
  157. geojsonPath = '/public.json'
  158. return template('map', geojson=geojsonPath)
  159. @route('/public.json')
  160. def public_geojson():
  161. return static_file('public.json', root=join(dirname(__file__), 'json/'))
  162. """
  163. GeoJSON Functions
  164. """
  165. # Save feature collection to a json file
  166. def save_featurecollection_json(id, features):
  167. with open('json/' + id + '.json', 'w') as outfile:
  168. json.dump({
  169. "type" : "FeatureCollection",
  170. "features" : features,
  171. "id" : id,
  172. }, outfile)
  173. # Build GeoJSON files from DB
  174. def build_geojson():
  175. # Read from DB
  176. DB.row_factory = sqlite3.Row
  177. cur = DB.execute("""
  178. SELECT * FROM {} ORDER BY id DESC
  179. """.format(TABLE_NAME))
  180. public_features = []
  181. private_features = []
  182. # Loop through results
  183. rows = cur.fetchall()
  184. for row in rows:
  185. # Private JSON file
  186. private_features.append({
  187. "type" : "Feature",
  188. "geometry" : {
  189. "type": "Point",
  190. "coordinates": [row['longitude'], row['latitude']],
  191. },
  192. "id" : row['id'],
  193. "properties": {
  194. "name" : row['name'],
  195. "place" : {
  196. 'floor' : row['floor'],
  197. 'floor_total' : row['floor_total'],
  198. 'orientations' : row['orientations'].split(','),
  199. 'roof' : row['roof'],
  200. },
  201. "comment" : row['comment']
  202. }
  203. })
  204. # Bypass non-public points
  205. if not row['privacy_coordinates']:
  206. continue
  207. # Public JSON file
  208. public_feature = {
  209. "type" : "Feature",
  210. "geometry" : {
  211. "type": "Point",
  212. "coordinates": [row['longitude'], row['latitude']],
  213. },
  214. "id" : row['id'],
  215. "properties": {}
  216. }
  217. # Add optionnal variables
  218. if not row['privacy_name']:
  219. public_feature['properties']['name'] = row['name']
  220. if not row['privacy_comment']:
  221. public_feature['properties']['comment'] = row['comment']
  222. if not row['privacy_place_details']:
  223. public_feature['properties']['place'] = {
  224. 'floor' : row['floor'],
  225. 'floor_total' : row['floor_total'],
  226. 'orientations' : row['orientations'].split(','),
  227. 'roof' : row['roof'],
  228. }
  229. # Add to public features list
  230. public_features.append(public_feature)
  231. # Build GeoJSON Feature Collection
  232. save_featurecollection_json('private', private_features)
  233. save_featurecollection_json('public', public_features)
  234. DEBUG = bool(os.environ.get('DEBUG', False))
  235. if __name__ == '__main__':
  236. if len(sys.argv) > 1:
  237. if sys.argv[1] == 'createdb':
  238. create_tabble(DB, TABLE_NAME, DB_COLS)
  239. if sys.argv[1] == 'buildgeojson':
  240. build_geojson()
  241. else:
  242. run(host='localhost', port=8080, reloader=DEBUG)
  243. DB.close()