app.py 58 KB

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