app.py 52 KB

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