app.py 65 KB

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