backend.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import cgi
  4. import os
  5. import sys
  6. import sqlite3
  7. import urlparse
  8. import datetime
  9. import json
  10. from email import utils
  11. from os.path import join, dirname
  12. from bottle import route, run, static_file, request, template, FormsDict, redirect, response
  13. ORIENTATIONS = (
  14. ('N', 'Nord'),
  15. ('NO', 'Nord-Ouest'),
  16. ('O', 'Ouest'),
  17. ('SO', 'Sud-Ouest'),
  18. ('S', 'Sud'),
  19. ('SE', 'Sud-Est'),
  20. ('E', 'Est'),
  21. ('NE', 'Nord-Est'),
  22. )
  23. # Angular sector for each direction, written as (start, stop) in degrees
  24. ANGLES = {
  25. 'N': (-23, 22),
  26. 'NO': (292, 337),
  27. 'O': (247, 292),
  28. 'SO': (202, 247),
  29. 'S': (157, 202),
  30. 'SE': (112, 157),
  31. 'E': (67, 112),
  32. 'NE': (22, 67)
  33. }
  34. TABLE_NAME = 'contribs'
  35. DB_FILENAME = join(dirname(__file__), 'db.sqlite3')
  36. DB = sqlite3.connect(DB_FILENAME)
  37. DB_COLS = (
  38. ('id', 'INTEGER PRIMARY KEY'),
  39. ('name', 'TEXT'),
  40. ('contrib_type', 'TEXT'),
  41. ('latitude', 'REAL'),
  42. ('longitude', 'REAL'),
  43. ('phone', 'TEXT'),
  44. ('email', 'TEXT'),
  45. ('access_type', 'TEXT'),
  46. ('connect_local', 'INTEGER'),
  47. ('connect_internet', 'INTEGER'),
  48. ('bandwidth', 'REAL'),
  49. ('share_part', 'REAL'),
  50. ('floor', 'INTEGER'),
  51. ('floor_total', 'INTEGER'),
  52. ('orientations', 'TEXT'),
  53. ('roof', 'INTEGER'),
  54. ('comment', 'TEXT'),
  55. ('privacy_name', 'INTEGER'),
  56. ('privacy_email', 'INTEGER'),
  57. ('privacy_coordinates', 'INTEGER'),
  58. ('privacy_place_details', 'INTEGER'),
  59. ('privacy_comment', 'INTEGER'),
  60. ('date', 'TEXT'),
  61. )
  62. GEOJSON_NAME = 'public.json'
  63. ANTISPAM_FIELD = 'url'
  64. @route('/')
  65. def home():
  66. redirect("/wifi-form")
  67. @route('/wifi-form')
  68. def show_wifi_form():
  69. return template('wifi-form', errors=None, data = FormsDict(),
  70. orientations=ORIENTATIONS, geojson=GEOJSON_NAME)
  71. def create_tabble(db, name, columns):
  72. col_defs = ','.join(['{} {}'.format(*i) for i in columns])
  73. db.execute('CREATE TABLE {} ({})'.format(name, col_defs))
  74. def escape(s):
  75. if not isinstance(s, (bool, float, int)) and (s != None):
  76. return cgi.escape(s)
  77. else:
  78. return s
  79. def save_to_db(db, dic):
  80. # SQLite is picky about encoding else
  81. tosave = {bytes(k):escape(v.decode('utf-8')) if isinstance(v,str)
  82. else escape(v)
  83. for k,v in dic.items()}
  84. tosave['date'] = utils.formatdate()
  85. return db.execute("""
  86. INSERT INTO {}
  87. (name, contrib_type, latitude, longitude, phone, email, access_type, connect_local, connect_internet, bandwidth, share_part, floor, floor_total, orientations, roof, comment,
  88. privacy_name, privacy_email, privacy_place_details, privacy_coordinates, privacy_comment, date)
  89. VALUES (:name, :contrib_type, :latitude, :longitude, :phone, :email, :access_type, :connect_local, :connect_internet, :bandwidth, :share_part, :floor, :floor_total, :orientations, :roof, :comment,
  90. :privacy_name, :privacy_email, :privacy_place_details, :privacy_coordinates, :privacy_comment, :date)
  91. """.format(TABLE_NAME), tosave)
  92. @route('/wifi-form', method='POST')
  93. def submit_wifi_form():
  94. required = ('name', 'contrib-type',
  95. 'latitude', 'longitude')
  96. required_or = (('email', 'phone'),)
  97. required_if = (
  98. ('contrib-type', 'share',('access-type', 'bandwidth',
  99. 'share-part')),
  100. )
  101. field_names = {
  102. 'name' : 'Nom/Pseudo',
  103. 'contrib-type': 'Type de participation',
  104. 'latitude' : 'Localisation',
  105. 'longitude' : 'Localisation',
  106. 'phone' : 'Téléphone',
  107. 'email' : 'Email',
  108. 'access-type' : 'Type de connexion',
  109. 'bandwidth' : 'Bande passante',
  110. 'share-part' : 'Débit partagé',
  111. 'floor' : 'Étage',
  112. 'floor_total' : 'Nombre d\'étages total'
  113. }
  114. errors = []
  115. if request.forms.get(ANTISPAM_FIELD):
  116. errors.append(('', "Une erreur s'est produite"))
  117. for name in required:
  118. if (not request.forms.get(name)):
  119. errors.append((field_names[name], 'ce champ est requis'))
  120. for name_list in required_or:
  121. filleds = [True for name in name_list if request.forms.get(name)]
  122. if len(filleds) <= 0:
  123. errors.append((
  124. ' ou '.join([field_names[i] for i in name_list]),
  125. 'au moins un des de ces champs est requis'))
  126. for key, value, fields in required_if:
  127. if request.forms.get(key) == value:
  128. for name in fields:
  129. if not request.forms.get(name):
  130. errors.append(
  131. (field_names[name], 'ce champ est requis'))
  132. floor = request.forms.get('floor')
  133. floor_total = request.forms.get('floor_total')
  134. if floor and not floor_total:
  135. errors.append((field_names['floor_total'], "ce champ est requis"))
  136. elif not floor and floor_total:
  137. errors.append((field_names['floor'], "ce champ est requis"))
  138. elif floor and floor_total and (int(floor) > int(floor_total)):
  139. errors.append((field_names['floor'], "Étage supérieur au nombre total"))
  140. if errors:
  141. return template('wifi-form', errors=errors, data=request.forms,
  142. orientations=ORIENTATIONS, geojson=GEOJSON_NAME)
  143. else:
  144. d = request.forms
  145. save_to_db(DB, {
  146. 'name' : d.get('name'),
  147. 'contrib_type' : d.get('contrib-type'),
  148. 'latitude' : d.get('latitude'),
  149. 'longitude' : d.get('longitude'),
  150. 'phone' : d.get('phone'),
  151. 'email' : d.get('email'),
  152. 'phone' : d.get('phone'),
  153. 'access_type' : d.get('access-type'),
  154. 'connect_local' : 'local' in d.getall('connect-type'),
  155. 'connect_internet' : 'internet' in d.getall('connect-type'),
  156. 'bandwidth' : d.get('bandwidth'),
  157. 'share_part' : d.get('share-part'),
  158. 'floor' : d.get('floor'),
  159. 'floor_total' : d.get('floor_total'),
  160. 'orientations' : ','.join(d.getall('orientation')),
  161. 'roof' : d.get('roof'),
  162. 'comment' : d.get('comment'),
  163. 'privacy_name' : 'name' in d.getall('privacy'),
  164. 'privacy_email' : 'email' in d.getall('privacy'),
  165. 'privacy_place_details': 'place_details' in d.getall('privacy'),
  166. 'privacy_coordinates' : 'coordinates' in d.getall('privacy'),
  167. 'privacy_comment' : 'comment' in d.getall('privacy'),
  168. })
  169. DB.commit()
  170. # Rebuild GeoJSON
  171. build_geojson()
  172. return redirect(urlparse.urljoin(request.path,'thanks'))
  173. @route('/thanks')
  174. def wifi_form_thanks():
  175. return template('thanks')
  176. @route('/assets/<filename:path>')
  177. def send_asset(filename):
  178. return static_file(filename, root=join(dirname(__file__), 'assets'))
  179. @route('/legal')
  180. def legal():
  181. return template('legal')
  182. """
  183. Results Map
  184. """
  185. @route('/map')
  186. def public_map():
  187. return template('map', geojson=GEOJSON_NAME)
  188. @route('/public.json')
  189. def public_geojson():
  190. return static_file('public.json', root=join(dirname(__file__), 'json/'))
  191. """
  192. GeoJSON Functions
  193. """
  194. # Useful for merging angle intervals (orientations)
  195. def merge_intervals(l, wrap=360):
  196. """Merge a list of intervals, assuming the space is cyclic. The
  197. intervals should already by sorted by start value."""
  198. if l == []:
  199. return []
  200. result = list()
  201. # Transform the 2-tuple into a 2-list to be able to modify it
  202. result.append(list(l[0]))
  203. for (start, stop) in l:
  204. current = result[-1]
  205. if start > current[1]:
  206. result.append([start, stop])
  207. else:
  208. result[-1][1] = max(result[-1][1], stop)
  209. if len(result) == 1:
  210. return result
  211. # Handle the cyclicity by merging the ends if necessary
  212. last = result[-1]
  213. first = result[0]
  214. if first[0] <= last[1] - wrap:
  215. result[-1][1] = max(result[-1][1], first[1] + wrap)
  216. result.pop(0)
  217. return result
  218. def orientations_to_angle(orientations):
  219. """Return a list of (start, stop) angles from a list of orientations."""
  220. # Cleanup
  221. orientations = [o for o in orientations if o in ANGLES.keys()]
  222. # Hack to make leaflet-semicircle happy (drawing a full circle only
  223. # works with (0, 360))
  224. if len(orientations) == 8:
  225. return [[0, 360]]
  226. angles = [ANGLES[orientation] for orientation in orientations]
  227. angles.sort(key=lambda (x, y): x)
  228. return merge_intervals(angles)
  229. # Save feature collection to a json file
  230. def save_featurecollection_json(id, features):
  231. with open('json/' + id + '.json', 'w') as outfile:
  232. json.dump({
  233. "type" : "FeatureCollection",
  234. "features" : features,
  235. "id" : id,
  236. }, outfile)
  237. # Build GeoJSON files from DB
  238. def build_geojson():
  239. # Read from DB
  240. DB.row_factory = sqlite3.Row
  241. cur = DB.execute("""
  242. SELECT * FROM {} ORDER BY id DESC
  243. """.format(TABLE_NAME))
  244. public_features = []
  245. private_features = []
  246. # Loop through results
  247. rows = cur.fetchall()
  248. for row in rows:
  249. orientations = row['orientations'].split(',')
  250. angles = orientations_to_angle(orientations)
  251. # Private JSON file
  252. private_features.append({
  253. "type" : "Feature",
  254. "geometry" : {
  255. "type": "Point",
  256. "coordinates": [row['longitude'], row['latitude']],
  257. },
  258. "id" : row['id'],
  259. "properties": {
  260. "name" : row['name'],
  261. "place" : {
  262. 'floor' : row['floor'],
  263. 'floor_total' : row['floor_total'],
  264. 'orientations' : orientations,
  265. 'angles' : angles,
  266. 'roof' : row['roof'],
  267. },
  268. "comment" : row['comment']
  269. }
  270. })
  271. # Bypass non-public points
  272. if not row['privacy_coordinates']:
  273. continue
  274. # Public JSON file
  275. public_feature = {
  276. "type" : "Feature",
  277. "geometry" : {
  278. "type": "Point",
  279. "coordinates": [row['longitude'], row['latitude']],
  280. },
  281. "id" : row['id'],
  282. "properties": {}
  283. }
  284. # Add optionnal variables
  285. if row['privacy_name']:
  286. public_feature['properties']['name'] = row['name']
  287. if row['privacy_comment']:
  288. public_feature['properties']['comment'] = row['comment']
  289. if row['privacy_place_details']:
  290. public_feature['properties']['place'] = {
  291. 'floor' : row['floor'],
  292. 'floor_total' : row['floor_total'],
  293. 'orientations' : orientations,
  294. 'angles' : angles,
  295. 'roof' : row['roof'],
  296. }
  297. # Add to public features list
  298. public_features.append(public_feature)
  299. # Build GeoJSON Feature Collection
  300. save_featurecollection_json('private', private_features)
  301. save_featurecollection_json('public', public_features)
  302. DEBUG = bool(os.environ.get('DEBUG', False))
  303. if __name__ == '__main__':
  304. if len(sys.argv) > 1:
  305. if sys.argv[1] == 'createdb':
  306. create_tabble(DB, TABLE_NAME, DB_COLS)
  307. if sys.argv[1] == 'buildgeojson':
  308. build_geojson()
  309. else:
  310. run(host='localhost', port=8080, reloader=DEBUG)
  311. DB.close()