app.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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('*')
  73. #async def ami_callback(mngr: Manager, msg: Message):
  74. # print("GOT MSG:", msg)
  75. @app.route('/openapi.json')
  76. async def openapi():
  77. '''Generates JSON that conforms OpenAPI Specification
  78. '''
  79. schema = app.__schema__
  80. schema['servers'] = [{'url':'{}://{}:{}'.format(app.config['SCHEME'],
  81. app.config['FQDN'],
  82. app.config['PORT'])}]
  83. schema['components'] = {'securitySchemes':{'ApiKey':{'type': 'apiKey',
  84. 'name': app.config['AUTH_HEADER'],
  85. 'in': 'header'}}}
  86. schema['security'] = [{'ApiKey':[]}]
  87. return jsonify(schema)
  88. @app.route('/ui')
  89. async def ui():
  90. '''Swagger UI
  91. '''
  92. return await render_template_string(SWAGGER_TEMPLATE,
  93. title=app.config['TITLE'],
  94. js_url=app.config['SWAGGER_JS_URL'],
  95. css_url=app.config['SWAGGER_CSS_URL'])
  96. @app.route('/ami/action', methods=['POST'])
  97. async def action():
  98. _payload = await request.get_data()
  99. reply = await manager.send_action(json.loads(_payload))
  100. return reply
  101. @app.route('/ami/getvar/<string:variable>')
  102. async def amiGetVar(variable):
  103. '''AMI GetVar
  104. Returns value of requested variable using AMI action GetVar in background.
  105. Parameters:
  106. variable (string): Variable to query for
  107. Returns:
  108. string: Variable value or empty string if variable not found
  109. '''
  110. reply = await manager.send_action({'Action': 'GetVar',
  111. 'Variable': variable})
  112. app.logger.warning('GetVar({})->{}'.format(variable, reply.value))
  113. return reply.value
  114. async def amiSetVar(variable, value):
  115. '''AMI SetVar
  116. Sets variable using AMI action SetVar to value in background.
  117. Parameters:
  118. variable (string): Variable to set
  119. value (string): Value to set for variable
  120. Returns:
  121. boolean: True if DBPut action was successfull, False overwise
  122. '''
  123. reply = await manager.send_action({'Action': 'SetVar',
  124. 'Variable': variable,
  125. 'Value': value})
  126. app.logger.warning('SetVar({}, {})'.format(variable, value))
  127. if (isinstance(reply, Message) and reply.success):
  128. return True
  129. return False
  130. async def amiDBGet(family, key):
  131. '''AMI DBGet
  132. Returns value of requested astdb key using AMI action DBGet in background.
  133. Parameters:
  134. family (string): astdb key family to query for
  135. key (string): astdb key to query for
  136. Returns:
  137. string: Value or empty string if variable not found
  138. '''
  139. reply = await manager.send_action({'Action': 'DBGet',
  140. 'Family': family,
  141. 'Key': key})
  142. if (isinstance(reply, list) and
  143. (len(reply) > 1)):
  144. for message in reply:
  145. if (message.event == 'DBGetResponse'):
  146. app.logger.warning('DBGet(/{}/{})->{}'.format(family, key, message.val))
  147. return message.val
  148. app.logger.warning('DBGet(/{}/{})->Error!'.format(family, key))
  149. return None
  150. async def amiDBPut(family, key, value):
  151. '''AMI DBPut
  152. Writes value to astdb by family and key using AMI action DBPut in background.
  153. Parameters:
  154. family (string): astdb key family to write to
  155. key (string): astdb key to write to
  156. value (string): value to write
  157. Returns:
  158. boolean: True if DBPut action was successfull, False overwise
  159. '''
  160. reply = await manager.send_action({'Action': 'DBPut',
  161. 'Family': family,
  162. 'Key': key,
  163. 'Val': value})
  164. app.logger.warning('DBPut(/{}/{}, {})'.format(family, key, value))
  165. if (isinstance(reply, Message) and reply.success):
  166. return True
  167. return False
  168. async def amiDBDel(family, key):
  169. '''AMI DBDel
  170. Deletes key from family in astdb using AMI action DBDel in background.
  171. Parameters:
  172. family (string): astdb key family
  173. key (string): astdb key to delete
  174. Returns:
  175. boolean: True if DBDel action was successfull, False overwise
  176. '''
  177. reply = await manager.send_action({'Action': 'DBDel',
  178. 'Family': family,
  179. 'Key': key})
  180. app.logger.warning('DBDel(/{}/{})'.format(family, key))
  181. if (isinstance(reply, Message) and reply.success):
  182. return True
  183. return False
  184. async def amiSetHint(context, user, hint):
  185. '''AMI SetHint
  186. Sets hint for user in context using AMI action DialplanUserAdd with Replace=true in background.
  187. Parameters:
  188. context (string): dialplan context
  189. user (string): user
  190. hint (string): hint for user
  191. Returns:
  192. boolean: True if DialplanUserAdd action was successfull, False overwise
  193. '''
  194. reply = await manager.send_action({'Action': 'DialplanExtensionAdd',
  195. 'Context': context,
  196. 'Extension': user,
  197. 'Priority': 'hint',
  198. 'Application': hint,
  199. 'Replace': 'yes'})
  200. app.logger.warning('SetHint({},{},{})'.format(context, user, hint))
  201. if (isinstance(reply, Message) and reply.success):
  202. return True
  203. return False
  204. async def amiPresenceState(user):
  205. '''AMI PresenceState request for CustomPresence provider
  206. Parameters:
  207. user (string): user
  208. Returns:
  209. string: One of: not_set, unavailable, available, away, xa, chat or dnd
  210. '''
  211. reply = await manager.send_action({'Action': 'PresenceState',
  212. 'Provider': 'CustomPresence:{}'.format(user)})
  213. app.logger.warning('PresenceState({})'.format(user))
  214. if (isinstance(reply, Message) and reply.success):
  215. return reply.state
  216. return None
  217. async def amiCommand(command):
  218. '''AMI Command
  219. Runs specified command using AMI action Command in background.
  220. Parameters:
  221. command (string): command to run
  222. Returns:
  223. boolean, list: tuple representing the boolean result of request and list of lines of command output
  224. '''
  225. reply = await manager.send_action({'Action': 'Command',
  226. 'Command': command})
  227. result = []
  228. if (isinstance(reply, Message) and reply.success):
  229. if isinstance(reply.output, list):
  230. result = reply.output
  231. else:
  232. result = reply.output.split('\n')
  233. app.logger.warning('Command({})->{}'.format(command, '\n'.join(result)))
  234. return True, result
  235. app.logger.warning('Command({})->Error!'.format(command))
  236. return False, result
  237. async def amiReload(module='core'):
  238. '''AMI Reload
  239. Reload specified asterisk module using AMI action reload in background.
  240. Parameters:
  241. module (string): module to reload, defaults to core
  242. Returns:
  243. boolean: True if Reload action was successfull, False overwise
  244. '''
  245. reply = await manager.send_action({'Action': 'Reload',
  246. 'Module': module})
  247. app.logger.warning('Reload({})'.format(module))
  248. if (isinstance(reply, Message) and reply.success):
  249. return True
  250. return False
  251. async def getGlobalVars():
  252. globalVars = GlobalVars()
  253. for _var in globalVars.d():
  254. setattr(globalVars, _var, await amiGetVar(_var))
  255. return globalVars
  256. async def setUserHint(user, dial, ast):
  257. if dial in NONEs:
  258. hint = 'CustomPresence:{}'.format(user)
  259. else:
  260. _dial= [dial]
  261. if (ast.DNDDEVSTATE == 'TRUE'):
  262. _dial.append('Custom:DND{}'.format(user))
  263. hint = '{},CustomPresence:{}'.format('&'.join(_dial), user)
  264. return await amiSetHint('ext-local', user, hint)
  265. async def amiQueues():
  266. queues = {}
  267. reply = await manager.send_action({'Action':'QueueStatus'})
  268. if len(reply) >= 2:
  269. for message in reply:
  270. if message.event == 'QueueMember':
  271. _qm = QueueMember(re.search('Local\/(\d+)', message.location).group(1))
  272. queues.setdefault(message.queue, []).append(_qm.fromMessage(message))
  273. return queues
  274. async def setQueueStates(queues, user, device, state):
  275. for queue in [_q for _q, _ma in queues.items() for _m in _ma if _m.user == user]:
  276. await amiSetVar('DEVICE_STATE(Custom:QUEUE{}*{})'.format(device, queue), state)
  277. async def getDeviceUser(device):
  278. return await amiDBGet('DEVICE', '{}/user'.format(device))
  279. async def getDeviceDial(device):
  280. return await amiDBGet('DEVICE', '{}/dial'.format(device))
  281. async def getUserCID(user):
  282. return await amiDBGet('AMPUSER', '{}/cidnum'.format(user))
  283. async def setDeviceUser(device, user):
  284. return await amiDBPut('DEVICE', '{}/user'.format(device), user)
  285. async def setUserDevice(user, device):
  286. if device is None:
  287. return await amiDBDel('AMPUSER', '{}/device'.format(user))
  288. else:
  289. return await amiDBPut('AMPUSER', '{}/device'.format(user), device)
  290. async def unbindOtherDevices(user, newDevice, queues, ast):
  291. '''Unbinds user from all devices except newDevice and sets
  292. all required device states.
  293. '''
  294. devices = await amiDBGet('AMPUSER', '{}/device'.format(user))
  295. if devices not in NONEs:
  296. for _device in sorted(set(devices.split('&')), key=int):
  297. if _device != newDevice:
  298. if ast.FMDEVSTATE == 'TRUE':
  299. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(_device), 'INVALID')
  300. if ast.QUEDEVSTATE == 'TRUE':
  301. await setQueueStates(queues, user, _device, 'NOT_INUSE')
  302. if ast.DNDDEVSTATE:
  303. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(_device), 'NOT_INUSE')
  304. if ast.CFDEVSTATE:
  305. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(_device), 'NOT_INUSE')
  306. await amiDBPut('DEVICE', '{}/user'.format(_device), 'none')
  307. async def setUserDeviceStates(user, device, queues, ast):
  308. if ast.FMDEVSTATE == 'TRUE':
  309. _followMe = await amiDBGet('AMPUSER', '{}/followme/ddial'.format(user))
  310. if _followMe is not None:
  311. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(device), followMe2DevState(_followMe))
  312. if ast.QUEDEVSTATE == 'TRUE':
  313. await setQueueStates(queues, user, device, 'INUSE')
  314. if ast.DNDDEVSTATE:
  315. _dnd = await amiDBGet('DND', user)
  316. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(device), 'INUSE' if _dnd == 'YES' else 'NOT_INUSE')
  317. if ast.CFDEVSTATE:
  318. _cf = await amiDBGet('CF', user)
  319. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(device), 'INUSE' if _cf != '' else 'NOT_INUSE')
  320. @app.route('/user/<user>/presence')
  321. class UserPresenceState(Resource):
  322. @app.param('user', 'User to query for presence state', 'path')
  323. @app.response(HTTPStatus.OK, 'Presence state string')
  324. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  325. @app.response(HTTPStatus.NOT_FOUND, 'User does not exist')
  326. @app.response(HTTPStatus.BAD_REQUEST, 'AMI error')
  327. async def get(self, user):
  328. '''Returns user's presence state.
  329. One of: not_set | unavailable | available | away | xa | chat | dnd
  330. '''
  331. cidnum = await getUserCID(user) # Check if user exists in astdb
  332. if cidnum is None:
  333. return '', HTTPStatus.NOT_FOUND
  334. state = await amiPresenceState(user)
  335. if state is None:
  336. return '', HTTPStatus.BAD_REQUEST
  337. return state
  338. @app.route('/user/<user>/presence/<state>')
  339. class SetUserPresenceState(Resource):
  340. @app.param('user', 'Target user to set the presence state', 'path')
  341. @app.param('state',
  342. 'The presence state to set for user, one of: not_set, unavailable, available, away, xa, chat or dnd',
  343. 'path')
  344. @app.response(HTTPStatus.OK, 'Successfuly set the presence state')
  345. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  346. @app.response(HTTPStatus.NOT_FOUND, 'User does not exist')
  347. @app.response(HTTPStatus.BAD_REQUEST, 'Wrong state string ot other AMI error')
  348. async def get(self, user, state):
  349. '''Sets user's presence state.
  350. Allowed states: not_set | unavailable | available | away | xa | chat | dnd
  351. '''
  352. cidnum = await getUserCID(user) # Check if user exists in astdb
  353. if cidnum is None:
  354. return '', HTTPStatus.NOT_FOUND
  355. if await amiSetVar('PRESENCE_STATE(CustomPresence:{})'.format(user),
  356. state):
  357. return ''
  358. else:
  359. return '', HTTPStatus.BAD_REQUEST
  360. @app.route('/device/<device>/<user>/on')
  361. @app.route('/user/<user>/<device>/on')
  362. class UserDeviceBind(Resource):
  363. @app.param('device', 'Device number to bind to', 'path')
  364. @app.param('user', 'User to bind to device', 'path')
  365. @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
  366. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  367. async def get(self, device, user):
  368. '''Binds user to device.
  369. Both user and device numbers are checked for existance.
  370. Any device user was previously bound to, is unbound.
  371. Any user previously bound to device is unbound also.
  372. '''
  373. cidnum = await getUserCID(user) # Check if user exists in astdb
  374. if cidnum is None:
  375. return noUser(user)
  376. dial = await getDeviceDial(device) # Check if device exists in astdb
  377. if dial is None:
  378. return noDevice(device)
  379. currentUser = await getDeviceUser(device) # Check if any user is already bound to device
  380. if currentUser == user:
  381. return beenBound(user, device)
  382. ast = await getGlobalVars()
  383. queues = await amiQueues()
  384. if currentUser not in NONEs: # If any other user is bound to device, unbind him,
  385. await setUserDevice(currentUser, None)
  386. if ast.QUEDEVSTATE == 'TRUE': # set device states for previous user queues
  387. await setQueueStates(queues, currentUser, device, 'NOT_INUSE')
  388. await setUserHint(currentUser, None, ast) # set hints for previous user
  389. await setDeviceUser(device, user) # Bind user to device
  390. # If user is bound to some other devices, unbind him and set
  391. # device states for those devices
  392. await unbindOtherDevices(user, device, queues, ast)
  393. if not (await setUserHint(user, dial, ast)): # Set hints for user on new device
  394. return hintError(user, device)
  395. await setUserDeviceStates(user, device, queues, ast) # Set device states for users new device
  396. if not (await setUserDevice(user, device)): # Bind device to user
  397. return bindError(user, device)
  398. return beenBound(user, device)
  399. @app.route('/device/<device>/off')
  400. class DeviceUnBind(Resource):
  401. @app.param('device', 'Device number to unbind', 'path')
  402. @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
  403. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  404. async def get(self, device):
  405. '''Unbinds any user from device.
  406. Device is checked for existance.
  407. '''
  408. dial = await getDeviceDial(device) # Check if device exists in astdb
  409. if dial is None:
  410. return noDevice(device)
  411. currentUser = await getDeviceUser(device) # Check if any user is bound to device
  412. if currentUser in NONEs:
  413. return noUserBound(device)
  414. else:
  415. ast = await getGlobalVars()
  416. queues = await amiQueues()
  417. await setUserDevice(currentUser, None) # Unbind device from current user
  418. if ast.QUEDEVSTATE == 'TRUE': # set device states for current user queues
  419. await setQueueStates(queues, currentUser, device, 'NOT_INUSE')
  420. await setUserHint(currentUser, None, ast) # set hints for current user
  421. await setDeviceUser(device, 'none') # Unbind user from device
  422. return beenUnbound(currentUser, device)
  423. manager.connect()
  424. app.run(loop=main_loop, host='0.0.0.0', port=app.config['PORT'])