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