app.py 56 KB

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