app.py 56 KB

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