eventman_server.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. #!/usr/bin/env python
  2. """Event Man(ager)
  3. Your friendly manager of attendees at an event.
  4. Copyright 2015 Davide Alberani <da@erlug.linux.it>
  5. RaspiBO <info@raspibo.org>
  6. Licensed under the Apache License, Version 2.0 (the "License");
  7. you may not use this file except in compliance with the License.
  8. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. """
  15. import os
  16. import re
  17. import glob
  18. import json
  19. import logging
  20. import datetime
  21. import tornado.httpserver
  22. import tornado.ioloop
  23. import tornado.options
  24. from tornado.options import define, options
  25. import tornado.web
  26. import tornado.websocket
  27. from tornado import gen, escape, process
  28. import utils
  29. import backend
  30. ENCODING = 'utf-8'
  31. PROCESS_TIMEOUT = 60
  32. re_env_key = re.compile('[^A-Z_]+')
  33. re_slashes = re.compile(r'//+')
  34. class BaseHandler(tornado.web.RequestHandler):
  35. """Base class for request handlers."""
  36. # A property to access the first value of each argument.
  37. arguments = property(lambda self: dict([(k, v[0])
  38. for k, v in self.request.arguments.iteritems()]))
  39. _bool_convert = {
  40. '0': False,
  41. 'n': False,
  42. 'f': False,
  43. 'no': False,
  44. 'off': False,
  45. 'false': False,
  46. '1': True,
  47. 'y': True,
  48. 't': True,
  49. 'on': True,
  50. 'yes': True,
  51. 'true': True
  52. }
  53. def tobool(self, obj):
  54. if isinstance(obj, (list, tuple)):
  55. obj = obj[0]
  56. if isinstance(obj, (str, unicode)):
  57. obj = obj.lower()
  58. return self._bool_convert.get(obj, obj)
  59. def _arguments_tobool(self):
  60. return dict([(k, self.tobool(v)) for k, v in self.arguments.iteritems()])
  61. def initialize(self, **kwargs):
  62. """Add every passed (key, value) as attributes of the instance."""
  63. for key, value in kwargs.iteritems():
  64. setattr(self, key, value)
  65. class RootHandler(BaseHandler):
  66. """Handler for the / path."""
  67. angular_app_path = os.path.join(os.path.dirname(__file__), "angular_app")
  68. @gen.coroutine
  69. def get(self, *args, **kwargs):
  70. # serve the ./angular_app/index.html file
  71. with open(self.angular_app_path + "/index.html", 'r') as fd:
  72. self.write(fd.read())
  73. # Keep track of WebSocket connections.
  74. _ws_clients = {}
  75. class CollectionHandler(BaseHandler):
  76. """Base class for handlers that need to interact with the database backend.
  77. Introduce basic CRUD operations."""
  78. # set of documents we're managing (a collection in MongoDB or a table in a SQL database)
  79. collection = None
  80. def _filter_results(self, results, params):
  81. """Filter a list using keys and values from a dictionary.
  82. :param results: the list to be filtered
  83. :type results: list
  84. :param params: a dictionary of items that must all be present in an original list item to be included in the return
  85. :return: list of items that have all the keys with the same values as params
  86. :rtype: list"""
  87. if not params:
  88. return results
  89. filtered = []
  90. for result in results:
  91. add = True
  92. for key, value in params.iteritems():
  93. if key not in result or result[key] != value:
  94. add = False
  95. break
  96. if add:
  97. filtered.append(result)
  98. return filtered
  99. def _dict2env(self, data):
  100. """Convert a dictionary into a form suitable to be passed as environment variables."""
  101. ret = {}
  102. for key, value in data.iteritems():
  103. if isinstance(value, (list, tuple, dict)):
  104. continue
  105. try:
  106. key = key.upper().encode('ascii', 'ignore')
  107. key = re_env_key.sub('', key)
  108. if not key:
  109. continue
  110. ret[key] = unicode(value).encode(ENCODING)
  111. except:
  112. continue
  113. return ret
  114. @gen.coroutine
  115. def get(self, id_=None, resource=None, resource_id=None, **kwargs):
  116. if resource:
  117. # Handle access to sub-resources.
  118. method = getattr(self, 'handle_get_%s' % resource, None)
  119. if method and callable(method):
  120. self.write(method(id_, resource_id, **kwargs))
  121. return
  122. if id_ is not None:
  123. # read a single document
  124. self.write(self.db.get(self.collection, id_))
  125. else:
  126. # return an object containing the list of all objects in the collection;
  127. # e.g.: {'events': [{'_id': 'obj1-id, ...}, {'_id': 'obj2-id, ...}, ...]}
  128. # Please, never return JSON lists that are not encapsulated into an object,
  129. # to avoid XSS vulnerabilities.
  130. self.write({self.collection: self.db.query(self.collection)})
  131. @gen.coroutine
  132. def post(self, id_=None, resource=None, resource_id=None, **kwargs):
  133. data = escape.json_decode(self.request.body or '{}')
  134. if resource:
  135. # Handle access to sub-resources.
  136. method = getattr(self, 'handle_%s_%s' % (self.request.method.lower(), resource), None)
  137. if method and callable(method):
  138. self.write(method(id_, resource_id, data, **kwargs))
  139. return
  140. if id_ is None:
  141. newData = self.db.add(self.collection, data)
  142. else:
  143. merged, newData = self.db.update(self.collection, id_, data)
  144. self.write(newData)
  145. # PUT (update an existing document) is handled by the POST (create a new document) method
  146. put = post
  147. @gen.coroutine
  148. def delete(self, id_=None, resource=None, resource_id=None, **kwargs):
  149. if resource:
  150. # Handle access to sub-resources.
  151. method = getattr(self, 'handle_delete_%s' % resource, None)
  152. if method and callable(method):
  153. self.write(method(id_, resource_id, **kwargs))
  154. return
  155. if id_:
  156. self.db.delete(self.collection, id_)
  157. self.write({'success': True})
  158. def on_timeout(self, cmd, pipe):
  159. """Kill a process that is taking too long to complete."""
  160. logging.debug('cmd %s is taking too long: killing it' % ' '.join(cmd))
  161. try:
  162. pipe.proc.kill()
  163. except:
  164. pass
  165. def on_exit(self, returncode, cmd, pipe):
  166. """Callback executed when a subprocess execution is over."""
  167. self.ioloop.remove_timeout(self.timeout)
  168. logging.debug('cmd: %s returncode: %d' % (' '.join(cmd), returncode))
  169. @gen.coroutine
  170. def run_subprocess(self, cmd, stdin_data=None, env=None):
  171. """Execute the given action.
  172. :param cmd: the command to be run with its command line arguments
  173. :type cmd: list
  174. :param stdin_data: data to be sent over stdin
  175. :type stdin_data: str
  176. :param env: environment of the process
  177. :type env: dict
  178. """
  179. self.ioloop = tornado.ioloop.IOLoop.instance()
  180. p = process.Subprocess(cmd, close_fds=True, stdin=process.Subprocess.STREAM,
  181. stdout=process.Subprocess.STREAM, stderr=process.Subprocess.STREAM, env=env)
  182. p.set_exit_callback(lambda returncode: self.on_exit(returncode, cmd, p))
  183. self.timeout = self.ioloop.add_timeout(datetime.timedelta(seconds=PROCESS_TIMEOUT),
  184. lambda: self.on_timeout(cmd, p))
  185. yield gen.Task(p.stdin.write, stdin_data or '')
  186. p.stdin.close()
  187. out, err = yield [gen.Task(p.stdout.read_until_close),
  188. gen.Task(p.stderr.read_until_close)]
  189. logging.debug('cmd: %s' % ' '.join(cmd))
  190. logging.debug('cmd stdout: %s' % out)
  191. logging.debug('cmd strerr: %s' % err)
  192. raise gen.Return((out, err))
  193. @gen.coroutine
  194. def run_triggers(self, action, stdin_data=None, env=None):
  195. """Asynchronously execute triggers for the given action.
  196. :param action: action name; scripts in directory ./data/triggers/{action}.d will be run
  197. :type action: str
  198. :param stdin_data: a python dictionary that will be serialized in JSON and sent to the process over stdin
  199. :type stdin_data: dict
  200. :param env: environment of the process
  201. :type stdin_data: dict
  202. """
  203. logging.debug('running triggers for action "%s"' % action)
  204. stdin_data = stdin_data or {}
  205. try:
  206. stdin_data = json.dumps(stdin_data)
  207. except:
  208. stdin_data = '{}'
  209. for script in glob.glob(os.path.join(self.data_dir, 'triggers', '%s.d' % action, '*')):
  210. if not (os.path.isfile(script) and os.access(script, os.X_OK)):
  211. continue
  212. out, err = yield gen.Task(self.run_subprocess, [script], stdin_data, env)
  213. def build_ws_url(self, path, proto='ws', host=None):
  214. """Return a WebSocket url from a path."""
  215. return '%s://%s/ws/%s' % (proto, host or self.request.host, path)
  216. @gen.coroutine
  217. def send_ws_message(self, url, message):
  218. """Send a WebSocket message to all the connected clients.
  219. :param url: WebSocket url
  220. :type url: str
  221. :param message: message to send
  222. :type message: str
  223. """
  224. ws = yield tornado.websocket.websocket_connect(url)
  225. ws.write_message(message)
  226. ws.close()
  227. class PersonsHandler(CollectionHandler):
  228. """Handle requests for Persons."""
  229. collection = 'persons'
  230. object_id = 'person_id'
  231. def handle_get_events(self, id_, resource_id=None, **kwargs):
  232. # Get a list of events attended by this person.
  233. # Inside the data of each event, a 'person_data' dictionary is
  234. # created, duplicating the entry for the current person (so that
  235. # there's no need to parse the 'persons' list on the client).
  236. #
  237. # If resource_id is given, only the specified event is considered.
  238. #
  239. # If the 'all' parameter is given, every event (also unattended ones) is returned.
  240. args = self.request.arguments
  241. query = {}
  242. if id_ and not self.tobool(args.get('all')):
  243. query = {'persons.person_id': id_}
  244. if resource_id:
  245. query['_id'] = resource_id
  246. events = self.db.query('events', query)
  247. for event in events:
  248. person_data = {}
  249. for persons in event.get('persons') or []:
  250. if str(persons.get('person_id')) == id_:
  251. person_data = persons
  252. break
  253. event['person_data'] = person_data
  254. if resource_id and events:
  255. return events[0]
  256. return {'events': events}
  257. class EventsHandler(CollectionHandler):
  258. """Handle requests for Events."""
  259. collection = 'events'
  260. object_id = 'event_id'
  261. def _get_person_data(self, person_id_or_query, persons):
  262. """Filter a list of persons returning the first item with a given person_id
  263. or which set of keys specified in a dictionary match their respective values."""
  264. for person in persons:
  265. if isinstance(person_id_or_query, dict):
  266. if all(person.get(k) == v for k, v in person_id_or_query.iteritems()):
  267. return person
  268. else:
  269. if str(person.get('person_id')) == person_id_or_query:
  270. return person
  271. return {}
  272. def handle_get_persons(self, id_, resource_id=None):
  273. # Return every person registered at this event, or the information
  274. # about a specific person.
  275. query = {'_id': id_}
  276. event = self.db.query('events', query)[0]
  277. if resource_id:
  278. return {'person': self._get_person_data(resource_id, event.get('persons') or [])}
  279. persons = self._filter_results(event.get('persons') or [], self.arguments)
  280. return {'persons': persons}
  281. def handle_post_persons(self, id_, person_id, data):
  282. # Add a person to the list of persons registered at this event.
  283. doc = self.db.query('events',
  284. {'_id': id_, 'persons.person_id': person_id})
  285. if '_id' in data:
  286. del data['_id']
  287. if not doc:
  288. merged, doc = self.db.update('events',
  289. {'_id': id_},
  290. {'persons': data},
  291. operation='append',
  292. create=False)
  293. return {'event': doc}
  294. def handle_put_persons(self, id_, person_id, data):
  295. # Update an existing entry for a person registered at this event.
  296. query = dict([('persons.%s' % k, v) for k, v in self.arguments.iteritems()])
  297. query['_id'] = id_
  298. if person_id is not None:
  299. query['persons.person_id'] = person_id
  300. old_person_data = {}
  301. current_event = self.db.query(self.collection, query)
  302. if current_event:
  303. current_event = current_event[0]
  304. else:
  305. current_event = {}
  306. old_person_data = self._get_person_data(person_id or self.arguments,
  307. current_event.get('persons') or [])
  308. merged, doc = self.db.update('events', query,
  309. data, updateList='persons', create=False)
  310. new_person_data = self._get_person_data(person_id or self.arguments,
  311. doc.get('persons') or [])
  312. env = self._dict2env(new_person_data)
  313. if person_id is None:
  314. person_id = new_person_data.get('person_id')
  315. env.update({'PERSON_ID': person_id, 'EVENT_ID': id_, 'EVENT_TITLE': doc.get('title', '')})
  316. stdin_data = {'old': old_person_data,
  317. 'new': new_person_data,
  318. 'event': doc,
  319. 'merged': merged
  320. }
  321. self.run_triggers('update_person_in_event', stdin_data=stdin_data, env=env)
  322. if old_person_data and old_person_data.get('attended') != new_person_data.get('attended'):
  323. ws_url = self.build_ws_url(path='event/%s/updates' % id_)
  324. self.send_ws_message(ws_url, json.dumps(doc.get('persons') or []))
  325. if new_person_data.get('attended'):
  326. self.run_triggers('attends', stdin_data=stdin_data, env=env)
  327. return {'event': doc}
  328. def handle_delete_persons(self, id_, person_id):
  329. # Remove a specific person from the list of persons registered at this event.
  330. merged, doc = self.db.update('events',
  331. {'_id': id_},
  332. {'persons': {'person_id': person_id}},
  333. operation='delete',
  334. create=False)
  335. return {'event': doc}
  336. class EbCSVImportPersonsHandler(BaseHandler):
  337. """Importer for CSV files exported from eventbrite."""
  338. csvRemap = {
  339. 'Nome evento': 'event_title',
  340. 'ID evento': 'event_id',
  341. 'N. codice a barre': 'ebqrcode',
  342. 'Cognome acquirente': 'surname',
  343. 'Nome acquirente': 'name',
  344. 'E-mail acquirente': 'email',
  345. 'Cognome': 'surname',
  346. 'Nome': 'name',
  347. 'E-mail': 'email',
  348. 'Indirizzo e-mail': 'email',
  349. 'Tipologia biglietto': 'ticket_kind',
  350. 'Data partecipazione': 'attending_datetime',
  351. 'Data check-in': 'checkin_datetime',
  352. 'Ordine n.': 'order_nr',
  353. 'ID ordine': 'order_nr',
  354. 'Titolo professionale': 'job_title',
  355. 'Azienda': 'company',
  356. 'Prefisso': 'name_title',
  357. 'Prefisso (Sig., Sig.ra, ecc.)': 'name_title',
  358. 'Order #': 'order_nr',
  359. 'Prefix': 'name_title',
  360. 'First Name': 'name',
  361. 'Last Name': 'surname',
  362. 'Suffix': 'name_suffix',
  363. 'Email': 'email',
  364. 'Attendee #': 'attendee_nr',
  365. 'Barcode #': 'ebqrcode',
  366. 'Company': 'company',
  367. }
  368. # Only these information are stored in the person collection.
  369. keepPersonData = ('name', 'surname', 'email', 'name_title', 'name_suffix',
  370. 'company', 'job_title')
  371. @gen.coroutine
  372. def post(self, **kwargs):
  373. targetEvent = None
  374. try:
  375. targetEvent = self.get_body_argument('targetEvent')
  376. except:
  377. pass
  378. reply = dict(total=0, valid=0, merged=0, new_in_event=0)
  379. for fieldname, contents in self.request.files.iteritems():
  380. for content in contents:
  381. filename = content['filename']
  382. parseStats, persons = utils.csvParse(content['body'], remap=self.csvRemap)
  383. reply['total'] += parseStats['total']
  384. reply['valid'] += parseStats['valid']
  385. for person in persons:
  386. person_data = dict([(k, person[k]) for k in self.keepPersonData
  387. if k in person])
  388. merged, stored_person = self.db.update('persons',
  389. [('email', 'name', 'surname')],
  390. person_data)
  391. if merged:
  392. reply['merged'] += 1
  393. if targetEvent and stored_person:
  394. event_id = targetEvent
  395. person_id = stored_person['_id']
  396. registered_data = {
  397. 'person_id': person_id,
  398. 'attended': False,
  399. 'from_file': filename}
  400. person.update(registered_data)
  401. if not self.db.query('events',
  402. {'_id': event_id, 'persons.person_id': person_id}):
  403. self.db.update('events', {'_id': event_id},
  404. {'persons': person},
  405. operation='appendUnique')
  406. reply['new_in_event'] += 1
  407. self.write(reply)
  408. class SettingsHandler(BaseHandler):
  409. """Handle requests for Settings."""
  410. @gen.coroutine
  411. def get(self, **kwds):
  412. query = self._arguments_tobool()
  413. settings = self.db.query('settings', query)
  414. self.write({'settings': settings})
  415. class WebSocketEventUpdatesHandler(tornado.websocket.WebSocketHandler):
  416. def _clean_url(self, url):
  417. return re_slashes.sub('/', url)
  418. def open(self, event_id, *args, **kwds):
  419. logging.debug('WebSocketEventUpdatesHandler.on_open event_id:%s' % event_id)
  420. _ws_clients.setdefault(self._clean_url(self.request.uri), set()).add(self)
  421. logging.debug('WebSocketEventUpdatesHandler.on_open %s clients connected' % len(_ws_clients))
  422. def on_message(self, message):
  423. logging.debug('WebSocketEventUpdatesHandler.on_message')
  424. count = 0
  425. for client in _ws_clients.get(self._clean_url(self.request.uri), []):
  426. if client == self:
  427. continue
  428. client.write_message(message)
  429. count += 1
  430. logging.debug('WebSocketEventUpdatesHandler.on_message sent message to %d clients' % count)
  431. def on_close(self):
  432. logging.debug('WebSocketEventUpdatesHandler.on_close')
  433. try:
  434. if self in _ws_clients.get(self._clean_url(self.request.uri), []):
  435. _ws_clients[self._clean_url(self.request.uri)].remove(self)
  436. except Exception, e:
  437. logging.warn('WebSocketEventUpdatesHandler.on_close error closing websocket: %s', str(e))
  438. def run():
  439. """Run the Tornado web application."""
  440. # command line arguments; can also be written in a configuration file,
  441. # specified with the --config argument.
  442. define("port", default=5242, help="run on the given port", type=int)
  443. define("data", default=os.path.join(os.path.dirname(__file__), "data"),
  444. help="specify the directory used to store the data")
  445. define("ssl_cert", default=os.path.join(os.path.dirname(__file__), 'ssl', 'eventman_cert.pem'),
  446. help="specify the SSL certificate to use for secure connections")
  447. define("ssl_key", default=os.path.join(os.path.dirname(__file__), 'ssl', 'eventman_key.pem'),
  448. help="specify the SSL private key to use for secure connections")
  449. define("mongodbURL", default=None,
  450. help="URL to MongoDB server", type=str)
  451. define("dbName", default='eventman',
  452. help="Name of the MongoDB database to use", type=str)
  453. define("debug", default=False, help="run in debug mode")
  454. define("config", help="read configuration file",
  455. callback=lambda path: tornado.options.parse_config_file(path, final=False))
  456. tornado.options.parse_command_line()
  457. if options.debug:
  458. logger = logging.getLogger()
  459. logger.setLevel(logging.DEBUG)
  460. # database backend connector
  461. db_connector = backend.EventManDB(url=options.mongodbURL, dbName=options.dbName)
  462. init_params = dict(db=db_connector, data_dir=options.data)
  463. application = tornado.web.Application([
  464. (r"/persons/?(?P<id_>\w+)?/?(?P<resource>\w+)?/?(?P<resource_id>\w+)?", PersonsHandler, init_params),
  465. (r"/events/?(?P<id_>\w+)?/?(?P<resource>\w+)?/?(?P<resource_id>\w+)?", EventsHandler, init_params),
  466. (r"/(?:index.html)?", RootHandler, init_params),
  467. (r"/ebcsvpersons", EbCSVImportPersonsHandler, init_params),
  468. (r"/settings", SettingsHandler, init_params),
  469. (r"/ws/+event/+(?P<event_id>\w+)/+updates/?", WebSocketEventUpdatesHandler),
  470. (r'/(.*)', tornado.web.StaticFileHandler, {"path": "angular_app"})
  471. ],
  472. template_path=os.path.join(os.path.dirname(__file__), "templates"),
  473. static_path=os.path.join(os.path.dirname(__file__), "static"),
  474. debug=options.debug)
  475. ssl_options = {}
  476. if os.path.isfile(options.ssl_key) and os.path.isfile(options.ssl_cert):
  477. ssl_options = dict(certfile=options.ssl_cert, keyfile=options.ssl_key)
  478. http_server = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options)
  479. http_server.listen(options.port)
  480. tornado.ioloop.IOLoop.instance().start()
  481. if __name__ == '__main__':
  482. run()