app.py 65 KB

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