backend.py 8.2 KB

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