app.py 32 KB

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