app.py 48 KB

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