app.py 32 KB

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