backend.py 8.0 KB

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