eventman_server.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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 tornado.httpserver
  17. import tornado.ioloop
  18. import tornado.options
  19. from tornado.options import define, options
  20. import tornado.web
  21. from tornado import gen, escape
  22. import utils
  23. import backend
  24. class BaseHandler(tornado.web.RequestHandler):
  25. """Base class for request handlers."""
  26. _bool_convert = {
  27. '0': False,
  28. 'n': False,
  29. 'no': False,
  30. 'off': False,
  31. 'false': False
  32. }
  33. def tobool(self, obj):
  34. if isinstance(obj, (list, tuple)):
  35. obj = obj[0]
  36. if isinstance(obj, (str, unicode)):
  37. obj = obj.lower()
  38. return bool(self._bool_convert.get(obj, obj))
  39. def initialize(self, **kwargs):
  40. """Add every passed (key, value) as attributes of the instance."""
  41. for key, value in kwargs.iteritems():
  42. setattr(self, key, value)
  43. class RootHandler(BaseHandler):
  44. """Handler for the / path."""
  45. angular_app_path = os.path.join(os.path.dirname(__file__), "angular_app")
  46. @gen.coroutine
  47. def get(self, *args, **kwargs):
  48. # serve the ./angular_app/index.html file
  49. with open(self.angular_app_path + "/index.html", 'r') as fd:
  50. self.write(fd.read())
  51. class CollectionHandler(BaseHandler):
  52. """Base class for handlers that need to interact with the database backend.
  53. Introduce basic CRUD operations."""
  54. # set of documents we're managing (a collection in MongoDB or a table in a SQL database)
  55. collection = None
  56. @gen.coroutine
  57. def get(self, id_=None, resource=None, resource_id=None, **kwargs):
  58. if resource:
  59. method = getattr(self, 'handle_get_%s' % resource, None)
  60. if method and callable(method):
  61. self.write(method(id_, resource_id, **kwargs))
  62. return
  63. if id_ is not None:
  64. # read a single document
  65. self.write(self.db.get(self.collection, id_))
  66. else:
  67. # return an object containing the list of all objects in the collection;
  68. # e.g.: {'events': [{'_id': 'obj1-id, ...}, {'_id': 'obj2-id, ...}, ...]}
  69. # Please, never return JSON lists that are not encapsulated into an object,
  70. # to avoid XSS vulnerabilities.
  71. self.write({self.collection: self.db.query(self.collection)})
  72. @gen.coroutine
  73. def post(self, id_=None, resource=None, resource_id=None, **kwargs):
  74. data = escape.json_decode(self.request.body or '{}')
  75. if resource:
  76. method = getattr(self, 'handle_%s_%s' % (self.request.method.lower(), resource), None)
  77. if method and callable(method):
  78. self.write(method(id_, resource_id, data, **kwargs))
  79. return
  80. if id_ is None:
  81. newData = self.db.add(self.collection, data)
  82. else:
  83. merged, newData = self.db.update(self.collection, id_, data)
  84. self.write(newData)
  85. # PUT (update an existing document) is handled by the POST (create a new document) method
  86. put = post
  87. @gen.coroutine
  88. def delete(self, id_=None, resource=None, resource_id=None, **kwargs):
  89. if resource:
  90. method = getattr(self, 'handle_delete_%s' % resource, None)
  91. if method and callable(method):
  92. self.write(method(id_, resource_id, **kwargs))
  93. return
  94. self.db.delete(self.collection, id_)
  95. class PersonsHandler(CollectionHandler):
  96. """Handle requests for Persons."""
  97. collection = 'persons'
  98. object_id = 'person_id'
  99. def handle_get_events(self, id_, resource_id=None, **kwargs):
  100. args = self.request.arguments
  101. query = {}
  102. if id_ and not self.tobool(args.get('all')):
  103. query = {'persons.person_id': id_}
  104. if resource_id:
  105. query['_id'] = resource_id
  106. events = self.db.query('events', query)
  107. for event in events:
  108. person_data = {}
  109. for persons in event.get('persons') or []:
  110. if str(persons.get('person_id')) == id_:
  111. person_data = persons
  112. break
  113. event['person_data'] = person_data
  114. return {'events': events}
  115. class EventsHandler(CollectionHandler):
  116. """Handle requests for Events."""
  117. collection = 'events'
  118. object_id = 'event_id'
  119. def handle_get_persons(self, id_, resource_id=None):
  120. query = {'_id': id_}
  121. event = self.db.query('events', query)[0]
  122. if resource_id:
  123. for person in event.get('persons', []):
  124. if str(person.get('person_id')) == resource_id:
  125. return {'person': person}
  126. return {'persons': event.get('persons') or {}}
  127. def handle_post_persons(self, id_, person_id, data):
  128. doc = self.db.query('events',
  129. {'_id': id_, 'persons.person_id': person_id})
  130. if '_id' in data:
  131. del data['_id']
  132. if not doc:
  133. merged, doc = self.db.update('events',
  134. {'_id': id_},
  135. {'persons': data},
  136. operator='$push',
  137. create=False)
  138. return {'event': doc}
  139. def handle_put_persons(self, id_, person_id, data):
  140. merged, doc = self.db.update('events',
  141. {'_id': id_, 'persons.person_id': person_id},
  142. data, create=False)
  143. return {'event': doc}
  144. def handle_delete_persons(self, id_, person_id):
  145. merged, doc = self.db.update('events',
  146. {'_id': id_},
  147. {'persons': {'person_id': person_id}},
  148. operator='$pull',
  149. create=False)
  150. return {'event': doc}
  151. class EbCSVImportPersonsHandler(BaseHandler):
  152. """Importer for CSV files exported from eventbrite."""
  153. csvRemap = {
  154. 'Nome evento': 'event_title',
  155. 'ID evento': 'event_id',
  156. 'N. codice a barre': 'ebqrcode',
  157. 'Cognome acquirente': 'surname',
  158. 'Nome acquirente': 'name',
  159. 'E-mail acquirente': 'email',
  160. 'Cognome': 'surname',
  161. 'Nome': 'name',
  162. 'E-mail': 'email',
  163. 'Indirizzo e-mail': 'email',
  164. 'Tipologia biglietto': 'ticket_kind',
  165. 'Data partecipazione': 'attending_datetime',
  166. 'Data check-in': 'checkin_datetime',
  167. 'Ordine n.': 'order_nr',
  168. 'ID ordine': 'order_nr',
  169. 'Prefisso (Sig., Sig.ra, ecc.)': 'name_title',
  170. }
  171. keepPersonData = ('name', 'surname', 'email')
  172. @gen.coroutine
  173. def post(self, **kwargs):
  174. targetEvent = None
  175. try:
  176. targetEvent = self.get_body_argument('targetEvent')
  177. except:
  178. pass
  179. reply = dict(total=0, valid=0, merged=0, new_in_event=0)
  180. for fieldname, contents in self.request.files.iteritems():
  181. for content in contents:
  182. filename = content['filename']
  183. parseStats, persons = utils.csvParse(content['body'], remap=self.csvRemap)
  184. reply['total'] += parseStats['total']
  185. reply['valid'] += parseStats['valid']
  186. for person in persons:
  187. person_data = dict([(k, person[k]) for k in self.keepPersonData
  188. if k in person])
  189. merged, person = self.db.update('persons',
  190. [('email',), ('name', 'surname')],
  191. person_data)
  192. if merged:
  193. reply['merged'] += 1
  194. if targetEvent and person:
  195. event_id = targetEvent
  196. person_id = person['_id']
  197. registered_data = {
  198. 'person_id': person_id,
  199. 'attended': False,
  200. 'from_file': filename}
  201. person.update(registered_data)
  202. if not self.db.query('events',
  203. {'_id': event_id, 'persons.person_id': person_id}):
  204. self.db.update('events', {'_id': event_id},
  205. {'persons': person},
  206. operator='$addToSet')
  207. reply['new_in_event'] += 1
  208. self.write(reply)
  209. def run():
  210. """Run the Tornado web application."""
  211. # command line arguments; can also be written in a configuration file,
  212. # specified with the --config argument.
  213. define("port", default=5242, help="run on the given port", type=int)
  214. define("data", default=os.path.join(os.path.dirname(__file__), "data"),
  215. help="specify the directory used to store the data")
  216. define("mongodbURL", default=None,
  217. help="URL to MongoDB server", type=str)
  218. define("dbName", default='eventman',
  219. help="Name of the MongoDB database to use", type=str)
  220. define("debug", default=False, help="run in debug mode")
  221. define("config", help="read configuration file",
  222. callback=lambda path: tornado.options.parse_config_file(path, final=False))
  223. tornado.options.parse_command_line()
  224. # database backend connector
  225. db_connector = backend.EventManDB(url=options.mongodbURL, dbName=options.dbName)
  226. init_params = dict(db=db_connector)
  227. application = tornado.web.Application([
  228. (r"/persons/?(?P<id_>\w+)?/?(?P<resource>\w+)?/?(?P<resource_id>\w+)?", PersonsHandler, init_params),
  229. (r"/events/?(?P<id_>\w+)?/?(?P<resource>\w+)?/?(?P<resource_id>\w+)?", EventsHandler, init_params),
  230. (r"/(?:index.html)?", RootHandler, init_params),
  231. (r"/ebcsvpersons", EbCSVImportPersonsHandler, init_params),
  232. (r'/(.*)', tornado.web.StaticFileHandler, {"path": "angular_app"})
  233. ],
  234. template_path=os.path.join(os.path.dirname(__file__), "templates"),
  235. static_path=os.path.join(os.path.dirname(__file__), "static"),
  236. debug=options.debug)
  237. http_server = tornado.httpserver.HTTPServer(application)
  238. http_server.listen(options.port)
  239. tornado.ioloop.IOLoop.instance().start()
  240. if __name__ == '__main__':
  241. run()