app.py 55 KB

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