app.py 53 KB

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