app.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  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, CdrChannel):
  25. return str(o)
  26. if isinstance(o, CdrEvent):
  27. return o.__dict__
  28. if isinstance(o, CdrEvents) or isinstance(o, CelEvents):
  29. return o.all
  30. if isinstance(o, CdrCall) or 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) or
  106. (scope['path'].startswith('/static/records')))):
  107. return await self.app(scope, receive, send)
  108. return await self.error_response(receive, send)
  109. async def error_response(self, receive, send):
  110. await send({'type': 'http.response.start',
  111. 'status': 401,
  112. 'headers': [(b'content-length', b'21')]})
  113. await send({'type': 'http.response.body',
  114. 'body': b'Authorization requred',
  115. 'more_body': False})
  116. app.asgi_app = AuthMiddleware(app.asgi_app)
  117. db = PintDB(app)
  118. @manager.register_event('FullyBooted')
  119. @manager.register_event('Reload')
  120. async def reloadCallback(mngr: Manager, msg: Message):
  121. await refreshDevicesCache()
  122. await refreshStatesCache()
  123. await refreshQueuesCache()
  124. await rebindLostDevices()
  125. @manager.register_event('ExtensionStatus')
  126. async def extensionStatusCallback(mngr: Manager, msg: Message):
  127. user = msg.exten
  128. state = msg.statustext.lower()
  129. if user in app.cache['ustates']:
  130. prevState = getUserStateCombined(user)
  131. app.cache['ustates'][user] = state
  132. combinedState = getUserStateCombined(user)
  133. if combinedState != prevState:
  134. await userStateChangeCallback(user, combinedState, prevState)
  135. @manager.register_event('PresenceStatus')
  136. async def presenceStatusCallback(mngr: Manager, msg: Message):
  137. user = msg.exten #hint = msg.hint
  138. state = msg.status.lower()
  139. if user in app.cache['ustates']:
  140. prevState = getUserStateCombined(user)
  141. app.cache['pstates'][user] = state
  142. combinedState = getUserStateCombined(user)
  143. if combinedState != prevState:
  144. await userStateChangeCallback(user, combinedState, prevState)
  145. async def getCDR(start=None,
  146. end=None,
  147. table='cdr',
  148. field='calldate',
  149. sort='calldate, SUBSTR(uniqueid,1,10), sequence'):
  150. _cdr = {}
  151. if end is None:
  152. end = dt.now()
  153. if start is None:
  154. start=(end - td(hours=24))
  155. async for row in db.iterate(query='''SELECT *
  156. FROM {table}
  157. WHERE linkedid
  158. IN (SELECT DISTINCT(linkedid)
  159. FROM {table}
  160. WHERE {field}
  161. BETWEEN :start AND :end)
  162. ORDER BY {sort};'''.format(table=table,
  163. field=field,
  164. sort=sort),
  165. values={'start':start,
  166. 'end':end}):
  167. if row['linkedid'] in _cdr:
  168. _cdr[row['linkedid']].events.add(row)
  169. else:
  170. _cdr[row['linkedid']]=CdrCall(row)
  171. cdr = []
  172. for _id in sorted(_cdr.keys()):
  173. cdr.append(_cdr[_id])
  174. return cdr
  175. async def getUserCDR(user,
  176. start=None,
  177. end=None,
  178. direction=None,
  179. limit=None,
  180. offset=None,
  181. order='ASC'):
  182. _q = f'''SELECT * FROM cdr AS c INNER JOIN (SELECT linkedid FROM cdr WHERE'''
  183. direction=direction.lower()
  184. if direction in ('in', True, '1', 'incoming', 'inbound'):
  185. direction = 'inbound'
  186. _q += f''' dst="{user}"'''
  187. elif direction in ('out', False, '0', 'outgoing', 'outbound'):
  188. direction = 'outbound'
  189. _q += f''' src="{user}"'''
  190. else:
  191. direction = None
  192. _q += f''' (src="{user}" or dst="{user}")'''
  193. if end is None:
  194. end = dt.now()
  195. if start is None:
  196. start=(end - td(hours=24))
  197. _q += f''' AND calldate BETWEEN "{start}" AND "{end}" GROUP BY linkedid'''
  198. if None not in (limit, offset):
  199. _q += f''' LIMIT {offset},{limit}'''
  200. _q += f''') AS c2 ON c.linkedid = c2.linkedid;'''
  201. app.logger.warning('SQL: {}'.format(_q))
  202. _cdr = {}
  203. async for row in db.iterate(query=_q):
  204. if row['linkedid'] in _cdr:
  205. _cdr[row['linkedid']].events.add(row)
  206. else:
  207. _cdr[row['linkedid']]=CdrUserCall(user, row)
  208. cdr = []
  209. for _id in sorted(_cdr.keys(), reverse = True if (order.lower() == 'desc') else False):
  210. record = _cdr[_id].simple
  211. if (direction is not None) and (record['src'] == record['dst']) and (record['direction'] != direction):
  212. record['direction'] = direction
  213. if record['file'] is not None:
  214. record['file'] = '/static/records/{d.year}/{d.month:02}/{d.day:02}/{filename}'.format(d=record['start'],
  215. filename=record['file'])
  216. cdr.append(record)
  217. return cdr
  218. async def getCEL(start=None, end=None, table='cel', field='eventtime', sort='id'):
  219. return await getCDR(start, end, table, field, sort)
  220. @app.before_first_request
  221. async def initHttpClient():
  222. app.config['HTTP_CLIENT'] = aiohttp.ClientSession(loop=main_loop)
  223. @app.route('/openapi.json')
  224. async def openapi():
  225. '''Generates JSON that conforms OpenAPI Specification
  226. '''
  227. schema = app.__schema__
  228. schema['servers'] = [{'url':'{}://{}:{}'.format(app.config['SCHEME'],
  229. app.config['FQDN'],
  230. app.config['PORT'])}]
  231. if app.config['EXTRA_API_URL'] is not None:
  232. schema['servers'].append({'url':app.config['EXTRA_API_URL']})
  233. schema['components'] = {'securitySchemes':{'ApiKey':{'type': 'apiKey',
  234. 'name': app.config['AUTH_HEADER'],
  235. 'in': 'header'}}}
  236. schema['security'] = [{'ApiKey':[]}]
  237. return jsonify(schema)
  238. @app.route('/ui')
  239. async def ui():
  240. '''Swagger UI
  241. '''
  242. return await render_template_string(SWAGGER_TEMPLATE,
  243. title=app.config['TITLE'],
  244. js_url=app.config['SWAGGER_JS_URL'],
  245. css_url=app.config['SWAGGER_CSS_URL'])
  246. @app.route('/ami/action', methods=['POST'])
  247. async def action():
  248. _payload = await request.get_data()
  249. reply = await manager.send_action(json.loads(_payload))
  250. return str(reply)
  251. @app.route('/ami/getvar/<string:variable>')
  252. async def amiGetVar(variable):
  253. '''AMI GetVar
  254. Returns value of requested variable using AMI action GetVar in background.
  255. Parameters:
  256. variable (string): Variable to query for
  257. Returns:
  258. string: Variable value or empty string if variable not found
  259. '''
  260. reply = await manager.send_action({'Action': 'GetVar',
  261. 'Variable': variable})
  262. app.logger.warning('GetVar({})->{}'.format(variable, reply.value))
  263. return reply.value
  264. @app.route('/ami/auths')
  265. async def amiPJSIPShowAuths():
  266. auths = {}
  267. reply = await manager.send_action({'Action':'PJSIPShowAuths'})
  268. if len(reply) >= 2:
  269. for message in reply:
  270. if ((message.event == 'AuthList') and
  271. ('objecttype' in message) and
  272. (message.objecttype == 'auth')):
  273. auths[message.username] = message.password
  274. return successReply(auths)
  275. @app.route('/ami/aors')
  276. async def amiPJSIPShowAors():
  277. aors = {}
  278. reply = await manager.send_action({'Action':'PJSIPShowAors'})
  279. if len(reply) >= 2:
  280. for message in reply:
  281. if ((message.event == 'AorList') and
  282. ('objecttype' in message) and
  283. (message.objecttype == 'aor') and
  284. (int(message.maxcontacts) > 0)):
  285. aors[message.objectname] = message.contacts
  286. app.logger.warning('AorsList: {}'.format(','.join(aors.keys())))
  287. return successReply(aors)
  288. async def amiSetVar(variable, value):
  289. '''AMI SetVar
  290. Sets variable using AMI action SetVar to value in background.
  291. Parameters:
  292. variable (string): Variable to set
  293. value (string): Value to set for variable
  294. Returns:
  295. string: None if SetVar was successfull, error message overwise
  296. '''
  297. reply = await manager.send_action({'Action': 'SetVar',
  298. 'Variable': variable,
  299. 'Value': value})
  300. app.logger.warning('SetVar({}, {})'.format(variable, value))
  301. if isinstance(reply, Message):
  302. if reply.success:
  303. return None
  304. else:
  305. return reply.message
  306. return 'AMI error'
  307. async def amiDBGet(family, key):
  308. '''AMI DBGet
  309. Returns value of requested astdb key using AMI action DBGet in background.
  310. Parameters:
  311. family (string): astdb key family to query for
  312. key (string): astdb key to query for
  313. Returns:
  314. string: Value or empty string if variable not found
  315. '''
  316. reply = await manager.send_action({'Action': 'DBGet',
  317. 'Family': family,
  318. 'Key': key})
  319. if (isinstance(reply, list) and
  320. (len(reply) > 1)):
  321. for message in reply:
  322. if (message.event == 'DBGetResponse'):
  323. app.logger.warning('DBGet(/{}/{})->{}'.format(family, key, message.val))
  324. return message.val
  325. app.logger.warning('DBGet(/{}/{})->Error!'.format(family, key))
  326. return None
  327. async def amiDBPut(family, key, value):
  328. '''AMI DBPut
  329. Writes value to astdb by family and key using AMI action DBPut in background.
  330. Parameters:
  331. family (string): astdb key family to write to
  332. key (string): astdb key to write to
  333. value (string): value to write
  334. Returns:
  335. boolean: True if DBPut action was successfull, False overwise
  336. '''
  337. reply = await manager.send_action({'Action': 'DBPut',
  338. 'Family': family,
  339. 'Key': key,
  340. 'Val': value})
  341. app.logger.warning('DBPut(/{}/{}, {})'.format(family, key, value))
  342. if (isinstance(reply, Message) and reply.success):
  343. return True
  344. return False
  345. async def amiDBDel(family, key):
  346. '''AMI DBDel
  347. Deletes key from family in astdb using AMI action DBDel in background.
  348. Parameters:
  349. family (string): astdb key family
  350. key (string): astdb key to delete
  351. Returns:
  352. boolean: True if DBDel action was successfull, False overwise
  353. '''
  354. reply = await manager.send_action({'Action': 'DBDel',
  355. 'Family': family,
  356. 'Key': key})
  357. app.logger.warning('DBDel(/{}/{})'.format(family, key))
  358. if (isinstance(reply, Message) and reply.success):
  359. return True
  360. return False
  361. async def amiSetHint(context, user, hint):
  362. '''AMI SetHint
  363. Sets hint for user in context using AMI action DialplanUserAdd with Replace=true in background.
  364. Parameters:
  365. context (string): dialplan context
  366. user (string): user
  367. hint (string): hint for user
  368. Returns:
  369. boolean: True if DialplanUserAdd action was successfull, False overwise
  370. '''
  371. reply = await manager.send_action({'Action': 'DialplanExtensionAdd',
  372. 'Context': context,
  373. 'Extension': user,
  374. 'Priority': 'hint',
  375. 'Application': hint,
  376. 'Replace': 'yes'})
  377. app.logger.warning('SetHint({},{},{})'.format(context, user, hint))
  378. if (isinstance(reply, Message) and reply.success):
  379. return True
  380. return False
  381. async def amiPresenceState(user):
  382. '''AMI PresenceState request for CustomPresence provider
  383. Parameters:
  384. user (string): user
  385. Returns:
  386. boolean, string: True and state or False and error message
  387. '''
  388. reply = await manager.send_action({'Action': 'PresenceState',
  389. 'Provider': 'CustomPresence:{}'.format(user)})
  390. app.logger.warning('PresenceState({})'.format(user))
  391. if isinstance(reply, Message):
  392. if reply.success:
  393. return True, reply.state
  394. else:
  395. return False, reply.message
  396. return False, 'AMI error'
  397. async def amiPresenceStateList():
  398. states = {}
  399. reply = await manager.send_action({'Action':'PresenceStateList'})
  400. if len(reply) >= 2:
  401. for message in reply:
  402. if message.event == 'PresenceStateChange':
  403. user = re.search('CustomPresence:(\d+)', message.presentity).group(1)
  404. states[user] = message.status
  405. app.logger.warning('PresenceStateList: {}'.format(','.join(states.keys())))
  406. return states
  407. async def amiExtensionStateList():
  408. states = {}
  409. reply = await manager.send_action({'Action':'ExtensionStateList'})
  410. if len(reply) >= 2:
  411. for message in reply:
  412. if ((message.event == 'ExtensionStatus') and
  413. (message.context == 'ext-local')):
  414. states[message.exten] = message.statustext.lower()
  415. app.logger.warning('ExtensionStateList: {}'.format(','.join(states.keys())))
  416. return states
  417. async def amiCommand(command):
  418. '''AMI Command
  419. Runs specified command using AMI action Command in background.
  420. Parameters:
  421. command (string): command to run
  422. Returns:
  423. boolean, list: tuple representing the boolean result of request and list of lines of command output
  424. '''
  425. reply = await manager.send_action({'Action': 'Command',
  426. 'Command': command})
  427. result = []
  428. if (isinstance(reply, Message) and reply.success):
  429. if isinstance(reply.output, list):
  430. result = reply.output
  431. else:
  432. result = reply.output.split('\n')
  433. app.logger.warning('Command({})->{}'.format(command, '\n'.join(result)))
  434. return True, result
  435. app.logger.warning('Command({})->Error!'.format(command))
  436. return False, result
  437. async def amiReload(module='core'):
  438. '''AMI Reload
  439. Reload specified asterisk module using AMI action reload in background.
  440. Parameters:
  441. module (string): module to reload, defaults to core
  442. Returns:
  443. boolean: True if Reload action was successfull, False overwise
  444. '''
  445. reply = await manager.send_action({'Action': 'Reload',
  446. 'Module': module})
  447. app.logger.warning('Reload({})'.format(module))
  448. if (isinstance(reply, Message) and reply.success):
  449. return True
  450. return False
  451. async def getGlobalVars():
  452. globalVars = GlobalVars()
  453. for _var in globalVars.d():
  454. setattr(globalVars, _var, await amiGetVar(_var))
  455. return globalVars
  456. async def setUserHint(user, dial, ast):
  457. if dial in NONEs:
  458. hint = 'CustomPresence:{}'.format(user)
  459. else:
  460. _dial= [dial]
  461. if (ast.DNDDEVSTATE == 'TRUE'):
  462. _dial.append('Custom:DND{}'.format(user))
  463. hint = '{},CustomPresence:{}'.format('&'.join(_dial), user)
  464. return await amiSetHint('ext-local', user, hint)
  465. async def amiQueues():
  466. queues = {}
  467. reply = await manager.send_action({'Action':'QueueStatus'})
  468. if len(reply) >= 2:
  469. for message in reply:
  470. if message.event == 'QueueMember':
  471. _qm = QueueMember(re.search('Local\/(\d+)', message.location).group(1))
  472. queues.setdefault(message.queue, []).append(_qm.fromMessage(message))
  473. app.logger.warning('QueuesList: {}'.format(','.join(queues.keys())))
  474. return queues
  475. async def amiDeviceChannel(device):
  476. reply = await manager.send_action({'Action':'CoreShowChannels'})
  477. if len(reply) >= 2:
  478. for message in reply:
  479. if message.event == 'CoreShowChannel':
  480. if message.calleridnum == device:
  481. return message.channel
  482. return None
  483. async def getUserChannel(user):
  484. device = await getUserDevice(user)
  485. if device in NONEs:
  486. return False
  487. channel = await amiDeviceChannel(device)
  488. if channel in NONEs:
  489. return False
  490. return channel
  491. async def setQueueStates(user, device, state):
  492. for queue in [_q for _q, _ma in app.cache['queues'].items() for _m in _ma if _m.user == user]:
  493. await amiSetVar('DEVICE_STATE(Custom:QUEUE{}*{})'.format(device, queue), state)
  494. async def getDeviceUser(device):
  495. return await amiDBGet('DEVICE', '{}/user'.format(device))
  496. async def getDeviceType(device):
  497. return await amiDBGet('DEVICE', '{}/type'.format(device))
  498. async def getDeviceDial(device):
  499. return await amiDBGet('DEVICE', '{}/dial'.format(device))
  500. async def getUserCID(user):
  501. return await amiDBGet('AMPUSER', '{}/cidnum'.format(user))
  502. async def setDeviceUser(device, user):
  503. return await amiDBPut('DEVICE', '{}/user'.format(device), user)
  504. async def getUserDevice(user):
  505. return await amiDBGet('AMPUSER', '{}/device'.format(user))
  506. async def setUserDevice(user, device):
  507. if device is None:
  508. return await amiDBDel('AMPUSER', '{}/device'.format(user))
  509. else:
  510. return await amiDBPut('AMPUSER', '{}/device'.format(user), device)
  511. async def unbindOtherDevices(user, newDevice, ast):
  512. '''Unbinds user from all devices except newDevice and sets
  513. all required device states.
  514. '''
  515. devices = await amiDBGet('AMPUSER', '{}/device'.format(user))
  516. if devices not in NONEs:
  517. for _device in sorted(set(devices.split('&')), key=int):
  518. if _device != newDevice:
  519. if ast.FMDEVSTATE == 'TRUE':
  520. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(_device), 'INVALID')
  521. if ast.QUEDEVSTATE == 'TRUE':
  522. await setQueueStates(user, _device, 'NOT_INUSE')
  523. if ast.DNDDEVSTATE:
  524. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(_device), 'NOT_INUSE')
  525. if ast.CFDEVSTATE:
  526. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(_device), 'NOT_INUSE')
  527. await amiDBPut('DEVICE', '{}/user'.format(_device), 'none')
  528. async def setUserDeviceStates(user, device, ast):
  529. if ast.FMDEVSTATE == 'TRUE':
  530. _followMe = await amiDBGet('AMPUSER', '{}/followme/ddial'.format(user))
  531. if _followMe is not None:
  532. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(device), followMe2DevState(_followMe))
  533. if ast.QUEDEVSTATE == 'TRUE':
  534. await setQueueStates(user, device, 'INUSE')
  535. if ast.DNDDEVSTATE:
  536. _dnd = await amiDBGet('DND', user)
  537. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(device), 'INUSE' if _dnd == 'YES' else 'NOT_INUSE')
  538. if ast.CFDEVSTATE:
  539. _cf = await amiDBGet('CF', user)
  540. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(device), 'INUSE' if _cf != '' else 'NOT_INUSE')
  541. async def refreshStatesCache():
  542. app.cache['ustates'] = await amiExtensionStateList()
  543. app.cache['pstates'] = await amiPresenceStateList()
  544. return len(app.cache['ustates'])
  545. async def refreshDevicesCache():
  546. _reply = await amiPJSIPShowAors()
  547. aors = _reply['data']
  548. app.cache['devices'] = list(aors.keys())
  549. return len(app.cache['devices'])
  550. async def refreshQueuesCache():
  551. app.cache['queues'] = await amiQueues()
  552. return len(app.cache['queues'])
  553. async def rebindLostDevices():
  554. ast = await getGlobalVars()
  555. for device in app.cache['devices']:
  556. user = await getDeviceUser(device)
  557. deviceType = await getDeviceType(device)
  558. if (deviceType != 'fixed') and (user != 'none') and (user in app.cache['ustates'].keys()):
  559. _device = await getUserDevice(user)
  560. if _device != device:
  561. app.logger.warning('Fixing bind user {} to device {}'.format(user, device))
  562. dial = await getDeviceDial(device)
  563. await setUserHint(user, dial, ast) # Set hints for user on new device
  564. await setUserDeviceStates(user, device, ast) # Set device states for users device
  565. await setUserDevice(user, device) # Bind device to user
  566. async def userStateChangeCallback(user, state, prevState = None):
  567. reply = None
  568. if ((app.config['STATE_CALLBACK_URL'] not in NONEs) and
  569. ('HTTP_CLIENT' in app.config)):
  570. reply = await app.config['HTTP_CLIENT'].post(app.config['STATE_CALLBACK_URL'],
  571. json={'user': user,
  572. 'state': state,
  573. 'prev_state':prevState})
  574. else:
  575. app.logger.warning('{} changed state to: {}'.format(user, state))
  576. return reply
  577. def getUserStateCombined(user):
  578. _uCache = app.cache['ustates']
  579. _pCache = app.cache['pstates']
  580. return combinedStates[_uCache.get(user, 'unavailable')][_pCache.get(user, 'not_set')]
  581. def getUsersStatesCombined():
  582. return {user:getUserStateCombined(user) for user in app.cache['ustates']}
  583. @app.route('/atxfer/<userA>/<userB>')
  584. class AtXfer(Resource):
  585. @app.param('userA', 'User initiating the attended transfer', 'path')
  586. @app.param('userB', 'Transfer destination user', 'path')
  587. @app.response(HTTPStatus.OK, 'Json reply')
  588. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  589. async def get(self, userA, userB):
  590. '''Attended call transfer
  591. '''
  592. channel = await getUserChannel(userA)
  593. if not channel:
  594. return noUserChannel(userA)
  595. reply = await manager.send_action({'Action':'Atxfer',
  596. 'Channel':channel,
  597. 'async':'false',
  598. 'Exten':userB})
  599. if isinstance(reply, Message):
  600. if reply.success:
  601. return successfullyTransfered(userA, userB)
  602. else:
  603. return errorReply(reply.message)
  604. @app.route('/bxfer/<userA>/<userB>')
  605. class BXfer(Resource):
  606. @app.param('userA', 'User initiating the blind transfer', 'path')
  607. @app.param('userB', 'Transfer destination user', 'path')
  608. @app.response(HTTPStatus.OK, 'Json reply')
  609. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  610. async def get(self, userA, userB):
  611. '''Blind call transfer
  612. '''
  613. channel = await getUserChannel(userA)
  614. if not channel:
  615. return noUserChannel(userA)
  616. reply = await manager.send_action({'Action':'BlindTransfer',
  617. 'Channel':channel,
  618. 'async':'false',
  619. 'Exten':userB})
  620. if isinstance(reply, Message):
  621. if reply.success:
  622. return successfullyTransfered(userA, userB)
  623. else:
  624. return errorReply(reply.message)
  625. @app.route('/hangup/<user>')
  626. class Hangup(Resource):
  627. @app.param('user', 'User to hangup', 'path')
  628. @app.response(HTTPStatus.OK, 'Json reply')
  629. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  630. async def get(self, user):
  631. '''Blind call transfer
  632. '''
  633. channel = await getUserChannel(user)
  634. if not channel:
  635. return noUserChannel(user)
  636. reply = await manager.send_action({'Action':'Hangup',
  637. 'Channel':channel})
  638. if isinstance(reply, Message):
  639. if reply.success:
  640. return successfullyHungup(user)
  641. else:
  642. return errorReply(reply.message)
  643. @app.route('/users/states')
  644. class UsersStates(Resource):
  645. @app.response(HTTPStatus.OK, 'JSON reply with user:state map or error message')
  646. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  647. async def get(self):
  648. '''Returns all users with their combined states.
  649. Possible states are: available, away, dnd, inuse, busy, unavailable, ringing
  650. '''
  651. usersCount = await refreshStatesCache()
  652. if usersCount == 0:
  653. return stateCacheEmpty()
  654. return successReply(getUsersStatesCombined())
  655. @app.route('/user/<user>/state')
  656. class UserState(Resource):
  657. @app.param('user', 'User to query for combined state', 'path')
  658. @app.response(HTTPStatus.OK, 'JSON data {"user":user,"state":state}')
  659. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  660. async def get(self, user):
  661. '''Returns user's combined state.
  662. One of: available, away, dnd, inuse, busy, unavailable, ringing
  663. '''
  664. if user not in app.cache['ustates']:
  665. return noUser(user)
  666. return successReply({'user':user,'state':getUserStateCombined(user)})
  667. @app.route('/user/<user>/presence')
  668. class PresenceState(Resource):
  669. @app.param('user', 'User to query for presence state', 'path')
  670. @app.response(HTTPStatus.OK, 'JSON data {"user":user,"state":state}')
  671. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  672. async def get(self, user):
  673. '''Returns user's presence state.
  674. One of: not_set, unavailable, available, away, xa, chat, dnd
  675. '''
  676. if user not in app.cache['ustates']:
  677. return noUser(user)
  678. return successReply({'user':user,'state':app.cache['pstates'].get(user, 'not_set')})
  679. @app.route('/user/<user>/presence/<state>')
  680. class SetPresenceState(Resource):
  681. @app.param('user', 'Target user to set the presence state', 'path')
  682. @app.param('state',
  683. 'The presence state for user, one of: not_set, unavailable, available, away, xa, chat or dnd',
  684. 'path')
  685. @app.response(HTTPStatus.OK, 'Json reply')
  686. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  687. async def get(self, user, state):
  688. '''Sets user's presence state.
  689. Allowed states: not_set | unavailable | available | away | xa | chat | dnd
  690. '''
  691. if state not in presenceStates:
  692. return invalidState(state)
  693. if user not in app.cache['ustates']:
  694. return noUser(user)
  695. if (state.lower() in ('available','not_set','away','xa','chat')) and (getUserStateCombined(user) == 'dnd'):
  696. result = await amiDBDel('DND', '{}'.format(user))
  697. result = await amiSetVar('PRESENCE_STATE(CustomPresence:{})'.format(user), state)
  698. if result is not None:
  699. return errorReply(result)
  700. if state.lower() == 'dnd':
  701. result = await amiDBPut('DND', '{}'.format(user), 'YES')
  702. return successfullySetState(user, state)
  703. @app.route('/users/devices')
  704. class UsersDevices(Resource):
  705. @app.response(HTTPStatus.OK, 'JSON reply with user:device map or error message')
  706. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  707. async def get(self):
  708. '''Returns all users with their combined states.
  709. Possible states are: available, away, dnd, inuse, busy, unavailable, ringing
  710. '''
  711. data = {}
  712. for user in app.cache['ustates']:
  713. device = await getUserDevice(user)
  714. if ((device in NONEs) or (device == user)):
  715. device = None
  716. data[user]=device.replace('{}&'.format(user), '')
  717. return successReply(data)
  718. @app.route('/device/<device>/<user>/on')
  719. @app.route('/user/<user>/<device>/on')
  720. class UserDeviceBind(Resource):
  721. @app.param('device', 'Device number to bind to', 'path')
  722. @app.param('user', 'User to bind to device', 'path')
  723. @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
  724. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  725. async def get(self, device, user):
  726. '''Binds user to device.
  727. Both user and device numbers are checked for existance.
  728. Any device user was previously bound to, is unbound.
  729. Any user previously bound to device is unbound also.
  730. '''
  731. if user not in app.cache['ustates']:
  732. return noUser(user)
  733. dial = await getDeviceDial(device) # Check if device exists in astdb
  734. if dial is None:
  735. return noDevice(device)
  736. currentUser = await getDeviceUser(device) # Check if any user is already bound to device
  737. if currentUser == user:
  738. return alreadyBound(user, device)
  739. ast = await getGlobalVars()
  740. if currentUser not in NONEs: # If any other user is bound to device, unbind him,
  741. await setUserDevice(currentUser, None)
  742. if ast.QUEDEVSTATE == 'TRUE': # set device states for previous user queues
  743. await setQueueStates(currentUser, device, 'NOT_INUSE')
  744. await setUserHint(currentUser, None, ast) # set hints for previous user
  745. await setDeviceUser(device, user) # Bind user to device
  746. # If user is bound to some other devices, unbind him and set
  747. # device states for those devices
  748. await unbindOtherDevices(user, device, ast)
  749. if not (await setUserHint(user, dial, ast)): # Set hints for user on new device
  750. return hintError(user, device)
  751. await setUserDeviceStates(user, device, ast) # Set device states for users new device
  752. if not (await setUserDevice(user, device)): # Bind device to user
  753. return bindError(user, device)
  754. return successfullyBound(user, device)
  755. @app.route('/device/<device>/off')
  756. class DeviceUnBind(Resource):
  757. @app.param('device', 'Device number to unbind', 'path')
  758. @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
  759. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  760. async def get(self, device):
  761. '''Unbinds any user from device.
  762. Device is checked for existance.
  763. '''
  764. dial = await getDeviceDial(device) # Check if device exists in astdb
  765. if dial is None:
  766. return noDevice(device)
  767. currentUser = await getDeviceUser(device) # Check if any user is bound to device
  768. if currentUser in NONEs:
  769. return noUserBound(device)
  770. else:
  771. ast = await getGlobalVars()
  772. await setUserDevice(currentUser, None) # Unbind device from current user
  773. if ast.QUEDEVSTATE == 'TRUE': # set device states for current user queues
  774. await setQueueStates(currentUser, device, 'NOT_INUSE')
  775. await setUserHint(currentUser, None, ast) # set hints for current user
  776. await setDeviceUser(device, 'none') # Unbind user from device
  777. return successfullyUnbound(currentUser, device)
  778. @app.route('/cdr')
  779. class CDR(Resource):
  780. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  781. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  782. @app.response(HTTPStatus.OK, 'JSON reply')
  783. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  784. async def get(self):
  785. '''Returns CDR data, groupped by logical call id.
  786. All request arguments are optional.
  787. '''
  788. start = parseDatetime(request.args.get('start'))
  789. end = parseDatetime(request.args.get('end'))
  790. cdr = await getCDR(start, end)
  791. return successReply(cdr)
  792. @app.route('/cel')
  793. class CEL(Resource):
  794. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  795. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  796. @app.response(HTTPStatus.OK, 'JSON reply')
  797. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  798. async def get(self):
  799. '''Returns CEL data, groupped by logical call id.
  800. All request arguments are optional.
  801. '''
  802. start = parseDatetime(request.args.get('start'))
  803. end = parseDatetime(request.args.get('end'))
  804. cel = await getCEL(start, end)
  805. return successReply(cel)
  806. @app.route('/calls')
  807. class Calls(Resource):
  808. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 and YYYYMMDDhhmmss', 'query')
  809. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 and YYYYMMDDhhmmss', 'query')
  810. @app.response(HTTPStatus.OK, 'JSON reply')
  811. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  812. async def get(self):
  813. '''Returns aggregated call data JSON. Draft implementation.
  814. All request arguments are optional.
  815. '''
  816. calls = []
  817. start = parseDatetime(request.args.get('start'))
  818. end = parseDatetime(request.args.get('end'))
  819. cdr = await getCDR(start, end)
  820. for c in cdr:
  821. _call = {'id':c.linkedid,
  822. 'start':c.start,
  823. 'type': c.direction,
  824. 'numberA': c.src,
  825. 'numberB': c.dst,
  826. 'line': c.did,
  827. 'duration': c.duration,
  828. 'waiting': c.waiting,
  829. 'status':c.disposition,
  830. 'url': c.file }
  831. calls.append(_call)
  832. return successReply(calls)
  833. @app.route('/user/<user>/calls')
  834. class UserCalls(Resource):
  835. @app.param('user', 'User to query for call stats', 'path')
  836. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 and YYYYMMDDhhmmss', 'query')
  837. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 and YYYYMMDDhhmmss', 'query')
  838. @app.param('direction', 'Calls direction, in or out. If not specified both are returned', 'query')
  839. @app.param('limit', 'Max number of returned records, defaults to unlimited. Use offset parameter together with limit', 'query')
  840. @app.param('offset', 'If limit is specified use offset parameter to request more results', 'query')
  841. @app.param('order', 'Calls sort order for datetime field. ASC or DESC. Defaults to ASC', 'query')
  842. @app.response(HTTPStatus.OK, 'JSON data {"user":user,"state":state}')
  843. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  844. async def get(self, user):
  845. '''Returns user's call stats.
  846. '''
  847. if user not in app.cache['ustates']:
  848. return noUser(user)
  849. cdr = await getUserCDR(user,
  850. parseDatetime(request.args.get('start')),
  851. parseDatetime(request.args.get('end')),
  852. request.args.get('direction', None),
  853. request.args.get('limit', None),
  854. request.args.get('offset', None),
  855. request.args.get('order', 'ASC'))
  856. return successReply(cdr)
  857. manager.connect()
  858. app.run(loop=main_loop, host='0.0.0.0', port=app.config['PORT'])