app.py 41 KB

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