app.py 34 KB

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