app.py 59 KB

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