app.py 39 KB

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