app.py 49 KB

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