app.py 45 KB

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