app.py 41 KB

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