app.py 73 KB

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