backend.py 12 KB

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