eventman_server.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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 re
  17. import glob
  18. import json
  19. import logging
  20. import datetime
  21. import tornado.httpserver
  22. import tornado.ioloop
  23. import tornado.options
  24. from tornado.options import define, options
  25. import tornado.web
  26. import tornado.websocket
  27. from tornado import gen, escape, process
  28. import utils
  29. import backend
  30. ENCODING = 'utf-8'
  31. PROCESS_TIMEOUT = 60
  32. re_env_key = re.compile('[^A-Z_]+')
  33. re_slashes = re.compile(r'//+')
  34. class BaseHandler(tornado.web.RequestHandler):
  35. """Base class for request handlers."""
  36. # A property to access the first value of each argument.
  37. arguments = property(lambda self: dict([(k, v[0])
  38. for k, v in self.request.arguments.iteritems()]))
  39. _bool_convert = {
  40. '0': False,
  41. 'n': False,
  42. 'f': False,
  43. 'no': False,
  44. 'off': False,
  45. 'false': False,
  46. '1': True,
  47. 'y': True,
  48. 't': True,
  49. 'on': True,
  50. 'yes': True,
  51. 'true': True
  52. }
  53. def tobool(self, obj):
  54. if isinstance(obj, (list, tuple)):
  55. obj = obj[0]
  56. if isinstance(obj, (str, unicode)):
  57. obj = obj.lower()
  58. return self._bool_convert.get(obj, obj)
  59. def _arguments_tobool(self):
  60. return dict([(k, self.tobool(v)) for k, v in self.arguments.iteritems()])
  61. def initialize(self, **kwargs):
  62. """Add every passed (key, value) as attributes of the instance."""
  63. for key, value in kwargs.iteritems():
  64. setattr(self, key, value)
  65. def get_current_user(self):
  66. """Retrieve current user from the secure cookie."""
  67. return self.get_secure_cookie("user")
  68. def logout(self):
  69. """Remove the secure cookie used fro authentication."""
  70. self.clear_cookie("user")
  71. class RootHandler(BaseHandler):
  72. """Handler for the / path."""
  73. angular_app_path = os.path.join(os.path.dirname(__file__), "angular_app")
  74. @gen.coroutine
  75. @tornado.web.authenticated
  76. def get(self, *args, **kwargs):
  77. # serve the ./angular_app/index.html file
  78. with open(self.angular_app_path + "/index.html", 'r') as fd:
  79. self.write(fd.read())
  80. # Keep track of WebSocket connections.
  81. _ws_clients = {}
  82. class CollectionHandler(BaseHandler):
  83. """Base class for handlers that need to interact with the database backend.
  84. Introduce basic CRUD operations."""
  85. # set of documents we're managing (a collection in MongoDB or a table in a SQL database)
  86. collection = None
  87. # set of documents used to store incremental sequences
  88. counters_collection = 'counters'
  89. def get_next_seq(self, seq):
  90. """Increment and return the new value of a ever-incrementing counter.
  91. :param seq: unique name of the sequence
  92. :type seq: str
  93. :return: the next value of the sequence
  94. :rtype: int
  95. """
  96. if not self.db.query(self.counters_collection, {'seq_name': seq}):
  97. self.db.add(self.counters_collection, {'seq_name': seq, 'seq': 0})
  98. merged, doc = self.db.update(self.counters_collection,
  99. {'seq_name': seq},
  100. {'seq': 1},
  101. operation='increment')
  102. return doc.get('seq', 0)
  103. def _filter_results(self, results, params):
  104. """Filter a list using keys and values from a dictionary.
  105. :param results: the list to be filtered
  106. :type results: list
  107. :param params: a dictionary of items that must all be present in an original list item to be included in the return
  108. :return: list of items that have all the keys with the same values as params
  109. :rtype: list"""
  110. if not params:
  111. return results
  112. filtered = []
  113. for result in results:
  114. add = True
  115. for key, value in params.iteritems():
  116. if key not in result or result[key] != value:
  117. add = False
  118. break
  119. if add:
  120. filtered.append(result)
  121. return filtered
  122. def _dict2env(self, data):
  123. """Convert a dictionary into a form suitable to be passed as environment variables."""
  124. ret = {}
  125. for key, value in data.iteritems():
  126. if isinstance(value, (list, tuple, dict)):
  127. continue
  128. try:
  129. key = key.upper().encode('ascii', 'ignore')
  130. key = re_env_key.sub('', key)
  131. if not key:
  132. continue
  133. ret[key] = unicode(value).encode(ENCODING)
  134. except:
  135. continue
  136. return ret
  137. @gen.coroutine
  138. @tornado.web.authenticated
  139. def get(self, id_=None, resource=None, resource_id=None, **kwargs):
  140. if resource:
  141. # Handle access to sub-resources.
  142. method = getattr(self, 'handle_get_%s' % resource, None)
  143. if method and callable(method):
  144. self.write(method(id_, resource_id, **kwargs))
  145. return
  146. if id_ is not None:
  147. # read a single document
  148. self.write(self.db.get(self.collection, id_))
  149. else:
  150. # return an object containing the list of all objects in the collection;
  151. # e.g.: {'events': [{'_id': 'obj1-id, ...}, {'_id': 'obj2-id, ...}, ...]}
  152. # Please, never return JSON lists that are not encapsulated into an object,
  153. # to avoid XSS vulnerabilities.
  154. self.write({self.collection: self.db.query(self.collection)})
  155. @gen.coroutine
  156. @tornado.web.authenticated
  157. def post(self, id_=None, resource=None, resource_id=None, **kwargs):
  158. data = escape.json_decode(self.request.body or '{}')
  159. if resource:
  160. # Handle access to sub-resources.
  161. method = getattr(self, 'handle_%s_%s' % (self.request.method.lower(), resource), None)
  162. if method and callable(method):
  163. self.write(method(id_, resource_id, data, **kwargs))
  164. return
  165. if id_ is None:
  166. newData = self.db.add(self.collection, data)
  167. else:
  168. merged, newData = self.db.update(self.collection, id_, data)
  169. self.write(newData)
  170. # PUT (update an existing document) is handled by the POST (create a new document) method
  171. put = post
  172. @gen.coroutine
  173. @tornado.web.authenticated
  174. def delete(self, id_=None, resource=None, resource_id=None, **kwargs):
  175. if resource:
  176. # Handle access to sub-resources.
  177. method = getattr(self, 'handle_delete_%s' % resource, None)
  178. if method and callable(method):
  179. self.write(method(id_, resource_id, **kwargs))
  180. return
  181. if id_:
  182. self.db.delete(self.collection, id_)
  183. self.write({'success': True})
  184. def on_timeout(self, cmd, pipe):
  185. """Kill a process that is taking too long to complete."""
  186. logging.debug('cmd %s is taking too long: killing it' % ' '.join(cmd))
  187. try:
  188. pipe.proc.kill()
  189. except:
  190. pass
  191. def on_exit(self, returncode, cmd, pipe):
  192. """Callback executed when a subprocess execution is over."""
  193. self.ioloop.remove_timeout(self.timeout)
  194. logging.debug('cmd: %s returncode: %d' % (' '.join(cmd), returncode))
  195. @gen.coroutine
  196. def run_subprocess(self, cmd, stdin_data=None, env=None):
  197. """Execute the given action.
  198. :param cmd: the command to be run with its command line arguments
  199. :type cmd: list
  200. :param stdin_data: data to be sent over stdin
  201. :type stdin_data: str
  202. :param env: environment of the process
  203. :type env: dict
  204. """
  205. self.ioloop = tornado.ioloop.IOLoop.instance()
  206. p = process.Subprocess(cmd, close_fds=True, stdin=process.Subprocess.STREAM,
  207. stdout=process.Subprocess.STREAM, stderr=process.Subprocess.STREAM, env=env)
  208. p.set_exit_callback(lambda returncode: self.on_exit(returncode, cmd, p))
  209. self.timeout = self.ioloop.add_timeout(datetime.timedelta(seconds=PROCESS_TIMEOUT),
  210. lambda: self.on_timeout(cmd, p))
  211. yield gen.Task(p.stdin.write, stdin_data or '')
  212. p.stdin.close()
  213. out, err = yield [gen.Task(p.stdout.read_until_close),
  214. gen.Task(p.stderr.read_until_close)]
  215. logging.debug('cmd: %s' % ' '.join(cmd))
  216. logging.debug('cmd stdout: %s' % out)
  217. logging.debug('cmd strerr: %s' % err)
  218. raise gen.Return((out, err))
  219. @gen.coroutine
  220. def run_triggers(self, action, stdin_data=None, env=None):
  221. """Asynchronously execute triggers for the given action.
  222. :param action: action name; scripts in directory ./data/triggers/{action}.d will be run
  223. :type action: str
  224. :param stdin_data: a python dictionary that will be serialized in JSON and sent to the process over stdin
  225. :type stdin_data: dict
  226. :param env: environment of the process
  227. :type stdin_data: dict
  228. """
  229. logging.debug('running triggers for action "%s"' % action)
  230. stdin_data = stdin_data or {}
  231. try:
  232. stdin_data = json.dumps(stdin_data)
  233. except:
  234. stdin_data = '{}'
  235. for script in glob.glob(os.path.join(self.data_dir, 'triggers', '%s.d' % action, '*')):
  236. if not (os.path.isfile(script) and os.access(script, os.X_OK)):
  237. continue
  238. out, err = yield gen.Task(self.run_subprocess, [script], stdin_data, env)
  239. def build_ws_url(self, path, proto='ws', host=None):
  240. """Return a WebSocket url from a path."""
  241. return 'ws://127.0.0.1:%s/ws/%s' % (self.listen_port + 1, path)
  242. @gen.coroutine
  243. def send_ws_message(self, path, message):
  244. """Send a WebSocket message to all the connected clients.
  245. :param path: partial path used to build the WebSocket url
  246. :type path: str
  247. :param message: message to send
  248. :type message: str
  249. """
  250. ws = yield tornado.websocket.websocket_connect(self.build_ws_url(path))
  251. ws.write_message(message)
  252. ws.close()
  253. class PersonsHandler(CollectionHandler):
  254. """Handle requests for Persons."""
  255. collection = 'persons'
  256. object_id = 'person_id'
  257. def handle_get_events(self, id_, resource_id=None, **kwargs):
  258. # Get a list of events attended by this person.
  259. # Inside the data of each event, a 'person_data' dictionary is
  260. # created, duplicating the entry for the current person (so that
  261. # there's no need to parse the 'persons' list on the client).
  262. #
  263. # If resource_id is given, only the specified event is considered.
  264. #
  265. # If the 'all' parameter is given, every event (also unattended ones) is returned.
  266. args = self.request.arguments
  267. query = {}
  268. if id_ and not self.tobool(args.get('all')):
  269. query = {'persons.person_id': id_}
  270. if resource_id:
  271. query['_id'] = resource_id
  272. events = self.db.query('events', query)
  273. for event in events:
  274. person_data = {}
  275. for persons in event.get('persons') or []:
  276. if str(persons.get('person_id')) == id_:
  277. person_data = persons
  278. break
  279. event['person_data'] = person_data
  280. if resource_id and events:
  281. return events[0]
  282. return {'events': events}
  283. class EventsHandler(CollectionHandler):
  284. """Handle requests for Events."""
  285. collection = 'events'
  286. object_id = 'event_id'
  287. def _get_person_data(self, person_id_or_query, persons):
  288. """Filter a list of persons returning the first item with a given person_id
  289. or which set of keys specified in a dictionary match their respective values."""
  290. for person in persons:
  291. if isinstance(person_id_or_query, dict):
  292. if all(person.get(k) == v for k, v in person_id_or_query.iteritems()):
  293. return person
  294. else:
  295. if str(person.get('person_id')) == person_id_or_query:
  296. return person
  297. return {}
  298. def handle_get_persons(self, id_, resource_id=None):
  299. # Return every person registered at this event, or the information
  300. # about a specific person.
  301. query = {'_id': id_}
  302. event = self.db.query('events', query)[0]
  303. if resource_id:
  304. return {'person': self._get_person_data(resource_id, event.get('persons') or [])}
  305. persons = self._filter_results(event.get('persons') or [], self.arguments)
  306. return {'persons': persons}
  307. def handle_post_persons(self, id_, person_id, data):
  308. # Add a person to the list of persons registered at this event.
  309. data['seq'] = self.get_next_seq('event_%s_persons' % id_)
  310. data['seq_hex'] = '%06X' % data['seq']
  311. doc = self.db.query('events',
  312. {'_id': id_, 'persons.person_id': person_id})
  313. if '_id' in data:
  314. del data['_id']
  315. if not doc:
  316. merged, doc = self.db.update('events',
  317. {'_id': id_},
  318. {'persons': data},
  319. operation='appendUnique',
  320. create=False)
  321. return {'event': doc}
  322. def handle_put_persons(self, id_, person_id, data):
  323. # Update an existing entry for a person registered at this event.
  324. query = dict([('persons.%s' % k, v) for k, v in self.arguments.iteritems()])
  325. query['_id'] = id_
  326. if person_id is not None:
  327. query['persons.person_id'] = person_id
  328. old_person_data = {}
  329. current_event = self.db.query(self.collection, query)
  330. if current_event:
  331. current_event = current_event[0]
  332. else:
  333. current_event = {}
  334. old_person_data = self._get_person_data(person_id or self.arguments,
  335. current_event.get('persons') or [])
  336. merged, doc = self.db.update('events', query,
  337. data, updateList='persons', create=False)
  338. new_person_data = self._get_person_data(person_id or self.arguments,
  339. doc.get('persons') or [])
  340. env = self._dict2env(new_person_data)
  341. if person_id is None:
  342. person_id = str(new_person_data.get('person_id'))
  343. env.update({'PERSON_ID': person_id, 'EVENT_ID': id_, 'EVENT_TITLE': doc.get('title', '')})
  344. stdin_data = {'old': old_person_data,
  345. 'new': new_person_data,
  346. 'event': doc,
  347. 'merged': merged
  348. }
  349. self.run_triggers('update_person_in_event', stdin_data=stdin_data, env=env)
  350. if old_person_data and old_person_data.get('attended') != new_person_data.get('attended'):
  351. if new_person_data.get('attended'):
  352. self.run_triggers('attends', stdin_data=stdin_data, env=env)
  353. if old_person_data != new_person_data:
  354. self.send_ws_message('event/%s/updates' % id_,
  355. json.dumps(doc.get('persons') or []))
  356. return {'event': doc}
  357. def handle_delete_persons(self, id_, person_id):
  358. # Remove a specific person from the list of persons registered at this event.
  359. merged, doc = self.db.update('events',
  360. {'_id': id_},
  361. {'persons': {'person_id': person_id}},
  362. operation='delete',
  363. create=False)
  364. return {'event': doc}
  365. class EbCSVImportPersonsHandler(BaseHandler):
  366. """Importer for CSV files exported from eventbrite."""
  367. csvRemap = {
  368. 'Nome evento': 'event_title',
  369. 'ID evento': 'event_id',
  370. 'N. codice a barre': 'ebqrcode',
  371. 'Cognome acquirente': 'surname',
  372. 'Nome acquirente': 'name',
  373. 'E-mail acquirente': 'email',
  374. 'Cognome': 'surname',
  375. 'Nome': 'name',
  376. 'E-mail': 'email',
  377. 'Indirizzo e-mail': 'email',
  378. 'Tipologia biglietto': 'ticket_kind',
  379. 'Data partecipazione': 'attending_datetime',
  380. 'Data check-in': 'checkin_datetime',
  381. 'Ordine n.': 'order_nr',
  382. 'ID ordine': 'order_nr',
  383. 'Titolo professionale': 'job_title',
  384. 'Azienda': 'company',
  385. 'Prefisso': 'name_title',
  386. 'Prefisso (Sig., Sig.ra, ecc.)': 'name_title',
  387. 'Order #': 'order_nr',
  388. 'Prefix': 'name_title',
  389. 'First Name': 'name',
  390. 'Last Name': 'surname',
  391. 'Suffix': 'name_suffix',
  392. 'Email': 'email',
  393. 'Attendee #': 'attendee_nr',
  394. 'Barcode #': 'ebqrcode',
  395. 'Company': 'company',
  396. }
  397. # Only these information are stored in the person collection.
  398. keepPersonData = ('name', 'surname', 'email', 'name_title', 'name_suffix',
  399. 'company', 'job_title')
  400. @gen.coroutine
  401. @tornado.web.authenticated
  402. def post(self, **kwargs):
  403. event_handler = EventsHandler(self.application, self.request)
  404. event_handler.db = self.db
  405. targetEvent = None
  406. try:
  407. targetEvent = self.get_body_argument('targetEvent')
  408. except:
  409. pass
  410. reply = dict(total=0, valid=0, merged=0, new_in_event=0)
  411. for fieldname, contents in self.request.files.iteritems():
  412. for content in contents:
  413. filename = content['filename']
  414. parseStats, persons = utils.csvParse(content['body'], remap=self.csvRemap)
  415. reply['total'] += parseStats['total']
  416. reply['valid'] += parseStats['valid']
  417. for person in persons:
  418. person_data = dict([(k, person[k]) for k in self.keepPersonData
  419. if k in person])
  420. merged, stored_person = self.db.update('persons',
  421. [('email', 'name', 'surname')],
  422. person_data)
  423. if merged:
  424. reply['merged'] += 1
  425. if targetEvent and stored_person:
  426. event_id = targetEvent
  427. person_id = stored_person['_id']
  428. registered_data = {
  429. 'person_id': person_id,
  430. 'attended': False,
  431. 'from_file': filename}
  432. person.update(registered_data)
  433. if not self.db.query('events',
  434. {'_id': event_id, 'persons.person_id': person_id}):
  435. event_handler.handle_post_persons(event_id, person_id, person)
  436. reply['new_in_event'] += 1
  437. self.write(reply)
  438. class SettingsHandler(BaseHandler):
  439. """Handle requests for Settings."""
  440. @gen.coroutine
  441. @tornado.web.authenticated
  442. def get(self, **kwds):
  443. query = self._arguments_tobool()
  444. settings = self.db.query('settings', query)
  445. self.write({'settings': settings})
  446. class WebSocketEventUpdatesHandler(tornado.websocket.WebSocketHandler):
  447. def _clean_url(self, url):
  448. return re_slashes.sub('/', url)
  449. def open(self, event_id, *args, **kwds):
  450. logging.debug('WebSocketEventUpdatesHandler.on_open event_id:%s' % event_id)
  451. _ws_clients.setdefault(self._clean_url(self.request.uri), set()).add(self)
  452. logging.debug('WebSocketEventUpdatesHandler.on_open %s clients connected' % len(_ws_clients))
  453. def on_message(self, message):
  454. logging.debug('WebSocketEventUpdatesHandler.on_message')
  455. count = 0
  456. for client in _ws_clients.get(self._clean_url(self.request.uri), []):
  457. if client == self:
  458. continue
  459. client.write_message(message)
  460. count += 1
  461. logging.debug('WebSocketEventUpdatesHandler.on_message sent message to %d clients' % count)
  462. def on_close(self):
  463. logging.debug('WebSocketEventUpdatesHandler.on_close')
  464. try:
  465. if self in _ws_clients.get(self._clean_url(self.request.uri), []):
  466. _ws_clients[self._clean_url(self.request.uri)].remove(self)
  467. except Exception, e:
  468. logging.warn('WebSocketEventUpdatesHandler.on_close error closing websocket: %s', str(e))
  469. class LoginHandler(RootHandler):
  470. """Handle user authentication requests."""
  471. re_split_salt = re.compile(r'\$(?P<salt>.+)\$(?P<hash>.+)')
  472. @gen.coroutine
  473. def get(self, **kwds):
  474. with open(self.angular_app_path + "/login.html", 'r') as fd:
  475. self.write(fd.read())
  476. def _authorize(self, username, password):
  477. res = self.db.query('users', {'username': username})
  478. if not res:
  479. return False
  480. user = res[0]
  481. db_password = user.get('password') or ''
  482. if not db_password:
  483. return False
  484. match = self.re_split_salt.match(db_password)
  485. if not match:
  486. return False
  487. salt = match.group('salt')
  488. if utils.hash_password(password, salt=salt) == db_password:
  489. return True
  490. return False
  491. @gen.coroutine
  492. def post(self):
  493. username = self.get_body_argument('username')
  494. password = self.get_body_argument('password')
  495. if self._authorize(username, password):
  496. self.set_secure_cookie("user", username)
  497. self.redirect('/')
  498. self.redirect('/login?failed=1')
  499. class LogoutHandler(RootHandler):
  500. """Handle user logout requests."""
  501. @gen.coroutine
  502. def get(self, **kwds):
  503. self.logout()
  504. self.redirect('/login')
  505. def run():
  506. """Run the Tornado web application."""
  507. # command line arguments; can also be written in a configuration file,
  508. # specified with the --config argument.
  509. define("port", default=5242, help="run on the given port", type=int)
  510. define("data", default=os.path.join(os.path.dirname(__file__), "data"),
  511. help="specify the directory used to store the data")
  512. define("ssl_cert", default=os.path.join(os.path.dirname(__file__), 'ssl', 'eventman_cert.pem'),
  513. help="specify the SSL certificate to use for secure connections")
  514. define("ssl_key", default=os.path.join(os.path.dirname(__file__), 'ssl', 'eventman_key.pem'),
  515. help="specify the SSL private key to use for secure connections")
  516. define("mongodbURL", default=None,
  517. help="URL to MongoDB server", type=str)
  518. define("dbName", default='eventman',
  519. help="Name of the MongoDB database to use", type=str)
  520. define("debug", default=False, help="run in debug mode")
  521. define("config", help="read configuration file",
  522. callback=lambda path: tornado.options.parse_config_file(path, final=False))
  523. tornado.options.parse_command_line()
  524. if options.debug:
  525. logger = logging.getLogger()
  526. logger.setLevel(logging.DEBUG)
  527. # database backend connector
  528. db_connector = backend.EventManDB(url=options.mongodbURL, dbName=options.dbName)
  529. init_params = dict(db=db_connector, data_dir=options.data, listen_port=options.port)
  530. # If not present, we store a user 'admin' with password 'eventman' into the database.
  531. if not db_connector.query('users', {'username': 'admin'}):
  532. db_connector.add('users',
  533. {'username': 'admin', 'password': utils.hash_password('eventman')})
  534. _ws_handler = (r"/ws/+event/+(?P<event_id>\w+)/+updates/?", WebSocketEventUpdatesHandler)
  535. application = tornado.web.Application([
  536. (r"/persons/?(?P<id_>\w+)?/?(?P<resource>\w+)?/?(?P<resource_id>\w+)?", PersonsHandler, init_params),
  537. (r"/events/?(?P<id_>\w+)?/?(?P<resource>\w+)?/?(?P<resource_id>\w+)?", EventsHandler, init_params),
  538. (r"/(?:index.html)?", RootHandler, init_params),
  539. (r"/ebcsvpersons", EbCSVImportPersonsHandler, init_params),
  540. (r"/settings", SettingsHandler, init_params),
  541. _ws_handler,
  542. (r'/login', LoginHandler, init_params),
  543. (r'/logout', LogoutHandler),
  544. (r'/(.*)', tornado.web.StaticFileHandler, {"path": "angular_app"})
  545. ],
  546. template_path=os.path.join(os.path.dirname(__file__), "templates"),
  547. static_path=os.path.join(os.path.dirname(__file__), "static"),
  548. cookie_secret='__COOKIE_SECRET__',
  549. login_url='/login',
  550. debug=options.debug)
  551. ssl_options = {}
  552. if os.path.isfile(options.ssl_key) and os.path.isfile(options.ssl_cert):
  553. ssl_options = dict(certfile=options.ssl_cert, keyfile=options.ssl_key)
  554. http_server = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options or None)
  555. http_server.listen(options.port)
  556. # Also listen on options.port+1 for our local ws connection.
  557. ws_application = tornado.web.Application([
  558. _ws_handler,
  559. ],
  560. debug=options.debug)
  561. ws_http_server = tornado.httpserver.HTTPServer(ws_application)
  562. ws_http_server.listen(options.port+1, address='127.0.0.1')
  563. tornado.ioloop.IOLoop.instance().start()
  564. if __name__ == '__main__':
  565. run()