app.py 39 KB

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