app.py 45 KB

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