app.py 39 KB

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