app.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  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. return successReply(aors)
  268. async def amiSetVar(variable, value):
  269. '''AMI SetVar
  270. Sets variable using AMI action SetVar to value in background.
  271. Parameters:
  272. variable (string): Variable to set
  273. value (string): Value to set for variable
  274. Returns:
  275. string: None if SetVar was successfull, error message overwise
  276. '''
  277. reply = await manager.send_action({'Action': 'SetVar',
  278. 'Variable': variable,
  279. 'Value': value})
  280. app.logger.warning('SetVar({}, {})'.format(variable, value))
  281. if isinstance(reply, Message):
  282. if reply.success:
  283. return None
  284. else:
  285. return reply.message
  286. return 'AMI error'
  287. async def amiDBGet(family, key):
  288. '''AMI DBGet
  289. Returns value of requested astdb key using AMI action DBGet in background.
  290. Parameters:
  291. family (string): astdb key family to query for
  292. key (string): astdb key to query for
  293. Returns:
  294. string: Value or empty string if variable not found
  295. '''
  296. reply = await manager.send_action({'Action': 'DBGet',
  297. 'Family': family,
  298. 'Key': key})
  299. if (isinstance(reply, list) and
  300. (len(reply) > 1)):
  301. for message in reply:
  302. if (message.event == 'DBGetResponse'):
  303. app.logger.warning('DBGet(/{}/{})->{}'.format(family, key, message.val))
  304. return message.val
  305. app.logger.warning('DBGet(/{}/{})->Error!'.format(family, key))
  306. return None
  307. async def amiDBPut(family, key, value):
  308. '''AMI DBPut
  309. Writes value to astdb by family and key using AMI action DBPut in background.
  310. Parameters:
  311. family (string): astdb key family to write to
  312. key (string): astdb key to write to
  313. value (string): value to write
  314. Returns:
  315. boolean: True if DBPut action was successfull, False overwise
  316. '''
  317. reply = await manager.send_action({'Action': 'DBPut',
  318. 'Family': family,
  319. 'Key': key,
  320. 'Val': value})
  321. app.logger.warning('DBPut(/{}/{}, {})'.format(family, key, value))
  322. if (isinstance(reply, Message) and reply.success):
  323. return True
  324. return False
  325. async def amiDBDel(family, key):
  326. '''AMI DBDel
  327. Deletes key from family in astdb using AMI action DBDel in background.
  328. Parameters:
  329. family (string): astdb key family
  330. key (string): astdb key to delete
  331. Returns:
  332. boolean: True if DBDel action was successfull, False overwise
  333. '''
  334. reply = await manager.send_action({'Action': 'DBDel',
  335. 'Family': family,
  336. 'Key': key})
  337. app.logger.warning('DBDel(/{}/{})'.format(family, key))
  338. if (isinstance(reply, Message) and reply.success):
  339. return True
  340. return False
  341. async def amiSetHint(context, user, hint):
  342. '''AMI SetHint
  343. Sets hint for user in context using AMI action DialplanUserAdd with Replace=true in background.
  344. Parameters:
  345. context (string): dialplan context
  346. user (string): user
  347. hint (string): hint for user
  348. Returns:
  349. boolean: True if DialplanUserAdd action was successfull, False overwise
  350. '''
  351. reply = await manager.send_action({'Action': 'DialplanExtensionAdd',
  352. 'Context': context,
  353. 'Extension': user,
  354. 'Priority': 'hint',
  355. 'Application': hint,
  356. 'Replace': 'yes'})
  357. app.logger.warning('SetHint({},{},{})'.format(context, user, hint))
  358. if (isinstance(reply, Message) and reply.success):
  359. return True
  360. return False
  361. async def amiPresenceState(user):
  362. '''AMI PresenceState request for CustomPresence provider
  363. Parameters:
  364. user (string): user
  365. Returns:
  366. boolean, string: True and state or False and error message
  367. '''
  368. reply = await manager.send_action({'Action': 'PresenceState',
  369. 'Provider': 'CustomPresence:{}'.format(user)})
  370. app.logger.warning('PresenceState({})'.format(user))
  371. if isinstance(reply, Message):
  372. if reply.success:
  373. return True, reply.state
  374. else:
  375. return False, reply.message
  376. return False, 'AMI error'
  377. async def amiPresenceStateList():
  378. states = {}
  379. reply = await manager.send_action({'Action':'PresenceStateList'})
  380. if len(reply) >= 2:
  381. for message in reply:
  382. if message.event == 'PresenceStateChange':
  383. user = re.search('CustomPresence:(\d+)', message.presentity).group(1)
  384. states[user] = message.status
  385. app.logger.warning('PresenceStateList: {}'.format(','.join(states.keys())))
  386. return states
  387. async def amiExtensionStateList():
  388. states = {}
  389. reply = await manager.send_action({'Action':'ExtensionStateList'})
  390. if len(reply) >= 2:
  391. for message in reply:
  392. if ((message.event == 'ExtensionStatus') and
  393. (message.context == 'ext-local')):
  394. states[message.exten] = message.statustext.lower()
  395. app.logger.warning('ExtensionStateList: {}'.format(','.join(states.keys())))
  396. return states
  397. async def amiCommand(command):
  398. '''AMI Command
  399. Runs specified command using AMI action Command in background.
  400. Parameters:
  401. command (string): command to run
  402. Returns:
  403. boolean, list: tuple representing the boolean result of request and list of lines of command output
  404. '''
  405. reply = await manager.send_action({'Action': 'Command',
  406. 'Command': command})
  407. result = []
  408. if (isinstance(reply, Message) and reply.success):
  409. if isinstance(reply.output, list):
  410. result = reply.output
  411. else:
  412. result = reply.output.split('\n')
  413. app.logger.warning('Command({})->{}'.format(command, '\n'.join(result)))
  414. return True, result
  415. app.logger.warning('Command({})->Error!'.format(command))
  416. return False, result
  417. async def amiReload(module='core'):
  418. '''AMI Reload
  419. Reload specified asterisk module using AMI action reload in background.
  420. Parameters:
  421. module (string): module to reload, defaults to core
  422. Returns:
  423. boolean: True if Reload action was successfull, False overwise
  424. '''
  425. reply = await manager.send_action({'Action': 'Reload',
  426. 'Module': module})
  427. app.logger.warning('Reload({})'.format(module))
  428. if (isinstance(reply, Message) and reply.success):
  429. return True
  430. return False
  431. async def getGlobalVars():
  432. globalVars = GlobalVars()
  433. for _var in globalVars.d():
  434. setattr(globalVars, _var, await amiGetVar(_var))
  435. return globalVars
  436. async def setUserHint(user, dial, ast):
  437. if dial in NONEs:
  438. hint = 'CustomPresence:{}'.format(user)
  439. else:
  440. _dial= [dial]
  441. if (ast.DNDDEVSTATE == 'TRUE'):
  442. _dial.append('Custom:DND{}'.format(user))
  443. hint = '{},CustomPresence:{}'.format('&'.join(_dial), user)
  444. return await amiSetHint('ext-local', user, hint)
  445. async def amiQueues():
  446. queues = {}
  447. reply = await manager.send_action({'Action':'QueueStatus'})
  448. if len(reply) >= 2:
  449. for message in reply:
  450. if message.event == 'QueueMember':
  451. _qm = QueueMember(re.search('Local\/(\d+)', message.location).group(1))
  452. queues.setdefault(message.queue, []).append(_qm.fromMessage(message))
  453. return queues
  454. async def amiDeviceChannel(device):
  455. reply = await manager.send_action({'Action':'CoreShowChannels'})
  456. if len(reply) >= 2:
  457. for message in reply:
  458. if message.event == 'CoreShowChannel':
  459. if message.calleridnum == device:
  460. return message.channel
  461. return None
  462. async def setQueueStates(user, device, state):
  463. for queue in [_q for _q, _ma in app.cache['queues'].items() for _m in _ma if _m.user == user]:
  464. await amiSetVar('DEVICE_STATE(Custom:QUEUE{}*{})'.format(device, queue), state)
  465. async def getDeviceUser(device):
  466. return await amiDBGet('DEVICE', '{}/user'.format(device))
  467. async def getDeviceDial(device):
  468. return await amiDBGet('DEVICE', '{}/dial'.format(device))
  469. async def getUserCID(user):
  470. return await amiDBGet('AMPUSER', '{}/cidnum'.format(user))
  471. async def setDeviceUser(device, user):
  472. return await amiDBPut('DEVICE', '{}/user'.format(device), user)
  473. async def getUserDevice(user):
  474. return await amiDBGet('AMPUSER', '{}/device'.format(user))
  475. async def setUserDevice(user, device):
  476. if device is None:
  477. return await amiDBDel('AMPUSER', '{}/device'.format(user))
  478. else:
  479. return await amiDBPut('AMPUSER', '{}/device'.format(user), device)
  480. async def unbindOtherDevices(user, newDevice, ast):
  481. '''Unbinds user from all devices except newDevice and sets
  482. all required device states.
  483. '''
  484. devices = await amiDBGet('AMPUSER', '{}/device'.format(user))
  485. if devices not in NONEs:
  486. for _device in sorted(set(devices.split('&')), key=int):
  487. if _device != newDevice:
  488. if ast.FMDEVSTATE == 'TRUE':
  489. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(_device), 'INVALID')
  490. if ast.QUEDEVSTATE == 'TRUE':
  491. await setQueueStates(user, _device, 'NOT_INUSE')
  492. if ast.DNDDEVSTATE:
  493. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(_device), 'NOT_INUSE')
  494. if ast.CFDEVSTATE:
  495. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(_device), 'NOT_INUSE')
  496. await amiDBPut('DEVICE', '{}/user'.format(_device), 'none')
  497. async def setUserDeviceStates(user, device, ast):
  498. if ast.FMDEVSTATE == 'TRUE':
  499. _followMe = await amiDBGet('AMPUSER', '{}/followme/ddial'.format(user))
  500. if _followMe is not None:
  501. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(device), followMe2DevState(_followMe))
  502. if ast.QUEDEVSTATE == 'TRUE':
  503. await setQueueStates(user, device, 'INUSE')
  504. if ast.DNDDEVSTATE:
  505. _dnd = await amiDBGet('DND', user)
  506. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(device), 'INUSE' if _dnd == 'YES' else 'NOT_INUSE')
  507. if ast.CFDEVSTATE:
  508. _cf = await amiDBGet('CF', user)
  509. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(device), 'INUSE' if _cf != '' else 'NOT_INUSE')
  510. async def refreshStatesCache():
  511. app.cache['ustates'] = await amiExtensionStateList()
  512. app.cache['pstates'] = await amiPresenceStateList()
  513. return len(app.cache['ustates'])
  514. async def refreshDevicesCache():
  515. aors = await amiPJSIPShowAors()
  516. app.cache['devices'] = list(aors.keys())
  517. return len(app.cache['devices'])
  518. async def refreshQueuesCache():
  519. app.cache['queues'] = await amiQueues()
  520. return len(app.cache['queues'])
  521. async def userStateChangeCallback(user, state, prevState = None):
  522. reply = None
  523. if ((app.config['STATE_CALLBACK_URL'] not in NONEs) and
  524. ('HTTP_CLIENT' in app.config)):
  525. reply = await app.config['HTTP_CLIENT'].post(app.config['STATE_CALLBACK_URL'],
  526. json={'user': user,
  527. 'state': state,
  528. 'prev_state':prevState})
  529. else:
  530. app.logger.warning('{} changed state to: {}'.format(user, state))
  531. return reply
  532. def getUserStateCombined(user):
  533. _uCache = app.cache['ustates']
  534. _pCache = app.cache['pstates']
  535. return combinedStates[_uCache.get(user, 'unavailable')][_pCache.get(user, 'not_set')]
  536. def getUsersStatesCombined():
  537. return {user:getUserStateCombined(user) for user in app.cache['ustates']}
  538. @app.route('/atxfer/<userA>/<userB>')
  539. class AtXfer(Resource):
  540. @app.param('userA', 'User initiating the attended 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. '''Attended 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':'Atxfer',
  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:
  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 and ddmmyyyyHHMMSS', 'query')
  696. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 and ddmmyyyyHHMMSS', '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 and ddmmyyyyHHMMSS', 'query')
  710. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 and ddmmyyyyHHMMSS', 'query')
  711. @app.response(HTTPStatus.OK, 'JSON reply')
  712. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  713. async def get(self):
  714. '''Returns CDR 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. manager.connect()
  722. app.run(loop=main_loop, host='0.0.0.0', port=app.config['PORT'])