eventman_server.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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, **kwargs):
  45. if resource:
  46. method = getattr(self, 'handle_%s' % resource, None)
  47. if method and callable(method):
  48. try:
  49. self.write(method(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, **kwargs):
  64. data = escape.json_decode(self.request.body or {})
  65. if id_ is None:
  66. # insert a new document
  67. newData = self.db.add(self.collection, data)
  68. else:
  69. # update an existing document
  70. newData = self.db.update(self.collection, id_, data)
  71. self.write(newData)
  72. # PUT (update an existing document) is handled by the POST (create a new document) method
  73. put = post
  74. @gen.coroutine
  75. def delete(self, id_=None, **kwargs):
  76. self.db.delete(self.collection, id_)
  77. class PersonsHandler(CollectionHandler):
  78. """Handle requests for Persons."""
  79. collection = 'persons'
  80. def handle_events(self, _id, **kwds):
  81. return {'events': []}
  82. class EventsHandler(CollectionHandler):
  83. """Handle requests for Events."""
  84. collection = 'events'
  85. class ActionsHandler(CollectionHandler):
  86. """Handle requests for Actions."""
  87. collection = 'actions'
  88. def get(self, *args, **kwargs):
  89. params = self.request.arguments or {}
  90. if 'event_id' in params:
  91. params['event_id'] = self.db.toID(params['event_id'][0])
  92. if 'person_id' in params:
  93. params['person_id'] = self.db.toID(params['person_id'][0])
  94. data = self.db.query(self.collection, params)
  95. self.write({'actions': data})
  96. class EbCSVImportPersonsHandler(BaseHandler):
  97. """Importer for CSV files exported from eventbrite."""
  98. csvRemap = {
  99. 'Nome evento': 'event_title',
  100. 'ID evento': 'event_id',
  101. 'N. codice a barre': 'ebqrcode',
  102. 'Cognome acquirente': 'surname',
  103. 'Nome acquirente': 'name',
  104. 'E-mail acquirente': 'email',
  105. 'Cognome': 'original_surname',
  106. 'Nome': 'original_name',
  107. 'E-mail': 'original_email',
  108. 'Tipologia biglietto': 'ticket_kind',
  109. 'Data partecipazione': 'attending_datetime',
  110. 'Data check-in': 'checkin_datetime',
  111. 'Ordine n.': 'order_nr',
  112. }
  113. @gen.coroutine
  114. def post(self, **kwargs):
  115. targetEvent = None
  116. try:
  117. targetEvent = self.get_body_argument('targetEvent')
  118. except:
  119. pass
  120. reply = dict(total=0, valid=0, merged=0)
  121. for fieldname, contents in self.request.files.iteritems():
  122. for content in contents:
  123. filename = content['filename']
  124. parseStats, persons = utils.csvParse(content['body'], remap=self.csvRemap)
  125. reply['total'] += parseStats['total']
  126. reply['valid'] += parseStats['valid']
  127. for person in persons:
  128. merged, _id = self.db.merge('persons', person,
  129. searchBy=[('email',), ('name', 'surname')])
  130. if merged:
  131. reply['merged'] += 1
  132. if targetEvent and _id:
  133. registered_data = {
  134. 'event_id': self.db.toID(targetEvent),
  135. 'person_id': self.db.toID(_id),
  136. 'action': 'registered',
  137. 'from_file': filename}
  138. self.db.insertOne('actions', registered_data)
  139. self.write(reply)
  140. def run():
  141. """Run the Tornado web application."""
  142. # command line arguments; can also be written in a configuration file,
  143. # specified with the --config argument.
  144. define("port", default=5242, help="run on the given port", type=int)
  145. define("data", default=os.path.join(os.path.dirname(__file__), "data"),
  146. help="specify the directory used to store the data")
  147. define("mongodbURL", default=None,
  148. help="URL to MongoDB server", type=str)
  149. define("dbName", default='eventman',
  150. help="Name of the MongoDB database to use", type=str)
  151. define("debug", default=False, help="run in debug mode")
  152. define("config", help="read configuration file",
  153. callback=lambda path: tornado.options.parse_config_file(path, final=False))
  154. tornado.options.parse_command_line()
  155. # database backend connector
  156. db_connector = backend.EventManDB(url=options.mongodbURL, dbName=options.dbName)
  157. init_params = dict(db=db_connector)
  158. application = tornado.web.Application([
  159. (r"/persons/?(?P<id_>\w+)?/?(?P<resource>\w+)?", PersonsHandler, init_params),
  160. (r"/events/?(?P<id_>\w+)?", EventsHandler, init_params),
  161. (r"/actions/?.*", ActionsHandler, init_params),
  162. (r"/(?:index.html)?", RootHandler, init_params),
  163. (r"/ebcsvpersons", EbCSVImportPersonsHandler, init_params),
  164. (r'/(.*)', tornado.web.StaticFileHandler, {"path": "angular_app"})
  165. ],
  166. template_path=os.path.join(os.path.dirname(__file__), "templates"),
  167. static_path=os.path.join(os.path.dirname(__file__), "static"),
  168. debug=options.debug)
  169. http_server = tornado.httpserver.HTTPServer(application)
  170. http_server.listen(options.port)
  171. tornado.ioloop.IOLoop.instance().start()
  172. if __name__ == '__main__':
  173. run()