app.py 35 KB

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