eventman_server.py 9.7 KB

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