backend.py 9.3 KB

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