app.py 31 KB

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