eventman_server.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178
  1. #!/usr/bin/env python
  2. """EventMan(ager)
  3. Your friendly manager of attendees at an event.
  4. Copyright 2015-2016 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 time
  20. import string
  21. import random
  22. import logging
  23. import datetime
  24. import dateutil.tz
  25. import dateutil.parser
  26. import tornado.httpserver
  27. import tornado.ioloop
  28. import tornado.options
  29. from tornado.options import define, options
  30. import tornado.web
  31. import tornado.websocket
  32. from tornado import gen, escape, process
  33. import utils
  34. import backend
  35. ENCODING = 'utf-8'
  36. PROCESS_TIMEOUT = 60
  37. API_VERSION = '1.0'
  38. re_env_key = re.compile('[^A-Z_]+')
  39. re_slashes = re.compile(r'//+')
  40. # Keep track of WebSocket connections.
  41. _ws_clients = {}
  42. def authenticated(method):
  43. """Decorator to handle forced authentication."""
  44. original_wrapper = tornado.web.authenticated(method)
  45. @tornado.web.functools.wraps(method)
  46. def my_wrapper(self, *args, **kwargs):
  47. # If no authentication was required from the command line or config file.
  48. if not self.authentication:
  49. return method(self, *args, **kwargs)
  50. # unauthenticated API calls gets redirected to /v1.0/[...]
  51. if self.is_api() and not self.current_user:
  52. self.redirect('/v%s%s' % (API_VERSION, self.get_login_url()))
  53. return
  54. return original_wrapper(self, *args, **kwargs)
  55. return my_wrapper
  56. class BaseException(Exception):
  57. """Base class for EventMan custom exceptions.
  58. :param message: text message
  59. :type message: str
  60. :param status: numeric http status code
  61. :type status: int"""
  62. def __init__(self, message, status=400):
  63. super(BaseException, self).__init__(message)
  64. self.message = message
  65. self.status = status
  66. class InputException(BaseException):
  67. """Exception raised by errors in input handling."""
  68. pass
  69. class BaseHandler(tornado.web.RequestHandler):
  70. """Base class for request handlers."""
  71. permissions = {
  72. 'event|read': True,
  73. 'event:tickets|read': True,
  74. 'event:tickets|create': True,
  75. 'event:tickets|update': True,
  76. 'event:tickets-all|create': True,
  77. 'events|read': True,
  78. 'users|create': True
  79. }
  80. # Cache currently connected users.
  81. _users_cache = {}
  82. # A property to access the first value of each argument.
  83. arguments = property(lambda self: dict([(k, v[0])
  84. for k, v in self.request.arguments.iteritems()]))
  85. # A property to access both the UUID and the clean arguments.
  86. @property
  87. def uuid_arguments(self):
  88. uuid = None
  89. arguments = self.arguments
  90. if 'uuid' in arguments:
  91. uuid = arguments['uuid']
  92. del arguments['uuid']
  93. return uuid, arguments
  94. _bool_convert = {
  95. '0': False,
  96. 'n': False,
  97. 'f': False,
  98. 'no': False,
  99. 'off': False,
  100. 'false': False,
  101. '1': True,
  102. 'y': True,
  103. 't': True,
  104. 'on': True,
  105. 'yes': True,
  106. 'true': True
  107. }
  108. _re_split_salt = re.compile(r'\$(?P<salt>.+)\$(?P<hash>.+)')
  109. def write_error(self, status_code, **kwargs):
  110. """Default error handler."""
  111. if isinstance(kwargs.get('exc_info', (None, None))[1], BaseException):
  112. exc = kwargs['exc_info'][1]
  113. status_code = exc.status
  114. message = exc.message
  115. else:
  116. message = 'internal error'
  117. self.build_error(message, status=status_code)
  118. def is_api(self):
  119. """Return True if the path is from an API call."""
  120. return self.request.path.startswith('/v%s' % API_VERSION)
  121. def tobool(self, obj):
  122. """Convert some textual values to boolean."""
  123. if isinstance(obj, (list, tuple)):
  124. obj = obj[0]
  125. if isinstance(obj, (str, unicode)):
  126. obj = obj.lower()
  127. return self._bool_convert.get(obj, obj)
  128. def arguments_tobool(self):
  129. """Return a dictionary of arguments, converted to booleans where possible."""
  130. return dict([(k, self.tobool(v)) for k, v in self.arguments.iteritems()])
  131. def initialize(self, **kwargs):
  132. """Add every passed (key, value) as attributes of the instance."""
  133. for key, value in kwargs.iteritems():
  134. setattr(self, key, value)
  135. @property
  136. def current_user(self):
  137. """Retrieve current user name from the secure cookie."""
  138. return self.get_secure_cookie("user")
  139. @property
  140. def current_user_info(self):
  141. """Information about the current user, including their permissions."""
  142. current_user = self.current_user
  143. if current_user in self._users_cache:
  144. return self._users_cache[current_user]
  145. permissions = set([k for (k, v) in self.permissions.iteritems() if v is True])
  146. user_info = {'permissions': permissions}
  147. if current_user:
  148. user_info['username'] = current_user
  149. res = self.db.query('users', {'username': current_user})
  150. if res:
  151. user = res[0]
  152. user_info = user
  153. permissions.update(set(user.get('permissions') or []))
  154. user_info['permissions'] = permissions
  155. self._users_cache[current_user] = user_info
  156. return user_info
  157. def has_permission(self, permission):
  158. """Check permissions of the current user.
  159. :param permission: the permission to check
  160. :type permission: str
  161. :returns: True if the user is allowed to perform the action or False
  162. :rtype: bool
  163. """
  164. user_info = self.current_user_info or {}
  165. user_permissions = user_info.get('permissions') or []
  166. global_permission = '%s|all' % permission.split('|')[0]
  167. if 'admin|all' in user_permissions or global_permission in user_permissions or permission in user_permissions:
  168. return True
  169. collection_permission = self.permissions.get(permission)
  170. if isinstance(collection_permission, bool):
  171. return collection_permission
  172. if callable(collection_permission):
  173. return collection_permission(permission)
  174. return False
  175. def user_authorized(self, username, password):
  176. """Check if a combination of username/password is valid.
  177. :param username: username or email
  178. :type username: str
  179. :param password: password
  180. :type password: str
  181. :returns: tuple like (bool_user_is_authorized, dict_user_info)
  182. :rtype: dict"""
  183. query = [{'username': username}, {'email': username}]
  184. res = self.db.query('users', query)
  185. if not res:
  186. return (False, {})
  187. user = res[0]
  188. db_password = user.get('password') or ''
  189. if not db_password:
  190. return (False, {})
  191. match = self._re_split_salt.match(db_password)
  192. if not match:
  193. return (False, {})
  194. salt = match.group('salt')
  195. if utils.hash_password(password, salt=salt) == db_password:
  196. return (True, user)
  197. return (False, {})
  198. def build_error(self, message='', status=400):
  199. """Build and write an error message.
  200. :param message: textual message
  201. :type message: str
  202. :param status: HTTP status code
  203. :type status: int
  204. """
  205. self.set_status(status)
  206. self.write({'error': True, 'message': message})
  207. def logout(self):
  208. """Remove the secure cookie used fro authentication."""
  209. if self.current_user in self._users_cache:
  210. del self._users_cache[self.current_user]
  211. self.clear_cookie("user")
  212. class RootHandler(BaseHandler):
  213. """Handler for the / path."""
  214. angular_app_path = os.path.join(os.path.dirname(__file__), "angular_app")
  215. @gen.coroutine
  216. def get(self, *args, **kwargs):
  217. # serve the ./angular_app/index.html file
  218. with open(self.angular_app_path + "/index.html", 'r') as fd:
  219. self.write(fd.read())
  220. class CollectionHandler(BaseHandler):
  221. """Base class for handlers that need to interact with the database backend.
  222. Introduce basic CRUD operations."""
  223. # set of documents we're managing (a collection in MongoDB or a table in a SQL database)
  224. document = None
  225. collection = None
  226. # set of documents used to store incremental sequences
  227. counters_collection = 'counters'
  228. _id_chars = string.ascii_lowercase + string.digits
  229. def get_next_seq(self, seq):
  230. """Increment and return the new value of a ever-incrementing counter.
  231. :param seq: unique name of the sequence
  232. :type seq: str
  233. :returns: the next value of the sequence
  234. :rtype: int
  235. """
  236. if not self.db.query(self.counters_collection, {'seq_name': seq}):
  237. self.db.add(self.counters_collection, {'seq_name': seq, 'seq': 0})
  238. merged, doc = self.db.update(self.counters_collection,
  239. {'seq_name': seq},
  240. {'seq': 1},
  241. operation='increment')
  242. return doc.get('seq', 0)
  243. def gen_id(self, seq='ids', random_alpha=32):
  244. """Generate a unique, non-guessable ID.
  245. :param seq: the scope of the ever-incrementing sequence
  246. :type seq: str
  247. :param random_alpha: number of random lowercase alphanumeric chars
  248. :type random_alpha: int
  249. :returns: unique ID
  250. :rtype: str"""
  251. t = str(time.time()).replace('.', '_')
  252. seq = str(self.get_next_seq(seq))
  253. rand = ''.join([random.choice(self._id_chars) for x in xrange(random_alpha)])
  254. return '-'.join((t, seq, rand))
  255. def _filter_results(self, results, params):
  256. """Filter a list using keys and values from a dictionary.
  257. :param results: the list to be filtered
  258. :type results: list
  259. :param params: a dictionary of items that must all be present in an original list item to be included in the return
  260. :type params: dict
  261. :returns: list of items that have all the keys with the same values as params
  262. :rtype: list"""
  263. if not params:
  264. return results
  265. params = backend.convert(params)
  266. filtered = []
  267. for result in results:
  268. add = True
  269. for key, value in params.iteritems():
  270. if key not in result or result[key] != value:
  271. add = False
  272. break
  273. if add:
  274. filtered.append(result)
  275. return filtered
  276. def _clean_dict(self, data):
  277. """Filter a dictionary (in place) to remove unwanted keywords in db queries.
  278. :param data: dictionary to clean
  279. :type data: dict"""
  280. if isinstance(data, dict):
  281. for key in data.keys():
  282. if isinstance(key, (str, unicode)) and key.startswith('$'):
  283. del data[key]
  284. return data
  285. def _dict2env(self, data):
  286. """Convert a dictionary into a form suitable to be passed as environment variables.
  287. :param data: dictionary to convert
  288. :type data: dict"""
  289. ret = {}
  290. for key, value in data.iteritems():
  291. if isinstance(value, (list, tuple, dict)):
  292. continue
  293. try:
  294. key = key.upper().encode('ascii', 'ignore')
  295. key = re_env_key.sub('', key)
  296. if not key:
  297. continue
  298. ret[key] = unicode(value).encode(ENCODING)
  299. except:
  300. continue
  301. return ret
  302. def apply_filter(self, data, filter_name):
  303. """Apply a filter to the data.
  304. :param data: the data to filter
  305. :returns: the modified (possibly also in place) data
  306. """
  307. filter_method = getattr(self, 'filter_%s' % filter_name, None)
  308. if filter_method is not None:
  309. data = filter_method(data)
  310. return data
  311. @gen.coroutine
  312. @authenticated
  313. def get(self, id_=None, resource=None, resource_id=None, acl=True, **kwargs):
  314. if resource:
  315. # Handle access to sub-resources.
  316. permission = '%s:%s%s|read' % (self.document, resource, '-all' if resource_id is None else '')
  317. if acl and not self.has_permission(permission):
  318. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  319. handler = getattr(self, 'handle_get_%s' % resource, None)
  320. if handler and callable(handler):
  321. output = handler(id_, resource_id, **kwargs) or {}
  322. output = self.apply_filter(output, 'get_%s' % resource)
  323. self.write(output)
  324. return
  325. return self.build_error(status=404, message='unable to access resource: %s' % resource)
  326. if id_ is not None:
  327. # read a single document
  328. permission = '%s|read' % self.document
  329. if acl and not self.has_permission(permission):
  330. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  331. output = self.db.get(self.collection, id_)
  332. output = self.apply_filter(output, 'get')
  333. self.write(output)
  334. else:
  335. # return an object containing the list of all objects in the collection;
  336. # e.g.: {'events': [{'_id': 'obj1-id, ...}, {'_id': 'obj2-id, ...}, ...]}
  337. # Please, never return JSON lists that are not encapsulated into an object,
  338. # to avoid XSS vulnerabilities.
  339. permission = '%s|read' % self.collection
  340. if acl and not self.has_permission(permission):
  341. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  342. output = {self.collection: self.db.query(self.collection, self.arguments)}
  343. output = self.apply_filter(output, 'get_all')
  344. self.write(output)
  345. @gen.coroutine
  346. @authenticated
  347. def post(self, id_=None, resource=None, resource_id=None, **kwargs):
  348. data = escape.json_decode(self.request.body or '{}')
  349. self._clean_dict(data)
  350. method = self.request.method.lower()
  351. crud_method = 'create' if method == 'post' else 'update'
  352. now = datetime.datetime.now()
  353. user_info = self.current_user_info
  354. user_id = user_info.get('_id')
  355. env = {}
  356. if id_ is not None:
  357. env['%s_ID' % self.document.upper()] = id_
  358. if crud_method == 'create':
  359. data['created_by'] = user_id
  360. data['created_at'] = now
  361. data['updated_by'] = user_id
  362. data['updated_at'] = now
  363. if resource:
  364. permission = '%s:%s%s|%s' % (self.document, resource, '-all' if resource_id is None else '', crud_method)
  365. if not self.has_permission(permission):
  366. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  367. # Handle access to sub-resources.
  368. handler = getattr(self, 'handle_%s_%s' % (method, resource), None)
  369. if handler and callable(handler):
  370. data = self.apply_filter(data, 'input_%s_%s' % (method, resource))
  371. output = handler(id_, resource_id, data, **kwargs)
  372. output = self.apply_filter(output, 'get_%s' % resource)
  373. env['RESOURCE'] = resource
  374. if resource_id:
  375. env['%s_ID' % resource] = resource_id
  376. self.run_triggers('%s_%s_%s' % ('create' if resource_id is None else 'update', self.document, resource),
  377. stdin_data=output, env=env)
  378. self.write(output)
  379. return
  380. return self.build_error(status=404, message='unable to access resource: %s' % resource)
  381. if id_ is not None:
  382. permission = '%s|%s' % (self.document, crud_method)
  383. if not self.has_permission(permission):
  384. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  385. data = self.apply_filter(data, 'input_%s' % method)
  386. merged, newData = self.db.update(self.collection, id_, data)
  387. newData = self.apply_filter(newData, method)
  388. self.run_triggers('update_%s' % self.document, stdin_data=newData, env=env)
  389. else:
  390. permission = '%s|%s' % (self.collection, crud_method)
  391. if not self.has_permission(permission):
  392. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  393. data = self.apply_filter(data, 'input_%s_all' % method)
  394. newData = self.db.add(self.collection, data, _id=self.gen_id())
  395. newData = self.apply_filter(newData, '%s_all' % method)
  396. self.run_triggers('create_%s' % self.document, stdin_data=newData, env=env)
  397. self.write(newData)
  398. # PUT (update an existing document) is handled by the POST (create a new document) method;
  399. # in subclasses you can always separate sub-resources handlers like handle_post_tickets and handle_put_tickets
  400. put = post
  401. @gen.coroutine
  402. @authenticated
  403. def delete(self, id_=None, resource=None, resource_id=None, **kwargs):
  404. env = {}
  405. if id_ is not None:
  406. env['%s_ID' % self.document.upper()] = id_
  407. if resource:
  408. # Handle access to sub-resources.
  409. permission = '%s:%s%s|delete' % (self.document, resource, '-all' if resource_id is None else '')
  410. if not self.has_permission(permission):
  411. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  412. method = getattr(self, 'handle_delete_%s' % resource, None)
  413. if method and callable(method):
  414. output = method(id_, resource_id, **kwargs)
  415. env['RESOURCE'] = resource
  416. if resource_id:
  417. env['%s_ID' % resource] = resource_id
  418. self.run_triggers('delete_%s_%s' % (self.document, resource), stdin_data=env, env=env)
  419. self.write(output)
  420. return
  421. return self.build_error(status=404, message='unable to access resource: %s' % resource)
  422. if id_ is not None:
  423. permission = '%s|delete' % self.document
  424. if not self.has_permission(permission):
  425. return self.build_error(status=401, message='insufficient permissions: %s' % permission)
  426. howMany = self.db.delete(self.collection, id_)
  427. env['DELETED_ITEMS'] = howMany
  428. self.run_triggers('delete_%s' % self.document, stdin_data=env, env=env)
  429. else:
  430. self.write({'success': False})
  431. self.write({'success': True})
  432. def on_timeout(self, cmd, pipe):
  433. """Kill a process that is taking too long to complete."""
  434. logging.debug('cmd %s is taking too long: killing it' % ' '.join(cmd))
  435. try:
  436. pipe.proc.kill()
  437. except:
  438. pass
  439. def on_exit(self, returncode, cmd, pipe):
  440. """Callback executed when a subprocess execution is over."""
  441. self.ioloop.remove_timeout(self.timeout)
  442. logging.debug('cmd: %s returncode: %d' % (' '.join(cmd), returncode))
  443. @gen.coroutine
  444. def run_subprocess(self, cmd, stdin_data=None, env=None):
  445. """Execute the given action.
  446. :param cmd: the command to be run with its command line arguments
  447. :type cmd: list
  448. :param stdin_data: data to be sent over stdin
  449. :type stdin_data: str
  450. :param env: environment of the process
  451. :type env: dict
  452. """
  453. self.ioloop = tornado.ioloop.IOLoop.instance()
  454. processed_env = self._dict2env(env)
  455. p = process.Subprocess(cmd, close_fds=True, stdin=process.Subprocess.STREAM,
  456. stdout=process.Subprocess.STREAM, stderr=process.Subprocess.STREAM, env=processed_env)
  457. p.set_exit_callback(lambda returncode: self.on_exit(returncode, cmd, p))
  458. self.timeout = self.ioloop.add_timeout(datetime.timedelta(seconds=PROCESS_TIMEOUT),
  459. lambda: self.on_timeout(cmd, p))
  460. yield gen.Task(p.stdin.write, stdin_data or '')
  461. p.stdin.close()
  462. out, err = yield [gen.Task(p.stdout.read_until_close),
  463. gen.Task(p.stderr.read_until_close)]
  464. logging.debug('cmd: %s' % ' '.join(cmd))
  465. logging.debug('cmd stdout: %s' % out)
  466. logging.debug('cmd strerr: %s' % err)
  467. raise gen.Return((out, err))
  468. @gen.coroutine
  469. def run_triggers(self, action, stdin_data=None, env=None):
  470. """Asynchronously execute triggers for the given action.
  471. :param action: action name; scripts in directory ./data/triggers/{action}.d will be run
  472. :type action: str
  473. :param stdin_data: a python dictionary that will be serialized in JSON and sent to the process over stdin
  474. :type stdin_data: dict
  475. :param env: environment of the process
  476. :type stdin_data: dict
  477. """
  478. logging.debug('running triggers for action "%s"' % action)
  479. stdin_data = stdin_data or {}
  480. try:
  481. stdin_data = json.dumps(stdin_data)
  482. except:
  483. stdin_data = '{}'
  484. for script in glob.glob(os.path.join(self.data_dir, 'triggers', '%s.d' % action, '*')):
  485. if not (os.path.isfile(script) and os.access(script, os.X_OK)):
  486. continue
  487. out, err = yield gen.Task(self.run_subprocess, [script], stdin_data, env)
  488. def build_ws_url(self, path, proto='ws', host=None):
  489. """Return a WebSocket url from a path."""
  490. try:
  491. args = '?uuid=%s' % self.get_argument('uuid')
  492. except:
  493. args = ''
  494. return 'ws://127.0.0.1:%s/ws/%s%s' % (self.listen_port + 1, path, args)
  495. @gen.coroutine
  496. def send_ws_message(self, path, message):
  497. """Send a WebSocket message to all the connected clients.
  498. :param path: partial path used to build the WebSocket url
  499. :type path: str
  500. :param message: message to send
  501. :type message: str
  502. """
  503. try:
  504. ws = yield tornado.websocket.websocket_connect(self.build_ws_url(path))
  505. ws.write_message(message)
  506. ws.close()
  507. except Exception, e:
  508. self.logger.error('Error yielding WebSocket message: %s', e)
  509. class EventsHandler(CollectionHandler):
  510. """Handle requests for Events."""
  511. document = 'event'
  512. collection = 'events'
  513. def _mangle_event(self, event):
  514. # Some in-place changes to an event
  515. if 'tickets' in event:
  516. event['tickets_sold'] = len([t for t in event['tickets'] if not t.get('cancelled')])
  517. event['no_tickets_for_sale'] = False
  518. try:
  519. self._check_sales_datetime(event)
  520. self._check_number_of_tickets(event)
  521. except InputException:
  522. event['no_tickets_for_sale'] = True
  523. if not self.has_permission('tickets-all|read'):
  524. event['tickets'] = []
  525. return event
  526. def filter_get(self, output):
  527. return self._mangle_event(output)
  528. def filter_get_all(self, output):
  529. for event in output.get('events') or []:
  530. self._mangle_event(event)
  531. return output
  532. def filter_input_post(self, data):
  533. # Auto-generate the group_id, if missing.
  534. if 'group_id' not in data:
  535. data['group_id'] = self.gen_id()
  536. return data
  537. filter_input_post_all = filter_input_post
  538. filter_input_put = filter_input_post
  539. def filter_input_post_tickets(self, data):
  540. # Avoid users to be able to auto-update their 'attendee' status.
  541. if not self.has_permission('event|update'):
  542. if 'attended' in data:
  543. del data['attended']
  544. return data
  545. filter_input_put_tickets = filter_input_post_tickets
  546. def handle_get_group_persons(self, id_, resource_id=None):
  547. persons = []
  548. this_query = {'_id': id_}
  549. this_event = self.db.query('events', this_query)[0]
  550. group_id = this_event.get('group_id')
  551. if group_id is None:
  552. return {'persons': persons}
  553. this_persons = [p for p in (this_event.get('tickets') or []) if not p.get('cancelled')]
  554. this_emails = filter(None, [p.get('email') for p in this_persons])
  555. all_query = {'group_id': group_id}
  556. events = self.db.query('events', all_query)
  557. for event in events:
  558. if id_ is not None and str(event.get('_id')) == id_:
  559. continue
  560. persons += [p for p in (event.get('tickets') or []) if p.get('email') and p.get('email') not in this_emails]
  561. return {'persons': persons}
  562. def _get_ticket_data(self, ticket_id_or_query, tickets):
  563. """Filter a list of tickets returning the first item with a given _id
  564. or which set of keys specified in a dictionary match their respective values."""
  565. for ticket in tickets:
  566. if isinstance(ticket_id_or_query, dict):
  567. if all(ticket.get(k) == v for k, v in ticket_id_or_query.iteritems()):
  568. return ticket
  569. else:
  570. if str(ticket.get('_id')) == ticket_id_or_query:
  571. return ticket
  572. return {}
  573. def handle_get_tickets(self, id_, resource_id=None):
  574. # Return every ticket registered at this event, or the information
  575. # about a specific ticket.
  576. query = {'_id': id_}
  577. event = self.db.query('events', query)[0]
  578. if resource_id:
  579. return {'ticket': self._get_ticket_data(resource_id, event.get('tickets') or [])}
  580. tickets = self._filter_results(event.get('tickets') or [], self.arguments)
  581. return {'tickets': tickets}
  582. def _check_number_of_tickets(self, event):
  583. if self.has_permission('admin|all'):
  584. return
  585. number_of_tickets = event.get('number_of_tickets')
  586. if number_of_tickets is None:
  587. return
  588. try:
  589. number_of_tickets = int(number_of_tickets)
  590. except ValueError:
  591. return
  592. tickets = event.get('tickets') or []
  593. tickets = [t for t in tickets if not t.get('cancelled')]
  594. if len(tickets) >= event['number_of_tickets']:
  595. raise InputException('no more tickets available')
  596. def _check_sales_datetime(self, event):
  597. if self.has_permission('admin|all'):
  598. return
  599. begin_date = event.get('ticket_sales_begin_date')
  600. begin_time = event.get('ticket_sales_begin_time')
  601. end_date = event.get('ticket_sales_end_date')
  602. end_time = event.get('ticket_sales_end_time')
  603. utc = dateutil.tz.tzutc()
  604. is_dst = time.daylight and time.localtime().tm_isdst > 0
  605. utc_offset = - (time.altzone if is_dst else time.timezone)
  606. if begin_date is None:
  607. begin_date = datetime.datetime.now(tz=utc).replace(hour=0, minute=0, second=0, microsecond=0)
  608. else:
  609. begin_date = dateutil.parser.parse(begin_date)
  610. # Compensate UTC and DST offset, that otherwise would be added 2 times (one for date, one for time)
  611. begin_date = begin_date + datetime.timedelta(seconds=utc_offset)
  612. if begin_time is None:
  613. begin_time_h = 0
  614. begin_time_m = 0
  615. else:
  616. begin_time = dateutil.parser.parse(begin_time)
  617. begin_time_h = begin_time.hour
  618. begin_time_m = begin_time.minute
  619. now = datetime.datetime.now(tz=utc)
  620. begin_datetime = begin_date + datetime.timedelta(hours=begin_time_h, minutes=begin_time_m)
  621. if now < begin_datetime:
  622. raise InputException('ticket sales not yet started')
  623. if end_date is None:
  624. end_date = datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=utc)
  625. else:
  626. end_date = dateutil.parser.parse(end_date)
  627. end_date = end_date + datetime.timedelta(seconds=utc_offset)
  628. if end_time is None:
  629. end_time = end_date
  630. end_time_h = 23
  631. end_time_m = 59
  632. else:
  633. end_time = dateutil.parser.parse(end_time, yearfirst=True)
  634. end_time_h = end_time.hour
  635. end_time_m = end_time.minute
  636. end_datetime = end_date + datetime.timedelta(hours=end_time_h, minutes=end_time_m+1)
  637. if now > end_datetime:
  638. raise InputException('ticket sales has ended')
  639. def handle_post_tickets(self, id_, resource_id, data):
  640. event = self.db.query('events', {'_id': id_})[0]
  641. self._check_sales_datetime(event)
  642. self._check_number_of_tickets(event)
  643. uuid, arguments = self.uuid_arguments
  644. self._clean_dict(data)
  645. data['seq'] = self.get_next_seq('event_%s_tickets' % id_)
  646. data['seq_hex'] = '%06X' % data['seq']
  647. data['_id'] = ticket_id = self.gen_id()
  648. ret = {'action': 'add', 'ticket': data, 'uuid': uuid}
  649. merged, doc = self.db.update('events',
  650. {'_id': id_},
  651. {'tickets': data},
  652. operation='appendUnique',
  653. create=False)
  654. if doc:
  655. self.send_ws_message('event/%s/tickets/updates' % id_, json.dumps(ret))
  656. ticket = self._get_ticket_data(ticket_id, doc.get('tickets') or [])
  657. env = dict(ticket)
  658. env.update({'PERSON_ID': ticket_id, 'TICKED_ID': ticket_id, 'EVENT_ID': id_,
  659. 'EVENT_TITLE': doc.get('title', ''), 'WEB_USER': self.current_user,
  660. 'WEB_REMOTE_IP': self.request.remote_ip})
  661. stdin_data = {'new': ticket,
  662. 'event': doc,
  663. 'merged': merged
  664. }
  665. self.run_triggers('create_ticket_in_event', stdin_data=stdin_data, env=env)
  666. return ret
  667. def handle_put_tickets(self, id_, ticket_id, data):
  668. # Update an existing entry for a ticket registered at this event.
  669. self._clean_dict(data)
  670. uuid, arguments = self.uuid_arguments
  671. query = dict([('tickets.%s' % k, v) for k, v in arguments.iteritems()])
  672. query['_id'] = id_
  673. if ticket_id is not None:
  674. query['tickets._id'] = ticket_id
  675. ticket_query = {'_id': ticket_id}
  676. else:
  677. ticket_query = self.arguments
  678. old_ticket_data = {}
  679. current_event = self.db.query(self.collection, query)
  680. if current_event:
  681. current_event = current_event[0]
  682. else:
  683. current_event = {}
  684. self._check_sales_datetime(current_event)
  685. tickets = current_event.get('tickets') or []
  686. old_ticket_data = self._get_ticket_data(ticket_query, tickets)
  687. # We have changed the "cancelled" status of a ticket to False; check if we still have a ticket available
  688. if 'number_of_tickets' in current_event and old_ticket_data.get('cancelled') and not data.get('cancelled'):
  689. self._check_number_of_tickets(current_event)
  690. merged, doc = self.db.update('events', query,
  691. data, updateList='tickets', create=False)
  692. new_ticket_data = self._get_ticket_data(ticket_query,
  693. doc.get('tickets') or [])
  694. env = dict(new_ticket_data)
  695. # always takes the ticket_id from the new ticket
  696. ticket_id = str(new_ticket_data.get('_id'))
  697. env.update({'PERSON_ID': ticket_id, 'TICKED_ID': ticket_id, 'EVENT_ID': id_,
  698. 'EVENT_TITLE': doc.get('title', ''), 'WEB_USER': self.current_user,
  699. 'WEB_REMOTE_IP': self.request.remote_ip})
  700. stdin_data = {'old': old_ticket_data,
  701. 'new': new_ticket_data,
  702. 'event': doc,
  703. 'merged': merged
  704. }
  705. self.run_triggers('update_ticket_in_event', stdin_data=stdin_data, env=env)
  706. if old_ticket_data and old_ticket_data.get('attended') != new_ticket_data.get('attended'):
  707. if new_ticket_data.get('attended'):
  708. self.run_triggers('attends', stdin_data=stdin_data, env=env)
  709. ret = {'action': 'update', '_id': ticket_id, 'ticket': new_ticket_data, 'uuid': uuid}
  710. if old_ticket_data != new_ticket_data:
  711. self.send_ws_message('event/%s/tickets/updates' % id_, json.dumps(ret))
  712. return ret
  713. def handle_delete_tickets(self, id_, ticket_id):
  714. # Remove a specific ticket from the list of tickets registered at this event.
  715. uuid, arguments = self.uuid_arguments
  716. doc = self.db.query('events',
  717. {'_id': id_, 'tickets._id': ticket_id})
  718. ret = {'action': 'delete', '_id': ticket_id, 'uuid': uuid}
  719. if doc:
  720. ticket = self._get_ticket_data(ticket_id, doc[0].get('tickets') or [])
  721. merged, rdoc = self.db.update('events',
  722. {'_id': id_},
  723. {'tickets': {'_id': ticket_id}},
  724. operation='delete',
  725. create=False)
  726. self.send_ws_message('event/%s/tickets/updates' % id_, json.dumps(ret))
  727. env = dict(ticket)
  728. env.update({'PERSON_ID': ticket_id, 'TICKED_ID': ticket_id, 'EVENT_ID': id_,
  729. 'EVENT_TITLE': rdoc.get('title', ''), 'WEB_USER': self.current_user,
  730. 'WEB_REMOTE_IP': self.request.remote_ip})
  731. stdin_data = {'old': ticket,
  732. 'event': rdoc,
  733. 'merged': merged
  734. }
  735. self.run_triggers('delete_ticket_in_event', stdin_data=stdin_data, env=env)
  736. return ret
  737. class UsersHandler(CollectionHandler):
  738. """Handle requests for Users."""
  739. document = 'user'
  740. collection = 'users'
  741. def filter_get(self, data):
  742. if 'password' in data:
  743. del data['password']
  744. if '_id' in data:
  745. # Also add a 'tickets' list with all the tickets created by this user
  746. tickets = []
  747. events = self.db.query('events', {'tickets.created_by': data['_id']})
  748. for event in events:
  749. event_title = event.get('title') or ''
  750. event_id = str(event.get('_id'))
  751. evt_tickets = self._filter_results(event.get('tickets') or [], {'created_by': data['_id']})
  752. for evt_ticket in evt_tickets:
  753. evt_ticket['event_title'] = event_title
  754. evt_ticket['event_id'] = event_id
  755. tickets.extend(evt_tickets)
  756. data['tickets'] = tickets
  757. return data
  758. def filter_get_all(self, data):
  759. if 'users' not in data:
  760. return data
  761. for user in data['users']:
  762. if 'password' in user:
  763. del user['password']
  764. return data
  765. @gen.coroutine
  766. @authenticated
  767. def get(self, id_=None, resource=None, resource_id=None, acl=True, **kwargs):
  768. if id_ is not None:
  769. if (self.has_permission('user|read') or str(self.current_user_info.get('_id')) == id_):
  770. acl = False
  771. super(UsersHandler, self).get(id_, resource, resource_id, acl=acl, **kwargs)
  772. def filter_input_post_all(self, data):
  773. username = (data.get('username') or '').strip()
  774. password = (data.get('password') or '').strip()
  775. email = (data.get('email') or '').strip()
  776. if not (username and password):
  777. raise InputException('missing username or password')
  778. res = self.db.query('users', {'username': username})
  779. if res:
  780. raise InputException('username already exists')
  781. return {'username': username, 'password': utils.hash_password(password),
  782. 'email': email, '_id': self.gen_id()}
  783. def filter_input_put(self, data):
  784. old_pwd = data.get('old_password')
  785. new_pwd = data.get('new_password')
  786. if old_pwd is not None:
  787. del data['old_password']
  788. if new_pwd is not None:
  789. del data['new_password']
  790. authorized, user = self.user_authorized(data['username'], old_pwd)
  791. if not (self.has_permission('user|update') or (authorized and self.current_user == data['username'])):
  792. raise InputException('not authorized to change password')
  793. data['password'] = utils.hash_password(new_pwd)
  794. if '_id' in data:
  795. # Avoid overriding _id
  796. del data['_id']
  797. return data
  798. @gen.coroutine
  799. @authenticated
  800. def put(self, id_=None, resource=None, resource_id=None, **kwargs):
  801. if id_ is None:
  802. return self.build_error(status=404, message='unable to access the resource')
  803. if not (self.has_permission('user|update') or str(self.current_user_info.get('_id')) == id_):
  804. return self.build_error(status=401, message='insufficient permissions: user|update or current user')
  805. super(UsersHandler, self).put(id_, resource, resource_id, **kwargs)
  806. class EbCSVImportPersonsHandler(BaseHandler):
  807. """Importer for CSV files exported from Eventbrite."""
  808. csvRemap = {
  809. 'Nome evento': 'event_title',
  810. 'ID evento': 'event_id',
  811. 'N. codice a barre': 'ebqrcode',
  812. 'Cognome acquirente': 'surname',
  813. 'Nome acquirente': 'name',
  814. 'E-mail acquirente': 'email',
  815. 'Cognome': 'surname',
  816. 'Nome': 'name',
  817. 'E-mail': 'email',
  818. 'Indirizzo e-mail': 'email',
  819. 'Tipologia biglietto': 'ticket_kind',
  820. 'Data partecipazione': 'attending_datetime',
  821. 'Data check-in': 'checkin_datetime',
  822. 'Ordine n.': 'order_nr',
  823. 'ID ordine': 'order_nr',
  824. 'Titolo professionale': 'job_title',
  825. 'Azienda': 'company',
  826. 'Prefisso': 'name_title',
  827. 'Prefisso (Sig., Sig.ra, ecc.)': 'name_title',
  828. 'Order #': 'order_nr',
  829. 'Prefix': 'name_title',
  830. 'First Name': 'name',
  831. 'Last Name': 'surname',
  832. 'Suffix': 'name_suffix',
  833. 'Email': 'email',
  834. 'Attendee #': 'attendee_nr',
  835. 'Barcode #': 'ebqrcode',
  836. 'Company': 'company'
  837. }
  838. @gen.coroutine
  839. @authenticated
  840. def post(self, **kwargs):
  841. # import a CSV list of persons
  842. event_handler = EventsHandler(self.application, self.request)
  843. event_handler.db = self.db
  844. event_id = None
  845. try:
  846. event_id = self.get_body_argument('targetEvent')
  847. except:
  848. pass
  849. if event_id is None:
  850. return self.build_error('invalid event')
  851. reply = dict(total=0, valid=0, merged=0, new_in_event=0)
  852. for fieldname, contents in self.request.files.iteritems():
  853. for content in contents:
  854. filename = content['filename']
  855. parseStats, persons = utils.csvParse(content['body'], remap=self.csvRemap)
  856. reply['total'] += parseStats['total']
  857. reply['valid'] += parseStats['valid']
  858. for person in persons:
  859. person['attended'] = False
  860. person['from_file'] = filename
  861. event_handler.handle_post_persons(event_id, None, person)
  862. reply['new_in_event'] += 1
  863. self.write(reply)
  864. class SettingsHandler(BaseHandler):
  865. """Handle requests for Settings."""
  866. @gen.coroutine
  867. @authenticated
  868. def get(self, **kwargs):
  869. query = self.arguments_tobool()
  870. settings = self.db.query('settings', query)
  871. self.write({'settings': settings})
  872. class InfoHandler(BaseHandler):
  873. """Handle requests for information about the logged in user."""
  874. @gen.coroutine
  875. def get(self, **kwargs):
  876. info = {}
  877. user_info = self.current_user_info
  878. if user_info:
  879. info['user'] = user_info
  880. info['authentication_required'] = self.authentication
  881. self.write({'info': info})
  882. class WebSocketEventUpdatesHandler(tornado.websocket.WebSocketHandler):
  883. """Manage WebSockets."""
  884. def _clean_url(self, url):
  885. url = re_slashes.sub('/', url)
  886. ridx = url.rfind('?')
  887. if ridx != -1:
  888. url = url[:ridx]
  889. return url
  890. def open(self, event_id, *args, **kwargs):
  891. self.uuid = self.get_argument('uuid')
  892. url = self._clean_url(self.request.uri)
  893. logging.debug('WebSocketEventUpdatesHandler.on_open event_id:%s url:%s' % (event_id, url))
  894. _ws_clients.setdefault(url, {})
  895. if self.uuid not in _ws_clients[url]:
  896. _ws_clients[url][self.uuid] = self
  897. logging.debug('WebSocketEventUpdatesHandler.on_open %s clients connected' % len(_ws_clients[url]))
  898. def on_message(self, message):
  899. url = self._clean_url(self.request.uri)
  900. logging.debug('WebSocketEventUpdatesHandler.on_message url:%s' % url)
  901. count = 0
  902. _to_delete = set()
  903. for uuid, client in _ws_clients.get(url, {}).iteritems():
  904. try:
  905. client.write_message(message)
  906. except:
  907. _to_delete.add(uuid)
  908. continue
  909. count += 1
  910. for uuid in _to_delete:
  911. try:
  912. del _ws_clients[url][uuid]
  913. except KeyError:
  914. pass
  915. logging.debug('WebSocketEventUpdatesHandler.on_message sent message to %d clients' % count)
  916. class LoginHandler(RootHandler):
  917. """Handle user authentication requests."""
  918. @gen.coroutine
  919. def get(self, **kwargs):
  920. # show the login page
  921. if self.is_api():
  922. self.set_status(401)
  923. self.write({'error': True,
  924. 'message': 'authentication required'})
  925. @gen.coroutine
  926. def post(self, *args, **kwargs):
  927. # authenticate a user
  928. try:
  929. password = self.get_body_argument('password')
  930. username = self.get_body_argument('username')
  931. except tornado.web.MissingArgumentError:
  932. data = escape.json_decode(self.request.body or '{}')
  933. username = data.get('username')
  934. password = data.get('password')
  935. if not (username and password):
  936. self.set_status(401)
  937. self.write({'error': True, 'message': 'missing username or password'})
  938. return
  939. authorized, user = self.user_authorized(username, password)
  940. if authorized and user.get('username'):
  941. username = user['username']
  942. logging.info('successful login for user %s' % username)
  943. self.set_secure_cookie("user", username)
  944. self.write({'error': False, 'message': 'successful login'})
  945. return
  946. logging.info('login failed for user %s' % username)
  947. self.set_status(401)
  948. self.write({'error': True, 'message': 'wrong username and password'})
  949. class LogoutHandler(BaseHandler):
  950. """Handle user logout requests."""
  951. @gen.coroutine
  952. def get(self, **kwargs):
  953. # log the user out
  954. logging.info('logout')
  955. self.logout()
  956. self.write({'error': False, 'message': 'logged out'})
  957. def run():
  958. """Run the Tornado web application."""
  959. # command line arguments; can also be written in a configuration file,
  960. # specified with the --config argument.
  961. define("port", default=5242, help="run on the given port", type=int)
  962. define("address", default='', help="bind the server at the given address", type=str)
  963. define("data_dir", default=os.path.join(os.path.dirname(__file__), "data"),
  964. help="specify the directory used to store the data")
  965. define("ssl_cert", default=os.path.join(os.path.dirname(__file__), 'ssl', 'eventman_cert.pem'),
  966. help="specify the SSL certificate to use for secure connections")
  967. define("ssl_key", default=os.path.join(os.path.dirname(__file__), 'ssl', 'eventman_key.pem'),
  968. help="specify the SSL private key to use for secure connections")
  969. define("mongo_url", default=None,
  970. help="URL to MongoDB server", type=str)
  971. define("db_name", default='eventman',
  972. help="Name of the MongoDB database to use", type=str)
  973. define("authentication", default=False, help="if set to true, authentication is required")
  974. define("debug", default=False, help="run in debug mode")
  975. define("config", help="read configuration file",
  976. callback=lambda path: tornado.options.parse_config_file(path, final=False))
  977. tornado.options.parse_command_line()
  978. logger = logging.getLogger()
  979. logger.setLevel(logging.INFO)
  980. if options.debug:
  981. logger.setLevel(logging.DEBUG)
  982. ssl_options = {}
  983. if os.path.isfile(options.ssl_key) and os.path.isfile(options.ssl_cert):
  984. ssl_options = dict(certfile=options.ssl_cert, keyfile=options.ssl_key)
  985. # database backend connector
  986. db_connector = backend.EventManDB(url=options.mongo_url, dbName=options.db_name)
  987. init_params = dict(db=db_connector, data_dir=options.data_dir, listen_port=options.port,
  988. authentication=options.authentication, logger=logger, ssl_options=ssl_options)
  989. # If not present, we store a user 'admin' with password 'eventman' into the database.
  990. if not db_connector.query('users', {'username': 'admin'}):
  991. db_connector.add('users',
  992. {'username': 'admin', 'password': utils.hash_password('eventman'),
  993. 'permissions': ['admin|all']})
  994. # If present, use the cookie_secret stored into the database.
  995. cookie_secret = db_connector.query('settings', {'setting': 'server_cookie_secret'})
  996. if cookie_secret:
  997. cookie_secret = cookie_secret[0]['cookie_secret']
  998. else:
  999. # the salt guarantees its uniqueness
  1000. cookie_secret = utils.hash_password('__COOKIE_SECRET__')
  1001. db_connector.add('settings',
  1002. {'setting': 'server_cookie_secret', 'cookie_secret': cookie_secret})
  1003. _ws_handler = (r"/ws/+event/+(?P<event_id>[\w\d_-]+)/+tickets/+updates/?", WebSocketEventUpdatesHandler)
  1004. _events_path = r"/events/?(?P<id_>[\w\d_-]+)?/?(?P<resource>[\w\d_-]+)?/?(?P<resource_id>[\w\d_-]+)?"
  1005. _users_path = r"/users/?(?P<id_>[\w\d_-]+)?/?(?P<resource>[\w\d_-]+)?/?(?P<resource_id>[\w\d_-]+)?"
  1006. application = tornado.web.Application([
  1007. (_events_path, EventsHandler, init_params),
  1008. (r'/v%s%s' % (API_VERSION, _events_path), EventsHandler, init_params),
  1009. (_users_path, UsersHandler, init_params),
  1010. (r'/v%s%s' % (API_VERSION, _users_path), UsersHandler, init_params),
  1011. (r"/(?:index.html)?", RootHandler, init_params),
  1012. (r"/ebcsvpersons", EbCSVImportPersonsHandler, init_params),
  1013. (r"/settings", SettingsHandler, init_params),
  1014. (r"/info", InfoHandler, init_params),
  1015. _ws_handler,
  1016. (r'/login', LoginHandler, init_params),
  1017. (r'/v%s/login' % API_VERSION, LoginHandler, init_params),
  1018. (r'/logout', LogoutHandler),
  1019. (r'/v%s/logout' % API_VERSION, LogoutHandler),
  1020. (r'/(.*)', tornado.web.StaticFileHandler, {"path": "angular_app"})
  1021. ],
  1022. template_path=os.path.join(os.path.dirname(__file__), "templates"),
  1023. static_path=os.path.join(os.path.dirname(__file__), "static"),
  1024. cookie_secret='__COOKIE_SECRET__',
  1025. login_url='/login',
  1026. debug=options.debug)
  1027. http_server = tornado.httpserver.HTTPServer(application, ssl_options=ssl_options or None)
  1028. logger.info('Start serving on %s://%s:%d', 'https' if ssl_options else 'http',
  1029. options.address if options.address else '127.0.0.1',
  1030. options.port)
  1031. http_server.listen(options.port, options.address)
  1032. # Also listen on options.port+1 for our local ws connection.
  1033. ws_application = tornado.web.Application([_ws_handler], debug=options.debug)
  1034. ws_http_server = tornado.httpserver.HTTPServer(ws_application)
  1035. ws_http_server.listen(options.port+1, address='127.0.0.1')
  1036. logger.debug('Starting WebSocket on %s://127.0.0.1:%d', 'wss' if ssl_options else 'ws', options.port+1)
  1037. tornado.ioloop.IOLoop.instance().start()
  1038. if __name__ == '__main__':
  1039. try:
  1040. run()
  1041. except KeyboardInterrupt:
  1042. print('Stop server')