app.py 38 KB

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