eventman_server.py 9.9 KB

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