backend.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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 (int(floor) < 0):
  141. errors.append((field_names['floor'], "l'étage doit-être positif"))
  142. if (int(floor_total) < 0):
  143. errors.append((field_names['floor_total'], "le nombre d'étages doit-être positif"))
  144. if errors:
  145. return template('wifi-form', errors=errors, data=request.forms,
  146. orientations=ORIENTATIONS, geojson=GEOJSON_NAME)
  147. else:
  148. d = request.forms
  149. save_to_db(DB, {
  150. 'name' : d.get('name'),
  151. 'contrib_type' : d.get('contrib-type'),
  152. 'latitude' : d.get('latitude'),
  153. 'longitude' : d.get('longitude'),
  154. 'phone' : d.get('phone'),
  155. 'email' : d.get('email'),
  156. 'phone' : d.get('phone'),
  157. 'access_type' : d.get('access-type'),
  158. 'connect_local' : 'local' in d.getall('connect-type'),
  159. 'connect_internet' : 'internet' in d.getall('connect-type'),
  160. 'bandwidth' : d.get('bandwidth'),
  161. 'share_part' : d.get('share-part'),
  162. 'floor' : d.get('floor'),
  163. 'floor_total' : d.get('floor_total'),
  164. 'orientations' : ','.join(d.getall('orientation')),
  165. 'roof' : d.get('roof'),
  166. 'comment' : d.get('comment'),
  167. 'privacy_name' : 'name' in d.getall('privacy'),
  168. 'privacy_email' : 'email' in d.getall('privacy'),
  169. 'privacy_place_details': 'place_details' in d.getall('privacy'),
  170. 'privacy_coordinates' : 'coordinates' in d.getall('privacy'),
  171. 'privacy_comment' : 'comment' in d.getall('privacy'),
  172. })
  173. DB.commit()
  174. # Rebuild GeoJSON
  175. build_geojson()
  176. return redirect(urlparse.urljoin(request.path,'thanks'))
  177. @route('/thanks')
  178. def wifi_form_thanks():
  179. return template('thanks')
  180. @route('/assets/<filename:path>')
  181. def send_asset(filename):
  182. return static_file(filename, root=join(dirname(__file__), 'assets'))
  183. @route('/legal')
  184. def legal():
  185. return template('legal')
  186. """
  187. Results Map
  188. """
  189. @route('/map')
  190. def public_map():
  191. return template('map', geojson=GEOJSON_NAME)
  192. @route('/public.json')
  193. def public_geojson():
  194. return static_file('public.json', root=join(dirname(__file__), 'json/'))
  195. """
  196. GeoJSON Functions
  197. """
  198. # Useful for merging angle intervals (orientations)
  199. def merge_intervals(l, wrap=360):
  200. """Merge a list of intervals, assuming the space is cyclic. The
  201. intervals should already by sorted by start value."""
  202. if l == []:
  203. return []
  204. result = list()
  205. # Transform the 2-tuple into a 2-list to be able to modify it
  206. result.append(list(l[0]))
  207. for (start, stop) in l:
  208. current = result[-1]
  209. if start > current[1]:
  210. result.append([start, stop])
  211. else:
  212. result[-1][1] = max(result[-1][1], stop)
  213. if len(result) == 1:
  214. return result
  215. # Handle the cyclicity by merging the ends if necessary
  216. last = result[-1]
  217. first = result[0]
  218. if first[0] <= last[1] - wrap:
  219. result[-1][1] = max(result[-1][1], first[1] + wrap)
  220. result.pop(0)
  221. return result
  222. def orientations_to_angle(orientations):
  223. """Return a list of (start, stop) angles from a list of orientations."""
  224. # Cleanup
  225. orientations = [o for o in orientations if o in ANGLES.keys()]
  226. # Hack to make leaflet-semicircle happy (drawing a full circle only
  227. # works with (0, 360))
  228. if len(orientations) == 8:
  229. return [[0, 360]]
  230. angles = [ANGLES[orientation] for orientation in orientations]
  231. angles.sort(key=lambda (x, y): x)
  232. return merge_intervals(angles)
  233. # Save feature collection to a json file
  234. def save_featurecollection_json(id, features):
  235. with open('json/' + id + '.json', 'w') as outfile:
  236. json.dump({
  237. "type" : "FeatureCollection",
  238. "features" : features,
  239. "id" : id,
  240. }, outfile)
  241. # Build GeoJSON files from DB
  242. def build_geojson():
  243. # Read from DB
  244. DB.row_factory = sqlite3.Row
  245. cur = DB.execute("""
  246. SELECT * FROM {} ORDER BY id DESC
  247. """.format(TABLE_NAME))
  248. public_features = []
  249. private_features = []
  250. # Loop through results
  251. rows = cur.fetchall()
  252. for row in rows:
  253. orientations = row['orientations'].split(',')
  254. if row['roof'] == "on":
  255. angles = [(0, 360)]
  256. else:
  257. angles = orientations_to_angle(orientations)
  258. # Private JSON file
  259. private_features.append({
  260. "type" : "Feature",
  261. "geometry" : {
  262. "type": "Point",
  263. "coordinates": [row['longitude'], row['latitude']],
  264. },
  265. "id" : row['id'],
  266. "properties": {
  267. "name" : row['name'],
  268. "place" : {
  269. 'floor' : row['floor'],
  270. 'floor_total' : row['floor_total'],
  271. 'orientations' : orientations,
  272. 'angles' : angles,
  273. 'roof' : row['roof'],
  274. },
  275. "comment" : row['comment']
  276. }
  277. })
  278. # Bypass non-public points
  279. if not row['privacy_coordinates']:
  280. continue
  281. # Public JSON file
  282. public_feature = {
  283. "type" : "Feature",
  284. "geometry" : {
  285. "type": "Point",
  286. "coordinates": [row['longitude'], row['latitude']],
  287. },
  288. "id" : row['id'],
  289. "properties": {}
  290. }
  291. # Add optionnal variables
  292. if row['privacy_name']:
  293. public_feature['properties']['name'] = row['name']
  294. if row['privacy_comment']:
  295. public_feature['properties']['comment'] = row['comment']
  296. if row['privacy_place_details']:
  297. public_feature['properties']['place'] = {
  298. 'floor' : row['floor'],
  299. 'floor_total' : row['floor_total'],
  300. 'orientations' : orientations,
  301. 'angles' : angles,
  302. 'roof' : row['roof'],
  303. }
  304. # Add to public features list
  305. public_features.append(public_feature)
  306. # Build GeoJSON Feature Collection
  307. save_featurecollection_json('private', private_features)
  308. save_featurecollection_json('public', public_features)
  309. DEBUG = bool(os.environ.get('DEBUG', False))
  310. LISTEN_ADDR= os.environ.get('BIND_ADDR', 'localhost')
  311. LISTEN_PORT= int(os.environ.get('BIND_PORT', 8080))
  312. if __name__ == '__main__':
  313. if len(sys.argv) > 1:
  314. if sys.argv[1] == 'createdb':
  315. create_tabble(DB, TABLE_NAME, DB_COLS)
  316. if sys.argv[1] == 'buildgeojson':
  317. build_geojson()
  318. else:
  319. run(host=LISTEN_ADDR, port=LISTEN_PORT, reloader=DEBUG)
  320. DB.close()