app.py 72 KB

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