app.py 71 KB

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