app.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  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')):
  266. aors[message.objectname] = message.contacts
  267. app.logger.warning('AorsList: {}'.format(','.join(aors.keys())))
  268. return successReply(aors)
  269. async def amiSetVar(variable, value):
  270. '''AMI SetVar
  271. Sets variable using AMI action SetVar to value in background.
  272. Parameters:
  273. variable (string): Variable to set
  274. value (string): Value to set for variable
  275. Returns:
  276. string: None if SetVar was successfull, error message overwise
  277. '''
  278. reply = await manager.send_action({'Action': 'SetVar',
  279. 'Variable': variable,
  280. 'Value': value})
  281. app.logger.warning('SetVar({}, {})'.format(variable, value))
  282. if isinstance(reply, Message):
  283. if reply.success:
  284. return None
  285. else:
  286. return reply.message
  287. return 'AMI error'
  288. async def amiDBGet(family, key):
  289. '''AMI DBGet
  290. Returns value of requested astdb key using AMI action DBGet in background.
  291. Parameters:
  292. family (string): astdb key family to query for
  293. key (string): astdb key to query for
  294. Returns:
  295. string: Value or empty string if variable not found
  296. '''
  297. reply = await manager.send_action({'Action': 'DBGet',
  298. 'Family': family,
  299. 'Key': key})
  300. if (isinstance(reply, list) and
  301. (len(reply) > 1)):
  302. for message in reply:
  303. if (message.event == 'DBGetResponse'):
  304. app.logger.warning('DBGet(/{}/{})->{}'.format(family, key, message.val))
  305. return message.val
  306. app.logger.warning('DBGet(/{}/{})->Error!'.format(family, key))
  307. return None
  308. async def amiDBPut(family, key, value):
  309. '''AMI DBPut
  310. Writes value to astdb by family and key using AMI action DBPut in background.
  311. Parameters:
  312. family (string): astdb key family to write to
  313. key (string): astdb key to write to
  314. value (string): value to write
  315. Returns:
  316. boolean: True if DBPut action was successfull, False overwise
  317. '''
  318. reply = await manager.send_action({'Action': 'DBPut',
  319. 'Family': family,
  320. 'Key': key,
  321. 'Val': value})
  322. app.logger.warning('DBPut(/{}/{}, {})'.format(family, key, value))
  323. if (isinstance(reply, Message) and reply.success):
  324. return True
  325. return False
  326. async def amiDBDel(family, key):
  327. '''AMI DBDel
  328. Deletes key from family in astdb using AMI action DBDel in background.
  329. Parameters:
  330. family (string): astdb key family
  331. key (string): astdb key to delete
  332. Returns:
  333. boolean: True if DBDel action was successfull, False overwise
  334. '''
  335. reply = await manager.send_action({'Action': 'DBDel',
  336. 'Family': family,
  337. 'Key': key})
  338. app.logger.warning('DBDel(/{}/{})'.format(family, key))
  339. if (isinstance(reply, Message) and reply.success):
  340. return True
  341. return False
  342. async def amiSetHint(context, user, hint):
  343. '''AMI SetHint
  344. Sets hint for user in context using AMI action DialplanUserAdd with Replace=true in background.
  345. Parameters:
  346. context (string): dialplan context
  347. user (string): user
  348. hint (string): hint for user
  349. Returns:
  350. boolean: True if DialplanUserAdd action was successfull, False overwise
  351. '''
  352. reply = await manager.send_action({'Action': 'DialplanExtensionAdd',
  353. 'Context': context,
  354. 'Extension': user,
  355. 'Priority': 'hint',
  356. 'Application': hint,
  357. 'Replace': 'yes'})
  358. app.logger.warning('SetHint({},{},{})'.format(context, user, hint))
  359. if (isinstance(reply, Message) and reply.success):
  360. return True
  361. return False
  362. async def amiPresenceState(user):
  363. '''AMI PresenceState request for CustomPresence provider
  364. Parameters:
  365. user (string): user
  366. Returns:
  367. boolean, string: True and state or False and error message
  368. '''
  369. reply = await manager.send_action({'Action': 'PresenceState',
  370. 'Provider': 'CustomPresence:{}'.format(user)})
  371. app.logger.warning('PresenceState({})'.format(user))
  372. if isinstance(reply, Message):
  373. if reply.success:
  374. return True, reply.state
  375. else:
  376. return False, reply.message
  377. return False, 'AMI error'
  378. async def amiPresenceStateList():
  379. states = {}
  380. reply = await manager.send_action({'Action':'PresenceStateList'})
  381. if len(reply) >= 2:
  382. for message in reply:
  383. if message.event == 'PresenceStateChange':
  384. user = re.search('CustomPresence:(\d+)', message.presentity).group(1)
  385. states[user] = message.status
  386. app.logger.warning('PresenceStateList: {}'.format(','.join(states.keys())))
  387. return states
  388. async def amiExtensionStateList():
  389. states = {}
  390. reply = await manager.send_action({'Action':'ExtensionStateList'})
  391. if len(reply) >= 2:
  392. for message in reply:
  393. if ((message.event == 'ExtensionStatus') and
  394. (message.context == 'ext-local')):
  395. states[message.exten] = message.statustext.lower()
  396. app.logger.warning('ExtensionStateList: {}'.format(','.join(states.keys())))
  397. return states
  398. async def amiCommand(command):
  399. '''AMI Command
  400. Runs specified command using AMI action Command in background.
  401. Parameters:
  402. command (string): command to run
  403. Returns:
  404. boolean, list: tuple representing the boolean result of request and list of lines of command output
  405. '''
  406. reply = await manager.send_action({'Action': 'Command',
  407. 'Command': command})
  408. result = []
  409. if (isinstance(reply, Message) and reply.success):
  410. if isinstance(reply.output, list):
  411. result = reply.output
  412. else:
  413. result = reply.output.split('\n')
  414. app.logger.warning('Command({})->{}'.format(command, '\n'.join(result)))
  415. return True, result
  416. app.logger.warning('Command({})->Error!'.format(command))
  417. return False, result
  418. async def amiReload(module='core'):
  419. '''AMI Reload
  420. Reload specified asterisk module using AMI action reload in background.
  421. Parameters:
  422. module (string): module to reload, defaults to core
  423. Returns:
  424. boolean: True if Reload action was successfull, False overwise
  425. '''
  426. reply = await manager.send_action({'Action': 'Reload',
  427. 'Module': module})
  428. app.logger.warning('Reload({})'.format(module))
  429. if (isinstance(reply, Message) and reply.success):
  430. return True
  431. return False
  432. async def getGlobalVars():
  433. globalVars = GlobalVars()
  434. for _var in globalVars.d():
  435. setattr(globalVars, _var, await amiGetVar(_var))
  436. return globalVars
  437. async def setUserHint(user, dial, ast):
  438. if dial in NONEs:
  439. hint = 'CustomPresence:{}'.format(user)
  440. else:
  441. _dial= [dial]
  442. if (ast.DNDDEVSTATE == 'TRUE'):
  443. _dial.append('Custom:DND{}'.format(user))
  444. hint = '{},CustomPresence:{}'.format('&'.join(_dial), user)
  445. return await amiSetHint('ext-local', user, hint)
  446. async def amiQueues():
  447. queues = {}
  448. reply = await manager.send_action({'Action':'QueueStatus'})
  449. if len(reply) >= 2:
  450. for message in reply:
  451. if message.event == 'QueueMember':
  452. _qm = QueueMember(re.search('Local\/(\d+)', message.location).group(1))
  453. queues.setdefault(message.queue, []).append(_qm.fromMessage(message))
  454. app.logger.warning('QueuesList: {}'.format(','.join(queues.keys())))
  455. return queues
  456. async def amiDeviceChannel(device):
  457. reply = await manager.send_action({'Action':'CoreShowChannels'})
  458. if len(reply) >= 2:
  459. for message in reply:
  460. if message.event == 'CoreShowChannel':
  461. if message.calleridnum == device:
  462. return message.channel
  463. return None
  464. async def setQueueStates(user, device, state):
  465. for queue in [_q for _q, _ma in app.cache['queues'].items() for _m in _ma if _m.user == user]:
  466. await amiSetVar('DEVICE_STATE(Custom:QUEUE{}*{})'.format(device, queue), state)
  467. async def getDeviceUser(device):
  468. return await amiDBGet('DEVICE', '{}/user'.format(device))
  469. async def getDeviceDial(device):
  470. return await amiDBGet('DEVICE', '{}/dial'.format(device))
  471. async def getUserCID(user):
  472. return await amiDBGet('AMPUSER', '{}/cidnum'.format(user))
  473. async def setDeviceUser(device, user):
  474. return await amiDBPut('DEVICE', '{}/user'.format(device), user)
  475. async def getUserDevice(user):
  476. return await amiDBGet('AMPUSER', '{}/device'.format(user))
  477. async def setUserDevice(user, device):
  478. if device is None:
  479. return await amiDBDel('AMPUSER', '{}/device'.format(user))
  480. else:
  481. return await amiDBPut('AMPUSER', '{}/device'.format(user), device)
  482. async def unbindOtherDevices(user, newDevice, ast):
  483. '''Unbinds user from all devices except newDevice and sets
  484. all required device states.
  485. '''
  486. devices = await amiDBGet('AMPUSER', '{}/device'.format(user))
  487. if devices not in NONEs:
  488. for _device in sorted(set(devices.split('&')), key=int):
  489. if _device != newDevice:
  490. if ast.FMDEVSTATE == 'TRUE':
  491. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(_device), 'INVALID')
  492. if ast.QUEDEVSTATE == 'TRUE':
  493. await setQueueStates(user, _device, 'NOT_INUSE')
  494. if ast.DNDDEVSTATE:
  495. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(_device), 'NOT_INUSE')
  496. if ast.CFDEVSTATE:
  497. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(_device), 'NOT_INUSE')
  498. await amiDBPut('DEVICE', '{}/user'.format(_device), 'none')
  499. async def setUserDeviceStates(user, device, ast):
  500. if ast.FMDEVSTATE == 'TRUE':
  501. _followMe = await amiDBGet('AMPUSER', '{}/followme/ddial'.format(user))
  502. if _followMe is not None:
  503. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(device), followMe2DevState(_followMe))
  504. if ast.QUEDEVSTATE == 'TRUE':
  505. await setQueueStates(user, device, 'INUSE')
  506. if ast.DNDDEVSTATE:
  507. _dnd = await amiDBGet('DND', user)
  508. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(device), 'INUSE' if _dnd == 'YES' else 'NOT_INUSE')
  509. if ast.CFDEVSTATE:
  510. _cf = await amiDBGet('CF', user)
  511. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(device), 'INUSE' if _cf != '' else 'NOT_INUSE')
  512. async def refreshStatesCache():
  513. app.cache['ustates'] = await amiExtensionStateList()
  514. app.cache['pstates'] = await amiPresenceStateList()
  515. return len(app.cache['ustates'])
  516. async def refreshDevicesCache():
  517. aors = await amiPJSIPShowAors()
  518. app.cache['devices'] = list(aors.keys())
  519. return len(app.cache['devices'])
  520. async def refreshQueuesCache():
  521. app.cache['queues'] = await amiQueues()
  522. return len(app.cache['queues'])
  523. async def userStateChangeCallback(user, state, prevState = None):
  524. reply = None
  525. if ((app.config['STATE_CALLBACK_URL'] not in NONEs) and
  526. ('HTTP_CLIENT' in app.config)):
  527. reply = await app.config['HTTP_CLIENT'].post(app.config['STATE_CALLBACK_URL'],
  528. json={'user': user,
  529. 'state': state,
  530. 'prev_state':prevState})
  531. else:
  532. app.logger.warning('{} changed state to: {}'.format(user, state))
  533. return reply
  534. def getUserStateCombined(user):
  535. _uCache = app.cache['ustates']
  536. _pCache = app.cache['pstates']
  537. return combinedStates[_uCache.get(user, 'unavailable')][_pCache.get(user, 'not_set')]
  538. def getUsersStatesCombined():
  539. return {user:getUserStateCombined(user) for user in app.cache['ustates']}
  540. @app.route('/atxfer/<userA>/<userB>')
  541. class AtXfer(Resource):
  542. @app.param('userA', 'User initiating the attended transfer', 'path')
  543. @app.param('userB', 'Transfer destination user', 'path')
  544. @app.response(HTTPStatus.OK, 'Json reply')
  545. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  546. async def get(self, userA, userB):
  547. '''Attended call transfer
  548. '''
  549. device = await getUserDevice(userA)
  550. if device in NONEs:
  551. return noUserDevice(userA)
  552. channel = await amiDeviceChannel(device)
  553. if channel in NONEs:
  554. return noUserChannel(userA)
  555. reply = await manager.send_action({'Action':'Atxfer',
  556. 'Channel':channel,
  557. 'async':'false',
  558. 'Exten':userB})
  559. if isinstance(reply, Message):
  560. if reply.success:
  561. return successfullyTransfered(userA, userB)
  562. else:
  563. return errorReply(reply.message)
  564. @app.route('/users/states')
  565. class UsersStates(Resource):
  566. @app.response(HTTPStatus.OK, 'JSON reply with user:state map or error message')
  567. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  568. async def get(self):
  569. '''Returns all users with their combined states.
  570. Possible states are: available, away, dnd, inuse, busy, unavailable, ringing
  571. '''
  572. usersCount = await refreshStatesCache()
  573. if usersCount == 0:
  574. return stateCacheEmpty()
  575. return successReply(getUsersStatesCombined())
  576. @app.route('/user/<user>/state')
  577. class UserState(Resource):
  578. @app.param('user', 'User to query for combined state', 'path')
  579. @app.response(HTTPStatus.OK, 'JSON data {"user":user,"state":state}')
  580. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  581. async def get(self, user):
  582. '''Returns user's combined state.
  583. One of: available, away, dnd, inuse, busy, unavailable, ringing
  584. '''
  585. if user not in app.cache['ustates']:
  586. return noUser(user)
  587. return successReply({'user':user,'state':getUserStateCombined(user)})
  588. @app.route('/user/<user>/presence')
  589. class PresenceState(Resource):
  590. @app.param('user', 'User to query for presence 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 presence state.
  595. One of: not_set, unavailable, available, away, xa, chat, dnd
  596. '''
  597. if user not in app.cache['ustates']:
  598. return noUser(user)
  599. return successReply({'user':user,'state':app.cache['pstates'].get(user, 'not_set')})
  600. @app.route('/user/<user>/presence/<state>')
  601. class SetPresenceState(Resource):
  602. @app.param('user', 'Target user to set the presence state', 'path')
  603. @app.param('state',
  604. 'The presence state for user, one of: not_set, unavailable, available, away, xa, chat or dnd',
  605. 'path')
  606. @app.response(HTTPStatus.OK, 'Json reply')
  607. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  608. async def get(self, user, state):
  609. '''Sets user's presence state.
  610. Allowed states: not_set | unavailable | available | away | xa | chat | dnd
  611. '''
  612. if state not in presenceStates:
  613. return invalidState(state)
  614. if user not in app.cache['ustates']:
  615. return noUser(user)
  616. result = await amiSetVar('PRESENCE_STATE(CustomPresence:{})'.format(user), state)
  617. if result is not None:
  618. return errorReply(result)
  619. return successfullySetState(user, state)
  620. @app.route('/users/devices')
  621. class UsersDevices(Resource):
  622. @app.response(HTTPStatus.OK, 'JSON reply with user:device map or error message')
  623. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  624. async def get(self):
  625. '''Returns all users with their combined states.
  626. Possible states are: available, away, dnd, inuse, busy, unavailable, ringing
  627. '''
  628. data = {}
  629. for user in app.cache['ustates']:
  630. device = await getUserDevice(user)
  631. if device in NONEs:
  632. device = None
  633. data[user]=device
  634. return successReply(data)
  635. @app.route('/device/<device>/<user>/on')
  636. @app.route('/user/<user>/<device>/on')
  637. class UserDeviceBind(Resource):
  638. @app.param('device', 'Device number to bind to', 'path')
  639. @app.param('user', 'User to bind to device', 'path')
  640. @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
  641. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  642. async def get(self, device, user):
  643. '''Binds user to device.
  644. Both user and device numbers are checked for existance.
  645. Any device user was previously bound to, is unbound.
  646. Any user previously bound to device is unbound also.
  647. '''
  648. if user not in app.cache['ustates']:
  649. return noUser(user)
  650. dial = await getDeviceDial(device) # Check if device exists in astdb
  651. if dial is None:
  652. return noDevice(device)
  653. currentUser = await getDeviceUser(device) # Check if any user is already bound to device
  654. if currentUser == user:
  655. return alreadyBound(user, device)
  656. ast = await getGlobalVars()
  657. if currentUser not in NONEs: # If any other user is bound to device, unbind him,
  658. await setUserDevice(currentUser, None)
  659. if ast.QUEDEVSTATE == 'TRUE': # set device states for previous user queues
  660. await setQueueStates(currentUser, device, 'NOT_INUSE')
  661. await setUserHint(currentUser, None, ast) # set hints for previous user
  662. await setDeviceUser(device, user) # Bind user to device
  663. # If user is bound to some other devices, unbind him and set
  664. # device states for those devices
  665. await unbindOtherDevices(user, device, ast)
  666. if not (await setUserHint(user, dial, ast)): # Set hints for user on new device
  667. return hintError(user, device)
  668. await setUserDeviceStates(user, device, ast) # Set device states for users new device
  669. if not (await setUserDevice(user, device)): # Bind device to user
  670. return bindError(user, device)
  671. return successfullyBound(user, device)
  672. @app.route('/device/<device>/off')
  673. class DeviceUnBind(Resource):
  674. @app.param('device', 'Device number to unbind', 'path')
  675. @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
  676. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  677. async def get(self, device):
  678. '''Unbinds any user from device.
  679. Device is checked for existance.
  680. '''
  681. dial = await getDeviceDial(device) # Check if device exists in astdb
  682. if dial is None:
  683. return noDevice(device)
  684. currentUser = await getDeviceUser(device) # Check if any user is bound to device
  685. if currentUser in NONEs:
  686. return noUserBound(device)
  687. else:
  688. ast = await getGlobalVars()
  689. await setUserDevice(currentUser, None) # Unbind device from current user
  690. if ast.QUEDEVSTATE == 'TRUE': # set device states for current user queues
  691. await setQueueStates(currentUser, device, 'NOT_INUSE')
  692. await setUserHint(currentUser, None, ast) # set hints for current user
  693. await setDeviceUser(device, 'none') # Unbind user from device
  694. return successfullyUnbound(currentUser, device)
  695. @app.route('/cdr')
  696. class CDR(Resource):
  697. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 and ddmmyyyyHHMMSS', 'query')
  698. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 and ddmmyyyyHHMMSS', 'query')
  699. @app.response(HTTPStatus.OK, 'JSON reply')
  700. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  701. async def get(self):
  702. '''Returns CDR data, groupped by logical call id.
  703. All request arguments are optional.
  704. '''
  705. start = parseDatetime(request.args.get('start'))
  706. end = parseDatetime(request.args.get('end'))
  707. cdr = await getCDR(start, end)
  708. return successReply(cdr)
  709. @app.route('/cel')
  710. class CEL(Resource):
  711. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 and ddmmyyyyHHMMSS', 'query')
  712. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 and ddmmyyyyHHMMSS', 'query')
  713. @app.response(HTTPStatus.OK, 'JSON reply')
  714. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  715. async def get(self):
  716. '''Returns CDR data, groupped by logical call id.
  717. All request arguments are optional.
  718. '''
  719. start = parseDatetime(request.args.get('start'))
  720. end = parseDatetime(request.args.get('end'))
  721. cel = await getCEL(start, end)
  722. return successReply(cel)
  723. manager.connect()
  724. app.run(loop=main_loop, host='0.0.0.0', port=app.config['PORT'])