app.py 41 KB

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