app.py 74 KB

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