app.py 38 KB

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