app.py 33 KB

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