backend.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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 static_file('thanks.html',
  146. root=join(dirname(__file__), 'views/'))
  147. @route('/assets/<filename:path>')
  148. def send_asset(filename):
  149. return static_file(filename, root=join(dirname(__file__), 'assets'))
  150. """
  151. Results Map
  152. """
  153. @route('/map')
  154. def public_map():
  155. geojsonPath = '/public.json'
  156. return template('map', geojson=geojsonPath)
  157. @route('/public.json')
  158. def public_geojson():
  159. return static_file('public.json', root=join(dirname(__file__), 'json/'))
  160. """
  161. GeoJSON Functions
  162. """
  163. # Save feature collection to a json file
  164. def save_featurecollection_json(id, features):
  165. with open('json/' + id + '.json', 'w') as outfile:
  166. json.dump({
  167. "type" : "FeatureCollection",
  168. "features" : features,
  169. "id" : id,
  170. }, outfile)
  171. # Build GeoJSON files from DB
  172. def build_geojson():
  173. # Read from DB
  174. DB.row_factory = sqlite3.Row
  175. cur = DB.execute("""
  176. SELECT * FROM {} ORDER BY id DESC
  177. """.format(TABLE_NAME))
  178. public_features = []
  179. private_features = []
  180. # Loop through results
  181. rows = cur.fetchall()
  182. for row in rows:
  183. # Private JSON file
  184. private_features.append({
  185. "type" : "Feature",
  186. "geometry" : {
  187. "type": "Point",
  188. "coordinates": [row['longitude'], row['latitude']],
  189. },
  190. "id" : row['id'],
  191. "properties": {
  192. "name" : row['name'],
  193. "place" : {
  194. 'floor' : row['floor'],
  195. 'floor_total' : row['floor_total'],
  196. 'orientations' : row['orientations'].split(','),
  197. 'roof' : row['roof'],
  198. },
  199. "comment" : row['comment']
  200. }
  201. })
  202. # Bypass non-public points
  203. if not row['privacy_coordinates']:
  204. continue
  205. # Public JSON file
  206. public_feature = {
  207. "type" : "Feature",
  208. "geometry" : {
  209. "type": "Point",
  210. "coordinates": [row['longitude'], row['latitude']],
  211. },
  212. "id" : row['id'],
  213. "properties": {}
  214. }
  215. # Add optionnal variables
  216. if not row['privacy_name']:
  217. public_feature['properties']['name'] = row['name']
  218. if not row['privacy_comment']:
  219. public_feature['properties']['comment'] = row['comment']
  220. if not row['privacy_place_details']:
  221. public_feature['properties']['place'] = {
  222. 'floor' : row['floor'],
  223. 'floor_total' : row['floor_total'],
  224. 'orientations' : row['orientations'].split(','),
  225. 'roof' : row['roof'],
  226. }
  227. # Add to public features list
  228. public_features.append(public_feature)
  229. # Build GeoJSON Feature Collection
  230. save_featurecollection_json('private', private_features)
  231. save_featurecollection_json('public', public_features)
  232. DEBUG = bool(os.environ.get('DEBUG', False))
  233. if __name__ == '__main__':
  234. if len(sys.argv) > 1:
  235. if sys.argv[1] == 'createdb':
  236. create_tabble(DB, TABLE_NAME, DB_COLS)
  237. if sys.argv[1] == 'buildgeojson':
  238. build_geojson()
  239. else:
  240. run(host='localhost', port=8080, reloader=DEBUG)
  241. DB.close()