backend.py 13 KB

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