app.py 70 KB

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