app.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  1. #!/usr/bin/env python3
  2. import asyncio
  3. import aiohttp
  4. import logging
  5. import os
  6. import re
  7. import json
  8. from datetime import datetime as dt
  9. from datetime import timedelta as td
  10. from typing import Any, Optional
  11. from functools import wraps
  12. from secrets import compare_digest
  13. from databases import Database
  14. from quart import jsonify, request, render_template_string, abort, current_app
  15. from quart.json import JSONEncoder
  16. from quart_openapi import Pint, Resource
  17. from http import HTTPStatus
  18. from panoramisk import Manager, Message
  19. from utils import *
  20. from cel import *
  21. from logging.config import dictConfig
  22. from pprint import pformat
  23. from inspect import getmembers
  24. class ApiJsonEncoder(JSONEncoder):
  25. def default(self, o):
  26. if isinstance(o, dt):
  27. return o.isoformat()
  28. if isinstance(o, CdrChannel):
  29. return str(o)
  30. if isinstance(o, CdrEvent):
  31. return o.__dict__
  32. if isinstance(o, CdrEvents) or isinstance(o, CelEvents):
  33. return o.all
  34. if isinstance(o, CdrCall) or isinstance(o, CelCall):
  35. return o.__dict__
  36. return JSONEncoder.default(self, o)
  37. class PintDB:
  38. def __init__(self, app: Optional[Pint] = None) -> None:
  39. self.init_app(app)
  40. self._db = Database(app.config["DB_URI"])
  41. def init_app(self, app: Pint) -> None:
  42. app.before_serving(self._before_serving)
  43. app.after_serving(self._after_serving)
  44. async def _before_serving(self) -> None:
  45. await self._db.connect()
  46. async def _after_serving(self) -> None:
  47. await self._db.disconnect()
  48. def __getattr__(self, name: str) -> Any:
  49. return getattr(self._db, name)
  50. # One asyncio event loop is used for AMI communication and HTTP requests routing with Quart
  51. main_loop = asyncio.get_event_loop()
  52. app = Pint(__name__, title=os.getenv('APP_TITLE', 'PBX API'), no_openapi=True)
  53. app.json_encoder = ApiJsonEncoder
  54. app.config.update({
  55. 'TITLE': os.getenv('APP_TITLE', 'PBX API'),
  56. 'APPLICATION_ROOT': os.getenv('APP_APPLICATION_ROOT', None),
  57. 'SCHEME': os.getenv('APP_SCHEME', 'http'),
  58. 'FQDN': os.getenv('APP_FQDN', '127.0.0.1'),
  59. 'PORT': int(os.getenv('APP_API_PORT', 8000)),
  60. 'BODY_TIMEOUT': int(os.getenv('APP_BODY_TIMEOUT', 60)),
  61. 'DEBUG': os.getenv('APP_DEBUG', 'False').lower() in TRUEs,
  62. 'MAX_CONTENT_LENGTH': int(os.getenv('APP_MAX_CONTENT_LENGTH', 16777216)),
  63. 'AMI_HOST': os.getenv('APP_AMI_HOST', '127.0.0.1'),
  64. 'AMI_PORT': int(os.getenv('APP_AMI_PORT', 5038)),
  65. 'AMI_USERNAME': os.getenv('APP_AMI_USERNAME', 'app'),
  66. 'AMI_SECRET': os.getenv('APP_AMI_SECRET', 'secret'),
  67. 'AMI_PING_DELAY': int(os.getenv('APP_AMI_PING_DELAY', 10)),
  68. 'AMI_PING_INTERVAL': int(os.getenv('APP_AMI_PING_INTERVAL', 10)),
  69. 'AMI_TIMEOUT': int(os.getenv('APP_AMI_TIMEOUT', 5)),
  70. 'AUTH_HEADER': os.getenv('APP_AUTH_HEADER', 'APP-auth-token'),
  71. 'AUTH_SECRET': os.getenv('APP_AUTH_SECRET', '3bfbeaabf363dd64fe263bd36830a6b6'),
  72. 'SWAGGER_JS_URL': os.getenv('APP_SWAGGER_JS_URL', SWAGGER_JS_URL),
  73. 'SWAGGER_CSS_URL': os.getenv('APP_SWAGGER_CSS_URL', SWAGGER_CSS_URL),
  74. 'STATE_CALLBACK_URL': os.getenv('APP_STATE_CALLBACK_URL', None),
  75. 'DB_URI': 'mysql://{}:{}@{}:{}/{}'.format(os.getenv('MYSQL_USER', 'asterisk'),
  76. os.getenv('MYSQL_PASSWORD', 'secret'),
  77. os.getenv('MYSQL_SERVER', 'db'),
  78. os.getenv('APP_PORT_MYSQL', '3306'),
  79. os.getenv('FREEPBX_CDRDBNAME', None)),
  80. 'EXTRA_API_URL': os.getenv('APP_EXTRA_API_URL', None)})
  81. app.cache = {'devices':{},
  82. 'usermap':{},
  83. 'devicemap':{},
  84. 'ustates':{},
  85. 'pstates':{},
  86. 'queues':{},
  87. 'calls':{}}
  88. manager = Manager(
  89. loop=main_loop,
  90. host=app.config['AMI_HOST'],
  91. port=app.config['AMI_PORT'],
  92. username=app.config['AMI_USERNAME'],
  93. secret=app.config['AMI_SECRET'],
  94. ping_delay=app.config['AMI_PING_DELAY'],
  95. ping_interval=app.config['AMI_PING_INTERVAL'],
  96. reconnect_timeout=app.config['AMI_TIMEOUT'],
  97. )
  98. def authRequired(func):
  99. @wraps(func)
  100. async def authWrapper(*args, **kwargs):
  101. request.user = None
  102. request.device = None
  103. request.admin = False
  104. auth = request.authorization
  105. headers = request.headers
  106. if ((auth is not None) and
  107. (auth.type == "basic") and
  108. (auth.username in current_app.cache['devices']) and
  109. (compare_digest(auth.password, current_app.cache['devices'][auth.username]))):
  110. request.device = auth.username
  111. if request.device in current_app.cache['usermap']:
  112. request.user = current_app.cache['usermap'][request.device]
  113. return await func(*args, **kwargs)
  114. elif ((current_app.config['AUTH_HEADER'].lower() in headers) and
  115. (headers[current_app.config['AUTH_HEADER'].lower()] == current_app.config['AUTH_SECRET'])):
  116. request.admin = True
  117. return await func(*args, **kwargs)
  118. else:
  119. abort(401)
  120. return authWrapper
  121. db = PintDB(app)
  122. @manager.register_event('FullyBooted')
  123. @manager.register_event('Reload')
  124. async def reloadCallback(mngr: Manager, msg: Message):
  125. await refreshDevicesCache()
  126. await refreshStatesCache()
  127. await refreshQueuesCache()
  128. await rebindLostDevices()
  129. # await db.execute(query='CREATE TABLE IF NOT EXISTS callback_urls (device VARCHAR(16) PRIMARY KEY, url VARCHAR(255))')
  130. @manager.register_event('ExtensionStatus')
  131. async def extensionStatusCallback(mngr: Manager, msg: Message):
  132. user = msg.exten
  133. state = msg.statustext.lower()
  134. app.logger.warning('ExtensionStatus({}, {})'.format(user, state))
  135. if user in app.cache['ustates']:
  136. prevState = getUserStateCombined(user)
  137. app.cache['ustates'][user] = state
  138. combinedState = getUserStateCombined(user)
  139. if combinedState != prevState:
  140. await userStateChangeCallback(user, combinedState, prevState)
  141. @manager.register_event('PresenceStatus')
  142. async def presenceStatusCallback(mngr: Manager, msg: Message):
  143. user = msg.exten #hint = msg.hint
  144. state = msg.status.lower()
  145. if user in app.cache['ustates']:
  146. prevState = getUserStateCombined(user)
  147. app.cache['pstates'][user] = state
  148. combinedState = getUserStateCombined(user)
  149. if combinedState != prevState:
  150. await userStateChangeCallback(user, combinedState, prevState)
  151. @manager.register_event('Hangup')
  152. async def hangupCallback(mngr: Manager, msg: Message):
  153. if msg.uniqueid in app.cache['calls']:
  154. del app.cache['calls'][msg.uniqueid]
  155. @manager.register_event('Newchannel')
  156. async def newchannelCallback(mngr: Manager, msg: Message):
  157. app.logger.warning(msg)
  158. if (msg.channelstate == '4') and ('HTTP_CLIENT' in app.config):
  159. did = None
  160. cid = None
  161. user = None
  162. device = None
  163. uid = None
  164. if msg.context in ('from-pstn'):
  165. app.cache['calls'][msg.uniqueid]=msg
  166. app.logger.warning('call from pstn')
  167. elif ((msg.context in ('from-queue')) and
  168. (msg.linkedid in app.cache['calls']) and
  169. (msg.exten in app.cache['devicemap'])):
  170. app.logger.warning('call from queue')
  171. did = app.cache['calls'][msg.linkedid].exten
  172. cid = app.cache['calls'][msg.linkedid].calleridnum
  173. user = msg.exten
  174. device = app.cache['devicemap'][user]
  175. uid = msg.linkedid
  176. elif ((msg.context in ('from-internal')) and
  177. (msg.exten in app.cache['devicemap'])):
  178. app.logger.warning('call from internal')
  179. user = msg.exten
  180. device = app.cache['devicemap'][user]
  181. if msg.calleridnum in app.cache['usermap']:
  182. cid = app.cache['usermap'][msg.calleridnum]
  183. else:
  184. cid = msg.calleridnum
  185. uid = msg.uniqueid
  186. if device is not None:
  187. row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
  188. values={'device': device})
  189. if (row is not None) and (row['url'].startswith('http')):
  190. reply = await app.config['HTTP_CLIENT'].post(row['url'],
  191. json={'user': user,
  192. 'device': device,
  193. 'state': 'ringing',
  194. 'callerId': cid,
  195. 'did': did,
  196. 'callId': uid})
  197. async def getCDR(start=None,
  198. end=None,
  199. table='cdr',
  200. field='calldate',
  201. sort='calldate, SUBSTR(uniqueid,1,10), sequence'):
  202. _cdr = {}
  203. if end is None:
  204. end = dt.now()
  205. if start is None:
  206. start=(end - td(hours=24))
  207. async for row in db.iterate(query='''SELECT *
  208. FROM {table}
  209. WHERE linkedid
  210. IN (SELECT DISTINCT(linkedid)
  211. FROM {table}
  212. WHERE {field}
  213. BETWEEN :start AND :end)
  214. ORDER BY {sort};'''.format(table=table,
  215. field=field,
  216. sort=sort),
  217. values={'start':start,
  218. 'end':end}):
  219. if row['linkedid'] in _cdr:
  220. _cdr[row['linkedid']].events.add(row)
  221. else:
  222. _cdr[row['linkedid']]=CdrCall(row)
  223. cdr = []
  224. for _id in sorted(_cdr.keys()):
  225. cdr.append(_cdr[_id])
  226. return cdr
  227. async def getUserCDR(user,
  228. start=None,
  229. end=None,
  230. direction=None,
  231. limit=None,
  232. offset=None,
  233. order='ASC'):
  234. _q = f'''SELECT * FROM cdr AS c INNER JOIN (SELECT linkedid FROM cdr WHERE'''
  235. direction=direction.lower()
  236. if direction in ('in', True, '1', 'incoming', 'inbound'):
  237. direction = 'inbound'
  238. _q += f''' dst="{user}"'''
  239. elif direction in ('out', False, '0', 'outgoing', 'outbound'):
  240. direction = 'outbound'
  241. _q += f''' src="{user}"'''
  242. else:
  243. direction = None
  244. _q += f''' (src="{user}" or dst="{user}")'''
  245. if end is None:
  246. end = dt.now()
  247. if start is None:
  248. start=(end - td(hours=24))
  249. _q += f''' AND calldate BETWEEN "{start}" AND "{end}" GROUP BY linkedid'''
  250. if None not in (limit, offset):
  251. _q += f''' LIMIT {offset},{limit}'''
  252. _q += f''') AS c2 ON c.linkedid = c2.linkedid;'''
  253. app.logger.warning('SQL: {}'.format(_q))
  254. _cdr = {}
  255. async for row in db.iterate(query=_q):
  256. if row['linkedid'] in _cdr:
  257. _cdr[row['linkedid']].events.add(row)
  258. else:
  259. _cdr[row['linkedid']]=CdrUserCall(user, row)
  260. cdr = []
  261. for _id in sorted(_cdr.keys(), reverse = True if (order.lower() == 'desc') else False):
  262. record = _cdr[_id].simple
  263. if (direction is not None) and (record['src'] == record['dst']) and (record['direction'] != direction):
  264. record['direction'] = direction
  265. if record['file'] is not None:
  266. record['file'] = '/static/records/{d.year}/{d.month:02}/{d.day:02}/{filename}'.format(d=record['start'],
  267. filename=record['file'])
  268. cdr.append(record)
  269. return cdr
  270. async def getCEL(start=None, end=None, table='cel', field='eventtime', sort='id'):
  271. return await getCDR(start, end, table, field, sort)
  272. @app.before_first_request
  273. async def initHttpClient():
  274. app.config['HTTP_CLIENT'] = aiohttp.ClientSession(loop=main_loop)
  275. @app.route('/openapi.json')
  276. async def openapi():
  277. '''Generates JSON that conforms OpenAPI Specification
  278. '''
  279. schema = app.__schema__
  280. schema['servers'] = [{'url':'{}://{}:{}'.format(app.config['SCHEME'],
  281. app.config['FQDN'],
  282. app.config['PORT'])}]
  283. if app.config['EXTRA_API_URL'] is not None:
  284. schema['servers'].append({'url':app.config['EXTRA_API_URL']})
  285. schema['components'] = {'securitySchemes':{'ApiKey':{'type': 'apiKey',
  286. 'name': app.config['AUTH_HEADER'],
  287. 'in': 'header'}}}
  288. schema['security'] = [{'ApiKey':[]}]
  289. return jsonify(schema)
  290. @app.route('/ui')
  291. async def ui():
  292. '''Swagger UI
  293. '''
  294. return await render_template_string(SWAGGER_TEMPLATE,
  295. title=app.config['TITLE'],
  296. js_url=app.config['SWAGGER_JS_URL'],
  297. css_url=app.config['SWAGGER_CSS_URL'])
  298. async def action():
  299. _payload = await request.get_data()
  300. reply = await manager.send_action(json.loads(_payload))
  301. return str(reply)
  302. async def amiGetVar(variable):
  303. '''AMI GetVar
  304. Returns value of requested variable using AMI action GetVar in background.
  305. Parameters:
  306. variable (string): Variable to query for
  307. Returns:
  308. string: Variable value or empty string if variable not found
  309. '''
  310. reply = await manager.send_action({'Action': 'GetVar',
  311. 'Variable': variable})
  312. app.logger.warning('GetVar({})->{}'.format(variable, reply.value))
  313. return reply.value
  314. @app.route('/ami/auths')
  315. @authRequired
  316. async def amiPJSIPShowAuths():
  317. if not request.admin:
  318. abort(401)
  319. return successReply(app.cache['devices'])
  320. @app.route('/blackhole', methods=['GET','POST'])
  321. async def blackhole():
  322. return ''
  323. @app.route('/ami/aors')
  324. @authRequired
  325. async def amiPJSIPShowAors():
  326. if not request.admin:
  327. abort(401)
  328. aors = {}
  329. reply = await manager.send_action({'Action':'PJSIPShowAors'})
  330. if len(reply) >= 2:
  331. for message in reply:
  332. if ((message.event == 'AorList') and
  333. ('objecttype' in message) and
  334. (message.objecttype == 'aor') and
  335. (int(message.maxcontacts) > 0)):
  336. aors[message.objectname] = message.contacts
  337. app.logger.warning('AorsList: {}'.format(','.join(aors.keys())))
  338. return successReply(aors)
  339. async def amiSetVar(variable, value):
  340. '''AMI SetVar
  341. Sets variable using AMI action SetVar to value in background.
  342. Parameters:
  343. variable (string): Variable to set
  344. value (string): Value to set for variable
  345. Returns:
  346. string: None if SetVar was successfull, error message overwise
  347. '''
  348. reply = await manager.send_action({'Action': 'SetVar',
  349. 'Variable': variable,
  350. 'Value': value})
  351. app.logger.warning('SetVar({}, {})'.format(variable, value))
  352. if isinstance(reply, Message):
  353. if reply.success:
  354. return None
  355. else:
  356. return reply.message
  357. return 'AMI error'
  358. async def amiDBGet(family, key):
  359. '''AMI DBGet
  360. Returns value of requested astdb key using AMI action DBGet in background.
  361. Parameters:
  362. family (string): astdb key family to query for
  363. key (string): astdb key to query for
  364. Returns:
  365. string: Value or empty string if variable not found
  366. '''
  367. reply = await manager.send_action({'Action': 'DBGet',
  368. 'Family': family,
  369. 'Key': key})
  370. if (isinstance(reply, list) and
  371. (len(reply) > 1)):
  372. for message in reply:
  373. if (message.event == 'DBGetResponse'):
  374. app.logger.warning('DBGet(/{}/{})->{}'.format(family, key, message.val))
  375. return message.val
  376. app.logger.warning('DBGet(/{}/{})->Error!'.format(family, key))
  377. return None
  378. async def amiDBPut(family, key, value):
  379. '''AMI DBPut
  380. Writes value to astdb by family and key using AMI action DBPut in background.
  381. Parameters:
  382. family (string): astdb key family to write to
  383. key (string): astdb key to write to
  384. value (string): value to write
  385. Returns:
  386. boolean: True if DBPut action was successfull, False overwise
  387. '''
  388. reply = await manager.send_action({'Action': 'DBPut',
  389. 'Family': family,
  390. 'Key': key,
  391. 'Val': value})
  392. app.logger.warning('DBPut(/{}/{}, {})'.format(family, key, value))
  393. if (isinstance(reply, Message) and reply.success):
  394. return True
  395. return False
  396. async def amiDBDel(family, key):
  397. '''AMI DBDel
  398. Deletes key from family in astdb using AMI action DBDel in background.
  399. Parameters:
  400. family (string): astdb key family
  401. key (string): astdb key to delete
  402. Returns:
  403. boolean: True if DBDel action was successfull, False overwise
  404. '''
  405. reply = await manager.send_action({'Action': 'DBDel',
  406. 'Family': family,
  407. 'Key': key})
  408. app.logger.warning('DBDel(/{}/{})'.format(family, key))
  409. if (isinstance(reply, Message) and reply.success):
  410. return True
  411. return False
  412. async def amiSetHint(context, user, hint):
  413. '''AMI SetHint
  414. Sets hint for user in context using AMI action DialplanUserAdd with Replace=true in background.
  415. Parameters:
  416. context (string): dialplan context
  417. user (string): user
  418. hint (string): hint for user
  419. Returns:
  420. boolean: True if DialplanUserAdd action was successfull, False overwise
  421. '''
  422. reply = await manager.send_action({'Action': 'DialplanExtensionAdd',
  423. 'Context': context,
  424. 'Extension': user,
  425. 'Priority': 'hint',
  426. 'Application': hint,
  427. 'Replace': 'yes'})
  428. app.logger.warning('SetHint({},{},{})'.format(context, user, hint))
  429. if (isinstance(reply, Message) and reply.success):
  430. return True
  431. return False
  432. async def amiPresenceState(user):
  433. '''AMI PresenceState request for CustomPresence provider
  434. Parameters:
  435. user (string): user
  436. Returns:
  437. boolean, string: True and state or False and error message
  438. '''
  439. reply = await manager.send_action({'Action': 'PresenceState',
  440. 'Provider': 'CustomPresence:{}'.format(user)})
  441. app.logger.warning('PresenceState({})'.format(user))
  442. if isinstance(reply, Message):
  443. if reply.success:
  444. return True, reply.state
  445. else:
  446. return False, reply.message
  447. return False, 'AMI error'
  448. async def amiPresenceStateList():
  449. states = {}
  450. reply = await manager.send_action({'Action':'PresenceStateList'})
  451. if len(reply) >= 2:
  452. for message in reply:
  453. if message.event == 'PresenceStateChange':
  454. user = re.search('CustomPresence:(\d+)', message.presentity).group(1)
  455. states[user] = message.status
  456. app.logger.warning('PresenceStateList: {}'.format(','.join(states.keys())))
  457. return states
  458. async def amiExtensionStateList():
  459. states = {}
  460. reply = await manager.send_action({'Action':'ExtensionStateList'})
  461. if len(reply) >= 2:
  462. for message in reply:
  463. if ((message.event == 'ExtensionStatus') and
  464. (message.context == 'ext-local')):
  465. states[message.exten] = message.statustext.lower()
  466. app.logger.warning('ExtensionStateList: {}'.format(','.join(states.keys())))
  467. return states
  468. async def amiCommand(command):
  469. '''AMI Command
  470. Runs specified command using AMI action Command in background.
  471. Parameters:
  472. command (string): command to run
  473. Returns:
  474. boolean, list: tuple representing the boolean result of request and list of lines of command output
  475. '''
  476. reply = await manager.send_action({'Action': 'Command',
  477. 'Command': command})
  478. result = []
  479. if (isinstance(reply, Message) and reply.success):
  480. if isinstance(reply.output, list):
  481. result = reply.output
  482. else:
  483. result = reply.output.split('\n')
  484. app.logger.warning('Command({})->{}'.format(command, '\n'.join(result)))
  485. return True, result
  486. app.logger.warning('Command({})->Error!'.format(command))
  487. return False, result
  488. async def amiReload(module='core'):
  489. '''AMI Reload
  490. Reload specified asterisk module using AMI action reload in background.
  491. Parameters:
  492. module (string): module to reload, defaults to core
  493. Returns:
  494. boolean: True if Reload action was successfull, False overwise
  495. '''
  496. reply = await manager.send_action({'Action': 'Reload',
  497. 'Module': module})
  498. app.logger.warning('Reload({})'.format(module))
  499. if (isinstance(reply, Message) and reply.success):
  500. return True
  501. return False
  502. async def getGlobalVars():
  503. globalVars = GlobalVars()
  504. for _var in globalVars.d():
  505. setattr(globalVars, _var, await amiGetVar(_var))
  506. return globalVars
  507. async def setUserHint(user, dial, ast):
  508. if dial in NONEs:
  509. hint = 'CustomPresence:{}'.format(user)
  510. else:
  511. _dial= [dial]
  512. if (ast.DNDDEVSTATE == 'TRUE'):
  513. _dial.append('Custom:DND{}'.format(user))
  514. hint = '{},CustomPresence:{}'.format('&'.join(_dial), user)
  515. return await amiSetHint('ext-local', user, hint)
  516. async def amiQueues():
  517. queues = {}
  518. reply = await manager.send_action({'Action':'QueueStatus'})
  519. if len(reply) >= 2:
  520. for message in reply:
  521. if message.event == 'QueueMember':
  522. _qm = QueueMember(re.search('Local\/(\d+)', message.location).group(1))
  523. queues.setdefault(message.queue, []).append(_qm.fromMessage(message))
  524. app.logger.warning('QueuesList: {}'.format(','.join(queues.keys())))
  525. return queues
  526. async def amiDeviceChannel(device):
  527. reply = await manager.send_action({'Action':'CoreShowChannels'})
  528. if len(reply) >= 2:
  529. for message in reply:
  530. if message.event == 'CoreShowChannel':
  531. if message.calleridnum == device:
  532. return message.channel
  533. return None
  534. async def getUserChannel(user):
  535. device = await getUserDevice(user)
  536. if device in NONEs:
  537. return False
  538. channel = await amiDeviceChannel(device)
  539. if channel in NONEs:
  540. return False
  541. return channel
  542. async def setQueueStates(user, device, state):
  543. for queue in [_q for _q, _ma in app.cache['queues'].items() for _m in _ma if _m.user == user]:
  544. await amiSetVar('DEVICE_STATE(Custom:QUEUE{}*{})'.format(device, queue), state)
  545. async def getDeviceUser(device):
  546. return await amiDBGet('DEVICE', '{}/user'.format(device))
  547. async def getDeviceType(device):
  548. return await amiDBGet('DEVICE', '{}/type'.format(device))
  549. async def getDeviceDial(device):
  550. return await amiDBGet('DEVICE', '{}/dial'.format(device))
  551. async def getUserCID(user):
  552. return await amiDBGet('AMPUSER', '{}/cidnum'.format(user))
  553. async def setDeviceUser(device, user):
  554. return await amiDBPut('DEVICE', '{}/user'.format(device), user)
  555. async def getUserDevice(user):
  556. return await amiDBGet('AMPUSER', '{}/device'.format(user))
  557. async def setUserDevice(user, device):
  558. if device is None:
  559. return await amiDBDel('AMPUSER', '{}/device'.format(user))
  560. else:
  561. return await amiDBPut('AMPUSER', '{}/device'.format(user), device)
  562. async def unbindOtherDevices(user, newDevice, ast):
  563. '''Unbinds user from all devices except newDevice and sets
  564. all required device states.
  565. '''
  566. devices = await amiDBGet('AMPUSER', '{}/device'.format(user))
  567. if devices not in NONEs:
  568. for _device in sorted(set(devices.split('&')), key=int):
  569. if _device != newDevice:
  570. if ast.FMDEVSTATE == 'TRUE':
  571. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(_device), 'INVALID')
  572. if ast.QUEDEVSTATE == 'TRUE':
  573. await setQueueStates(user, _device, 'NOT_INUSE')
  574. if ast.DNDDEVSTATE:
  575. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(_device), 'NOT_INUSE')
  576. if ast.CFDEVSTATE:
  577. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(_device), 'NOT_INUSE')
  578. await amiDBPut('DEVICE', '{}/user'.format(_device), 'none')
  579. async def setUserDeviceStates(user, device, ast):
  580. if ast.FMDEVSTATE == 'TRUE':
  581. _followMe = await amiDBGet('AMPUSER', '{}/followme/ddial'.format(user))
  582. if _followMe is not None:
  583. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(device), followMe2DevState(_followMe))
  584. if ast.QUEDEVSTATE == 'TRUE':
  585. await setQueueStates(user, device, 'INUSE')
  586. if ast.DNDDEVSTATE:
  587. _dnd = await amiDBGet('DND', user)
  588. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(device), 'INUSE' if _dnd == 'YES' else 'NOT_INUSE')
  589. if ast.CFDEVSTATE:
  590. _cf = await amiDBGet('CF', user)
  591. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(device), 'INUSE' if _cf != '' else 'NOT_INUSE')
  592. async def refreshStatesCache():
  593. app.cache['ustates'] = await amiExtensionStateList()
  594. app.cache['pstates'] = await amiPresenceStateList()
  595. return len(app.cache['ustates'])
  596. async def refreshDevicesCache():
  597. auths = {}
  598. reply = await manager.send_action({'Action':'PJSIPShowAuths'})
  599. if len(reply) >= 2:
  600. for message in reply:
  601. if ((message.event == 'AuthList') and
  602. ('objecttype' in message) and
  603. (message.objecttype == 'auth')):
  604. auths[message.username] = message.password
  605. app.cache['devices'] = auths
  606. return len(app.cache['devices'])
  607. async def refreshQueuesCache():
  608. app.cache['queues'] = await amiQueues()
  609. return len(app.cache['queues'])
  610. async def rebindLostDevices():
  611. app.cache['usermap'] = {}
  612. app.cache['devicemap'] = {}
  613. ast = await getGlobalVars()
  614. for device in app.cache['devices']:
  615. user = await getDeviceUser(device)
  616. deviceType = await getDeviceType(device)
  617. if (deviceType != 'fixed') and (user != 'none') and (user in app.cache['ustates'].keys()):
  618. _device = await getUserDevice(user)
  619. if _device != device:
  620. app.logger.warning('Fixing bind user {} to device {}'.format(user, device))
  621. dial = await getDeviceDial(device)
  622. await setUserHint(user, dial, ast) # Set hints for user on new device
  623. await setUserDeviceStates(user, device, ast) # Set device states for users device
  624. await setUserDevice(user, device) # Bind device to user
  625. app.cache['usermap'][device] = user
  626. if user != 'none':
  627. app.cache['devicemap'][user] = device
  628. async def userStateChangeCallback(user, state, prevState = None):
  629. reply = None
  630. if ('HTTP_CLIENT' in app.config) and (user in app.cache['devicemap']):
  631. row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
  632. values={'device': app.cache['devicemap'][user]})
  633. if row is not None:
  634. reply = await app.config['HTTP_CLIENT'].post(row['url'],
  635. json={'user': user,
  636. 'state': state,
  637. 'prev_state':prevState})
  638. app.logger.warning('{} changed state to: {}'.format(user, state))
  639. return reply
  640. def getUserStateCombined(user):
  641. _uCache = app.cache['ustates']
  642. _pCache = app.cache['pstates']
  643. return combinedStates[_uCache.get(user, 'unavailable')][_pCache.get(user, 'not_set')]
  644. def getUsersStatesCombined():
  645. return {user:getUserStateCombined(user) for user in app.cache['ustates']}
  646. @app.route('/atxfer/<userA>/<userB>')
  647. class AtXfer(Resource):
  648. @authRequired
  649. @app.param('userA', 'User initiating the attended transfer', 'path')
  650. @app.param('userB', 'Transfer destination user', 'path')
  651. @app.response(HTTPStatus.OK, 'Json reply')
  652. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  653. async def get(self, userA, userB):
  654. '''Attended call transfer
  655. '''
  656. if (userA != request.user) and (not request.admin):
  657. abort(401)
  658. channel = await getUserChannel(userA)
  659. if not channel:
  660. return noUserChannel(userA)
  661. reply = await manager.send_action({'Action':'Atxfer',
  662. 'Channel':channel,
  663. 'async':'false',
  664. 'Exten':userB})
  665. if isinstance(reply, Message):
  666. if reply.success:
  667. return successfullyTransfered(userA, userB)
  668. else:
  669. return errorReply(reply.message)
  670. @app.route('/bxfer/<userA>/<userB>')
  671. class BXfer(Resource):
  672. @authRequired
  673. @app.param('userA', 'User initiating the blind transfer', 'path')
  674. @app.param('userB', 'Transfer destination user', 'path')
  675. @app.response(HTTPStatus.OK, 'Json reply')
  676. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  677. async def get(self, userA, userB):
  678. '''Blind call transfer
  679. '''
  680. if (userA != request.user) and (not request.admin):
  681. abort(401)
  682. channel = await getUserChannel(userA)
  683. if not channel:
  684. return noUserChannel(userA)
  685. reply = await manager.send_action({'Action':'BlindTransfer',
  686. 'Channel':channel,
  687. 'async':'false',
  688. 'Exten':userB})
  689. if isinstance(reply, Message):
  690. if reply.success:
  691. return successfullyTransfered(userA, userB)
  692. else:
  693. return errorReply(reply.message)
  694. @app.route('/originate/<user>/<number>')
  695. class Originate(Resource):
  696. @authRequired
  697. @app.param('user', 'User initiating the call', 'path')
  698. @app.param('number', 'Destination number', 'path')
  699. @app.response(HTTPStatus.OK, 'Json reply')
  700. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  701. async def get(self, user, number):
  702. '''Originate call
  703. '''
  704. if (user != request.user) and (not request.admin):
  705. abort(401)
  706. device = await getUserDevice(user)
  707. if device in NONEs:
  708. return noUserDevice(user)
  709. reply = await manager.send_action({'Action':'Originate',
  710. 'Channel':'PJSIP/{}'.format(device),
  711. 'Context':'from-internal',
  712. 'Exten':number,
  713. 'Priority': '1',
  714. 'async':'false',
  715. 'Callerid': user})
  716. if isinstance(reply, Message):
  717. if reply.success:
  718. return successfullyOriginated(user, number)
  719. else:
  720. return errorReply(reply.message)
  721. @app.route('/hangup/<user>')
  722. class Hangup(Resource):
  723. @authRequired
  724. @app.param('user', 'User to hangup', 'path')
  725. @app.response(HTTPStatus.OK, 'Json reply')
  726. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  727. async def get(self, user):
  728. '''Call hangup
  729. '''
  730. if (user != request.user) and (not request.admin):
  731. abort(401)
  732. channel = await getUserChannel(user)
  733. if not channel:
  734. return noUserChannel(user)
  735. reply = await manager.send_action({'Action':'Hangup',
  736. 'Channel':channel})
  737. if isinstance(reply, Message):
  738. if reply.success:
  739. return successfullyHungup(user)
  740. else:
  741. return errorReply(reply.message)
  742. @app.route('/users/states')
  743. class UsersStates(Resource):
  744. @authRequired
  745. @app.response(HTTPStatus.OK, 'JSON reply with user:state map or error message')
  746. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  747. async def get(self):
  748. '''Returns all users with their combined states.
  749. Possible states are: available, away, dnd, inuse, busy, unavailable, ringing
  750. '''
  751. if not request.admin:
  752. abort(401)
  753. #app.logger.warning('request device: {}'.format(request.device))
  754. usersCount = await refreshStatesCache()
  755. if usersCount == 0:
  756. return stateCacheEmpty()
  757. return successReply(getUsersStatesCombined())
  758. @app.route('/user/<user>/state')
  759. class UserState(Resource):
  760. @authRequired
  761. @app.param('user', 'User to query for combined state', 'path')
  762. @app.response(HTTPStatus.OK, 'JSON data {"user":user,"state":state}')
  763. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  764. async def get(self, user):
  765. '''Returns user's combined state.
  766. One of: available, away, dnd, inuse, busy, unavailable, ringing
  767. '''
  768. if (user != request.user) and (not request.admin):
  769. abort(401)
  770. if user not in app.cache['ustates']:
  771. return noUser(user)
  772. return successReply({'user':user,'state':getUserStateCombined(user)})
  773. @app.route('/user/<user>/presence')
  774. class PresenceState(Resource):
  775. @authRequired
  776. @app.param('user', 'User to query for presence state', 'path')
  777. @app.response(HTTPStatus.OK, 'JSON data {"user":user,"state":state}')
  778. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  779. async def get(self, user):
  780. '''Returns user's presence state.
  781. One of: not_set, unavailable, available, away, xa, chat, dnd
  782. '''
  783. if (user != request.user) and (not request.admin):
  784. abort(401)
  785. if user not in app.cache['ustates']:
  786. return noUser(user)
  787. return successReply({'user':user,'state':app.cache['pstates'].get(user, 'not_set')})
  788. @app.route('/user/<user>/presence/<state>')
  789. class SetPresenceState(Resource):
  790. @authRequired
  791. @app.param('user', 'Target user to set the presence state', 'path')
  792. @app.param('state',
  793. 'The presence state for user, one of: not_set, unavailable, available, away, xa, chat or dnd',
  794. 'path')
  795. @app.response(HTTPStatus.OK, 'Json reply')
  796. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  797. async def get(self, user, state):
  798. '''Sets user's presence state.
  799. Allowed states: not_set | unavailable | available | away | xa | chat | dnd
  800. '''
  801. if (user != request.user) and (not request.admin):
  802. abort(401)
  803. if state not in presenceStates:
  804. return invalidState(state)
  805. if user not in app.cache['ustates']:
  806. return noUser(user)
  807. if (state.lower() in ('available','not_set','away','xa','chat')) and (getUserStateCombined(user) == 'dnd'):
  808. result = await amiDBDel('DND', '{}'.format(user))
  809. result = await amiSetVar('PRESENCE_STATE(CustomPresence:{})'.format(user), state)
  810. if result is not None:
  811. return errorReply(result)
  812. if state.lower() == 'dnd':
  813. result = await amiDBPut('DND', '{}'.format(user), 'YES')
  814. return successfullySetState(user, state)
  815. @app.route('/users/devices')
  816. class UsersDevices(Resource):
  817. @authRequired
  818. @app.response(HTTPStatus.OK, 'JSON reply with user:device map or error message')
  819. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  820. async def get(self):
  821. '''Returns users to device maping.
  822. '''
  823. if not request.admin:
  824. abort(401)
  825. data = {}
  826. for user in app.cache['ustates']:
  827. device = await getUserDevice(user)
  828. if ((device in NONEs) or (device == user)):
  829. device = None
  830. else:
  831. device = device.replace('{}&'.format(user), '')
  832. data[user]= device
  833. return successReply(data)
  834. @app.route('/device/<device>/<user>/on')
  835. @app.route('/user/<user>/<device>/on')
  836. class UserDeviceBind(Resource):
  837. @authRequired
  838. @app.param('device', 'Device number to bind to', 'path')
  839. @app.param('user', 'User to bind to device', 'path')
  840. @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
  841. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  842. async def get(self, device, user):
  843. '''Binds user to device.
  844. Both user and device numbers are checked for existance.
  845. Any device user was previously bound to, is unbound.
  846. Any user previously bound to device is unbound also.
  847. '''
  848. if (device != request.device) and (not request.admin):
  849. abort(401)
  850. if user not in app.cache['ustates']:
  851. return noUser(user)
  852. dial = await getDeviceDial(device) # Check if device exists in astdb
  853. if dial is None:
  854. return noDevice(device)
  855. currentUser = await getDeviceUser(device) # Check if any user is already bound to device
  856. if currentUser == user:
  857. return alreadyBound(user, device)
  858. ast = await getGlobalVars()
  859. if currentUser not in NONEs: # If any other user is bound to device, unbind him,
  860. await setUserDevice(currentUser, None)
  861. if ast.QUEDEVSTATE == 'TRUE': # set device states for previous user queues
  862. await setQueueStates(currentUser, device, 'NOT_INUSE')
  863. await setUserHint(currentUser, None, ast) # set hints for previous user
  864. await setDeviceUser(device, user) # Bind user to device
  865. # If user is bound to some other devices, unbind him and set
  866. # device states for those devices
  867. await unbindOtherDevices(user, device, ast)
  868. if not (await setUserHint(user, dial, ast)): # Set hints for user on new device
  869. return hintError(user, device)
  870. await setUserDeviceStates(user, device, ast) # Set device states for users new device
  871. if not (await setUserDevice(user, device)): # Bind device to user
  872. return bindError(user, device)
  873. app.cache['usermap'][device] = user
  874. app.cache['devicemap'][user] = device
  875. return successfullyBound(user, device)
  876. @app.route('/device/<device>/off')
  877. class DeviceUnBind(Resource):
  878. @authRequired
  879. @app.param('device', 'Device number to unbind', 'path')
  880. @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
  881. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  882. async def get(self, device):
  883. '''Unbinds any user from device.
  884. Device is checked for existance.
  885. '''
  886. if (device != request.device) and (not request.admin):
  887. abort(401)
  888. dial = await getDeviceDial(device) # Check if device exists in astdb
  889. if dial is None:
  890. return noDevice(device)
  891. currentUser = await getDeviceUser(device) # Check if any user is bound to device
  892. if currentUser in NONEs:
  893. return noUserBound(device)
  894. else:
  895. ast = await getGlobalVars()
  896. await setUserDevice(currentUser, None) # Unbind device from current user
  897. if ast.QUEDEVSTATE == 'TRUE': # set device states for current user queues
  898. await setQueueStates(currentUser, device, 'NOT_INUSE')
  899. await setUserHint(currentUser, None, ast) # set hints for current user
  900. await setDeviceUser(device, 'none') # Unbind user from device
  901. del app.cache['usermap'][device]
  902. del app.cache['devicemap'][currentUser]
  903. return successfullyUnbound(currentUser, device)
  904. @app.route('/cdr')
  905. class CDR(Resource):
  906. @authRequired
  907. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  908. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  909. @app.response(HTTPStatus.OK, 'JSON reply')
  910. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  911. async def get(self):
  912. '''Returns CDR data, groupped by logical call id.
  913. All request arguments are optional.
  914. '''
  915. if not request.admin:
  916. abort(401)
  917. start = parseDatetime(request.args.get('start'))
  918. end = parseDatetime(request.args.get('end'))
  919. cdr = await getCDR(start, end)
  920. return successReply(cdr)
  921. @app.route('/cel')
  922. class CEL(Resource):
  923. @authRequired
  924. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  925. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  926. @app.response(HTTPStatus.OK, 'JSON reply')
  927. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  928. async def get(self):
  929. '''Returns CEL data, groupped by logical call id.
  930. All request arguments are optional.
  931. '''
  932. if not request.admin:
  933. abort(401)
  934. start = parseDatetime(request.args.get('start'))
  935. end = parseDatetime(request.args.get('end'))
  936. cel = await getCEL(start, end)
  937. return successReply(cel)
  938. @app.route('/calls')
  939. class Calls(Resource):
  940. @authRequired
  941. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 and YYYYMMDDhhmmss', 'query')
  942. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 and YYYYMMDDhhmmss', 'query')
  943. @app.response(HTTPStatus.OK, 'JSON reply')
  944. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  945. async def get(self):
  946. '''Returns aggregated call data JSON. Draft implementation.
  947. All request arguments are optional.
  948. '''
  949. if not request.admin:
  950. abort(401)
  951. calls = []
  952. start = parseDatetime(request.args.get('start'))
  953. end = parseDatetime(request.args.get('end'))
  954. cdr = await getCDR(start, end)
  955. for c in cdr:
  956. _call = {'id':c.linkedid,
  957. 'start':c.start,
  958. 'type': c.direction,
  959. 'numberA': c.src,
  960. 'numberB': c.dst,
  961. 'line': c.did,
  962. 'duration': c.duration,
  963. 'waiting': c.waiting,
  964. 'status':c.disposition,
  965. 'url': c.file }
  966. calls.append(_call)
  967. return successReply(calls)
  968. @app.route('/user/<user>/calls')
  969. class UserCalls(Resource):
  970. @authRequired
  971. @app.param('user', 'User to query for call stats', 'path')
  972. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 and YYYYMMDDhhmmss', 'query')
  973. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 and YYYYMMDDhhmmss', 'query')
  974. @app.param('direction', 'Calls direction, in or out. If not specified both are returned', 'query')
  975. @app.param('limit', 'Max number of returned records, defaults to unlimited. Use offset parameter together with limit', 'query')
  976. @app.param('offset', 'If limit is specified use offset parameter to request more results', 'query')
  977. @app.param('order', 'Calls sort order for datetime field. ASC or DESC. Defaults to ASC', 'query')
  978. @app.response(HTTPStatus.OK, 'JSON data {"status":status,"data":data,"message":message}')
  979. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  980. async def get(self, user):
  981. '''Returns user's call stats.
  982. '''
  983. if (user != request.user) and (not request.admin):
  984. abort(401)
  985. if user not in app.cache['ustates']:
  986. return noUser(user)
  987. cdr = await getUserCDR(user,
  988. parseDatetime(request.args.get('start')),
  989. parseDatetime(request.args.get('end')),
  990. request.args.get('direction', None),
  991. request.args.get('limit', None),
  992. request.args.get('offset', None),
  993. request.args.get('order', 'ASC'))
  994. return successReply(cdr)
  995. @app.route('/device/<device>/callback')
  996. class DeviceCallback(Resource):
  997. @authRequired
  998. @app.param('device', 'Device to get/set the callback url for', 'path')
  999. @app.param('url', 'used to set the Callback url for the device', 'query')
  1000. @app.response(HTTPStatus.OK, 'JSON data {"user":user,"state":state}')
  1001. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1002. async def get(self, device):
  1003. '''Returns and sets device's callback url.
  1004. '''
  1005. if (device != request.device) and (not request.admin):
  1006. abort(401)
  1007. url = request.args.get('url', None)
  1008. if url is not None:
  1009. await db.execute(query='REPLACE INTO callback_urls (device, url) VALUES (:device, :url)',
  1010. values={'device': device,'url': url})
  1011. else:
  1012. row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
  1013. values={'device': device})
  1014. if row is not None:
  1015. url = row['url']
  1016. return successCallbackURL(device, url)
  1017. manager.connect()
  1018. app.run(loop=main_loop, host='0.0.0.0', port=app.config['PORT'])