app.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  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 quart import jsonify, request, render_template_string, abort
  9. from quart_openapi import Pint, Resource
  10. from http import HTTPStatus
  11. from panoramisk import Manager, Message
  12. from utils import *
  13. from logging.config import dictConfig
  14. # One asyncio event loop is used for AMI communication and HTTP requests routing with Quart
  15. main_loop = asyncio.get_event_loop()
  16. app = Pint(__name__, title=os.getenv('APP_TITLE', 'PBX API'), no_openapi=True)
  17. app.config.update({
  18. 'TITLE': os.getenv('APP_TITLE', 'PBX API'),
  19. 'APPLICATION_ROOT': os.getenv('APP_APPLICATION_ROOT', None),
  20. 'SCHEME': os.getenv('APP_SCHEME', 'http'),
  21. 'FQDN': os.getenv('APP_FQDN', '127.0.0.1'),
  22. 'PORT': int(os.getenv('APP_API_PORT', 8000)),
  23. 'BODY_TIMEOUT': int(os.getenv('APP_BODY_TIMEOUT', 60)),
  24. 'DEBUG': os.getenv('APP_DEBUG', 'False').lower() in TRUEs,
  25. 'MAX_CONTENT_LENGTH': int(os.getenv('APP_MAX_CONTENT_LENGTH', 16777216)),
  26. 'AMI_HOST': os.getenv('APP_AMI_HOST', '127.0.0.1'),
  27. 'AMI_PORT': int(os.getenv('APP_AMI_PORT', 5038)),
  28. 'AMI_USERNAME': os.getenv('APP_AMI_USERNAME', 'app'),
  29. 'AMI_SECRET': os.getenv('APP_AMI_SECRET', 'secret'),
  30. 'AMI_PING_DELAY': int(os.getenv('APP_AMI_PING_DELAY', 10)),
  31. 'AMI_PING_INTERVAL': int(os.getenv('APP_AMI_PING_INTERVAL', 10)),
  32. 'AMI_TIMEOUT': int(os.getenv('APP_AMI_TIMEOUT', 5)),
  33. 'AUTH_HEADER': os.getenv('APP_AUTH_HEADER', 'APP-auth-token'),
  34. 'AUTH_SECRET': os.getenv('APP_AUTH_SECRET', '3bfbeaabf363dd64fe263bd36830a6b6'),
  35. 'SWAGGER_JS_URL': os.getenv('APP_SWAGGER_JS_URL', SWAGGER_JS_URL),
  36. 'SWAGGER_CSS_URL': os.getenv('APP_SWAGGER_CSS_URL', SWAGGER_CSS_URL),
  37. 'STATE_CALLBACK_URL': os.getenv('APP_STATE_CALLBACK_URL', None),
  38. 'EXTRA_API_URL': os.getenv('APP_EXTRA_API_URL', None),
  39. 'STATE_CACHE': {'user':{},
  40. 'presence':{}}})
  41. manager = Manager(
  42. loop=main_loop,
  43. host=app.config['AMI_HOST'],
  44. port=app.config['AMI_PORT'],
  45. username=app.config['AMI_USERNAME'],
  46. secret=app.config['AMI_SECRET'],
  47. ping_delay=app.config['AMI_PING_DELAY'],
  48. ping_interval=app.config['AMI_PING_INTERVAL'],
  49. reconnect_timeout=app.config['AMI_TIMEOUT'],
  50. )
  51. class AuthMiddleware:
  52. '''ASGI process middleware that rejects requests missing
  53. the correct authentication header'''
  54. def __init__(self, app):
  55. self.app = app
  56. async def __call__(self, scope, receive, send):
  57. if 'headers' not in scope:
  58. return await self.app(scope, receive, send)
  59. for header, value in scope['headers']:
  60. if ((header == bytes(app.config['AUTH_HEADER'].lower(), 'utf-8')) and
  61. (value == bytes(app.config['AUTH_SECRET'], 'utf-8'))):
  62. return await self.app(scope, receive, send)
  63. # Paths "/openapi.json" and "/ui" do not require auth
  64. if (('path' in scope) and
  65. (scope['path'] in NO_AUTH_ROUTES)):
  66. return await self.app(scope, receive, send)
  67. return await self.error_response(receive, send)
  68. async def error_response(self, receive, send):
  69. await send({'type': 'http.response.start',
  70. 'status': 401,
  71. 'headers': [(b'content-length', b'21')]})
  72. await send({'type': 'http.response.body',
  73. 'body': b'Authorization requred',
  74. 'more_body': False})
  75. app.asgi_app = AuthMiddleware(app.asgi_app)
  76. @manager.register_event('FullyBooted')
  77. async def fullyBootedCallback(mngr: Manager, msg: Message):
  78. await refreshStatesCache()
  79. @manager.register_event('ExtensionStatus')
  80. async def extensionStatusCallback(mngr: Manager, msg: Message):
  81. user = msg.exten #hint = msg.hint
  82. state = msg.statustext.lower()
  83. if user in app.config['STATE_CACHE']['user']:
  84. prevState = getUserStateCombined(user)
  85. app.config['STATE_CACHE']['user'][user] = state
  86. combinedState = getUserStateCombined(user)
  87. if combinedState != prevState:
  88. await userStateChangeCallback(user, combinedState, prevState)
  89. @manager.register_event('PresenceStatus')
  90. async def presenceStatusCallback(mngr: Manager, msg: Message):
  91. user = msg.exten #hint = msg.hint
  92. state = msg.status.lower()
  93. if user in app.config['STATE_CACHE']['user']:
  94. prevState = getUserStateCombined(user)
  95. app.config['STATE_CACHE']['presence'][user] = state
  96. combinedState = getUserStateCombined(user)
  97. if combinedState != prevState:
  98. await userStateChangeCallback(user, combinedState, prevState)
  99. @app.before_first_request
  100. async def initHttpClient():
  101. app.config['HTTP_CLIENT'] = aiohttp.ClientSession(loop=main_loop)
  102. @app.route('/openapi.json')
  103. async def openapi():
  104. '''Generates JSON that conforms OpenAPI Specification
  105. '''
  106. schema = app.__schema__
  107. schema['servers'] = [{'url':'{}://{}:{}'.format(app.config['SCHEME'],
  108. app.config['FQDN'],
  109. app.config['PORT'])}]
  110. if app.config['EXTRA_API_URL'] is not None:
  111. schema['servers'].append({'url':app.config['EXTRA_API_URL']})
  112. schema['components'] = {'securitySchemes':{'ApiKey':{'type': 'apiKey',
  113. 'name': app.config['AUTH_HEADER'],
  114. 'in': 'header'}}}
  115. schema['security'] = [{'ApiKey':[]}]
  116. return jsonify(schema)
  117. @app.route('/ui')
  118. async def ui():
  119. '''Swagger UI
  120. '''
  121. return await render_template_string(SWAGGER_TEMPLATE,
  122. title=app.config['TITLE'],
  123. js_url=app.config['SWAGGER_JS_URL'],
  124. css_url=app.config['SWAGGER_CSS_URL'])
  125. @app.route('/ami/action', methods=['POST'])
  126. async def action():
  127. _payload = await request.get_data()
  128. reply = await manager.send_action(json.loads(_payload))
  129. return str(reply)
  130. @app.route('/ami/getvar/<string:variable>')
  131. async def amiGetVar(variable):
  132. '''AMI GetVar
  133. Returns value of requested variable using AMI action GetVar in background.
  134. Parameters:
  135. variable (string): Variable to query for
  136. Returns:
  137. string: Variable value or empty string if variable not found
  138. '''
  139. reply = await manager.send_action({'Action': 'GetVar',
  140. 'Variable': variable})
  141. app.logger.warning('GetVar({})->{}'.format(variable, reply.value))
  142. return reply.value
  143. @app.route('/ami/auths')
  144. async def amiPJSIPShowAuths():
  145. auths = {}
  146. reply = await manager.send_action({'Action':'PJSIPShowAuths'})
  147. if len(reply) >= 2:
  148. for message in reply:
  149. if ((message.event == 'AuthList') and
  150. ('objecttype' in message) and
  151. (message.objecttype == 'auth')):
  152. auths[message.username] = message.password
  153. return successReply(auths)
  154. @app.route('/ami/aors')
  155. async def amiPJSIPShowAors():
  156. aors = {}
  157. reply = await manager.send_action({'Action':'PJSIPShowAors'})
  158. if len(reply) >= 2:
  159. for message in reply:
  160. if ((message.event == 'AorList') and
  161. ('objecttype' in message) and
  162. (message.objecttype == 'aor')):
  163. aors[message.objectname] = message.contacts
  164. return successReply(aors)
  165. async def amiSetVar(variable, value):
  166. '''AMI SetVar
  167. Sets variable using AMI action SetVar to value in background.
  168. Parameters:
  169. variable (string): Variable to set
  170. value (string): Value to set for variable
  171. Returns:
  172. string: None if SetVar was successfull, error message overwise
  173. '''
  174. reply = await manager.send_action({'Action': 'SetVar',
  175. 'Variable': variable,
  176. 'Value': value})
  177. app.logger.warning('SetVar({}, {})'.format(variable, value))
  178. if isinstance(reply, Message):
  179. if reply.success:
  180. return None
  181. else:
  182. return reply.message
  183. return 'AMI error'
  184. async def amiDBGet(family, key):
  185. '''AMI DBGet
  186. Returns value of requested astdb key using AMI action DBGet in background.
  187. Parameters:
  188. family (string): astdb key family to query for
  189. key (string): astdb key to query for
  190. Returns:
  191. string: Value or empty string if variable not found
  192. '''
  193. reply = await manager.send_action({'Action': 'DBGet',
  194. 'Family': family,
  195. 'Key': key})
  196. if (isinstance(reply, list) and
  197. (len(reply) > 1)):
  198. for message in reply:
  199. if (message.event == 'DBGetResponse'):
  200. app.logger.warning('DBGet(/{}/{})->{}'.format(family, key, message.val))
  201. return message.val
  202. app.logger.warning('DBGet(/{}/{})->Error!'.format(family, key))
  203. return None
  204. async def amiDBPut(family, key, value):
  205. '''AMI DBPut
  206. Writes value to astdb by family and key using AMI action DBPut in background.
  207. Parameters:
  208. family (string): astdb key family to write to
  209. key (string): astdb key to write to
  210. value (string): value to write
  211. Returns:
  212. boolean: True if DBPut action was successfull, False overwise
  213. '''
  214. reply = await manager.send_action({'Action': 'DBPut',
  215. 'Family': family,
  216. 'Key': key,
  217. 'Val': value})
  218. app.logger.warning('DBPut(/{}/{}, {})'.format(family, key, value))
  219. if (isinstance(reply, Message) and reply.success):
  220. return True
  221. return False
  222. async def amiDBDel(family, key):
  223. '''AMI DBDel
  224. Deletes key from family in astdb using AMI action DBDel in background.
  225. Parameters:
  226. family (string): astdb key family
  227. key (string): astdb key to delete
  228. Returns:
  229. boolean: True if DBDel action was successfull, False overwise
  230. '''
  231. reply = await manager.send_action({'Action': 'DBDel',
  232. 'Family': family,
  233. 'Key': key})
  234. app.logger.warning('DBDel(/{}/{})'.format(family, key))
  235. if (isinstance(reply, Message) and reply.success):
  236. return True
  237. return False
  238. async def amiSetHint(context, user, hint):
  239. '''AMI SetHint
  240. Sets hint for user in context using AMI action DialplanUserAdd with Replace=true in background.
  241. Parameters:
  242. context (string): dialplan context
  243. user (string): user
  244. hint (string): hint for user
  245. Returns:
  246. boolean: True if DialplanUserAdd action was successfull, False overwise
  247. '''
  248. reply = await manager.send_action({'Action': 'DialplanExtensionAdd',
  249. 'Context': context,
  250. 'Extension': user,
  251. 'Priority': 'hint',
  252. 'Application': hint,
  253. 'Replace': 'yes'})
  254. app.logger.warning('SetHint({},{},{})'.format(context, user, hint))
  255. if (isinstance(reply, Message) and reply.success):
  256. return True
  257. return False
  258. async def amiPresenceState(user):
  259. '''AMI PresenceState request for CustomPresence provider
  260. Parameters:
  261. user (string): user
  262. Returns:
  263. boolean, string: True and state or False and error message
  264. '''
  265. reply = await manager.send_action({'Action': 'PresenceState',
  266. 'Provider': 'CustomPresence:{}'.format(user)})
  267. app.logger.warning('PresenceState({})'.format(user))
  268. if isinstance(reply, Message):
  269. if reply.success:
  270. return True, reply.state
  271. else:
  272. return False, reply.message
  273. return False, 'AMI error'
  274. async def amiPresenceStateList():
  275. states = {}
  276. reply = await manager.send_action({'Action':'PresenceStateList'})
  277. if len(reply) >= 2:
  278. for message in reply:
  279. if message.event == 'PresenceStateChange':
  280. user = re.search('CustomPresence:(\d+)', message.presentity).group(1)
  281. states[user] = message.status
  282. app.logger.warning('PresenceStateList: {}'.format(','.join(states.keys())))
  283. return states
  284. async def amiExtensionStateList():
  285. states = {}
  286. reply = await manager.send_action({'Action':'ExtensionStateList'})
  287. if len(reply) >= 2:
  288. for message in reply:
  289. if ((message.event == 'ExtensionStatus') and
  290. (message.context == 'ext-local')):
  291. states[message.exten] = message.statustext.lower()
  292. app.logger.warning('ExtensionStateList: {}'.format(','.join(states.keys())))
  293. return states
  294. async def amiCommand(command):
  295. '''AMI Command
  296. Runs specified command using AMI action Command in background.
  297. Parameters:
  298. command (string): command to run
  299. Returns:
  300. boolean, list: tuple representing the boolean result of request and list of lines of command output
  301. '''
  302. reply = await manager.send_action({'Action': 'Command',
  303. 'Command': command})
  304. result = []
  305. if (isinstance(reply, Message) and reply.success):
  306. if isinstance(reply.output, list):
  307. result = reply.output
  308. else:
  309. result = reply.output.split('\n')
  310. app.logger.warning('Command({})->{}'.format(command, '\n'.join(result)))
  311. return True, result
  312. app.logger.warning('Command({})->Error!'.format(command))
  313. return False, result
  314. async def amiReload(module='core'):
  315. '''AMI Reload
  316. Reload specified asterisk module using AMI action reload in background.
  317. Parameters:
  318. module (string): module to reload, defaults to core
  319. Returns:
  320. boolean: True if Reload action was successfull, False overwise
  321. '''
  322. reply = await manager.send_action({'Action': 'Reload',
  323. 'Module': module})
  324. app.logger.warning('Reload({})'.format(module))
  325. if (isinstance(reply, Message) and reply.success):
  326. return True
  327. return False
  328. async def getGlobalVars():
  329. globalVars = GlobalVars()
  330. for _var in globalVars.d():
  331. setattr(globalVars, _var, await amiGetVar(_var))
  332. return globalVars
  333. async def setUserHint(user, dial, ast):
  334. if dial in NONEs:
  335. hint = 'CustomPresence:{}'.format(user)
  336. else:
  337. _dial= [dial]
  338. if (ast.DNDDEVSTATE == 'TRUE'):
  339. _dial.append('Custom:DND{}'.format(user))
  340. hint = '{},CustomPresence:{}'.format('&'.join(_dial), user)
  341. return await amiSetHint('ext-local', user, hint)
  342. async def amiQueues():
  343. queues = {}
  344. reply = await manager.send_action({'Action':'QueueStatus'})
  345. if len(reply) >= 2:
  346. for message in reply:
  347. if message.event == 'QueueMember':
  348. _qm = QueueMember(re.search('Local\/(\d+)', message.location).group(1))
  349. queues.setdefault(message.queue, []).append(_qm.fromMessage(message))
  350. return queues
  351. async def amiDeviceChannel(device):
  352. reply = await manager.send_action({'Action':'CoreShowChannels'})
  353. if len(reply) >= 2:
  354. for message in reply:
  355. if message.event == 'CoreShowChannel':
  356. if message.calleridnum == device:
  357. return message.channel
  358. return None
  359. async def setQueueStates(queues, user, device, state):
  360. for queue in [_q for _q, _ma in queues.items() for _m in _ma if _m.user == user]:
  361. await amiSetVar('DEVICE_STATE(Custom:QUEUE{}*{})'.format(device, queue), state)
  362. async def getDeviceUser(device):
  363. return await amiDBGet('DEVICE', '{}/user'.format(device))
  364. async def getDeviceDial(device):
  365. return await amiDBGet('DEVICE', '{}/dial'.format(device))
  366. async def getUserCID(user):
  367. return await amiDBGet('AMPUSER', '{}/cidnum'.format(user))
  368. async def setDeviceUser(device, user):
  369. return await amiDBPut('DEVICE', '{}/user'.format(device), user)
  370. async def getUserDevice(user):
  371. return await amiDBGet('AMPUSER', '{}/device'.format(user))
  372. async def setUserDevice(user, device):
  373. if device is None:
  374. return await amiDBDel('AMPUSER', '{}/device'.format(user))
  375. else:
  376. return await amiDBPut('AMPUSER', '{}/device'.format(user), device)
  377. async def unbindOtherDevices(user, newDevice, queues, ast):
  378. '''Unbinds user from all devices except newDevice and sets
  379. all required device states.
  380. '''
  381. devices = await amiDBGet('AMPUSER', '{}/device'.format(user))
  382. if devices not in NONEs:
  383. for _device in sorted(set(devices.split('&')), key=int):
  384. if _device != newDevice:
  385. if ast.FMDEVSTATE == 'TRUE':
  386. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(_device), 'INVALID')
  387. if ast.QUEDEVSTATE == 'TRUE':
  388. await setQueueStates(queues, user, _device, 'NOT_INUSE')
  389. if ast.DNDDEVSTATE:
  390. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(_device), 'NOT_INUSE')
  391. if ast.CFDEVSTATE:
  392. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(_device), 'NOT_INUSE')
  393. await amiDBPut('DEVICE', '{}/user'.format(_device), 'none')
  394. async def setUserDeviceStates(user, device, queues, ast):
  395. if ast.FMDEVSTATE == 'TRUE':
  396. _followMe = await amiDBGet('AMPUSER', '{}/followme/ddial'.format(user))
  397. if _followMe is not None:
  398. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(device), followMe2DevState(_followMe))
  399. if ast.QUEDEVSTATE == 'TRUE':
  400. await setQueueStates(queues, user, device, 'INUSE')
  401. if ast.DNDDEVSTATE:
  402. _dnd = await amiDBGet('DND', user)
  403. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(device), 'INUSE' if _dnd == 'YES' else 'NOT_INUSE')
  404. if ast.CFDEVSTATE:
  405. _cf = await amiDBGet('CF', user)
  406. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(device), 'INUSE' if _cf != '' else 'NOT_INUSE')
  407. async def refreshStatesCache():
  408. app.config['STATE_CACHE']['user'] = await amiExtensionStateList()
  409. app.config['STATE_CACHE']['presence'] = await amiPresenceStateList()
  410. return len(app.config['STATE_CACHE']['user'])
  411. async def userStateChangeCallback(user, state, prevState = None):
  412. reply = None
  413. if ((app.config['STATE_CALLBACK_URL'] not in NONEs) and
  414. ('HTTP_CLIENT' in app.config)):
  415. reply = await app.config['HTTP_CLIENT'].post(app.config['STATE_CALLBACK_URL'],
  416. json={'user': user,
  417. 'state': state,
  418. 'prev_state':prevState})
  419. else:
  420. app.logger.warning('{} changed state to: {}'.format(user, state))
  421. return reply
  422. def getUserStateCombined(user):
  423. _uCache = app.config['STATE_CACHE']['user']
  424. _pCache = app.config['STATE_CACHE']['presence']
  425. return combinedStates[_uCache.get(user, 'unavailable')][_pCache.get(user, 'not_set')]
  426. def getUsersStatesCombined():
  427. return {user:getUserStateCombined(user) for user in app.config['STATE_CACHE']['user']}
  428. @app.route('/atxfer/<userA>/<userB>')
  429. class AtXfer(Resource):
  430. @app.param('userA', 'User initiating the attended transfer', 'path')
  431. @app.param('userB', 'Transfer destination user', 'path')
  432. @app.response(HTTPStatus.OK, 'Json reply')
  433. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  434. async def get(self, userA, userB):
  435. '''Attended call transfer
  436. '''
  437. device = await getUserDevice(userA)
  438. if device in NONEs:
  439. return noUserDevice(userA)
  440. channel = await amiDeviceChannel(device)
  441. if channel in NONEs:
  442. return noUserChannel(userA)
  443. reply = await manager.send_action({'Action':'Atxfer',
  444. 'Channel':channel,
  445. 'async':'false',
  446. 'Exten':userB})
  447. if isinstance(reply, Message):
  448. if reply.success:
  449. return successfullyTransfered(userA, userB)
  450. else:
  451. return errorReply(reply.message)
  452. @app.route('/users/states')
  453. class UsersStates(Resource):
  454. @app.response(HTTPStatus.OK, 'JSON reply with user:state map or error message')
  455. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  456. async def get(self):
  457. '''Returns all users with their combined states.
  458. Possible states are: available, away, dnd, inuse, busy, unavailable, ringing
  459. '''
  460. usersCount = await refreshStatesCache()
  461. if usersCount == 0:
  462. return stateCacheEmpty()
  463. return successReply(getUsersStatesCombined())
  464. @app.route('/user/<user>/state')
  465. class UserState(Resource):
  466. @app.param('user', 'User to query for combined state', 'path')
  467. @app.response(HTTPStatus.OK, 'JSON data {"user":user,"state":state}')
  468. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  469. async def get(self, user):
  470. '''Returns user's combined state.
  471. One of: available, away, dnd, inuse, busy, unavailable, ringing
  472. '''
  473. if user not in app.config['STATE_CACHE']['user']:
  474. return noUser(user)
  475. return successReply({'user':user,'state':getUserStateCombined(user)})
  476. @app.route('/user/<user>/presence')
  477. class PresenceState(Resource):
  478. @app.param('user', 'User to query for presence state', 'path')
  479. @app.response(HTTPStatus.OK, 'JSON data {"user":user,"state":state}')
  480. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  481. async def get(self, user):
  482. '''Returns user's presence state.
  483. One of: not_set, unavailable, available, away, xa, chat, dnd
  484. '''
  485. if user not in app.config['STATE_CACHE']['user']:
  486. return noUser(user)
  487. return successReply({'user':user,'state':app.config['STATE_CACHE']['presence'].get(user, 'not_set')})
  488. @app.route('/user/<user>/presence/<state>')
  489. class SetPresenceState(Resource):
  490. @app.param('user', 'Target user to set the presence state', 'path')
  491. @app.param('state',
  492. 'The presence state for user, one of: not_set, unavailable, available, away, xa, chat or dnd',
  493. 'path')
  494. @app.response(HTTPStatus.OK, 'Json reply')
  495. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  496. async def get(self, user, state):
  497. '''Sets user's presence state.
  498. Allowed states: not_set | unavailable | available | away | xa | chat | dnd
  499. '''
  500. if state not in presenceStates:
  501. return invalidState(state)
  502. if user not in app.config['STATE_CACHE']['user']:
  503. return noUser(user)
  504. result = await amiSetVar('PRESENCE_STATE(CustomPresence:{})'.format(user), state)
  505. if result is not None:
  506. return errorReply(result)
  507. return successfullySetState(user, state)
  508. @app.route('/users/devices')
  509. class UsersDevices(Resource):
  510. @app.response(HTTPStatus.OK, 'JSON reply with user:device map or error message')
  511. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  512. async def get(self):
  513. '''Returns all users with their combined states.
  514. Possible states are: available, away, dnd, inuse, busy, unavailable, ringing
  515. '''
  516. data = {}
  517. for user in app.config['STATE_CACHE']['user']:
  518. device = await getUserDevice(user)
  519. if device in NONEs:
  520. device = None
  521. data[user]=device
  522. return successReply(data)
  523. @app.route('/device/<device>/<user>/on')
  524. @app.route('/user/<user>/<device>/on')
  525. class UserDeviceBind(Resource):
  526. @app.param('device', 'Device number to bind to', 'path')
  527. @app.param('user', 'User to bind to device', 'path')
  528. @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
  529. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  530. async def get(self, device, user):
  531. '''Binds user to device.
  532. Both user and device numbers are checked for existance.
  533. Any device user was previously bound to, is unbound.
  534. Any user previously bound to device is unbound also.
  535. '''
  536. if user not in app.config['STATE_CACHE']['user']:
  537. return noUser(user)
  538. dial = await getDeviceDial(device) # Check if device exists in astdb
  539. if dial is None:
  540. return noDevice(device)
  541. currentUser = await getDeviceUser(device) # Check if any user is already bound to device
  542. if currentUser == user:
  543. return alreadyBound(user, device)
  544. ast = await getGlobalVars()
  545. queues = await amiQueues()
  546. if currentUser not in NONEs: # If any other user is bound to device, unbind him,
  547. await setUserDevice(currentUser, None)
  548. if ast.QUEDEVSTATE == 'TRUE': # set device states for previous user queues
  549. await setQueueStates(queues, currentUser, device, 'NOT_INUSE')
  550. await setUserHint(currentUser, None, ast) # set hints for previous user
  551. await setDeviceUser(device, user) # Bind user to device
  552. # If user is bound to some other devices, unbind him and set
  553. # device states for those devices
  554. await unbindOtherDevices(user, device, queues, ast)
  555. if not (await setUserHint(user, dial, ast)): # Set hints for user on new device
  556. return hintError(user, device)
  557. await setUserDeviceStates(user, device, queues, ast) # Set device states for users new device
  558. if not (await setUserDevice(user, device)): # Bind device to user
  559. return bindError(user, device)
  560. return successfullyBound(user, device)
  561. @app.route('/device/<device>/off')
  562. class DeviceUnBind(Resource):
  563. @app.param('device', 'Device number to unbind', 'path')
  564. @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
  565. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  566. async def get(self, device):
  567. '''Unbinds any user from device.
  568. Device is checked for existance.
  569. '''
  570. dial = await getDeviceDial(device) # Check if device exists in astdb
  571. if dial is None:
  572. return noDevice(device)
  573. currentUser = await getDeviceUser(device) # Check if any user is bound to device
  574. if currentUser in NONEs:
  575. return noUserBound(device)
  576. else:
  577. ast = await getGlobalVars()
  578. queues = await amiQueues()
  579. await setUserDevice(currentUser, None) # Unbind device from current user
  580. if ast.QUEDEVSTATE == 'TRUE': # set device states for current user queues
  581. await setQueueStates(queues, currentUser, device, 'NOT_INUSE')
  582. await setUserHint(currentUser, None, ast) # set hints for current user
  583. await setDeviceUser(device, 'none') # Unbind user from device
  584. return successfullyUnbound(currentUser, device)
  585. manager.connect()
  586. app.run(loop=main_loop, host='0.0.0.0', port=app.config['PORT'])