app.py 65 KB

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