app.py 52 KB

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