eventman_server.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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 datetime
  18. import subprocess
  19. import tornado.httpserver
  20. import tornado.ioloop
  21. import tornado.options
  22. from tornado.options import define, options
  23. import tornado.web
  24. from tornado import gen, escape
  25. import utils
  26. import backend
  27. PROCESS_TIMEOUT = 60
  28. class BaseHandler(tornado.web.RequestHandler):
  29. """Base class for request handlers."""
  30. _bool_convert = {
  31. '0': False,
  32. 'n': False,
  33. 'f': False,
  34. 'no': False,
  35. 'off': False,
  36. 'false': False
  37. }
  38. def tobool(self, obj):
  39. if isinstance(obj, (list, tuple)):
  40. obj = obj[0]
  41. if isinstance(obj, (str, unicode)):
  42. obj = obj.lower()
  43. return bool(self._bool_convert.get(obj, obj))
  44. def initialize(self, **kwargs):
  45. """Add every passed (key, value) as attributes of the instance."""
  46. for key, value in kwargs.iteritems():
  47. setattr(self, key, value)
  48. class RootHandler(BaseHandler):
  49. """Handler for the / path."""
  50. angular_app_path = os.path.join(os.path.dirname(__file__), "angular_app")
  51. @gen.coroutine
  52. def get(self, *args, **kwargs):
  53. # serve the ./angular_app/index.html file
  54. with open(self.angular_app_path + "/index.html", 'r') as fd:
  55. self.write(fd.read())
  56. class CollectionHandler(BaseHandler):
  57. """Base class for handlers that need to interact with the database backend.
  58. Introduce basic CRUD operations."""
  59. # set of documents we're managing (a collection in MongoDB or a table in a SQL database)
  60. collection = None
  61. def _filter_results(self, results, params):
  62. """Filter a list using keys and values from a dictionary.
  63. :param results: the list to be filtered
  64. :type results: list
  65. :param params: a dictionary of items that must all be present in an original list item to be included in the return
  66. :return: list of items that have all the keys with the same values as params
  67. :rtype: list"""
  68. if not params:
  69. return results
  70. filtered = []
  71. for result in results:
  72. add = True
  73. for key, value in params.iteritems():
  74. if key not in result or result[key] != value:
  75. add = False
  76. break
  77. if add:
  78. filtered.append(result)
  79. return filtered
  80. # A property to access the first value of each argument.
  81. arguments = property(lambda self: dict([(k, v[0])
  82. for k, v in self.request.arguments.iteritems()]))
  83. @gen.coroutine
  84. def get(self, id_=None, resource=None, resource_id=None, **kwargs):
  85. if resource:
  86. # Handle access to sub-resources.
  87. method = getattr(self, 'handle_get_%s' % resource, None)
  88. if method and callable(method):
  89. self.write(method(id_, resource_id, **kwargs))
  90. return
  91. if id_ is not None:
  92. # read a single document
  93. self.write(self.db.get(self.collection, id_))
  94. else:
  95. # return an object containing the list of all objects in the collection;
  96. # e.g.: {'events': [{'_id': 'obj1-id, ...}, {'_id': 'obj2-id, ...}, ...]}
  97. # Please, never return JSON lists that are not encapsulated into an object,
  98. # to avoid XSS vulnerabilities.
  99. self.write({self.collection: self.db.query(self.collection)})
  100. @gen.coroutine
  101. def post(self, id_=None, resource=None, resource_id=None, **kwargs):
  102. data = escape.json_decode(self.request.body or '{}')
  103. if resource:
  104. # Handle access to sub-resources.
  105. method = getattr(self, 'handle_%s_%s' % (self.request.method.lower(), resource), None)
  106. if method and callable(method):
  107. self.write(method(id_, resource_id, data, **kwargs))
  108. return
  109. if id_ is None:
  110. newData = self.db.add(self.collection, data)
  111. else:
  112. merged, newData = self.db.update(self.collection, id_, data)
  113. self.write(newData)
  114. # PUT (update an existing document) is handled by the POST (create a new document) method
  115. put = post
  116. @gen.coroutine
  117. def delete(self, id_=None, resource=None, resource_id=None, **kwargs):
  118. if resource:
  119. # Handle access to sub-resources.
  120. method = getattr(self, 'handle_delete_%s' % resource, None)
  121. if method and callable(method):
  122. self.write(method(id_, resource_id, **kwargs))
  123. return
  124. if id_:
  125. self.db.delete(self.collection, id_)
  126. self.write({'success': True})
  127. def run_command(self, cmd, callback=None):
  128. """Execute the given action.
  129. :param cmd: the command to be run with its command line arguments
  130. :type cmd: list
  131. """
  132. self.ioloop = tornado.ioloop.IOLoop.instance()
  133. p = subprocess.Popen(cmd, close_fds=True,
  134. stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  135. self.ioloop.add_handler(p.stdout.fileno(),
  136. self.async_callback(self.on_response, callback, p), self.ioloop.READ)
  137. # also set a timeout
  138. self.timeout = self.ioloop.add_timeout(datetime.timedelta(seconds=PROCESS_TIMEOUT),
  139. lambda: self.on_timeout(callback, p))
  140. def on_timeout(self, callback, pipe, *args):
  141. """Kill a process that is taking too long to complete."""
  142. pipe.kill()
  143. callback((None, 'killed process pid:%d' % pipe.pid))
  144. def on_response(self, callback, pipe, fd, events):
  145. """Handle the execution of a script."""
  146. self.ioloop.remove_timeout(self.timeout)
  147. stdoutdata, stderrdata = pipe.communicate()
  148. callback((pipe.returncode, stdoutdata))
  149. self.ioloop.remove_handler(fd)
  150. @gen.coroutine
  151. def run_triggers(self, action):
  152. """Asynchronously execute triggers for the given action.
  153. :param action: action name; scripts in directory ./data/triggers/{action}.d will be run
  154. :type action: str
  155. """
  156. for script in glob.glob(os.path.join(self.data_dir, 'triggers', '%s.d' % action, '*')):
  157. if not (os.path.isfile(script) and os.access(script, os.X_OK)):
  158. continue
  159. ret, resp = yield gen.Task(self.run_command, [script])
  160. class PersonsHandler(CollectionHandler):
  161. """Handle requests for Persons."""
  162. collection = 'persons'
  163. object_id = 'person_id'
  164. def handle_get_events(self, id_, resource_id=None, **kwargs):
  165. # Get a list of events attended by this person.
  166. # Inside the data of each event, a 'person_data' dictionary is
  167. # created, duplicating the entry for the current person (so that
  168. # there's no need to parse the 'persons' list on the client).
  169. #
  170. # If resource_id is given, only the specified event is considered.
  171. #
  172. # If the 'all' parameter is given, every event (also unattended ones) is returned.
  173. args = self.request.arguments
  174. query = {}
  175. if id_ and not self.tobool(args.get('all')):
  176. query = {'persons.person_id': id_}
  177. if resource_id:
  178. query['_id'] = resource_id
  179. events = self.db.query('events', query)
  180. for event in events:
  181. person_data = {}
  182. for persons in event.get('persons') or []:
  183. if str(persons.get('person_id')) == id_:
  184. person_data = persons
  185. break
  186. event['person_data'] = person_data
  187. if resource_id and events:
  188. return events[0]
  189. return {'events': events}
  190. class EventsHandler(CollectionHandler):
  191. """Handle requests for Events."""
  192. collection = 'events'
  193. object_id = 'event_id'
  194. def handle_get_persons(self, id_, resource_id=None):
  195. # Return every person registered at this event, or the information
  196. # about a specific person.
  197. query = {'_id': id_}
  198. event = self.db.query('events', query)[0]
  199. if resource_id:
  200. for person in event.get('persons', []):
  201. if str(person.get('person_id')) == resource_id:
  202. return {'person': person}
  203. if resource_id:
  204. return {'person': {}}
  205. persons = self._filter_results(event.get('persons') or [], self.arguments)
  206. return {'persons': persons}
  207. def handle_post_persons(self, id_, person_id, data):
  208. # Add a person to the list of persons registered at this event.
  209. doc = self.db.query('events',
  210. {'_id': id_, 'persons.person_id': person_id})
  211. if '_id' in data:
  212. del data['_id']
  213. if not doc:
  214. merged, doc = self.db.update('events',
  215. {'_id': id_},
  216. {'persons': data},
  217. operation='append',
  218. create=False)
  219. return {'event': doc}
  220. def handle_put_persons(self, id_, person_id, data):
  221. # Update an existing entry for a person registered at this event.
  222. query = dict([('persons.%s' % k, v) for k, v in self.arguments.iteritems()])
  223. query['_id'] = id_
  224. if person_id is not None:
  225. query['persons.person_id'] = person_id
  226. merged, doc = self.db.update('events', query,
  227. data, updateList='persons', create=False)
  228. return {'event': doc}
  229. def handle_delete_persons(self, id_, person_id):
  230. # Remove a specific person from the list of persons registered at this event.
  231. merged, doc = self.db.update('events',
  232. {'_id': id_},
  233. {'persons': {'person_id': person_id}},
  234. operation='delete',
  235. create=False)
  236. return {'event': doc}
  237. class EbCSVImportPersonsHandler(BaseHandler):
  238. """Importer for CSV files exported from eventbrite."""
  239. csvRemap = {
  240. 'Nome evento': 'event_title',
  241. 'ID evento': 'event_id',
  242. 'N. codice a barre': 'ebqrcode',
  243. 'Cognome acquirente': 'surname',
  244. 'Nome acquirente': 'name',
  245. 'E-mail acquirente': 'email',
  246. 'Cognome': 'surname',
  247. 'Nome': 'name',
  248. 'E-mail': 'email',
  249. 'Indirizzo e-mail': 'email',
  250. 'Tipologia biglietto': 'ticket_kind',
  251. 'Data partecipazione': 'attending_datetime',
  252. 'Data check-in': 'checkin_datetime',
  253. 'Ordine n.': 'order_nr',
  254. 'ID ordine': 'order_nr',
  255. 'Prefisso (Sig., Sig.ra, ecc.)': 'name_title',
  256. }
  257. keepPersonData = ('name', 'surname', 'email', 'name_title')
  258. @gen.coroutine
  259. def post(self, **kwargs):
  260. targetEvent = None
  261. try:
  262. targetEvent = self.get_body_argument('targetEvent')
  263. except:
  264. pass
  265. reply = dict(total=0, valid=0, merged=0, new_in_event=0)
  266. for fieldname, contents in self.request.files.iteritems():
  267. for content in contents:
  268. filename = content['filename']
  269. parseStats, persons = utils.csvParse(content['body'], remap=self.csvRemap)
  270. reply['total'] += parseStats['total']
  271. reply['valid'] += parseStats['valid']
  272. for person in persons:
  273. person_data = dict([(k, person[k]) for k in self.keepPersonData
  274. if k in person])
  275. merged, person = self.db.update('persons',
  276. [('email',), ('name', 'surname')],
  277. person_data)
  278. if merged:
  279. reply['merged'] += 1
  280. if targetEvent and person:
  281. event_id = targetEvent
  282. person_id = person['_id']
  283. registered_data = {
  284. 'person_id': person_id,
  285. 'attended': False,
  286. 'from_file': filename}
  287. person.update(registered_data)
  288. if not self.db.query('events',
  289. {'_id': event_id, 'persons.person_id': person_id}):
  290. self.db.update('events', {'_id': event_id},
  291. {'persons': person},
  292. operation='appendUnique')
  293. reply['new_in_event'] += 1
  294. self.write(reply)
  295. def run():
  296. """Run the Tornado web application."""
  297. # command line arguments; can also be written in a configuration file,
  298. # specified with the --config argument.
  299. define("port", default=5242, help="run on the given port", type=int)
  300. define("data", default=os.path.join(os.path.dirname(__file__), "data"),
  301. help="specify the directory used to store the data")
  302. define("mongodbURL", default=None,
  303. help="URL to MongoDB server", type=str)
  304. define("dbName", default='eventman',
  305. help="Name of the MongoDB database to use", type=str)
  306. define("debug", default=False, help="run in debug mode")
  307. define("config", help="read configuration file",
  308. callback=lambda path: tornado.options.parse_config_file(path, final=False))
  309. tornado.options.parse_command_line()
  310. # database backend connector
  311. db_connector = backend.EventManDB(url=options.mongodbURL, dbName=options.dbName)
  312. init_params = dict(db=db_connector, data_dir=options.data)
  313. application = tornado.web.Application([
  314. (r"/persons/?(?P<id_>\w+)?/?(?P<resource>\w+)?/?(?P<resource_id>\w+)?", PersonsHandler, init_params),
  315. (r"/events/?(?P<id_>\w+)?/?(?P<resource>\w+)?/?(?P<resource_id>\w+)?", EventsHandler, init_params),
  316. (r"/(?:index.html)?", RootHandler, init_params),
  317. (r"/ebcsvpersons", EbCSVImportPersonsHandler, init_params),
  318. (r'/(.*)', tornado.web.StaticFileHandler, {"path": "angular_app"})
  319. ],
  320. template_path=os.path.join(os.path.dirname(__file__), "templates"),
  321. static_path=os.path.join(os.path.dirname(__file__), "static"),
  322. debug=options.debug)
  323. http_server = tornado.httpserver.HTTPServer(application)
  324. http_server.listen(options.port)
  325. tornado.ioloop.IOLoop.instance().start()
  326. if __name__ == '__main__':
  327. run()