app.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. #!/usr/bin/env python3
  2. import asyncio
  3. import logging
  4. import os
  5. import re
  6. import json
  7. import base64
  8. from quart import jsonify, request, render_template_string
  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. manager = Manager(
  38. loop=main_loop,
  39. host=app.config['AMI_HOST'],
  40. port=app.config['AMI_PORT'],
  41. username=app.config['AMI_USERNAME'],
  42. secret=app.config['AMI_SECRET'],
  43. ping_delay=app.config['AMI_PING_DELAY'],
  44. ping_interval=app.config['AMI_PING_INTERVAL'],
  45. reconnect_timeout=app.config['AMI_TIMEOUT'],
  46. )
  47. class AuthMiddleware:
  48. '''ASGI process middleware that rejects requests missing
  49. the correct authentication header'''
  50. def __init__(self, app):
  51. self.app = app
  52. async def __call__(self, scope, receive, send):
  53. if 'headers' not in scope:
  54. return await self.app(scope, receive, send)
  55. for header, value in scope['headers']:
  56. if ((header == bytes(app.config['AUTH_HEADER'].lower(), 'utf-8')) and
  57. (value == bytes(app.config['AUTH_SECRET'], 'utf-8'))):
  58. return await self.app(scope, receive, send)
  59. # Paths "/openapi.json" and "/ui" do not require auth
  60. if (('path' in scope) and
  61. (scope['path'] in NO_AUTH_ROUTES)):
  62. return await self.app(scope, receive, send)
  63. return await self.error_response(receive, send)
  64. async def error_response(self, receive, send):
  65. await send({'type': 'http.response.start',
  66. 'status': 401,
  67. 'headers': [(b'content-length', b'21')]})
  68. await send({'type': 'http.response.body',
  69. 'body': b'Authorization requred',
  70. 'more_body': False})
  71. app.asgi_app = AuthMiddleware(app.asgi_app)
  72. @manager.register_event('ExtensionStatus')
  73. async def extensionStatusCallback(mngr: Manager, msg: Message):
  74. user = msg.exten
  75. hint = msg.hint
  76. state = msg.statustext.lower()
  77. print('ExtensionStatus', user, hint, state)
  78. @manager.register_event('PresenceStatus')
  79. async def presenceStatusCallback(mngr: Manager, msg: Message):
  80. user = msg.exten
  81. hint = msg.hint
  82. state = msg.status.lower()
  83. print('PresenceStatus', user, hint, state)
  84. @app.route('/openapi.json')
  85. async def openapi():
  86. '''Generates JSON that conforms OpenAPI Specification
  87. '''
  88. schema = app.__schema__
  89. schema['servers'] = [{'url':'{}://{}:{}'.format(app.config['SCHEME'],
  90. app.config['FQDN'],
  91. app.config['PORT'])}]
  92. schema['components'] = {'securitySchemes':{'ApiKey':{'type': 'apiKey',
  93. 'name': app.config['AUTH_HEADER'],
  94. 'in': 'header'}}}
  95. schema['security'] = [{'ApiKey':[]}]
  96. return jsonify(schema)
  97. @app.route('/ui')
  98. async def ui():
  99. '''Swagger UI
  100. '''
  101. return await render_template_string(SWAGGER_TEMPLATE,
  102. title=app.config['TITLE'],
  103. js_url=app.config['SWAGGER_JS_URL'],
  104. css_url=app.config['SWAGGER_CSS_URL'])
  105. @app.route('/ami/action', methods=['POST'])
  106. async def action():
  107. _payload = await request.get_data()
  108. reply = await manager.send_action(json.loads(_payload))
  109. return str(reply)
  110. @app.route('/ami/getvar/<string:variable>')
  111. async def amiGetVar(variable):
  112. '''AMI GetVar
  113. Returns value of requested variable using AMI action GetVar in background.
  114. Parameters:
  115. variable (string): Variable to query for
  116. Returns:
  117. string: Variable value or empty string if variable not found
  118. '''
  119. reply = await manager.send_action({'Action': 'GetVar',
  120. 'Variable': variable})
  121. app.logger.warning('GetVar({})->{}'.format(variable, reply.value))
  122. return reply.value
  123. async def amiSetVar(variable, value):
  124. '''AMI SetVar
  125. Sets variable using AMI action SetVar to value in background.
  126. Parameters:
  127. variable (string): Variable to set
  128. value (string): Value to set for variable
  129. Returns:
  130. boolean: True if DBPut action was successfull, False overwise
  131. '''
  132. reply = await manager.send_action({'Action': 'SetVar',
  133. 'Variable': variable,
  134. 'Value': value})
  135. app.logger.warning('SetVar({}, {})'.format(variable, value))
  136. if (isinstance(reply, Message) and reply.success):
  137. return True
  138. return False
  139. async def amiDBGet(family, key):
  140. '''AMI DBGet
  141. Returns value of requested astdb key using AMI action DBGet in background.
  142. Parameters:
  143. family (string): astdb key family to query for
  144. key (string): astdb key to query for
  145. Returns:
  146. string: Value or empty string if variable not found
  147. '''
  148. reply = await manager.send_action({'Action': 'DBGet',
  149. 'Family': family,
  150. 'Key': key})
  151. if (isinstance(reply, list) and
  152. (len(reply) > 1)):
  153. for message in reply:
  154. if (message.event == 'DBGetResponse'):
  155. app.logger.warning('DBGet(/{}/{})->{}'.format(family, key, message.val))
  156. return message.val
  157. app.logger.warning('DBGet(/{}/{})->Error!'.format(family, key))
  158. return None
  159. async def amiDBPut(family, key, value):
  160. '''AMI DBPut
  161. Writes value to astdb by family and key using AMI action DBPut in background.
  162. Parameters:
  163. family (string): astdb key family to write to
  164. key (string): astdb key to write to
  165. value (string): value to write
  166. Returns:
  167. boolean: True if DBPut action was successfull, False overwise
  168. '''
  169. reply = await manager.send_action({'Action': 'DBPut',
  170. 'Family': family,
  171. 'Key': key,
  172. 'Val': value})
  173. app.logger.warning('DBPut(/{}/{}, {})'.format(family, key, value))
  174. if (isinstance(reply, Message) and reply.success):
  175. return True
  176. return False
  177. async def amiDBDel(family, key):
  178. '''AMI DBDel
  179. Deletes key from family in astdb using AMI action DBDel in background.
  180. Parameters:
  181. family (string): astdb key family
  182. key (string): astdb key to delete
  183. Returns:
  184. boolean: True if DBDel action was successfull, False overwise
  185. '''
  186. reply = await manager.send_action({'Action': 'DBDel',
  187. 'Family': family,
  188. 'Key': key})
  189. app.logger.warning('DBDel(/{}/{})'.format(family, key))
  190. if (isinstance(reply, Message) and reply.success):
  191. return True
  192. return False
  193. async def amiSetHint(context, user, hint):
  194. '''AMI SetHint
  195. Sets hint for user in context using AMI action DialplanUserAdd with Replace=true in background.
  196. Parameters:
  197. context (string): dialplan context
  198. user (string): user
  199. hint (string): hint for user
  200. Returns:
  201. boolean: True if DialplanUserAdd action was successfull, False overwise
  202. '''
  203. reply = await manager.send_action({'Action': 'DialplanExtensionAdd',
  204. 'Context': context,
  205. 'Extension': user,
  206. 'Priority': 'hint',
  207. 'Application': hint,
  208. 'Replace': 'yes'})
  209. app.logger.warning('SetHint({},{},{})'.format(context, user, hint))
  210. if (isinstance(reply, Message) and reply.success):
  211. return True
  212. return False
  213. async def amiPresenceState(user):
  214. '''AMI PresenceState request for CustomPresence provider
  215. Parameters:
  216. user (string): user
  217. Returns:
  218. string: One of: not_set, unavailable, available, away, xa, chat or dnd
  219. '''
  220. reply = await manager.send_action({'Action': 'PresenceState',
  221. 'Provider': 'CustomPresence:{}'.format(user)})
  222. app.logger.warning('PresenceState({})'.format(user))
  223. if (isinstance(reply, Message) and reply.success):
  224. return reply.state
  225. return None
  226. async def amiPresenceStateList():
  227. states = {}
  228. reply = await manager.send_action({'Action':'PresenceStateList'})
  229. if len(reply) >= 2:
  230. for message in reply:
  231. if message.event == 'PresenceStateChange':
  232. user = re.search('CustomPresence:(\d+)', message.presentity).group(1)
  233. states[user] = message.status
  234. return states
  235. async def amiExtensionStateList():
  236. states = {}
  237. reply = await manager.send_action({'Action':'ExtensionStateList'})
  238. if len(reply) >= 2:
  239. for message in reply:
  240. if ((message.event == 'ExtensionStatus') and
  241. (message.context == 'ext-local')):
  242. states[message.exten] = message.statustext.lower()
  243. return states
  244. async def amiCommand(command):
  245. '''AMI Command
  246. Runs specified command using AMI action Command in background.
  247. Parameters:
  248. command (string): command to run
  249. Returns:
  250. boolean, list: tuple representing the boolean result of request and list of lines of command output
  251. '''
  252. reply = await manager.send_action({'Action': 'Command',
  253. 'Command': command})
  254. result = []
  255. if (isinstance(reply, Message) and reply.success):
  256. if isinstance(reply.output, list):
  257. result = reply.output
  258. else:
  259. result = reply.output.split('\n')
  260. app.logger.warning('Command({})->{}'.format(command, '\n'.join(result)))
  261. return True, result
  262. app.logger.warning('Command({})->Error!'.format(command))
  263. return False, result
  264. async def amiReload(module='core'):
  265. '''AMI Reload
  266. Reload specified asterisk module using AMI action reload in background.
  267. Parameters:
  268. module (string): module to reload, defaults to core
  269. Returns:
  270. boolean: True if Reload action was successfull, False overwise
  271. '''
  272. reply = await manager.send_action({'Action': 'Reload',
  273. 'Module': module})
  274. app.logger.warning('Reload({})'.format(module))
  275. if (isinstance(reply, Message) and reply.success):
  276. return True
  277. return False
  278. async def getGlobalVars():
  279. globalVars = GlobalVars()
  280. for _var in globalVars.d():
  281. setattr(globalVars, _var, await amiGetVar(_var))
  282. return globalVars
  283. async def setUserHint(user, dial, ast):
  284. if dial in NONEs:
  285. hint = 'CustomPresence:{}'.format(user)
  286. else:
  287. _dial= [dial]
  288. if (ast.DNDDEVSTATE == 'TRUE'):
  289. _dial.append('Custom:DND{}'.format(user))
  290. hint = '{},CustomPresence:{}'.format('&'.join(_dial), user)
  291. return await amiSetHint('ext-local', user, hint)
  292. async def amiQueues():
  293. queues = {}
  294. reply = await manager.send_action({'Action':'QueueStatus'})
  295. if len(reply) >= 2:
  296. for message in reply:
  297. if message.event == 'QueueMember':
  298. _qm = QueueMember(re.search('Local\/(\d+)', message.location).group(1))
  299. queues.setdefault(message.queue, []).append(_qm.fromMessage(message))
  300. return queues
  301. async def amiDeviceChannel(device):
  302. reply = await manager.send_action({'Action':'CoreShowChannels'})
  303. if len(reply) >= 2:
  304. for message in reply:
  305. if message.event == 'CoreShowChannel':
  306. print(message.calleridnum)
  307. if message.calleridnum == device:
  308. return message.channel
  309. return None
  310. async def setQueueStates(queues, user, device, state):
  311. for queue in [_q for _q, _ma in queues.items() for _m in _ma if _m.user == user]:
  312. await amiSetVar('DEVICE_STATE(Custom:QUEUE{}*{})'.format(device, queue), state)
  313. async def getDeviceUser(device):
  314. return await amiDBGet('DEVICE', '{}/user'.format(device))
  315. async def getDeviceDial(device):
  316. return await amiDBGet('DEVICE', '{}/dial'.format(device))
  317. async def getUserCID(user):
  318. return await amiDBGet('AMPUSER', '{}/cidnum'.format(user))
  319. async def setDeviceUser(device, user):
  320. return await amiDBPut('DEVICE', '{}/user'.format(device), user)
  321. async def getUserDevice(user):
  322. return await amiDBGet('AMPUSER', '{}/device'.format(user))
  323. async def setUserDevice(user, device):
  324. if device is None:
  325. return await amiDBDel('AMPUSER', '{}/device'.format(user))
  326. else:
  327. return await amiDBPut('AMPUSER', '{}/device'.format(user), device)
  328. async def unbindOtherDevices(user, newDevice, queues, ast):
  329. '''Unbinds user from all devices except newDevice and sets
  330. all required device states.
  331. '''
  332. devices = await amiDBGet('AMPUSER', '{}/device'.format(user))
  333. if devices not in NONEs:
  334. for _device in sorted(set(devices.split('&')), key=int):
  335. if _device != newDevice:
  336. if ast.FMDEVSTATE == 'TRUE':
  337. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(_device), 'INVALID')
  338. if ast.QUEDEVSTATE == 'TRUE':
  339. await setQueueStates(queues, user, _device, 'NOT_INUSE')
  340. if ast.DNDDEVSTATE:
  341. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(_device), 'NOT_INUSE')
  342. if ast.CFDEVSTATE:
  343. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(_device), 'NOT_INUSE')
  344. await amiDBPut('DEVICE', '{}/user'.format(_device), 'none')
  345. async def setUserDeviceStates(user, device, queues, ast):
  346. if ast.FMDEVSTATE == 'TRUE':
  347. _followMe = await amiDBGet('AMPUSER', '{}/followme/ddial'.format(user))
  348. if _followMe is not None:
  349. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(device), followMe2DevState(_followMe))
  350. if ast.QUEDEVSTATE == 'TRUE':
  351. await setQueueStates(queues, user, device, 'INUSE')
  352. if ast.DNDDEVSTATE:
  353. _dnd = await amiDBGet('DND', user)
  354. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(device), 'INUSE' if _dnd == 'YES' else 'NOT_INUSE')
  355. if ast.CFDEVSTATE:
  356. _cf = await amiDBGet('CF', user)
  357. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(device), 'INUSE' if _cf != '' else 'NOT_INUSE')
  358. async def getUsersStates():
  359. states = {}
  360. uStates = await amiExtensionStateList()
  361. pStates = await amiPresenceStateList()
  362. for user, uState in uStates.items():
  363. if (uState == 'idle') and (user in pStates.keys()):
  364. if pStates[user] in ('not_set','available', 'xa', 'chat'):
  365. states[user] = 'available'
  366. else:
  367. states[user] = pStates[user]
  368. else:
  369. if uState in ('unavailable', 'ringing'):
  370. states[user] = uState
  371. else:
  372. states[user] = 'busy'
  373. return states
  374. @app.route('/atxfer/<userA>/<userB>')
  375. class AtXfer(Resource):
  376. @app.param('userA', 'User initiating the attended transfer', 'path')
  377. @app.param('userB', 'Transfer destination user', 'path')
  378. @app.response(HTTPStatus.OK, 'Successfuly transfered the call')
  379. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  380. @app.response(HTTPStatus.NOT_FOUND, 'User does not exist, or user is not bound to device, \
  381. or device is offline, or no current call for user')
  382. @app.response(HTTPStatus.BAD_REQUEST, 'Transfer failed somehow or other AMI error')
  383. async def get(self, userA, userB):
  384. '''Attended call transfer
  385. '''
  386. device = await getUserDevice(userA)
  387. if device in NONEs:
  388. return '', HTTPStatus.NOT_FOUND
  389. channel = await amiDeviceChannel(device)
  390. if channel in NONEs:
  391. return '', HTTPStatus.NOT_FOUND
  392. reply = await manager.send_action({'Action':'Atxfer',
  393. 'Channel':channel,
  394. 'async':'false',
  395. 'Exten':userB})
  396. if (isinstance(reply, Message) and reply.success):
  397. return '', HTTPStatus.OK
  398. return '', HTTPStatus.BAD_REQUEST
  399. @app.route('/users/states')
  400. class UsersStates(Resource):
  401. @app.response(HTTPStatus.OK, 'JSON map of form {user1:state1, user2:state2, ...}')
  402. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  403. async def get(self):
  404. '''Returns all users with their states.
  405. Possible states are: available, away, dnd, inuse, busy, unavailable, ringing
  406. '''
  407. return await getUsersStates()
  408. @app.route('/user/<user>/presence')
  409. class UserPresenceState(Resource):
  410. @app.param('user', 'User to query for presence state', 'path')
  411. @app.response(HTTPStatus.OK, 'Presence state string')
  412. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  413. @app.response(HTTPStatus.NOT_FOUND, 'User does not exist')
  414. @app.response(HTTPStatus.BAD_REQUEST, 'AMI error')
  415. async def get(self, user):
  416. '''Returns user's presence state.
  417. One of: not_set | unavailable | available | away | xa | chat | dnd
  418. '''
  419. cidnum = await getUserCID(user) # Check if user exists in astdb
  420. if cidnum is None:
  421. return '', HTTPStatus.NOT_FOUND
  422. state = await amiPresenceState(user)
  423. if state is None:
  424. return '', HTTPStatus.BAD_REQUEST
  425. return state
  426. @app.route('/user/<user>/presence/<state>')
  427. class SetUserPresenceState(Resource):
  428. @app.param('user', 'Target user to set the presence state', 'path')
  429. @app.param('state',
  430. 'The presence state to set for user, one of: not_set, unavailable, available, away, xa, chat or dnd',
  431. 'path')
  432. @app.response(HTTPStatus.OK, 'Successfuly set the presence state')
  433. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  434. @app.response(HTTPStatus.NOT_FOUND, 'User does not exist')
  435. @app.response(HTTPStatus.BAD_REQUEST, 'Wrong state string ot other AMI error')
  436. async def get(self, user, state):
  437. '''Sets user's presence state.
  438. Allowed states: not_set | unavailable | available | away | xa | chat | dnd
  439. '''
  440. cidnum = await getUserCID(user) # Check if user exists in astdb
  441. if cidnum is None:
  442. return '', HTTPStatus.NOT_FOUND
  443. if await amiSetVar('PRESENCE_STATE(CustomPresence:{})'.format(user),
  444. state):
  445. return ''
  446. else:
  447. return '', HTTPStatus.BAD_REQUEST
  448. @app.route('/device/<device>/<user>/on')
  449. @app.route('/user/<user>/<device>/on')
  450. class UserDeviceBind(Resource):
  451. @app.param('device', 'Device number to bind to', 'path')
  452. @app.param('user', 'User to bind to device', 'path')
  453. @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
  454. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  455. async def get(self, device, user):
  456. '''Binds user to device.
  457. Both user and device numbers are checked for existance.
  458. Any device user was previously bound to, is unbound.
  459. Any user previously bound to device is unbound also.
  460. '''
  461. cidnum = await getUserCID(user) # Check if user exists in astdb
  462. if cidnum is None:
  463. return noUser(user)
  464. dial = await getDeviceDial(device) # Check if device exists in astdb
  465. if dial is None:
  466. return noDevice(device)
  467. currentUser = await getDeviceUser(device) # Check if any user is already bound to device
  468. if currentUser == user:
  469. return beenBound(user, device)
  470. ast = await getGlobalVars()
  471. queues = await amiQueues()
  472. if currentUser not in NONEs: # If any other user is bound to device, unbind him,
  473. await setUserDevice(currentUser, None)
  474. if ast.QUEDEVSTATE == 'TRUE': # set device states for previous user queues
  475. await setQueueStates(queues, currentUser, device, 'NOT_INUSE')
  476. await setUserHint(currentUser, None, ast) # set hints for previous user
  477. await setDeviceUser(device, user) # Bind user to device
  478. # If user is bound to some other devices, unbind him and set
  479. # device states for those devices
  480. await unbindOtherDevices(user, device, queues, ast)
  481. if not (await setUserHint(user, dial, ast)): # Set hints for user on new device
  482. return hintError(user, device)
  483. await setUserDeviceStates(user, device, queues, ast) # Set device states for users new device
  484. if not (await setUserDevice(user, device)): # Bind device to user
  485. return bindError(user, device)
  486. return beenBound(user, device)
  487. @app.route('/device/<device>/off')
  488. class DeviceUnBind(Resource):
  489. @app.param('device', 'Device number to unbind', 'path')
  490. @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
  491. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  492. async def get(self, device):
  493. '''Unbinds any user from device.
  494. Device is checked for existance.
  495. '''
  496. dial = await getDeviceDial(device) # Check if device exists in astdb
  497. if dial is None:
  498. return noDevice(device)
  499. currentUser = await getDeviceUser(device) # Check if any user is bound to device
  500. if currentUser in NONEs:
  501. return noUserBound(device)
  502. else:
  503. ast = await getGlobalVars()
  504. queues = await amiQueues()
  505. await setUserDevice(currentUser, None) # Unbind device from current user
  506. if ast.QUEDEVSTATE == 'TRUE': # set device states for current user queues
  507. await setQueueStates(queues, currentUser, device, 'NOT_INUSE')
  508. await setUserHint(currentUser, None, ast) # set hints for current user
  509. await setDeviceUser(device, 'none') # Unbind user from device
  510. return beenUnbound(currentUser, device)
  511. manager.connect()
  512. app.run(loop=main_loop, host='0.0.0.0', port=app.config['PORT'])