app.py 43 KB

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