app.py 53 KB

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