app.py 64 KB

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