app.py 67 KB

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