backend.py 8.1 KB

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