eventman_server.py 15 KB

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