app.py 38 KB

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