app.py 76 KB

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