app.py 52 KB

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