app.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330
  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. 'calls':{},
  88. 'cel_queue_calls':{},
  89. 'cel_calls':{}}
  90. manager = Manager(
  91. loop=main_loop,
  92. host=app.config['AMI_HOST'],
  93. port=app.config['AMI_PORT'],
  94. username=app.config['AMI_USERNAME'],
  95. secret=app.config['AMI_SECRET'],
  96. ping_delay=app.config['AMI_PING_DELAY'],
  97. ping_interval=app.config['AMI_PING_INTERVAL'],
  98. reconnect_timeout=app.config['AMI_TIMEOUT'],
  99. )
  100. def authRequired(func):
  101. @wraps(func)
  102. async def authWrapper(*args, **kwargs):
  103. request.user = None
  104. request.device = None
  105. request.admin = False
  106. auth = request.authorization
  107. headers = request.headers
  108. if ((auth is not None) and
  109. (auth.type == "basic") and
  110. (auth.username in current_app.cache['devices']) and
  111. (compare_digest(auth.password, current_app.cache['devices'][auth.username]))):
  112. request.device = auth.username
  113. if request.device in current_app.cache['usermap']:
  114. request.user = current_app.cache['usermap'][request.device]
  115. return await func(*args, **kwargs)
  116. elif ((current_app.config['AUTH_HEADER'].lower() in headers) and
  117. (headers[current_app.config['AUTH_HEADER'].lower()] == current_app.config['AUTH_SECRET'])):
  118. request.admin = True
  119. return await func(*args, **kwargs)
  120. else:
  121. abort(401)
  122. return authWrapper
  123. db = PintDB(app)
  124. @manager.register_event('FullyBooted')
  125. @manager.register_event('Reload')
  126. async def reloadCallback(mngr: Manager, msg: Message):
  127. await refreshDevicesCache()
  128. await refreshStatesCache()
  129. await refreshQueuesCache()
  130. await rebindLostDevices()
  131. # await db.execute(query='CREATE TABLE IF NOT EXISTS callback_urls (device VARCHAR(16) PRIMARY KEY, url VARCHAR(255))')
  132. @manager.register_event('ExtensionStatus')
  133. async def extensionStatusCallback(mngr: Manager, msg: Message):
  134. user = msg.exten
  135. state = msg.statustext.lower()
  136. app.logger.warning('ExtensionStatus({}, {})'.format(user, state))
  137. if user in app.cache['ustates']:
  138. prevState = getUserStateCombined(user)
  139. app.cache['ustates'][user] = state
  140. combinedState = getUserStateCombined(user)
  141. if combinedState != prevState:
  142. await userStateChangeCallback(user, combinedState, prevState)
  143. @manager.register_event('PresenceStatus')
  144. async def presenceStatusCallback(mngr: Manager, msg: Message):
  145. user = msg.exten #hint = msg.hint
  146. state = msg.status.lower()
  147. if user in app.cache['ustates']:
  148. prevState = getUserStateCombined(user)
  149. app.cache['pstates'][user] = state
  150. combinedState = getUserStateCombined(user)
  151. if combinedState != prevState:
  152. await userStateChangeCallback(user, combinedState, prevState)
  153. @manager.register_event('Hangup')
  154. async def hangupCallback(mngr: Manager, msg: Message):
  155. if msg.uniqueid in app.cache['calls']:
  156. del app.cache['calls'][msg.uniqueid]
  157. @manager.register_event('Newchannel')
  158. async def newchannelCallback(mngr: Manager, msg: Message):
  159. if (msg.channelstate == '4') and ('HTTP_CLIENT' in app.config):
  160. did = None
  161. cid = None
  162. user = None
  163. device = None
  164. uid = None
  165. if msg.context in ('from-pstn'):
  166. app.cache['calls'][msg.uniqueid]=msg
  167. elif ((msg.context in ('from-queue')) and
  168. (msg.linkedid in app.cache['calls']) and
  169. (msg.exten in app.cache['devicemap'])):
  170. did = app.cache['calls'][msg.linkedid].exten
  171. cid = app.cache['calls'][msg.linkedid].calleridnum
  172. user = msg.exten
  173. device = app.cache['devicemap'][user]
  174. uid = msg.linkedid
  175. elif ((msg.context in ('from-internal')) and
  176. (msg.exten in app.cache['devicemap'])):
  177. user = msg.exten
  178. device = app.cache['devicemap'][user]
  179. if msg.calleridnum in app.cache['usermap']:
  180. cid = app.cache['usermap'][msg.calleridnum]
  181. else:
  182. cid = msg.calleridnum
  183. uid = msg.uniqueid
  184. if device is not None:
  185. _cb = {'user': user,
  186. 'device': device,
  187. 'state': 'ringing',
  188. 'callerId': cid,
  189. 'did': did,
  190. 'callId': uid}
  191. reply = await doCallback(device, _cb)
  192. @manager.register_event('CEL')
  193. async def celCallback(mngr: Manager, msg: Message):
  194. #app.logger.warning('CEL {}'.format(msg))
  195. lid = msg.LinkedID
  196. if ((msg.EventName == 'CHAN_START') and (lid == msg.UniqueID)): #save first msg
  197. app.cache['cel_calls'][lid] = msg
  198. app.cache['cel_calls'][lid]['channels'] = {}
  199. if (lid in app.cache['cel_calls']):
  200. firstMessage = app.cache['cel_calls'][lid]
  201. cid = firstMessage.CallerIDnum
  202. uid = firstMessage.LinkedID
  203. if (cid is not None) and (len(cid) < 7): #for local calls only
  204. if msg.Context in ('from-queue'):
  205. if ((msg.EventName == 'CHAN_START') or
  206. ((msg.EventName == 'CHAN_END') and ('answered' not in firstMessage))):
  207. if msg.EventName == 'CHAN_START': #start dial
  208. app.cache['cel_calls'][lid]['channels'][msg.Exten] = msg.Channel
  209. else: #end dial
  210. app.cache['cel_calls'][uid]['channels'].pop(msg.CallerIDname, False)
  211. app.logger.warning(f'''NEW CALLING LIST: {','.join(app.cache['cel_calls'][uid]['channels'].keys())}''')
  212. _cb = {'users': list(app.cache['cel_calls'][uid]['channels'].keys()),
  213. 'state': 'group_ringing',
  214. 'callId': uid}
  215. reply = await doCallback(cid, _cb)
  216. if ((msg.EventName == 'ANSWER') and
  217. (msg.Application == 'AppDial') and
  218. (lid in app.cache['cel_calls'])):
  219. called = msg.Exten
  220. app.cache['cel_calls'][lid]['answered'] = True
  221. app.logger.warning(f'''answered {called}''')
  222. _cb = {'user': called,
  223. 'state': 'group_answer',
  224. 'callId': uid}
  225. reply = await doCallback(cid, _cb)
  226. if ((msg.Application == 'Queue') and
  227. (msg.Exten in ('1','2200'))): #shouldn't be hardcoded!
  228. queue_changed=False
  229. if (msg.EventName == 'APP_START'):
  230. app.cache['cel_queue_calls'][lid] = {'caller': msg.CallerIDnum, 'start': msg.EventTime}
  231. queue_changed = True
  232. if (msg.EventName in ('APP_END', 'BRIDGE_ENTER')):
  233. call = app.cache['cel_queue_calls'].pop(lid,False)
  234. queue_changed = (call != None)
  235. app.logger.warning(f'''EVENT:{msg} changed:{queue_changed}''')
  236. if queue_changed :
  237. _cb = {'caller': msg.CallerIDnum,
  238. 'all': app.cache['cel_queue_calls'],
  239. 'callId': lid}
  240. if (msg.EventName == 'APP_START'):
  241. reply = await doCallback('queueEnter', _cb)
  242. else:
  243. reply = await doCallback('queueLeave', _cb)
  244. if (msg.EventName == 'LINKEDID_END'):
  245. app.cache['cel_calls'].pop(lid, False)
  246. app.cache['cel_queue_calls'].pop(lid, False)
  247. app.logger.warning(f'''Left Calls {','.join(app.cache['cel_calls'].keys())}''')
  248. if (msg.EventName == 'USER_DEFINED') and (msg.UserDefType == 'SETVARIABLE'):
  249. app.logger.warning(f'''SETVARIABLE({str(msg)})''')
  250. varname, value = msg.AppData.split(',')[1].split('=')[0:2]
  251. app.logger.warning(f'''SETVARIABLE({varname} is {value})''')
  252. app.cache['cel_calls'][msg.linkedid][varname]=value
  253. async def getCDR(start=None,
  254. end=None,
  255. table='cdr',
  256. field='calldate',
  257. sort='calldate, SUBSTR(uniqueid,1,10), sequence'):
  258. _cdr = {}
  259. if end is None:
  260. end = dt.now()
  261. if start is None:
  262. start=(end - td(hours=24))
  263. async for row in db.iterate(query='''SELECT *
  264. FROM {table}
  265. WHERE linkedid
  266. IN (SELECT DISTINCT(linkedid)
  267. FROM {table}
  268. WHERE {field}
  269. BETWEEN :start AND :end)
  270. ORDER BY {sort};'''.format(table=table,
  271. field=field,
  272. sort=sort),
  273. values={'start':start,
  274. 'end':end}):
  275. if row['linkedid'] in _cdr:
  276. _cdr[row['linkedid']].events.add(row)
  277. else:
  278. _cdr[row['linkedid']]=CdrCall(row)
  279. cdr = []
  280. for _id in sorted(_cdr.keys()):
  281. cdr.append(_cdr[_id])
  282. return cdr
  283. async def getUserCDR(user,
  284. start=None,
  285. end=None,
  286. direction=None,
  287. limit=None,
  288. offset=None,
  289. order='ASC'):
  290. _q = f'''SELECT * FROM cdr AS c INNER JOIN (SELECT linkedid FROM cdr WHERE'''
  291. if direction:
  292. direction=direction.lower()
  293. if direction in ('in', True, '1', 'incoming', 'inbound'):
  294. direction = 'inbound'
  295. _q += f''' dst="{user}"'''
  296. elif direction in ('out', False, '0', 'outgoing', 'outbound'):
  297. direction = 'outbound'
  298. _q += f''' src="{user}"'''
  299. else:
  300. direction = None
  301. _q += f''' (src="{user}" or dst="{user}")'''
  302. if end is None:
  303. end = dt.now()
  304. if start is None:
  305. start=(end - td(hours=24))
  306. _q += f''' AND calldate BETWEEN "{start}" AND "{end}" GROUP BY linkedid'''
  307. if None not in (limit, offset):
  308. _q += f''' LIMIT {offset},{limit}'''
  309. _q += f''') AS c2 ON c.linkedid = c2.linkedid;'''
  310. app.logger.warning('SQL: {}'.format(_q))
  311. _cdr = {}
  312. async for row in db.iterate(query=_q):
  313. if (row['disposition']=='FAILED' and row['lastapp']=='Queue'):
  314. continue
  315. if row['linkedid'] in _cdr:
  316. _cdr[row['linkedid']].events.add(row)
  317. else:
  318. _cdr[row['linkedid']]=CdrUserCall(user, row)
  319. cdr = []
  320. for _id in sorted(_cdr.keys(), reverse = True if (order.lower() == 'desc') else False):
  321. record = _cdr[_id].simple
  322. if (direction is not None) and (record['src'] == record['dst']) and (record['direction'] != direction):
  323. record['direction'] = direction
  324. if record['file'] is not None:
  325. record['file'] = '/static/records/{d.year}/{d.month:02}/{d.day:02}/{filename}'.format(d=record['start'],
  326. filename=record['file'])
  327. cdr.append(record)
  328. return cdr
  329. async def getCEL(start=None, end=None, table='cel', field='eventtime', sort='id'):
  330. return await getCDR(start, end, table, field, sort)
  331. async def doCallback(entity, msg):
  332. row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device', values={'device': entity})
  333. if (row is not None) and (row['url'].startswith('http')):
  334. app.logger.warning(f'''POST {row['url']} data: {str(msg)}''')
  335. if not 'HTTP_CLIENT' in app.config:
  336. await initHttpClient()
  337. reply = await app.config['HTTP_CLIENT'].post(row['url'], json=msg)
  338. return reply
  339. else:
  340. app.logger.warning('No callback url defined for {}'.format(entity))
  341. return None
  342. @app.before_first_request
  343. async def initHttpClient():
  344. app.config['HTTP_CLIENT'] = aiohttp.ClientSession(loop=main_loop)
  345. @app.route('/openapi.json')
  346. async def openapi():
  347. '''Generates JSON that conforms OpenAPI Specification
  348. '''
  349. schema = app.__schema__
  350. schema['servers'] = [{'url':'http://aster.rrt.ru:8000'},
  351. {'url':'{}://{}:{}'.format(app.config['SCHEME'],
  352. app.config['FQDN'],
  353. app.config['PORT'])}]
  354. if app.config['EXTRA_API_URL'] is not None:
  355. schema['servers'].append({'url':app.config['EXTRA_API_URL']})
  356. schema['components'] = {'securitySchemes':{'ApiKey':{'type': 'apiKey',
  357. 'name': app.config['AUTH_HEADER'],
  358. 'in': 'header'}}}
  359. schema['security'] = [{'ApiKey':[]}]
  360. return jsonify(schema)
  361. @app.route('/ui')
  362. async def ui():
  363. '''Swagger UI
  364. '''
  365. return await render_template_string(SWAGGER_TEMPLATE,
  366. title=app.config['TITLE'],
  367. js_url=app.config['SWAGGER_JS_URL'],
  368. css_url=app.config['SWAGGER_CSS_URL'])
  369. async def action():
  370. _payload = await request.get_data()
  371. reply = await manager.send_action(json.loads(_payload))
  372. return str(reply)
  373. async def amiGetVar(variable):
  374. '''AMI GetVar
  375. Returns value of requested variable using AMI action GetVar in background.
  376. Parameters:
  377. variable (string): Variable to query for
  378. Returns:
  379. string: Variable value or empty string if variable not found
  380. '''
  381. reply = await manager.send_action({'Action': 'GetVar',
  382. 'Variable': variable})
  383. app.logger.warning('GetVar({})->{}'.format(variable, reply.value))
  384. return reply.value
  385. @app.route('/ami/auths')
  386. @authRequired
  387. async def amiPJSIPShowAuths():
  388. if not request.admin:
  389. abort(401)
  390. return successReply(app.cache['devices'])
  391. @app.route('/blackhole', methods=['GET','POST'])
  392. async def blackhole():
  393. return ''
  394. @app.route('/ami/aors')
  395. @authRequired
  396. async def amiPJSIPShowAors():
  397. if not request.admin:
  398. abort(401)
  399. aors = {}
  400. reply = await manager.send_action({'Action':'PJSIPShowAors'})
  401. if len(reply) >= 2:
  402. for message in reply:
  403. if ((message.event == 'AorList') and
  404. ('objecttype' in message) and
  405. (message.objecttype == 'aor') and
  406. (int(message.maxcontacts) > 0)):
  407. aors[message.objectname] = message.contacts
  408. app.logger.warning('AorsList: {}'.format(','.join(aors.keys())))
  409. return successReply(aors)
  410. async def amiUserEvent(name, data):
  411. '''AMI UserEvent
  412. Generates AMI Event using AMI action UserEvent with name and data supplied.
  413. Parameters:
  414. name (string): UserEvent name
  415. data (dict): UserEvent data
  416. Returns:
  417. string: None if UserEvent was successfull, error message overwise
  418. '''
  419. reply = await manager.send_action({**{'Action': 'UserEvent',
  420. 'UserEvent': name},
  421. **data})
  422. app.logger.warning('UserEvent({})'.format(name))
  423. if isinstance(reply, Message):
  424. if reply.success:
  425. return None
  426. else:
  427. return reply.message
  428. return 'AMI error'
  429. async def amiSetVar(variable, value):
  430. '''AMI SetVar
  431. Sets variable using AMI action SetVar to value in background.
  432. Parameters:
  433. variable (string): Variable to set
  434. value (string): Value to set for variable
  435. Returns:
  436. string: None if SetVar was successfull, error message overwise
  437. '''
  438. reply = await manager.send_action({'Action': 'SetVar',
  439. 'Variable': variable,
  440. 'Value': value})
  441. app.logger.warning('SetVar({}, {})'.format(variable, value))
  442. if isinstance(reply, Message):
  443. if reply.success:
  444. return None
  445. else:
  446. return reply.message
  447. return 'AMI error'
  448. async def amiDBGet(family, key):
  449. '''AMI DBGet
  450. Returns value of requested astdb key using AMI action DBGet in background.
  451. Parameters:
  452. family (string): astdb key family to query for
  453. key (string): astdb key to query for
  454. Returns:
  455. string: Value or empty string if variable not found
  456. '''
  457. reply = await manager.send_action({'Action': 'DBGet',
  458. 'Family': family,
  459. 'Key': key})
  460. if (isinstance(reply, list) and
  461. (len(reply) > 1)):
  462. for message in reply:
  463. if (message.event == 'DBGetResponse'):
  464. app.logger.warning('DBGet(/{}/{})->{}'.format(family, key, message.val))
  465. return message.val
  466. app.logger.warning('DBGet(/{}/{})->Error!'.format(family, key))
  467. return None
  468. async def amiDBPut(family, key, value):
  469. '''AMI DBPut
  470. Writes value to astdb by family and key using AMI action DBPut in background.
  471. Parameters:
  472. family (string): astdb key family to write to
  473. key (string): astdb key to write to
  474. value (string): value to write
  475. Returns:
  476. boolean: True if DBPut action was successfull, False overwise
  477. '''
  478. reply = await manager.send_action({'Action': 'DBPut',
  479. 'Family': family,
  480. 'Key': key,
  481. 'Val': value})
  482. app.logger.warning('DBPut(/{}/{}, {})'.format(family, key, value))
  483. if (isinstance(reply, Message) and reply.success):
  484. return True
  485. return False
  486. async def amiDBDel(family, key):
  487. '''AMI DBDel
  488. Deletes key from family in astdb using AMI action DBDel in background.
  489. Parameters:
  490. family (string): astdb key family
  491. key (string): astdb key to delete
  492. Returns:
  493. boolean: True if DBDel action was successfull, False overwise
  494. '''
  495. reply = await manager.send_action({'Action': 'DBDel',
  496. 'Family': family,
  497. 'Key': key})
  498. app.logger.warning('DBDel(/{}/{})'.format(family, key))
  499. if (isinstance(reply, Message) and reply.success):
  500. return True
  501. return False
  502. async def amiSetHint(context, user, hint):
  503. '''AMI SetHint
  504. Sets hint for user in context using AMI action DialplanUserAdd with Replace=true in background.
  505. Parameters:
  506. context (string): dialplan context
  507. user (string): user
  508. hint (string): hint for user
  509. Returns:
  510. boolean: True if DialplanUserAdd action was successfull, False overwise
  511. '''
  512. reply = await manager.send_action({'Action': 'DialplanExtensionAdd',
  513. 'Context': context,
  514. 'Extension': user,
  515. 'Priority': 'hint',
  516. 'Application': hint,
  517. 'Replace': 'yes'})
  518. app.logger.warning('SetHint({},{},{})'.format(context, user, hint))
  519. if (isinstance(reply, Message) and reply.success):
  520. return True
  521. return False
  522. async def amiPresenceState(user):
  523. '''AMI PresenceState request for CustomPresence provider
  524. Parameters:
  525. user (string): user
  526. Returns:
  527. boolean, string: True and state or False and error message
  528. '''
  529. reply = await manager.send_action({'Action': 'PresenceState',
  530. 'Provider': 'CustomPresence:{}'.format(user)})
  531. app.logger.warning('PresenceState({})'.format(user))
  532. if isinstance(reply, Message):
  533. if reply.success:
  534. return True, reply.state
  535. else:
  536. return False, reply.message
  537. return False, 'AMI error'
  538. async def amiPresenceStateList():
  539. states = {}
  540. reply = await manager.send_action({'Action':'PresenceStateList'})
  541. if len(reply) >= 2:
  542. for message in reply:
  543. if message.event == 'PresenceStateChange':
  544. user = re.search('CustomPresence:(\d+)', message.presentity).group(1)
  545. states[user] = message.status
  546. app.logger.warning('PresenceStateList: {}'.format(','.join(states.keys())))
  547. return states
  548. async def amiExtensionStateList():
  549. states = {}
  550. reply = await manager.send_action({'Action':'ExtensionStateList'})
  551. if len(reply) >= 2:
  552. for message in reply:
  553. if ((message.event == 'ExtensionStatus') and
  554. (message.context == 'ext-local')):
  555. states[message.exten] = message.statustext.lower()
  556. app.logger.warning('ExtensionStateList: {}'.format(','.join(states.keys())))
  557. return states
  558. async def amiCommand(command):
  559. '''AMI Command
  560. Runs specified command using AMI action Command in background.
  561. Parameters:
  562. command (string): command to run
  563. Returns:
  564. boolean, list: tuple representing the boolean result of request and list of lines of command output
  565. '''
  566. reply = await manager.send_action({'Action': 'Command',
  567. 'Command': command})
  568. result = []
  569. if (isinstance(reply, Message) and reply.success):
  570. if isinstance(reply.output, list):
  571. result = reply.output
  572. else:
  573. result = reply.output.split('\n')
  574. app.logger.warning('Command({})->{}'.format(command, '\n'.join(result)))
  575. return True, result
  576. app.logger.warning('Command({})->Error!'.format(command))
  577. return False, result
  578. async def amiReload(module='core'):
  579. '''AMI Reload
  580. Reload specified asterisk module using AMI action reload in background.
  581. Parameters:
  582. module (string): module to reload, defaults to core
  583. Returns:
  584. boolean: True if Reload action was successfull, False overwise
  585. '''
  586. reply = await manager.send_action({'Action': 'Reload',
  587. 'Module': module})
  588. app.logger.warning('Reload({})'.format(module))
  589. if (isinstance(reply, Message) and reply.success):
  590. return True
  591. return False
  592. async def getGlobalVars():
  593. globalVars = GlobalVars()
  594. for _var in globalVars.d():
  595. setattr(globalVars, _var, await amiGetVar(_var))
  596. return globalVars
  597. async def setUserHint(user, dial, ast):
  598. if dial in NONEs:
  599. hint = 'CustomPresence:{}'.format(user)
  600. else:
  601. _dial= [dial]
  602. if (ast.DNDDEVSTATE == 'TRUE'):
  603. _dial.append('Custom:DND{}'.format(user))
  604. hint = '{},CustomPresence:{}'.format('&'.join(_dial), user)
  605. return await amiSetHint('ext-local', user, hint)
  606. async def amiQueues():
  607. queues = {}
  608. reply = await manager.send_action({'Action':'QueueStatus'})
  609. if len(reply) >= 2:
  610. for message in reply:
  611. if message.event == 'QueueMember':
  612. _qm = QueueMember(re.search('Local\/(\d+)', message.location).group(1))
  613. queues.setdefault(message.queue, []).append(_qm.fromMessage(message))
  614. app.logger.warning('QueuesList: {}'.format(','.join(queues.keys())))
  615. return queues
  616. async def amiDeviceChannel(device):
  617. reply = await manager.send_action({'Action':'CoreShowChannels'})
  618. if len(reply) >= 2:
  619. for message in reply:
  620. if message.event == 'CoreShowChannel':
  621. if message.calleridnum == device:
  622. return message.channel
  623. return None
  624. async def getUserChannel(user):
  625. device = await getUserDevice(user)
  626. if device in NONEs:
  627. return False
  628. channel = await amiDeviceChannel(device)
  629. if channel in NONEs:
  630. return False
  631. return channel
  632. async def setQueueStates(user, device, state):
  633. for queue in [_q for _q, _ma in app.cache['queues'].items() for _m in _ma if _m.user == user]:
  634. await amiSetVar('DEVICE_STATE(Custom:QUEUE{}*{})'.format(device, queue), state)
  635. async def getDeviceUser(device):
  636. return await amiDBGet('DEVICE', '{}/user'.format(device))
  637. async def getDeviceType(device):
  638. return await amiDBGet('DEVICE', '{}/type'.format(device))
  639. async def getDeviceDial(device):
  640. return await amiDBGet('DEVICE', '{}/dial'.format(device))
  641. async def getUserCID(user):
  642. return await amiDBGet('AMPUSER', '{}/cidnum'.format(user))
  643. async def setDeviceUser(device, user):
  644. return await amiDBPut('DEVICE', '{}/user'.format(device), user)
  645. async def getUserDevice(user):
  646. return await amiDBGet('AMPUSER', '{}/device'.format(user))
  647. async def setUserDevice(user, device):
  648. if device is None:
  649. return await amiDBDel('AMPUSER', '{}/device'.format(user))
  650. else:
  651. return await amiDBPut('AMPUSER', '{}/device'.format(user), device)
  652. async def unbindOtherDevices(user, newDevice, ast):
  653. '''Unbinds user from all devices except newDevice and sets
  654. all required device states.
  655. '''
  656. devices = await amiDBGet('AMPUSER', '{}/device'.format(user))
  657. if devices not in NONEs:
  658. for _device in sorted(set(devices.split('&')), key=int):
  659. if _device == user:
  660. continue
  661. if _device != newDevice:
  662. if ast.FMDEVSTATE == 'TRUE':
  663. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(_device), 'INVALID')
  664. if ast.QUEDEVSTATE == 'TRUE':
  665. await setQueueStates(user, _device, 'NOT_INUSE')
  666. if ast.DNDDEVSTATE:
  667. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(_device), 'NOT_INUSE')
  668. if ast.CFDEVSTATE:
  669. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(_device), 'NOT_INUSE')
  670. await amiDBPut('DEVICE', '{}/user'.format(_device), 'none')
  671. async def setUserDeviceStates(user, device, ast):
  672. if ast.FMDEVSTATE == 'TRUE':
  673. _followMe = await amiDBGet('AMPUSER', '{}/followme/ddial'.format(user))
  674. if _followMe is not None:
  675. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(device), followMe2DevState(_followMe))
  676. if ast.QUEDEVSTATE == 'TRUE':
  677. await setQueueStates(user, device, 'INUSE')
  678. if ast.DNDDEVSTATE:
  679. _dnd = await amiDBGet('DND', user)
  680. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(device), 'INUSE' if _dnd == 'YES' else 'NOT_INUSE')
  681. if ast.CFDEVSTATE:
  682. _cf = await amiDBGet('CF', user)
  683. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(device), 'INUSE' if _cf != '' else 'NOT_INUSE')
  684. async def refreshStatesCache():
  685. app.cache['ustates'] = await amiExtensionStateList()
  686. app.cache['pstates'] = await amiPresenceStateList()
  687. return len(app.cache['ustates'])
  688. async def refreshDevicesCache():
  689. auths = {}
  690. reply = await manager.send_action({'Action':'PJSIPShowAuths'})
  691. if len(reply) >= 2:
  692. for message in reply:
  693. if ((message.event == 'AuthList') and
  694. ('objecttype' in message) and
  695. (message.objecttype == 'auth')):
  696. auths[message.username] = message.password
  697. app.cache['devices'] = auths
  698. return len(app.cache['devices'])
  699. async def refreshQueuesCache():
  700. app.cache['queues'] = await amiQueues()
  701. return len(app.cache['queues'])
  702. async def rebindLostDevices():
  703. app.cache['usermap'] = {}
  704. app.cache['devicemap'] = {}
  705. ast = await getGlobalVars()
  706. for device in app.cache['devices']:
  707. user = await getDeviceUser(device)
  708. deviceType = await getDeviceType(device)
  709. if (deviceType != 'fixed') and (user != 'none') and (user in app.cache['ustates'].keys()):
  710. _device = await getUserDevice(user)
  711. if _device != device:
  712. app.logger.warning('Fixing bind user {} to device {}'.format(user, device))
  713. dial = await getDeviceDial(device)
  714. await setUserHint(user, dial, ast) # Set hints for user on new device
  715. await setUserDeviceStates(user, device, ast) # Set device states for users device
  716. await setUserDevice(user, device) # Bind device to user
  717. app.cache['usermap'][device] = user
  718. if user != 'none':
  719. app.cache['devicemap'][user] = device
  720. async def userStateChangeCallback(user, state, prevState = None):
  721. reply = None
  722. if ('HTTP_CLIENT' in app.config) and (user in app.cache['devicemap']):
  723. row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
  724. values={'device': app.cache['devicemap'][user]})
  725. if row is not None:
  726. reply = await app.config['HTTP_CLIENT'].post(row['url'],
  727. json={'user': user,
  728. 'state': state,
  729. 'prev_state':prevState})
  730. app.logger.warning('{} changed state to: {}'.format(user, state))
  731. return reply
  732. def getUserStateCombined(user):
  733. _uCache = app.cache['ustates']
  734. _pCache = app.cache['pstates']
  735. return combinedStates[_uCache.get(user, 'unavailable')][_pCache.get(user, 'not_set')]
  736. def getUsersStatesCombined():
  737. return {user:getUserStateCombined(user) for user in app.cache['ustates']}
  738. @app.route('/atxfer/<userA>/<userB>')
  739. class AtXfer(Resource):
  740. @authRequired
  741. @app.param('userA', 'User initiating the attended transfer', 'path')
  742. @app.param('userB', 'Transfer destination user', 'path')
  743. @app.response(HTTPStatus.OK, 'Json reply')
  744. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  745. async def get(self, userA, userB):
  746. '''Attended call transfer
  747. '''
  748. if (userA != request.user) and (not request.admin):
  749. abort(401)
  750. channel = await getUserChannel(userA)
  751. if not channel:
  752. return noUserChannel(userA)
  753. reply = await manager.send_action({'Action':'Atxfer',
  754. 'Channel':channel,
  755. 'async':'false',
  756. 'Exten':userB})
  757. if isinstance(reply, Message):
  758. if reply.success:
  759. return successfullyTransfered(userA, userB)
  760. else:
  761. return errorReply(reply.message)
  762. @app.route('/bxfer/<userA>/<userB>')
  763. class BXfer(Resource):
  764. @authRequired
  765. @app.param('userA', 'User initiating the blind transfer', 'path')
  766. @app.param('userB', 'Transfer destination user', 'path')
  767. @app.response(HTTPStatus.OK, 'Json reply')
  768. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  769. async def get(self, userA, userB):
  770. '''Blind call transfer
  771. '''
  772. if (userA != request.user) and (not request.admin):
  773. abort(401)
  774. channel = await getUserChannel(userA)
  775. if not channel:
  776. return noUserChannel(userA)
  777. reply = await manager.send_action({'Action':'BlindTransfer',
  778. 'Channel':channel,
  779. 'async':'false',
  780. 'Exten':userB})
  781. if isinstance(reply, Message):
  782. if reply.success:
  783. return successfullyTransfered(userA, userB)
  784. else:
  785. return errorReply(reply.message)
  786. @app.route('/originate/<user>/<number>')
  787. class Originate(Resource):
  788. @authRequired
  789. @app.param('user', 'User initiating the call', 'path')
  790. @app.param('number', 'Destination number', 'path')
  791. @app.response(HTTPStatus.OK, 'Json reply')
  792. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  793. async def get(self, user, number):
  794. '''Originate call
  795. '''
  796. if (user != request.user) and (not request.admin):
  797. abort(401)
  798. device = await getUserDevice(user)
  799. if device in NONEs:
  800. return noUserDevice(user)
  801. device = device.replace('{}&'.format(user), '')
  802. _act = { 'Action':'Originate',
  803. 'Channel':'PJSIP/{}'.format(device),
  804. 'Context':'from-internal',
  805. 'Exten':number,
  806. 'Priority': '1',
  807. 'async':'false',
  808. 'Callerid': '{} <{}>'.format(user, user)}
  809. app.logger.warning(_act)
  810. reply = await manager.send_action(_act)
  811. if isinstance(reply, Message):
  812. if reply.success:
  813. return successfullyOriginated(user, number)
  814. else:
  815. return errorReply(reply.message)
  816. @app.route('/hangup/<user>')
  817. class Hangup(Resource):
  818. @authRequired
  819. @app.param('user', 'User to hangup', 'path')
  820. @app.response(HTTPStatus.OK, 'Json reply')
  821. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  822. async def get(self, user):
  823. '''Call hangup
  824. '''
  825. if (user != request.user) and (not request.admin):
  826. abort(401)
  827. channel = await getUserChannel(user)
  828. if not channel:
  829. return noUserChannel(user)
  830. reply = await manager.send_action({'Action':'Hangup',
  831. 'Channel':channel})
  832. if isinstance(reply, Message):
  833. if reply.success:
  834. return successfullyHungup(user)
  835. else:
  836. return errorReply(reply.message)
  837. @app.route('/users/states')
  838. class UsersStates(Resource):
  839. @authRequired
  840. @app.response(HTTPStatus.OK, 'JSON reply with user:state map or error message')
  841. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  842. async def get(self):
  843. '''Returns all users with their combined states.
  844. Possible states are: available, away, dnd, inuse, busy, unavailable, ringing
  845. '''
  846. if not request.admin:
  847. abort(401)
  848. #app.logger.warning('request device: {}'.format(request.device))
  849. #usersCount = await refreshStatesCache()
  850. #if usersCount == 0:
  851. # return stateCacheEmpty()
  852. return successReply(getUsersStatesCombined())
  853. @app.route('/users/states/<users_list>')
  854. class UsersStatesSelected(Resource):
  855. @authRequired
  856. @app.param('users_list', 'Comma separated list of users to query for combined states', 'path')
  857. @app.response(HTTPStatus.OK, 'JSON reply with user:state map or error message')
  858. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  859. async def get(self, users_list):
  860. '''Returns selected users with their combined states.
  861. Possible states are: available, away, dnd, inuse, busy, unavailable, ringing
  862. '''
  863. if not request.admin:
  864. abort(401)
  865. users = users_list.split(',')
  866. states = getUsersStatesCombined()
  867. result={}
  868. for user in states:
  869. if user in users:
  870. result[user] = states[user]
  871. return successReply(result)
  872. @app.route('/user/<user>/state')
  873. class UserState(Resource):
  874. @authRequired
  875. @app.param('user', 'User to query for combined state', 'path')
  876. @app.response(HTTPStatus.OK, 'JSON data {"user":user,"state":state}')
  877. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  878. async def get(self, user):
  879. '''Returns user's combined state.
  880. One of: available, away, dnd, inuse, busy, unavailable, ringing
  881. '''
  882. if (user != request.user) and (not request.admin):
  883. abort(401)
  884. if user not in app.cache['ustates']:
  885. return noUser(user)
  886. return successReply({'user':user,'state':getUserStateCombined(user)})
  887. @app.route('/user/<user>/presence')
  888. class PresenceState(Resource):
  889. @authRequired
  890. @app.param('user', 'User to query for presence state', 'path')
  891. @app.response(HTTPStatus.OK, 'JSON data {"user":user,"state":state}')
  892. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  893. async def get(self, user):
  894. '''Returns user's presence state.
  895. One of: not_set, unavailable, available, away, xa, chat, dnd
  896. '''
  897. if (user != request.user) and (not request.admin):
  898. abort(401)
  899. if user not in app.cache['ustates']:
  900. return noUser(user)
  901. return successReply({'user':user,'state':app.cache['pstates'].get(user, 'not_set')})
  902. @app.route('/user/<user>/presence/<state>')
  903. class SetPresenceState(Resource):
  904. @authRequired
  905. @app.param('user', 'Target user to set the presence state', 'path')
  906. @app.param('state',
  907. 'The presence state for user, one of: not_set, unavailable, available, away, xa, chat or dnd',
  908. 'path')
  909. @app.response(HTTPStatus.OK, 'Json reply')
  910. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  911. async def get(self, user, state):
  912. '''Sets user's presence state.
  913. Allowed states: not_set | unavailable | available | away | xa | chat | dnd
  914. '''
  915. if (user != request.user) and (not request.admin):
  916. abort(401)
  917. if state not in presenceStates:
  918. return invalidState(state)
  919. if user not in app.cache['ustates']:
  920. return noUser(user)
  921. # app.logger.warning('state={}, getUserStateCombined({})={}'.format(state, user, getUserStateCombined(user)))
  922. if (state.lower() in ('available','away','not_set','xa','chat')) and (getUserStateCombined(user) in ('dnd')):
  923. result = await amiDBDel('DND', '{}'.format(user))
  924. result = await amiSetVar('PRESENCE_STATE(CustomPresence:{})'.format(user), state)
  925. if result is not None:
  926. return errorReply(result)
  927. if state.lower() in ('dnd'):
  928. result = await amiDBPut('DND', '{}'.format(user), 'YES')
  929. return successfullySetState(user, state)
  930. @app.route('/users/devices')
  931. class UsersDevices(Resource):
  932. @authRequired
  933. @app.response(HTTPStatus.OK, 'JSON reply with user:device map or error message')
  934. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  935. async def get(self):
  936. '''Returns users to device maping.
  937. '''
  938. if not request.admin:
  939. abort(401)
  940. data = {}
  941. for user in app.cache['ustates']:
  942. device = await getUserDevice(user)
  943. if ((device in NONEs) or (device == user)):
  944. device = None
  945. else:
  946. device = device.replace('{}&'.format(user), '')
  947. data[user]= device
  948. return successReply(data)
  949. @app.route('/device/<device>/<user>/on')
  950. @app.route('/user/<user>/<device>/on')
  951. class UserDeviceBind(Resource):
  952. @authRequired
  953. @app.param('device', 'Device number to bind to', 'path')
  954. @app.param('user', 'User to bind to device', 'path')
  955. @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
  956. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  957. async def get(self, device, user):
  958. '''Binds user to device.
  959. Both user and device numbers are checked for existance.
  960. Any device user was previously bound to, is unbound.
  961. Any user previously bound to device is unbound also.
  962. '''
  963. if (device != request.device) and (not request.admin):
  964. abort(401)
  965. if user not in app.cache['ustates']:
  966. return noUser(user)
  967. dial = await getDeviceDial(device) # Check if device exists in astdb
  968. if dial is None:
  969. return noDevice(device)
  970. currentUser = await getDeviceUser(device) # Check if any user is already bound to device
  971. if currentUser == user:
  972. return alreadyBound(user, device)
  973. ast = await getGlobalVars()
  974. if currentUser not in NONEs: # If any other user is bound to device, unbind him,
  975. result = await amiSetVar('PRESENCE_STATE(CustomPresence:{})'.format(user), 'available')
  976. result = await amiDBDel('DND', '{}'.format(user))
  977. await setUserDevice(currentUser, None)
  978. if ast.QUEDEVSTATE == 'TRUE': # set device states for previous user queues
  979. await setQueueStates(currentUser, device, 'NOT_INUSE')
  980. await setUserHint(currentUser, None, ast) # set hints for previous user
  981. await setDeviceUser(device, user) # Bind user to device
  982. # If user is bound to some other devices, unbind him and set
  983. # device states for those devices
  984. await unbindOtherDevices(user, device, ast)
  985. if not (await setUserHint(user, dial, ast)): # Set hints for user on new device
  986. return hintError(user, device)
  987. await setUserDeviceStates(user, device, ast) # Set device states for users new device
  988. if not (await setUserDevice(user, device)): # Bind device to user
  989. return bindError(user, device)
  990. app.cache['usermap'][device] = user
  991. app.cache['devicemap'][user] = device
  992. await amiUserEvent('DeviceBound',{'device': device, 'newUser': user, 'oldUser': currentUser})
  993. return successfullyBound(user, device)
  994. @app.route('/device/<device>/off')
  995. class DeviceUnBind(Resource):
  996. @authRequired
  997. @app.param('device', 'Device number to unbind', 'path')
  998. @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
  999. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1000. async def get(self, device):
  1001. '''Unbinds any user from device.
  1002. Device is checked for existance.
  1003. '''
  1004. if (device != request.device) and (not request.admin):
  1005. abort(401)
  1006. dial = await getDeviceDial(device) # Check if device exists in astdb
  1007. if dial is None:
  1008. return noDevice(device)
  1009. currentUser = await getDeviceUser(device) # Check if any user is bound to device
  1010. if currentUser in NONEs:
  1011. return noUserBound(device)
  1012. else:
  1013. result = await amiSetVar('PRESENCE_STATE(CustomPresence:{})'.format(currentUser), 'available')
  1014. result = await amiDBDel('DND', '{}'.format(currentUser))
  1015. ast = await getGlobalVars()
  1016. await setUserDevice(currentUser, None) # Unbind device from current user
  1017. if ast.QUEDEVSTATE == 'TRUE': # set device states for current user queues
  1018. await setQueueStates(currentUser, device, 'NOT_INUSE')
  1019. await setUserHint(currentUser, None, ast) # set hints for current user
  1020. await setDeviceUser(device, 'none') # Unbind user from device
  1021. del app.cache['usermap'][device]
  1022. del app.cache['devicemap'][currentUser]
  1023. await amiUserEvent('DeviceUnbound',{'device': device, 'oldUser': currentUser})
  1024. return successfullyUnbound(currentUser, device)
  1025. @app.route('/cdr')
  1026. class CDR(Resource):
  1027. @authRequired
  1028. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  1029. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  1030. @app.response(HTTPStatus.OK, 'JSON reply')
  1031. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1032. async def get(self):
  1033. '''Returns CDR data, groupped by logical call id.
  1034. All request arguments are optional.
  1035. '''
  1036. if not request.admin:
  1037. abort(401)
  1038. start = parseDatetime(request.args.get('start'))
  1039. end = parseDatetime(request.args.get('end'))
  1040. cdr = await getCDR(start, end)
  1041. return successReply(cdr)
  1042. @app.route('/cel')
  1043. class CEL(Resource):
  1044. @authRequired
  1045. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  1046. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  1047. @app.response(HTTPStatus.OK, 'JSON reply')
  1048. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1049. async def get(self):
  1050. '''Returns CEL data, groupped by logical call id.
  1051. All request arguments are optional.
  1052. '''
  1053. if not request.admin:
  1054. abort(401)
  1055. start = parseDatetime(request.args.get('start'))
  1056. end = parseDatetime(request.args.get('end'))
  1057. cel = await getCEL(start, end)
  1058. return successReply(cel)
  1059. @app.route('/calls')
  1060. class Calls(Resource):
  1061. @authRequired
  1062. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 and YYYYMMDDhhmmss', 'query')
  1063. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 and YYYYMMDDhhmmss', 'query')
  1064. @app.response(HTTPStatus.OK, 'JSON reply')
  1065. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1066. async def get(self):
  1067. '''Returns aggregated call data JSON. Draft implementation.
  1068. All request arguments are optional.
  1069. '''
  1070. if not request.admin:
  1071. abort(401)
  1072. calls = []
  1073. start = parseDatetime(request.args.get('start'))
  1074. end = parseDatetime(request.args.get('end'))
  1075. cdr = await getCDR(start, end)
  1076. for c in cdr:
  1077. _call = {'id':c.linkedid,
  1078. 'start':c.start,
  1079. 'type': c.direction,
  1080. 'numberA': c.src,
  1081. 'numberB': c.dst,
  1082. 'line': c.did,
  1083. 'duration': c.duration,
  1084. 'waiting': c.waiting,
  1085. 'status':c.disposition,
  1086. 'url': c.file }
  1087. calls.append(_call)
  1088. return successReply(calls)
  1089. @app.route('/user/<user>/calls')
  1090. class UserCalls(Resource):
  1091. @authRequired
  1092. @app.param('user', 'User to query for call stats', 'path')
  1093. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 and YYYYMMDDhhmmss', 'query')
  1094. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 and YYYYMMDDhhmmss', 'query')
  1095. @app.param('direction', 'Calls direction, in or out. If not specified both are returned', 'query')
  1096. @app.param('limit', 'Max number of returned records, defaults to unlimited. Use offset parameter together with limit', 'query')
  1097. @app.param('offset', 'If limit is specified use offset parameter to request more results', 'query')
  1098. @app.param('order', 'Calls sort order for datetime field. ASC or DESC. Defaults to ASC', 'query')
  1099. @app.response(HTTPStatus.OK, 'JSON data {"status":status,"data":data,"message":message}')
  1100. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1101. async def get(self, user):
  1102. '''Returns user's call stats.
  1103. '''
  1104. if (user != request.user) and (not request.admin):
  1105. abort(401)
  1106. if user not in app.cache['ustates']:
  1107. return noUser(user)
  1108. cdr = await getUserCDR(user,
  1109. parseDatetime(request.args.get('start')),
  1110. parseDatetime(request.args.get('end')),
  1111. request.args.get('direction', None),
  1112. request.args.get('limit', None),
  1113. request.args.get('offset', None),
  1114. request.args.get('order', 'ASC'))
  1115. return successReply(cdr)
  1116. @app.route('/device/<device>/callback')
  1117. class DeviceCallback(Resource):
  1118. @authRequired
  1119. @app.param('device', 'Device to get/set the callback url for', 'path')
  1120. @app.param('url', 'used to set the Callback url for the device', 'query')
  1121. @app.response(HTTPStatus.OK, 'JSON data {"user":user,"state":state}')
  1122. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1123. async def get(self, device):
  1124. '''Returns and sets device's callback url.
  1125. '''
  1126. if (device != request.device) and (not request.admin):
  1127. abort(401)
  1128. url = request.args.get('url', None)
  1129. if url is not None:
  1130. await db.execute(query='REPLACE INTO callback_urls (device, url) VALUES (:device, :url)',
  1131. values={'device': device,'url': url})
  1132. else:
  1133. row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
  1134. values={'device': device})
  1135. if row is not None:
  1136. url = row['url']
  1137. return successCallbackURL(device, url)
  1138. @app.route('/group/ringing/callback')
  1139. class GroupRingingCallback(Resource):
  1140. @authRequired
  1141. @app.param('url', 'used to set the Callback url for the group ringing callback', 'query')
  1142. @app.response(HTTPStatus.OK, 'JSON data {"url":url}')
  1143. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1144. async def get(self):
  1145. '''Returns and sets groupRinging callback url.
  1146. '''
  1147. if not request.admin:
  1148. abort(401)
  1149. url = request.args.get('url', None)
  1150. if url is not None:
  1151. await db.execute(query='REPLACE INTO callback_urls (device, url) VALUES (:device, :url)',
  1152. values={'device': 'groupRinging','url': url})
  1153. else:
  1154. row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
  1155. values={'device': 'groupRinging'})
  1156. if row is not None:
  1157. url = row['url']
  1158. return successCommonCallbackURL('groupRinging', url)
  1159. @app.route('/group/answered/callback')
  1160. class GroupAnsweredCallback(Resource):
  1161. @authRequired
  1162. @app.param('url', 'used to set the Callback url for the group answered callback', 'query')
  1163. @app.response(HTTPStatus.OK, 'JSON data {"url":url}')
  1164. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1165. async def get(self):
  1166. '''Returns and sets groupAnswered callback url.
  1167. '''
  1168. if not request.admin:
  1169. abort(401)
  1170. url = request.args.get('url', None)
  1171. if url is not None:
  1172. await db.execute(query='REPLACE INTO callback_urls (device, url) VALUES (:device, :url)',
  1173. values={'device': 'groupAnswered','url': url})
  1174. else:
  1175. row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
  1176. values={'device': 'groupAnswered'})
  1177. if row is not None:
  1178. url = row['url']
  1179. return successCommonCallbackURL('groupAnswered', url)
  1180. @app.route('/queue/enter/callback')
  1181. class QueueEnterCallback(Resource):
  1182. @authRequired
  1183. @app.param('url', 'used to set the Callback url for the queue enter callback', 'query')
  1184. @app.response(HTTPStatus.OK, 'JSON data {"url":url}')
  1185. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1186. async def get(self):
  1187. '''Returns and sets queueEnter callback url.
  1188. '''
  1189. if not request.admin:
  1190. abort(401)
  1191. url = request.args.get('url', None)
  1192. if url is not None:
  1193. await db.execute(query='REPLACE INTO callback_urls (device, url) VALUES (:device, :url)',
  1194. values={'device': 'queueEnter','url': url})
  1195. else:
  1196. row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
  1197. values={'device': 'queueEnter'})
  1198. if row is not None:
  1199. url = row['url']
  1200. return successCommonCallbackURL('queueEnter', url)
  1201. @app.route('/queue/leave/callback')
  1202. class QueueLeaveCallback(Resource):
  1203. @authRequired
  1204. @app.param('url', 'used to set the Callback url for the queue leave callback', 'query')
  1205. @app.response(HTTPStatus.OK, 'JSON data {"url":url}')
  1206. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1207. async def get(self):
  1208. '''Returns and sets queueLeave callback url.
  1209. '''
  1210. if not request.admin:
  1211. abort(401)
  1212. url = request.args.get('url', None)
  1213. if url is not None:
  1214. await db.execute(query='REPLACE INTO callback_urls (device, url) VALUES (:device, :url)',
  1215. values={'device': 'queueLeave','url': url})
  1216. else:
  1217. row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
  1218. values={'device': 'queueLeave'})
  1219. if row is not None:
  1220. url = row['url']
  1221. return successCommonCallbackURL('queueLeave', url)
  1222. manager.connect()
  1223. app.run(loop=main_loop, host='0.0.0.0', port=app.config['PORT'])