app.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  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 databases import Database
  12. from quart import jsonify, request, render_template_string, abort
  13. from quart.json import JSONEncoder
  14. from quart_openapi import Pint, Resource
  15. from http import HTTPStatus
  16. from panoramisk import Manager, Message
  17. from utils import *
  18. from cel import *
  19. from logging.config import dictConfig
  20. class ApiJsonEncoder(JSONEncoder):
  21. def default(self, o):
  22. if isinstance(o, dt):
  23. return o.isoformat()
  24. if isinstance(o, CdrChannel):
  25. return str(o)
  26. if isinstance(o, CdrEvent):
  27. return o.__dict__
  28. if isinstance(o, CdrEvents) or isinstance(o, CelEvents):
  29. return o.all
  30. if isinstance(o, CdrCall) or isinstance(o, CelCall):
  31. return o.__dict__
  32. return JSONEncoder.default(self, o)
  33. class PintDB:
  34. def __init__(self, app: Optional[Pint] = None) -> None:
  35. self.init_app(app)
  36. self._db = Database(app.config["DB_URI"])
  37. def init_app(self, app: Pint) -> None:
  38. app.before_serving(self._before_serving)
  39. app.after_serving(self._after_serving)
  40. async def _before_serving(self) -> None:
  41. await self._db.connect()
  42. async def _after_serving(self) -> None:
  43. await self._db.disconnect()
  44. def __getattr__(self, name: str) -> Any:
  45. return getattr(self._db, name)
  46. # One asyncio event loop is used for AMI communication and HTTP requests routing with Quart
  47. main_loop = asyncio.get_event_loop()
  48. app = Pint(__name__, title=os.getenv('APP_TITLE', 'PBX API'), no_openapi=True)
  49. app.json_encoder = ApiJsonEncoder
  50. app.config.update({
  51. 'TITLE': os.getenv('APP_TITLE', 'PBX API'),
  52. 'APPLICATION_ROOT': os.getenv('APP_APPLICATION_ROOT', None),
  53. 'SCHEME': os.getenv('APP_SCHEME', 'http'),
  54. 'FQDN': os.getenv('APP_FQDN', '127.0.0.1'),
  55. 'PORT': int(os.getenv('APP_API_PORT', 8000)),
  56. 'BODY_TIMEOUT': int(os.getenv('APP_BODY_TIMEOUT', 60)),
  57. 'DEBUG': os.getenv('APP_DEBUG', 'False').lower() in TRUEs,
  58. 'MAX_CONTENT_LENGTH': int(os.getenv('APP_MAX_CONTENT_LENGTH', 16777216)),
  59. 'AMI_HOST': os.getenv('APP_AMI_HOST', '127.0.0.1'),
  60. 'AMI_PORT': int(os.getenv('APP_AMI_PORT', 5038)),
  61. 'AMI_USERNAME': os.getenv('APP_AMI_USERNAME', 'app'),
  62. 'AMI_SECRET': os.getenv('APP_AMI_SECRET', 'secret'),
  63. 'AMI_PING_DELAY': int(os.getenv('APP_AMI_PING_DELAY', 10)),
  64. 'AMI_PING_INTERVAL': int(os.getenv('APP_AMI_PING_INTERVAL', 10)),
  65. 'AMI_TIMEOUT': int(os.getenv('APP_AMI_TIMEOUT', 5)),
  66. 'AUTH_HEADER': os.getenv('APP_AUTH_HEADER', 'APP-auth-token'),
  67. 'AUTH_SECRET': os.getenv('APP_AUTH_SECRET', '3bfbeaabf363dd64fe263bd36830a6b6'),
  68. 'SWAGGER_JS_URL': os.getenv('APP_SWAGGER_JS_URL', SWAGGER_JS_URL),
  69. 'SWAGGER_CSS_URL': os.getenv('APP_SWAGGER_CSS_URL', SWAGGER_CSS_URL),
  70. 'STATE_CALLBACK_URL': os.getenv('APP_STATE_CALLBACK_URL', None),
  71. 'DB_URI': 'mysql://{}:{}@{}:{}/{}'.format(os.getenv('MYSQL_USER', 'asterisk'),
  72. os.getenv('MYSQL_PASSWORD', 'secret'),
  73. os.getenv('MYSQL_SERVER', 'db'),
  74. os.getenv('APP_PORT_MYSQL', '3306'),
  75. os.getenv('FREEPBX_CDRDBNAME', None)),
  76. 'EXTRA_API_URL': os.getenv('APP_EXTRA_API_URL', None)})
  77. app.cache = {'devices':[],
  78. 'ustates':{},
  79. 'pstates':{},
  80. 'queues':{}}
  81. manager = Manager(
  82. loop=main_loop,
  83. host=app.config['AMI_HOST'],
  84. port=app.config['AMI_PORT'],
  85. username=app.config['AMI_USERNAME'],
  86. secret=app.config['AMI_SECRET'],
  87. ping_delay=app.config['AMI_PING_DELAY'],
  88. ping_interval=app.config['AMI_PING_INTERVAL'],
  89. reconnect_timeout=app.config['AMI_TIMEOUT'],
  90. )
  91. class AuthMiddleware:
  92. '''ASGI process middleware that rejects requests missing
  93. the correct authentication header'''
  94. def __init__(self, app):
  95. self.app = app
  96. async def __call__(self, scope, receive, send):
  97. if 'headers' not in scope:
  98. return await self.app(scope, receive, send)
  99. for header, value in scope['headers']:
  100. if ((header == bytes(app.config['AUTH_HEADER'].lower(), 'utf-8')) and
  101. (value == bytes(app.config['AUTH_SECRET'], 'utf-8'))):
  102. return await self.app(scope, receive, send)
  103. # Paths "/openapi.json" and "/ui" do not require auth
  104. if (('path' in scope) and
  105. (scope['path'] in NO_AUTH_ROUTES)):
  106. return await self.app(scope, receive, send)
  107. return await self.error_response(receive, send)
  108. async def error_response(self, receive, send):
  109. await send({'type': 'http.response.start',
  110. 'status': 401,
  111. 'headers': [(b'content-length', b'21')]})
  112. await send({'type': 'http.response.body',
  113. 'body': b'Authorization requred',
  114. 'more_body': False})
  115. app.asgi_app = AuthMiddleware(app.asgi_app)
  116. db = PintDB(app)
  117. @manager.register_event('FullyBooted')
  118. @manager.register_event('Reload')
  119. async def reloadCallback(mngr: Manager, msg: Message):
  120. await refreshDevicesCache()
  121. await refreshStatesCache()
  122. await refreshQueuesCache()
  123. await rebindLostDevices()
  124. @manager.register_event('ExtensionStatus')
  125. async def extensionStatusCallback(mngr: Manager, msg: Message):
  126. user = msg.exten
  127. state = msg.statustext.lower()
  128. if user in app.cache['ustates']:
  129. prevState = getUserStateCombined(user)
  130. app.cache['ustates'][user] = state
  131. combinedState = getUserStateCombined(user)
  132. if combinedState != prevState:
  133. await userStateChangeCallback(user, combinedState, prevState)
  134. @manager.register_event('PresenceStatus')
  135. async def presenceStatusCallback(mngr: Manager, msg: Message):
  136. user = msg.exten #hint = msg.hint
  137. state = msg.status.lower()
  138. if user in app.cache['ustates']:
  139. prevState = getUserStateCombined(user)
  140. app.cache['pstates'][user] = state
  141. combinedState = getUserStateCombined(user)
  142. if combinedState != prevState:
  143. await userStateChangeCallback(user, combinedState, prevState)
  144. async def getCDR(start=None,
  145. end=None,
  146. table='cdr',
  147. field='calldate',
  148. sort='calldate, SUBSTR(uniqueid,1,10), sequence'):
  149. _cdr = {}
  150. if end is None:
  151. end = dt.now()
  152. if start is None:
  153. start=(end - td(hours=24))
  154. async for row in db.iterate(query='''SELECT *
  155. FROM {table}
  156. WHERE linkedid
  157. IN (SELECT DISTINCT(linkedid)
  158. FROM {table}
  159. WHERE {field}
  160. BETWEEN :start AND :end)
  161. ORDER BY {sort};'''.format(table=table,
  162. field=field,
  163. sort=sort),
  164. values={'start':start,
  165. 'end':end}):
  166. if row['linkedid'] in _cdr:
  167. _cdr[row['linkedid']].events.add(row)
  168. else:
  169. _cdr[row['linkedid']]=CdrCall(row)
  170. cdr = []
  171. for _id in sorted(_cdr.keys()):
  172. cdr.append(_cdr[_id])
  173. return cdr
  174. async def getCEL(start=None, end=None, table='cel', field='eventtime', sort='id'):
  175. return await getCDR(start, end, table, field, sort)
  176. @app.before_first_request
  177. async def initHttpClient():
  178. app.config['HTTP_CLIENT'] = aiohttp.ClientSession(loop=main_loop)
  179. @app.route('/openapi.json')
  180. async def openapi():
  181. '''Generates JSON that conforms OpenAPI Specification
  182. '''
  183. schema = app.__schema__
  184. schema['servers'] = [{'url':'{}://{}:{}'.format(app.config['SCHEME'],
  185. app.config['FQDN'],
  186. app.config['PORT'])}]
  187. if app.config['EXTRA_API_URL'] is not None:
  188. schema['servers'].append({'url':app.config['EXTRA_API_URL']})
  189. schema['components'] = {'securitySchemes':{'ApiKey':{'type': 'apiKey',
  190. 'name': app.config['AUTH_HEADER'],
  191. 'in': 'header'}}}
  192. schema['security'] = [{'ApiKey':[]}]
  193. return jsonify(schema)
  194. @app.route('/ui')
  195. async def ui():
  196. '''Swagger UI
  197. '''
  198. return await render_template_string(SWAGGER_TEMPLATE,
  199. title=app.config['TITLE'],
  200. js_url=app.config['SWAGGER_JS_URL'],
  201. css_url=app.config['SWAGGER_CSS_URL'])
  202. @app.route('/ami/action', methods=['POST'])
  203. async def action():
  204. _payload = await request.get_data()
  205. reply = await manager.send_action(json.loads(_payload))
  206. return str(reply)
  207. @app.route('/ami/getvar/<string:variable>')
  208. async def amiGetVar(variable):
  209. '''AMI GetVar
  210. Returns value of requested variable using AMI action GetVar in background.
  211. Parameters:
  212. variable (string): Variable to query for
  213. Returns:
  214. string: Variable value or empty string if variable not found
  215. '''
  216. reply = await manager.send_action({'Action': 'GetVar',
  217. 'Variable': variable})
  218. app.logger.warning('GetVar({})->{}'.format(variable, reply.value))
  219. return reply.value
  220. @app.route('/ami/auths')
  221. async def amiPJSIPShowAuths():
  222. auths = {}
  223. reply = await manager.send_action({'Action':'PJSIPShowAuths'})
  224. if len(reply) >= 2:
  225. for message in reply:
  226. if ((message.event == 'AuthList') and
  227. ('objecttype' in message) and
  228. (message.objecttype == 'auth')):
  229. auths[message.username] = message.password
  230. return successReply(auths)
  231. @app.route('/ami/aors')
  232. async def amiPJSIPShowAors():
  233. aors = {}
  234. reply = await manager.send_action({'Action':'PJSIPShowAors'})
  235. if len(reply) >= 2:
  236. for message in reply:
  237. if ((message.event == 'AorList') and
  238. ('objecttype' in message) and
  239. (message.objecttype == 'aor') and
  240. (int(message.maxcontacts) > 0)):
  241. aors[message.objectname] = message.contacts
  242. app.logger.warning('AorsList: {}'.format(','.join(aors.keys())))
  243. return successReply(aors)
  244. async def amiSetVar(variable, value):
  245. '''AMI SetVar
  246. Sets variable using AMI action SetVar to value in background.
  247. Parameters:
  248. variable (string): Variable to set
  249. value (string): Value to set for variable
  250. Returns:
  251. string: None if SetVar was successfull, error message overwise
  252. '''
  253. reply = await manager.send_action({'Action': 'SetVar',
  254. 'Variable': variable,
  255. 'Value': value})
  256. app.logger.warning('SetVar({}, {})'.format(variable, value))
  257. if isinstance(reply, Message):
  258. if reply.success:
  259. return None
  260. else:
  261. return reply.message
  262. return 'AMI error'
  263. async def amiDBGet(family, key):
  264. '''AMI DBGet
  265. Returns value of requested astdb key using AMI action DBGet in background.
  266. Parameters:
  267. family (string): astdb key family to query for
  268. key (string): astdb key to query for
  269. Returns:
  270. string: Value or empty string if variable not found
  271. '''
  272. reply = await manager.send_action({'Action': 'DBGet',
  273. 'Family': family,
  274. 'Key': key})
  275. if (isinstance(reply, list) and
  276. (len(reply) > 1)):
  277. for message in reply:
  278. if (message.event == 'DBGetResponse'):
  279. app.logger.warning('DBGet(/{}/{})->{}'.format(family, key, message.val))
  280. return message.val
  281. app.logger.warning('DBGet(/{}/{})->Error!'.format(family, key))
  282. return None
  283. async def amiDBPut(family, key, value):
  284. '''AMI DBPut
  285. Writes value to astdb by family and key using AMI action DBPut in background.
  286. Parameters:
  287. family (string): astdb key family to write to
  288. key (string): astdb key to write to
  289. value (string): value to write
  290. Returns:
  291. boolean: True if DBPut action was successfull, False overwise
  292. '''
  293. reply = await manager.send_action({'Action': 'DBPut',
  294. 'Family': family,
  295. 'Key': key,
  296. 'Val': value})
  297. app.logger.warning('DBPut(/{}/{}, {})'.format(family, key, value))
  298. if (isinstance(reply, Message) and reply.success):
  299. return True
  300. return False
  301. async def amiDBDel(family, key):
  302. '''AMI DBDel
  303. Deletes key from family in astdb using AMI action DBDel in background.
  304. Parameters:
  305. family (string): astdb key family
  306. key (string): astdb key to delete
  307. Returns:
  308. boolean: True if DBDel action was successfull, False overwise
  309. '''
  310. reply = await manager.send_action({'Action': 'DBDel',
  311. 'Family': family,
  312. 'Key': key})
  313. app.logger.warning('DBDel(/{}/{})'.format(family, key))
  314. if (isinstance(reply, Message) and reply.success):
  315. return True
  316. return False
  317. async def amiSetHint(context, user, hint):
  318. '''AMI SetHint
  319. Sets hint for user in context using AMI action DialplanUserAdd with Replace=true in background.
  320. Parameters:
  321. context (string): dialplan context
  322. user (string): user
  323. hint (string): hint for user
  324. Returns:
  325. boolean: True if DialplanUserAdd action was successfull, False overwise
  326. '''
  327. reply = await manager.send_action({'Action': 'DialplanExtensionAdd',
  328. 'Context': context,
  329. 'Extension': user,
  330. 'Priority': 'hint',
  331. 'Application': hint,
  332. 'Replace': 'yes'})
  333. app.logger.warning('SetHint({},{},{})'.format(context, user, hint))
  334. if (isinstance(reply, Message) and reply.success):
  335. return True
  336. return False
  337. async def amiPresenceState(user):
  338. '''AMI PresenceState request for CustomPresence provider
  339. Parameters:
  340. user (string): user
  341. Returns:
  342. boolean, string: True and state or False and error message
  343. '''
  344. reply = await manager.send_action({'Action': 'PresenceState',
  345. 'Provider': 'CustomPresence:{}'.format(user)})
  346. app.logger.warning('PresenceState({})'.format(user))
  347. if isinstance(reply, Message):
  348. if reply.success:
  349. return True, reply.state
  350. else:
  351. return False, reply.message
  352. return False, 'AMI error'
  353. async def amiPresenceStateList():
  354. states = {}
  355. reply = await manager.send_action({'Action':'PresenceStateList'})
  356. if len(reply) >= 2:
  357. for message in reply:
  358. if message.event == 'PresenceStateChange':
  359. user = re.search('CustomPresence:(\d+)', message.presentity).group(1)
  360. states[user] = message.status
  361. app.logger.warning('PresenceStateList: {}'.format(','.join(states.keys())))
  362. return states
  363. async def amiExtensionStateList():
  364. states = {}
  365. reply = await manager.send_action({'Action':'ExtensionStateList'})
  366. if len(reply) >= 2:
  367. for message in reply:
  368. if ((message.event == 'ExtensionStatus') and
  369. (message.context == 'ext-local')):
  370. states[message.exten] = message.statustext.lower()
  371. app.logger.warning('ExtensionStateList: {}'.format(','.join(states.keys())))
  372. return states
  373. async def amiCommand(command):
  374. '''AMI Command
  375. Runs specified command using AMI action Command in background.
  376. Parameters:
  377. command (string): command to run
  378. Returns:
  379. boolean, list: tuple representing the boolean result of request and list of lines of command output
  380. '''
  381. reply = await manager.send_action({'Action': 'Command',
  382. 'Command': command})
  383. result = []
  384. if (isinstance(reply, Message) and reply.success):
  385. if isinstance(reply.output, list):
  386. result = reply.output
  387. else:
  388. result = reply.output.split('\n')
  389. app.logger.warning('Command({})->{}'.format(command, '\n'.join(result)))
  390. return True, result
  391. app.logger.warning('Command({})->Error!'.format(command))
  392. return False, result
  393. async def amiReload(module='core'):
  394. '''AMI Reload
  395. Reload specified asterisk module using AMI action reload in background.
  396. Parameters:
  397. module (string): module to reload, defaults to core
  398. Returns:
  399. boolean: True if Reload action was successfull, False overwise
  400. '''
  401. reply = await manager.send_action({'Action': 'Reload',
  402. 'Module': module})
  403. app.logger.warning('Reload({})'.format(module))
  404. if (isinstance(reply, Message) and reply.success):
  405. return True
  406. return False
  407. async def getGlobalVars():
  408. globalVars = GlobalVars()
  409. for _var in globalVars.d():
  410. setattr(globalVars, _var, await amiGetVar(_var))
  411. return globalVars
  412. async def setUserHint(user, dial, ast):
  413. if dial in NONEs:
  414. hint = 'CustomPresence:{}'.format(user)
  415. else:
  416. _dial= [dial]
  417. if (ast.DNDDEVSTATE == 'TRUE'):
  418. _dial.append('Custom:DND{}'.format(user))
  419. hint = '{},CustomPresence:{}'.format('&'.join(_dial), user)
  420. return await amiSetHint('ext-local', user, hint)
  421. async def amiQueues():
  422. queues = {}
  423. reply = await manager.send_action({'Action':'QueueStatus'})
  424. if len(reply) >= 2:
  425. for message in reply:
  426. if message.event == 'QueueMember':
  427. _qm = QueueMember(re.search('Local\/(\d+)', message.location).group(1))
  428. queues.setdefault(message.queue, []).append(_qm.fromMessage(message))
  429. app.logger.warning('QueuesList: {}'.format(','.join(queues.keys())))
  430. return queues
  431. async def amiDeviceChannel(device):
  432. reply = await manager.send_action({'Action':'CoreShowChannels'})
  433. if len(reply) >= 2:
  434. for message in reply:
  435. if message.event == 'CoreShowChannel':
  436. if message.calleridnum == device:
  437. return message.channel
  438. return None
  439. async def setQueueStates(user, device, state):
  440. for queue in [_q for _q, _ma in app.cache['queues'].items() for _m in _ma if _m.user == user]:
  441. await amiSetVar('DEVICE_STATE(Custom:QUEUE{}*{})'.format(device, queue), state)
  442. async def getDeviceUser(device):
  443. return await amiDBGet('DEVICE', '{}/user'.format(device))
  444. async def getDeviceDial(device):
  445. return await amiDBGet('DEVICE', '{}/dial'.format(device))
  446. async def getUserCID(user):
  447. return await amiDBGet('AMPUSER', '{}/cidnum'.format(user))
  448. async def setDeviceUser(device, user):
  449. return await amiDBPut('DEVICE', '{}/user'.format(device), user)
  450. async def getUserDevice(user):
  451. return await amiDBGet('AMPUSER', '{}/device'.format(user))
  452. async def setUserDevice(user, device):
  453. if device is None:
  454. return await amiDBDel('AMPUSER', '{}/device'.format(user))
  455. else:
  456. return await amiDBPut('AMPUSER', '{}/device'.format(user), device)
  457. async def unbindOtherDevices(user, newDevice, ast):
  458. '''Unbinds user from all devices except newDevice and sets
  459. all required device states.
  460. '''
  461. devices = await amiDBGet('AMPUSER', '{}/device'.format(user))
  462. if devices not in NONEs:
  463. for _device in sorted(set(devices.split('&')), key=int):
  464. if _device != newDevice:
  465. if ast.FMDEVSTATE == 'TRUE':
  466. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(_device), 'INVALID')
  467. if ast.QUEDEVSTATE == 'TRUE':
  468. await setQueueStates(user, _device, 'NOT_INUSE')
  469. if ast.DNDDEVSTATE:
  470. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(_device), 'NOT_INUSE')
  471. if ast.CFDEVSTATE:
  472. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(_device), 'NOT_INUSE')
  473. await amiDBPut('DEVICE', '{}/user'.format(_device), 'none')
  474. async def setUserDeviceStates(user, device, ast):
  475. if ast.FMDEVSTATE == 'TRUE':
  476. _followMe = await amiDBGet('AMPUSER', '{}/followme/ddial'.format(user))
  477. if _followMe is not None:
  478. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(device), followMe2DevState(_followMe))
  479. if ast.QUEDEVSTATE == 'TRUE':
  480. await setQueueStates(user, device, 'INUSE')
  481. if ast.DNDDEVSTATE:
  482. _dnd = await amiDBGet('DND', user)
  483. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(device), 'INUSE' if _dnd == 'YES' else 'NOT_INUSE')
  484. if ast.CFDEVSTATE:
  485. _cf = await amiDBGet('CF', user)
  486. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(device), 'INUSE' if _cf != '' else 'NOT_INUSE')
  487. async def refreshStatesCache():
  488. app.cache['ustates'] = await amiExtensionStateList()
  489. app.cache['pstates'] = await amiPresenceStateList()
  490. return len(app.cache['ustates'])
  491. async def refreshDevicesCache():
  492. _reply = await amiPJSIPShowAors()
  493. aors = _reply['data']
  494. app.cache['devices'] = list(aors.keys())
  495. return len(app.cache['devices'])
  496. async def refreshQueuesCache():
  497. app.cache['queues'] = await amiQueues()
  498. return len(app.cache['queues'])
  499. async def rebindLostDevices():
  500. ast = await getGlobalVars()
  501. for device in app.cache['devices']:
  502. user = await getDeviceUser(device)
  503. if (user != 'none') and (user in app.cache['ustates'].keys()):
  504. _device = await getUserDevice(_user)
  505. if _device != device:
  506. app.logger.warning('Fixing bind user {} to device {}'.format(user, device))
  507. dial = await getDeviceDial(device)
  508. await setUserHint(user, dial, ast) # Set hints for user on new device
  509. await setUserDeviceStates(user, device, ast) # Set device states for users device
  510. await setUserDevice(user, device) # Bind device to user
  511. async def userStateChangeCallback(user, state, prevState = None):
  512. reply = None
  513. if ((app.config['STATE_CALLBACK_URL'] not in NONEs) and
  514. ('HTTP_CLIENT' in app.config)):
  515. reply = await app.config['HTTP_CLIENT'].post(app.config['STATE_CALLBACK_URL'],
  516. json={'user': user,
  517. 'state': state,
  518. 'prev_state':prevState})
  519. else:
  520. app.logger.warning('{} changed state to: {}'.format(user, state))
  521. return reply
  522. def getUserStateCombined(user):
  523. _uCache = app.cache['ustates']
  524. _pCache = app.cache['pstates']
  525. return combinedStates[_uCache.get(user, 'unavailable')][_pCache.get(user, 'not_set')]
  526. def getUsersStatesCombined():
  527. return {user:getUserStateCombined(user) for user in app.cache['ustates']}
  528. @app.route('/atxfer/<userA>/<userB>')
  529. class AtXfer(Resource):
  530. @app.param('userA', 'User initiating the attended transfer', 'path')
  531. @app.param('userB', 'Transfer destination user', 'path')
  532. @app.response(HTTPStatus.OK, 'Json reply')
  533. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  534. async def get(self, userA, userB):
  535. '''Attended call transfer
  536. '''
  537. device = await getUserDevice(userA)
  538. if device in NONEs:
  539. return noUserDevice(userA)
  540. channel = await amiDeviceChannel(device)
  541. if channel in NONEs:
  542. return noUserChannel(userA)
  543. reply = await manager.send_action({'Action':'Atxfer',
  544. 'Channel':channel,
  545. 'async':'false',
  546. 'Exten':userB})
  547. if isinstance(reply, Message):
  548. if reply.success:
  549. return successfullyTransfered(userA, userB)
  550. else:
  551. return errorReply(reply.message)
  552. @app.route('/bxfer/<userA>/<userB>')
  553. class BXfer(Resource):
  554. @app.param('userA', 'User initiating the blind transfer', 'path')
  555. @app.param('userB', 'Transfer destination user', 'path')
  556. @app.response(HTTPStatus.OK, 'Json reply')
  557. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  558. async def get(self, userA, userB):
  559. '''Blind call transfer
  560. '''
  561. device = await getUserDevice(userA)
  562. if device in NONEs:
  563. return noUserDevice(userA)
  564. channel = await amiDeviceChannel(device)
  565. if channel in NONEs:
  566. return noUserChannel(userA)
  567. reply = await manager.send_action({'Action':'BlindTransfer',
  568. 'Channel':channel,
  569. 'async':'false',
  570. 'Exten':userB})
  571. if isinstance(reply, Message):
  572. if reply.success:
  573. return successfullyTransfered(userA, userB)
  574. else:
  575. return errorReply(reply.message)
  576. @app.route('/users/states')
  577. class UsersStates(Resource):
  578. @app.response(HTTPStatus.OK, 'JSON reply with user:state map or error message')
  579. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  580. async def get(self):
  581. '''Returns all users with their combined states.
  582. Possible states are: available, away, dnd, inuse, busy, unavailable, ringing
  583. '''
  584. usersCount = await refreshStatesCache()
  585. if usersCount == 0:
  586. return stateCacheEmpty()
  587. return successReply(getUsersStatesCombined())
  588. @app.route('/user/<user>/state')
  589. class UserState(Resource):
  590. @app.param('user', 'User to query for combined state', 'path')
  591. @app.response(HTTPStatus.OK, 'JSON data {"user":user,"state":state}')
  592. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  593. async def get(self, user):
  594. '''Returns user's combined state.
  595. One of: available, away, dnd, inuse, busy, unavailable, ringing
  596. '''
  597. if user not in app.cache['ustates']:
  598. return noUser(user)
  599. return successReply({'user':user,'state':getUserStateCombined(user)})
  600. @app.route('/user/<user>/presence')
  601. class PresenceState(Resource):
  602. @app.param('user', 'User to query for presence state', 'path')
  603. @app.response(HTTPStatus.OK, 'JSON data {"user":user,"state":state}')
  604. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  605. async def get(self, user):
  606. '''Returns user's presence state.
  607. One of: not_set, unavailable, available, away, xa, chat, dnd
  608. '''
  609. if user not in app.cache['ustates']:
  610. return noUser(user)
  611. return successReply({'user':user,'state':app.cache['pstates'].get(user, 'not_set')})
  612. @app.route('/user/<user>/presence/<state>')
  613. class SetPresenceState(Resource):
  614. @app.param('user', 'Target user to set the presence state', 'path')
  615. @app.param('state',
  616. 'The presence state for user, one of: not_set, unavailable, available, away, xa, chat or dnd',
  617. 'path')
  618. @app.response(HTTPStatus.OK, 'Json reply')
  619. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  620. async def get(self, user, state):
  621. '''Sets user's presence state.
  622. Allowed states: not_set | unavailable | available | away | xa | chat | dnd
  623. '''
  624. if state not in presenceStates:
  625. return invalidState(state)
  626. if user not in app.cache['ustates']:
  627. return noUser(user)
  628. result = await amiSetVar('PRESENCE_STATE(CustomPresence:{})'.format(user), state)
  629. if result is not None:
  630. return errorReply(result)
  631. return successfullySetState(user, state)
  632. @app.route('/users/devices')
  633. class UsersDevices(Resource):
  634. @app.response(HTTPStatus.OK, 'JSON reply with user:device map or error message')
  635. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  636. async def get(self):
  637. '''Returns all users with their combined states.
  638. Possible states are: available, away, dnd, inuse, busy, unavailable, ringing
  639. '''
  640. data = {}
  641. for user in app.cache['ustates']:
  642. device = await getUserDevice(user)
  643. if ((device in NONEs) or (device == user)):
  644. device = None
  645. data[user]=device
  646. return successReply(data)
  647. @app.route('/device/<device>/<user>/on')
  648. @app.route('/user/<user>/<device>/on')
  649. class UserDeviceBind(Resource):
  650. @app.param('device', 'Device number to bind to', 'path')
  651. @app.param('user', 'User to bind to device', 'path')
  652. @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
  653. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  654. async def get(self, device, user):
  655. '''Binds user to device.
  656. Both user and device numbers are checked for existance.
  657. Any device user was previously bound to, is unbound.
  658. Any user previously bound to device is unbound also.
  659. '''
  660. if user not in app.cache['ustates']:
  661. return noUser(user)
  662. dial = await getDeviceDial(device) # Check if device exists in astdb
  663. if dial is None:
  664. return noDevice(device)
  665. currentUser = await getDeviceUser(device) # Check if any user is already bound to device
  666. if currentUser == user:
  667. return alreadyBound(user, device)
  668. ast = await getGlobalVars()
  669. if currentUser not in NONEs: # If any other user is bound to device, unbind him,
  670. await setUserDevice(currentUser, None)
  671. if ast.QUEDEVSTATE == 'TRUE': # set device states for previous user queues
  672. await setQueueStates(currentUser, device, 'NOT_INUSE')
  673. await setUserHint(currentUser, None, ast) # set hints for previous user
  674. await setDeviceUser(device, user) # Bind user to device
  675. # If user is bound to some other devices, unbind him and set
  676. # device states for those devices
  677. await unbindOtherDevices(user, device, ast)
  678. if not (await setUserHint(user, dial, ast)): # Set hints for user on new device
  679. return hintError(user, device)
  680. await setUserDeviceStates(user, device, ast) # Set device states for users new device
  681. if not (await setUserDevice(user, device)): # Bind device to user
  682. return bindError(user, device)
  683. return successfullyBound(user, device)
  684. @app.route('/device/<device>/off')
  685. class DeviceUnBind(Resource):
  686. @app.param('device', 'Device number to unbind', 'path')
  687. @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
  688. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  689. async def get(self, device):
  690. '''Unbinds any user from device.
  691. Device is checked for existance.
  692. '''
  693. dial = await getDeviceDial(device) # Check if device exists in astdb
  694. if dial is None:
  695. return noDevice(device)
  696. currentUser = await getDeviceUser(device) # Check if any user is bound to device
  697. if currentUser in NONEs:
  698. return noUserBound(device)
  699. else:
  700. ast = await getGlobalVars()
  701. await setUserDevice(currentUser, None) # Unbind device from current user
  702. if ast.QUEDEVSTATE == 'TRUE': # set device states for current user queues
  703. await setQueueStates(currentUser, device, 'NOT_INUSE')
  704. await setUserHint(currentUser, None, ast) # set hints for current user
  705. await setDeviceUser(device, 'none') # Unbind user from device
  706. return successfullyUnbound(currentUser, device)
  707. @app.route('/cdr')
  708. class CDR(Resource):
  709. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  710. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  711. @app.response(HTTPStatus.OK, 'JSON reply')
  712. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  713. async def get(self):
  714. '''Returns CDR data, groupped by logical call id.
  715. All request arguments are optional.
  716. '''
  717. start = parseDatetime(request.args.get('start'))
  718. end = parseDatetime(request.args.get('end'))
  719. cdr = await getCDR(start, end)
  720. return successReply(cdr)
  721. @app.route('/cel')
  722. class CEL(Resource):
  723. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  724. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  725. @app.response(HTTPStatus.OK, 'JSON reply')
  726. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  727. async def get(self):
  728. '''Returns CEL data, groupped by logical call id.
  729. All request arguments are optional.
  730. '''
  731. start = parseDatetime(request.args.get('start'))
  732. end = parseDatetime(request.args.get('end'))
  733. cel = await getCEL(start, end)
  734. return successReply(cel)
  735. @app.route('/calls')
  736. class Calls(Resource):
  737. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 and YYYYMMDDhhmmss', 'query')
  738. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 and YYYYMMDDhhmmss', 'query')
  739. @app.response(HTTPStatus.OK, 'JSON reply')
  740. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  741. async def get(self):
  742. '''Returns aggregated call data JSON. Draft implementation.
  743. All request arguments are optional.
  744. '''
  745. calls = []
  746. start = parseDatetime(request.args.get('start'))
  747. end = parseDatetime(request.args.get('end'))
  748. cdr = await getCDR(start, end)
  749. for c in cdr:
  750. _call = {'id':c.linkedid,
  751. 'start':c.start,
  752. 'type': c.direction,
  753. 'numberA': c.src,
  754. 'numberB': c.dst,
  755. 'line': c.did,
  756. 'duration': c.duration,
  757. 'waiting': c.waiting,
  758. 'status':c.disposition,
  759. 'url': c.file }
  760. calls.append(_call)
  761. return successReply(calls)
  762. manager.connect()
  763. app.run(loop=main_loop, host='0.0.0.0', port=app.config['PORT'])