app.py 52 KB

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