app.py 55 KB

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