app.py 39 KB

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