app.py 63 KB

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