backend.py 13 KB

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