app.py 65 KB

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