app.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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. _combinedState = getUserStateCombined(user)
  85. app.config['STATE_CACHE']['user'][user] = state
  86. combinedState = getUserStateCombined(user)
  87. if combinedState != _combinedState:
  88. await userStateChangeCallback(user, combinedState)
  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. _combinedState = getUserStateCombined(user)
  95. app.config['STATE_CACHE']['presence'][user] = state
  96. combinedState = getUserStateCombined(user)
  97. if combinedState != _combinedState:
  98. await userStateChangeCallback(user, combinedState)
  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. async def amiSetVar(variable, value):
  144. '''AMI SetVar
  145. Sets variable using AMI action SetVar to value in background.
  146. Parameters:
  147. variable (string): Variable to set
  148. value (string): Value to set for variable
  149. Returns:
  150. boolean: True if DBPut action was successfull, False overwise
  151. '''
  152. reply = await manager.send_action({'Action': 'SetVar',
  153. 'Variable': variable,
  154. 'Value': value})
  155. app.logger.warning('SetVar({}, {})'.format(variable, value))
  156. if (isinstance(reply, Message) and reply.success):
  157. return True
  158. return False
  159. async def amiDBGet(family, key):
  160. '''AMI DBGet
  161. Returns value of requested astdb key using AMI action DBGet in background.
  162. Parameters:
  163. family (string): astdb key family to query for
  164. key (string): astdb key to query for
  165. Returns:
  166. string: Value or empty string if variable not found
  167. '''
  168. reply = await manager.send_action({'Action': 'DBGet',
  169. 'Family': family,
  170. 'Key': key})
  171. if (isinstance(reply, list) and
  172. (len(reply) > 1)):
  173. for message in reply:
  174. if (message.event == 'DBGetResponse'):
  175. app.logger.warning('DBGet(/{}/{})->{}'.format(family, key, message.val))
  176. return message.val
  177. app.logger.warning('DBGet(/{}/{})->Error!'.format(family, key))
  178. return None
  179. async def amiDBPut(family, key, value):
  180. '''AMI DBPut
  181. Writes value to astdb by family and key using AMI action DBPut in background.
  182. Parameters:
  183. family (string): astdb key family to write to
  184. key (string): astdb key to write to
  185. value (string): value to write
  186. Returns:
  187. boolean: True if DBPut action was successfull, False overwise
  188. '''
  189. reply = await manager.send_action({'Action': 'DBPut',
  190. 'Family': family,
  191. 'Key': key,
  192. 'Val': value})
  193. app.logger.warning('DBPut(/{}/{}, {})'.format(family, key, value))
  194. if (isinstance(reply, Message) and reply.success):
  195. return True
  196. return False
  197. async def amiDBDel(family, key):
  198. '''AMI DBDel
  199. Deletes key from family in astdb using AMI action DBDel in background.
  200. Parameters:
  201. family (string): astdb key family
  202. key (string): astdb key to delete
  203. Returns:
  204. boolean: True if DBDel action was successfull, False overwise
  205. '''
  206. reply = await manager.send_action({'Action': 'DBDel',
  207. 'Family': family,
  208. 'Key': key})
  209. app.logger.warning('DBDel(/{}/{})'.format(family, key))
  210. if (isinstance(reply, Message) and reply.success):
  211. return True
  212. return False
  213. async def amiSetHint(context, user, hint):
  214. '''AMI SetHint
  215. Sets hint for user in context using AMI action DialplanUserAdd with Replace=true in background.
  216. Parameters:
  217. context (string): dialplan context
  218. user (string): user
  219. hint (string): hint for user
  220. Returns:
  221. boolean: True if DialplanUserAdd action was successfull, False overwise
  222. '''
  223. reply = await manager.send_action({'Action': 'DialplanExtensionAdd',
  224. 'Context': context,
  225. 'Extension': user,
  226. 'Priority': 'hint',
  227. 'Application': hint,
  228. 'Replace': 'yes'})
  229. app.logger.warning('SetHint({},{},{})'.format(context, user, hint))
  230. if (isinstance(reply, Message) and reply.success):
  231. return True
  232. return False
  233. async def amiPresenceState(user):
  234. '''AMI PresenceState request for CustomPresence provider
  235. Parameters:
  236. user (string): user
  237. Returns:
  238. string: One of: not_set, unavailable, available, away, xa, chat or dnd
  239. '''
  240. reply = await manager.send_action({'Action': 'PresenceState',
  241. 'Provider': 'CustomPresence:{}'.format(user)})
  242. app.logger.warning('PresenceState({})'.format(user))
  243. if (isinstance(reply, Message) and reply.success):
  244. return reply.state
  245. return None
  246. async def amiPresenceStateList():
  247. states = {}
  248. reply = await manager.send_action({'Action':'PresenceStateList'})
  249. if len(reply) >= 2:
  250. for message in reply:
  251. if message.event == 'PresenceStateChange':
  252. user = re.search('CustomPresence:(\d+)', message.presentity).group(1)
  253. states[user] = message.status
  254. app.logger.warning('PresenceStateList: {}'.format(','.join(states.keys())))
  255. return states
  256. async def amiExtensionStateList():
  257. states = {}
  258. reply = await manager.send_action({'Action':'ExtensionStateList'})
  259. if len(reply) >= 2:
  260. for message in reply:
  261. if ((message.event == 'ExtensionStatus') and
  262. (message.context == 'ext-local')):
  263. states[message.exten] = message.statustext.lower()
  264. app.logger.warning('ExtensionStateList: {}'.format(','.join(states.keys())))
  265. return states
  266. async def amiCommand(command):
  267. '''AMI Command
  268. Runs specified command using AMI action Command in background.
  269. Parameters:
  270. command (string): command to run
  271. Returns:
  272. boolean, list: tuple representing the boolean result of request and list of lines of command output
  273. '''
  274. reply = await manager.send_action({'Action': 'Command',
  275. 'Command': command})
  276. result = []
  277. if (isinstance(reply, Message) and reply.success):
  278. if isinstance(reply.output, list):
  279. result = reply.output
  280. else:
  281. result = reply.output.split('\n')
  282. app.logger.warning('Command({})->{}'.format(command, '\n'.join(result)))
  283. return True, result
  284. app.logger.warning('Command({})->Error!'.format(command))
  285. return False, result
  286. async def amiReload(module='core'):
  287. '''AMI Reload
  288. Reload specified asterisk module using AMI action reload in background.
  289. Parameters:
  290. module (string): module to reload, defaults to core
  291. Returns:
  292. boolean: True if Reload action was successfull, False overwise
  293. '''
  294. reply = await manager.send_action({'Action': 'Reload',
  295. 'Module': module})
  296. app.logger.warning('Reload({})'.format(module))
  297. if (isinstance(reply, Message) and reply.success):
  298. return True
  299. return False
  300. async def getGlobalVars():
  301. globalVars = GlobalVars()
  302. for _var in globalVars.d():
  303. setattr(globalVars, _var, await amiGetVar(_var))
  304. return globalVars
  305. async def setUserHint(user, dial, ast):
  306. if dial in NONEs:
  307. hint = 'CustomPresence:{}'.format(user)
  308. else:
  309. _dial= [dial]
  310. if (ast.DNDDEVSTATE == 'TRUE'):
  311. _dial.append('Custom:DND{}'.format(user))
  312. hint = '{},CustomPresence:{}'.format('&'.join(_dial), user)
  313. return await amiSetHint('ext-local', user, hint)
  314. async def amiQueues():
  315. queues = {}
  316. reply = await manager.send_action({'Action':'QueueStatus'})
  317. if len(reply) >= 2:
  318. for message in reply:
  319. if message.event == 'QueueMember':
  320. _qm = QueueMember(re.search('Local\/(\d+)', message.location).group(1))
  321. queues.setdefault(message.queue, []).append(_qm.fromMessage(message))
  322. return queues
  323. async def amiDeviceChannel(device):
  324. reply = await manager.send_action({'Action':'CoreShowChannels'})
  325. if len(reply) >= 2:
  326. for message in reply:
  327. if message.event == 'CoreShowChannel':
  328. if message.calleridnum == device:
  329. return message.channel
  330. return None
  331. async def setQueueStates(queues, user, device, state):
  332. for queue in [_q for _q, _ma in queues.items() for _m in _ma if _m.user == user]:
  333. await amiSetVar('DEVICE_STATE(Custom:QUEUE{}*{})'.format(device, queue), state)
  334. async def getDeviceUser(device):
  335. return await amiDBGet('DEVICE', '{}/user'.format(device))
  336. async def getDeviceDial(device):
  337. return await amiDBGet('DEVICE', '{}/dial'.format(device))
  338. async def getUserCID(user):
  339. return await amiDBGet('AMPUSER', '{}/cidnum'.format(user))
  340. async def setDeviceUser(device, user):
  341. return await amiDBPut('DEVICE', '{}/user'.format(device), user)
  342. async def getUserDevice(user):
  343. return await amiDBGet('AMPUSER', '{}/device'.format(user))
  344. async def setUserDevice(user, device):
  345. if device is None:
  346. return await amiDBDel('AMPUSER', '{}/device'.format(user))
  347. else:
  348. return await amiDBPut('AMPUSER', '{}/device'.format(user), device)
  349. async def unbindOtherDevices(user, newDevice, queues, ast):
  350. '''Unbinds user from all devices except newDevice and sets
  351. all required device states.
  352. '''
  353. devices = await amiDBGet('AMPUSER', '{}/device'.format(user))
  354. if devices not in NONEs:
  355. for _device in sorted(set(devices.split('&')), key=int):
  356. if _device != newDevice:
  357. if ast.FMDEVSTATE == 'TRUE':
  358. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(_device), 'INVALID')
  359. if ast.QUEDEVSTATE == 'TRUE':
  360. await setQueueStates(queues, user, _device, 'NOT_INUSE')
  361. if ast.DNDDEVSTATE:
  362. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(_device), 'NOT_INUSE')
  363. if ast.CFDEVSTATE:
  364. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(_device), 'NOT_INUSE')
  365. await amiDBPut('DEVICE', '{}/user'.format(_device), 'none')
  366. async def setUserDeviceStates(user, device, queues, ast):
  367. if ast.FMDEVSTATE == 'TRUE':
  368. _followMe = await amiDBGet('AMPUSER', '{}/followme/ddial'.format(user))
  369. if _followMe is not None:
  370. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(device), followMe2DevState(_followMe))
  371. if ast.QUEDEVSTATE == 'TRUE':
  372. await setQueueStates(queues, user, device, 'INUSE')
  373. if ast.DNDDEVSTATE:
  374. _dnd = await amiDBGet('DND', user)
  375. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(device), 'INUSE' if _dnd == 'YES' else 'NOT_INUSE')
  376. if ast.CFDEVSTATE:
  377. _cf = await amiDBGet('CF', user)
  378. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(device), 'INUSE' if _cf != '' else 'NOT_INUSE')
  379. async def refreshStatesCache():
  380. app.config['STATE_CACHE']['user'] = await amiExtensionStateList()
  381. app.config['STATE_CACHE']['presence'] = await amiPresenceStateList()
  382. return len(app.config['STATE_CACHE']['user'])
  383. async def userStateChangeCallback(user, state):
  384. reply = None
  385. if ((app.config['STATE_CALLBACK_URL'] not in NONEs) and
  386. ('HTTP_CLIENT' in app.config)):
  387. reply = await app.config['HTTP_CLIENT'].post(app.config['STATE_CALLBACK_URL'],
  388. json={'user': user,
  389. 'state': state})
  390. else:
  391. app.logger.warning('{} changed state to: {}'.format(user, state))
  392. return reply
  393. def getUserStateCombined(user):
  394. if user not in app.config['STATE_CACHE']['user']:
  395. return None
  396. _state = app.config['STATE_CACHE']['user'][user]
  397. if (_state == 'idle'):
  398. if (user in app.config['STATE_CACHE']['presence']):
  399. if app.config['STATE_CACHE']['presence'][user] in ('not_set','available', 'xa', 'chat'):
  400. return 'available'
  401. else:
  402. return app.config['STATE_CACHE']['presence'][user]
  403. else:
  404. return 'available'
  405. else:
  406. if _state in ('unavailable', 'ringing'):
  407. return _state
  408. else:
  409. return 'busy'
  410. def getUsersStatesCombined():
  411. return {user:getUserStateCombined(user) for user in app.config['STATE_CACHE']['user']}
  412. @app.route('/atxfer/<userA>/<userB>')
  413. class AtXfer(Resource):
  414. @app.param('userA', 'User initiating the attended transfer', 'path')
  415. @app.param('userB', 'Transfer destination user', 'path')
  416. @app.response(HTTPStatus.OK, 'Successfuly transfered the call')
  417. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  418. @app.response(HTTPStatus.NOT_FOUND, 'User does not exist, or user is not bound to device, \
  419. or device is offline, or no current call for user')
  420. @app.response(HTTPStatus.BAD_REQUEST, 'Transfer failed somehow or other AMI error')
  421. async def get(self, userA, userB):
  422. '''Attended call transfer
  423. '''
  424. device = await getUserDevice(userA)
  425. if device in NONEs:
  426. abort(HTTPStatus.NOT_FOUND)
  427. channel = await amiDeviceChannel(device)
  428. if channel in NONEs:
  429. abort(HTTPStatus.NOT_FOUND)
  430. reply = await manager.send_action({'Action':'Atxfer',
  431. 'Channel':channel,
  432. 'async':'false',
  433. 'Exten':userB})
  434. if (isinstance(reply, Message) and reply.success):
  435. return '', HTTPStatus.OK
  436. abort(HTTPStatus.BAD_REQUEST)
  437. @app.route('/users/states')
  438. class UsersStates(Resource):
  439. @app.response(HTTPStatus.OK, 'JSON map of form {user1:state1, user2:state2, ...}')
  440. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  441. async def get(self):
  442. '''Returns all users with their states.
  443. Possible states are: available, away, dnd, inuse, busy, unavailable, ringing
  444. '''
  445. await refreshStatesCache()
  446. return getUsersStatesCombined()
  447. @app.route('/user/<user>/presence')
  448. class UserPresenceState(Resource):
  449. @app.param('user', 'User to query for presence state', 'path')
  450. @app.response(HTTPStatus.OK, 'Presence state string')
  451. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  452. @app.response(HTTPStatus.NOT_FOUND, 'User does not exist')
  453. @app.response(HTTPStatus.BAD_REQUEST, 'AMI error')
  454. async def get(self, user):
  455. '''Returns user's presence state.
  456. One of: not_set | unavailable | available | away | xa | chat | dnd
  457. '''
  458. cidnum = await getUserCID(user) # Check if user exists in astdb
  459. if cidnum is None:
  460. abort(HTTPStatus.NOT_FOUND)
  461. state = await amiPresenceState(user)
  462. if state is None:
  463. abort(HTTPStatus.BAD_REQUEST)
  464. return state
  465. @app.route('/user/<user>/presence/<state>')
  466. class SetUserPresenceState(Resource):
  467. @app.param('user', 'Target user to set the presence state', 'path')
  468. @app.param('state',
  469. 'The presence state to set for user, one of: not_set, unavailable, available, away, xa, chat or dnd',
  470. 'path')
  471. @app.response(HTTPStatus.OK, 'Successfuly set the presence state')
  472. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  473. @app.response(HTTPStatus.NOT_FOUND, 'User does not exist')
  474. @app.response(HTTPStatus.BAD_REQUEST, 'Wrong state string ot other AMI error')
  475. async def get(self, user, state):
  476. '''Sets user's presence state.
  477. Allowed states: not_set | unavailable | available | away | xa | chat | dnd
  478. '''
  479. cidnum = await getUserCID(user) # Check if user exists in astdb
  480. if cidnum is None:
  481. abort(HTTPStatus.NOT_FOUND)
  482. if await amiSetVar('PRESENCE_STATE(CustomPresence:{})'.format(user),
  483. state):
  484. return '', HTTPStatus.OK
  485. else:
  486. abort(HTTPStatus.BAD_REQUEST)
  487. @app.route('/device/<device>/<user>/on')
  488. @app.route('/user/<user>/<device>/on')
  489. class UserDeviceBind(Resource):
  490. @app.param('device', 'Device number to bind to', 'path')
  491. @app.param('user', 'User to bind to device', 'path')
  492. @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
  493. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  494. async def get(self, device, user):
  495. '''Binds user to device.
  496. Both user and device numbers are checked for existance.
  497. Any device user was previously bound to, is unbound.
  498. Any user previously bound to device is unbound also.
  499. '''
  500. cidnum = await getUserCID(user) # Check if user exists in astdb
  501. if cidnum is None:
  502. return noUser(user)
  503. dial = await getDeviceDial(device) # Check if device exists in astdb
  504. if dial is None:
  505. return noDevice(device)
  506. currentUser = await getDeviceUser(device) # Check if any user is already bound to device
  507. if currentUser == user:
  508. return beenBound(user, device)
  509. ast = await getGlobalVars()
  510. queues = await amiQueues()
  511. if currentUser not in NONEs: # If any other user is bound to device, unbind him,
  512. await setUserDevice(currentUser, None)
  513. if ast.QUEDEVSTATE == 'TRUE': # set device states for previous user queues
  514. await setQueueStates(queues, currentUser, device, 'NOT_INUSE')
  515. await setUserHint(currentUser, None, ast) # set hints for previous user
  516. await setDeviceUser(device, user) # Bind user to device
  517. # If user is bound to some other devices, unbind him and set
  518. # device states for those devices
  519. await unbindOtherDevices(user, device, queues, ast)
  520. if not (await setUserHint(user, dial, ast)): # Set hints for user on new device
  521. return hintError(user, device)
  522. await setUserDeviceStates(user, device, queues, ast) # Set device states for users new device
  523. if not (await setUserDevice(user, device)): # Bind device to user
  524. return bindError(user, device)
  525. return beenBound(user, device)
  526. @app.route('/device/<device>/off')
  527. class DeviceUnBind(Resource):
  528. @app.param('device', 'Device number to unbind', 'path')
  529. @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
  530. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  531. async def get(self, device):
  532. '''Unbinds any user from device.
  533. Device is checked for existance.
  534. '''
  535. dial = await getDeviceDial(device) # Check if device exists in astdb
  536. if dial is None:
  537. return noDevice(device)
  538. currentUser = await getDeviceUser(device) # Check if any user is bound to device
  539. if currentUser in NONEs:
  540. return noUserBound(device)
  541. else:
  542. ast = await getGlobalVars()
  543. queues = await amiQueues()
  544. await setUserDevice(currentUser, None) # Unbind device from current user
  545. if ast.QUEDEVSTATE == 'TRUE': # set device states for current user queues
  546. await setQueueStates(queues, currentUser, device, 'NOT_INUSE')
  547. await setUserHint(currentUser, None, ast) # set hints for current user
  548. await setDeviceUser(device, 'none') # Unbind user from device
  549. return beenUnbound(currentUser, device)
  550. manager.connect()
  551. app.run(loop=main_loop, host='0.0.0.0', port=app.config['PORT'])