app.py 39 KB

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