app.py 33 KB

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