backend.py 8.2 KB

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