eventman_server.py 8.2 KB

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