app.py 67 KB

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