app.py 75 KB

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