app.py 73 KB

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