eventman_server.py 19 KB

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