app.py 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335
  1. #!/usr/bin/env python3
  2. import asyncio
  3. import logging
  4. import os
  5. import re
  6. import json
  7. from datetime import datetime as dt
  8. from datetime import timedelta as td
  9. from typing import Any, Optional
  10. from functools import wraps
  11. from secrets import compare_digest
  12. from databases import Database
  13. from quart import jsonify, request, render_template_string, abort, current_app
  14. from quart.json import JSONEncoder
  15. from quart_openapi import Pint, Resource
  16. from http import HTTPStatus
  17. from panoramisk import Manager, Message
  18. from utils import *
  19. from cel import *
  20. from logging.config import dictConfig
  21. from pprint import pformat
  22. from inspect import getmembers
  23. class ApiJsonEncoder(JSONEncoder):
  24. def default(self, o):
  25. if isinstance(o, dt):
  26. return o.isoformat()
  27. if isinstance(o, CdrChannel):
  28. return str(o)
  29. if isinstance(o, CdrEvent):
  30. return o.__dict__
  31. if isinstance(o, CdrEvents) or isinstance(o, CelEvents):
  32. return o.all
  33. if isinstance(o, CdrCall) or isinstance(o, CelCall):
  34. return o.__dict__
  35. return JSONEncoder.default(self, o)
  36. class PintDB:
  37. def __init__(self, app: Optional[Pint] = None) -> None:
  38. self.init_app(app)
  39. self._db = Database(app.config["DB_URI"])
  40. def init_app(self, app: Pint) -> None:
  41. app.before_serving(self._before_serving)
  42. app.after_serving(self._after_serving)
  43. async def _before_serving(self) -> None:
  44. await self._db.connect()
  45. async def _after_serving(self) -> None:
  46. await self._db.disconnect()
  47. def __getattr__(self, name: str) -> Any:
  48. return getattr(self._db, name)
  49. # One asyncio event loop is used for AMI communication and HTTP requests routing with Quart
  50. main_loop = asyncio.get_event_loop()
  51. app = Pint(__name__, title=os.getenv('APP_TITLE', 'PBX API'), no_openapi=True)
  52. app.json_encoder = ApiJsonEncoder
  53. app.config.update({
  54. 'TITLE': os.getenv('APP_TITLE', 'PBX API'),
  55. 'APPLICATION_ROOT': os.getenv('APP_APPLICATION_ROOT', None),
  56. 'SCHEME': os.getenv('APP_SCHEME', 'http'),
  57. 'FQDN': os.getenv('APP_FQDN', '127.0.0.1'),
  58. 'PORT': int(os.getenv('APP_API_PORT', 8000)),
  59. 'BODY_TIMEOUT': int(os.getenv('APP_BODY_TIMEOUT', 60)),
  60. 'DEBUG': os.getenv('APP_DEBUG', 'False').lower() in TRUEs,
  61. 'MAX_CONTENT_LENGTH': int(os.getenv('APP_MAX_CONTENT_LENGTH', 16777216)),
  62. 'AMI_HOST': os.getenv('APP_AMI_HOST', '127.0.0.1'),
  63. 'AMI_PORT': int(os.getenv('APP_AMI_PORT', 5038)),
  64. 'AMI_USERNAME': os.getenv('APP_AMI_USERNAME', 'app'),
  65. 'AMI_SECRET': os.getenv('APP_AMI_SECRET', 'secret'),
  66. 'AMI_PING_DELAY': int(os.getenv('APP_AMI_PING_DELAY', 10)),
  67. 'AMI_PING_INTERVAL': int(os.getenv('APP_AMI_PING_INTERVAL', 10)),
  68. 'AMI_TIMEOUT': int(os.getenv('APP_AMI_TIMEOUT', 5)),
  69. 'AUTH_HEADER': os.getenv('APP_AUTH_HEADER', 'APP-auth-token'),
  70. 'AUTH_SECRET': os.getenv('APP_AUTH_SECRET', '3bfbeaabf363dd64fe263bd36830a6b6'),
  71. 'SWAGGER_JS_URL': os.getenv('APP_SWAGGER_JS_URL', SWAGGER_JS_URL),
  72. 'SWAGGER_CSS_URL': os.getenv('APP_SWAGGER_CSS_URL', SWAGGER_CSS_URL),
  73. 'STATE_CALLBACK_URL': os.getenv('APP_STATE_CALLBACK_URL', None),
  74. 'DB_URI': 'mysql://{}:{}@{}:{}/{}'.format(os.getenv('MYSQL_USER', 'asterisk'),
  75. os.getenv('MYSQL_PASSWORD', 'secret'),
  76. os.getenv('MYSQL_SERVER', 'db'),
  77. os.getenv('APP_PORT_MYSQL', '3306'),
  78. os.getenv('FREEPBX_CDRDBNAME', None)),
  79. 'EXTRA_API_URL': os.getenv('APP_EXTRA_API_URL', None)})
  80. app.cache = {'devices':{},
  81. 'usermap':{},
  82. 'devicemap':{},
  83. 'ustates':{},
  84. 'pstates':{},
  85. 'queues':{},
  86. 'calls':{},
  87. 'cel_queue_calls':{},
  88. 'cel_calls':{}}
  89. manager = Manager(
  90. loop=main_loop,
  91. host=app.config['AMI_HOST'],
  92. port=app.config['AMI_PORT'],
  93. username=app.config['AMI_USERNAME'],
  94. secret=app.config['AMI_SECRET'],
  95. ping_delay=app.config['AMI_PING_DELAY'],
  96. ping_interval=app.config['AMI_PING_INTERVAL'],
  97. reconnect_timeout=app.config['AMI_TIMEOUT'],
  98. )
  99. def authRequired(func):
  100. @wraps(func)
  101. async def authWrapper(*args, **kwargs):
  102. request.user = None
  103. request.device = None
  104. request.admin = False
  105. auth = request.authorization
  106. headers = request.headers
  107. if ((auth is not None) and
  108. (auth.type == "basic") and
  109. (auth.username in current_app.cache['devices']) and
  110. (compare_digest(auth.password, current_app.cache['devices'][auth.username]))):
  111. request.device = auth.username
  112. if request.device in current_app.cache['usermap']:
  113. request.user = current_app.cache['usermap'][request.device]
  114. return await func(*args, **kwargs)
  115. elif ((current_app.config['AUTH_HEADER'].lower() in headers) and
  116. (headers[current_app.config['AUTH_HEADER'].lower()] == current_app.config['AUTH_SECRET'])):
  117. request.admin = True
  118. return await func(*args, **kwargs)
  119. else:
  120. abort(401)
  121. return authWrapper
  122. db = PintDB(app)
  123. @manager.register_event('FullyBooted')
  124. @manager.register_event('Reload')
  125. async def reloadCallback(mngr: Manager, msg: Message):
  126. await refreshDevicesCache()
  127. await refreshStatesCache()
  128. await refreshQueuesCache()
  129. await rebindLostDevices()
  130. # await db.execute(query='CREATE TABLE IF NOT EXISTS callback_urls (device VARCHAR(16) PRIMARY KEY, url VARCHAR(255))')
  131. @manager.register_event('ExtensionStatus')
  132. async def extensionStatusCallback(mngr: Manager, msg: Message):
  133. user = msg.exten
  134. state = msg.statustext.lower()
  135. app.logger.warning('ExtensionStatus({}, {})'.format(user, state))
  136. if user in app.cache['ustates']:
  137. prevState = getUserStateCombined(user)
  138. app.cache['ustates'][user] = state
  139. combinedState = getUserStateCombined(user)
  140. if combinedState != prevState:
  141. await userStateChangeCallback(user, combinedState, prevState)
  142. @manager.register_event('PresenceStatus')
  143. async def presenceStatusCallback(mngr: Manager, msg: Message):
  144. user = msg.exten #hint = msg.hint
  145. state = msg.status.lower()
  146. if user in app.cache['ustates']:
  147. prevState = getUserStateCombined(user)
  148. app.cache['pstates'][user] = state
  149. combinedState = getUserStateCombined(user)
  150. if combinedState != prevState:
  151. await userStateChangeCallback(user, combinedState, prevState)
  152. @manager.register_event('Hangup')
  153. async def hangupCallback(mngr: Manager, msg: Message):
  154. if msg.uniqueid in app.cache['calls']:
  155. del app.cache['calls'][msg.uniqueid]
  156. @manager.register_event('Newchannel')
  157. async def newchannelCallback(mngr: Manager, msg: Message):
  158. if (msg.channelstate == '4'):
  159. did = None
  160. cid = None
  161. user = None
  162. device = None
  163. uid = None
  164. if msg.context in ('from-pstn'):
  165. app.cache['calls'][msg.uniqueid]=msg
  166. elif ((msg.context in ('from-queue')) and
  167. (msg.linkedid in app.cache['calls']) and
  168. (msg.exten in app.cache['devicemap'])):
  169. did = app.cache['calls'][msg.linkedid].exten
  170. cid = app.cache['calls'][msg.linkedid].calleridnum
  171. user = msg.exten
  172. device = app.cache['devicemap'][user]
  173. uid = msg.linkedid
  174. elif ((msg.context in ('from-internal')) and
  175. (msg.exten in app.cache['devicemap'])):
  176. user = msg.exten
  177. device = app.cache['devicemap'][user]
  178. if msg.calleridnum in app.cache['usermap']:
  179. cid = app.cache['usermap'][msg.calleridnum]
  180. else:
  181. cid = msg.calleridnum
  182. uid = msg.uniqueid
  183. if device is not None:
  184. _cb = {'user': user,
  185. 'device': device,
  186. 'state': 'ringing',
  187. 'callerId': cid,
  188. 'did': did,
  189. 'callId': uid}
  190. if ('WebCallId' in app.cache['calls'][msg.linkedid]):
  191. _cb['WebCallId'] = app.cache['calls'][msg.linkedid]['WebCallId']
  192. reply = await doCallback(device, _cb)
  193. @manager.register_event('CEL')
  194. async def celCallback(mngr: Manager, msg: Message):
  195. app.logger.warning('CEL {}'.format(msg))
  196. lid = msg.LinkedID
  197. if ((msg.EventName == 'CHAN_START') and (lid == msg.UniqueID)): #save first msg
  198. app.cache['cel_calls'][lid] = msg
  199. app.cache['cel_calls'][lid]['current_channels'] = {}
  200. app.cache['cel_calls'][lid]['all_channels'] = {}
  201. if (lid in app.cache['cel_calls']):
  202. firstMessage = app.cache['cel_calls'][lid]
  203. cid = firstMessage.CallerIDnum
  204. if firstMessage.CallerIDnum in app.cache['usermap']:
  205. cid = app.cache['usermap'][firstMessage.CallerIDnum]
  206. uid = firstMessage.LinkedID
  207. if ((msg.Application == 'Queue') and
  208. (msg.EventName == 'APP_START') and
  209. (firstMessage.Context == 'from-internal')):
  210. app.cache['cel_calls'][lid]['groupCall'] = True
  211. if ((msg.Application == 'Queue') and
  212. (msg.EventName == 'APP_END') and
  213. (firstMessage.Context == 'from-internal')):
  214. app.cache['cel_calls'][lid]['groupCall'] = False
  215. if (cid is not None) and (len(cid) < 7): #for local calls only
  216. if msg.Context in ('from-queue'):
  217. if ((msg.EventName == 'CHAN_START') or
  218. ((msg.EventName == 'CHAN_END') and ('answered' not in firstMessage))):
  219. old_count = len(app.cache['cel_calls'][lid]['current_channels'])
  220. channel = msg.Channel.split(';')[0]
  221. if msg.EventName == 'CHAN_START': #start dial
  222. app.cache['cel_calls'][lid]['current_channels'][channel] = msg.Exten
  223. app.cache['cel_calls'][lid]['all_channels'][channel] = msg.Exten
  224. else: #end dial
  225. app.cache['cel_calls'][uid]['current_channels'].pop(channel, False)
  226. if old_count != len(app.cache['cel_calls'][lid]['current_channels']):
  227. _cb = {'users': list(app.cache['cel_calls'][uid]['current_channels'].values()),
  228. 'state': 'group_ringing',
  229. 'callerId': cid,
  230. 'callId': uid}
  231. if ('WebCallId' in app.cache['cel_calls'][msg.linkedid]):
  232. _cb['WebCallId'] = app.cache['cel_calls'][msg.linkedid]['WebCallId']
  233. reply = await doCallback('groupRinging', _cb)
  234. if ((msg.EventName == 'ANSWER') and
  235. (msg.Application == 'AppDial') and
  236. firstMessage.get('groupCall',False) and
  237. (lid in app.cache['cel_calls'])):
  238. called = msg.Exten
  239. app.cache['cel_calls'][lid]['answered'] = True
  240. _cb = {'user': called,
  241. 'users': list(app.cache['cel_calls'][uid]['all_channels'].keys()),
  242. 'state': 'group_answer',
  243. 'callerId': cid,
  244. 'callId': uid}
  245. if ('WebCallId' in app.cache['cel_calls'][msg.linkedid]):
  246. _cb['WebCallId'] = app.cache['cel_calls'][msg.linkedid]['WebCallId']
  247. reply = await doCallback('groupAnswered', _cb)
  248. if ((msg.Application == 'Queue') and
  249. (firstMessage.Context == 'from-pstn')):
  250. if (msg.EventName == 'APP_START'):
  251. app.cache['cel_queue_calls'][lid] = {'caller': msg.CallerIDnum, 'start': parseDatetime(msg.EventTime).isoformat()}
  252. _cb = {'callid': lid,
  253. 'caller': msg.CallerIDnum,
  254. 'start': parseDatetime(msg.EventTime).isoformat(),
  255. 'callerfrom': firstMessage.Exten,
  256. 'queue': msg.Exten,
  257. 'agents': [q.user for q in app.cache['queues'][msg.Exten]]}
  258. reply = await doCallback('queueEnter', _cb)
  259. if (msg.EventName in ('APP_END', 'BRIDGE_ENTER')):
  260. call = app.cache['cel_queue_calls'].pop(lid,False)
  261. queue_changed = (call != None)
  262. if queue_changed :
  263. _cb = {'callid': lid,
  264. 'queue': msg.Exten,
  265. 'agents': [q.user for q in app.cache['queues'][msg.Exten]]}
  266. reply = await doCallback('queueLeave', _cb)
  267. if (msg.EventName == 'LINKEDID_END'):
  268. app.cache['cel_calls'].pop(lid, False)
  269. app.cache['cel_queue_calls'].pop(lid, False)
  270. if (msg.EventName == 'USER_DEFINED') and (msg.UserDefType == 'SETVARIABLE'):
  271. varname, value = msg.AppData.split(',')[1].split('=')[0:2]
  272. app.cache['cel_calls'][lid][varname]=value
  273. if (lid in app.cache['calls']):
  274. app.cache['calls'][lid][varname]=value
  275. async def getCDR(start=None,
  276. end=None,
  277. table='cdr',
  278. field='calldate',
  279. sort='calldate, SUBSTR(uniqueid,1,10), sequence'):
  280. _cdr = {}
  281. if end is None:
  282. end = dt.now()
  283. if start is None:
  284. start=(end - td(hours=24))
  285. async for row in db.iterate(query='''SELECT *
  286. FROM {table}
  287. WHERE linkedid
  288. IN (SELECT DISTINCT(linkedid)
  289. FROM {table}
  290. WHERE {field}
  291. BETWEEN :start AND :end)
  292. ORDER BY {sort};'''.format(table=table,
  293. field=field,
  294. sort=sort),
  295. values={'start':start,
  296. 'end':end}):
  297. if row['linkedid'] in _cdr:
  298. _cdr[row['linkedid']].events.add(row)
  299. else:
  300. _cdr[row['linkedid']]=CdrCall(row)
  301. cdr = []
  302. for _id in sorted(_cdr.keys()):
  303. cdr.append(_cdr[_id])
  304. return cdr
  305. async def getUserCDR(user,
  306. start=None,
  307. end=None,
  308. direction=None,
  309. limit=None,
  310. offset=None,
  311. order='ASC'):
  312. _q = f'''SELECT * FROM cdr AS c INNER JOIN (SELECT linkedid FROM cdr WHERE'''
  313. if direction:
  314. direction=direction.lower()
  315. if direction in ('in', True, '1', 'incoming', 'inbound'):
  316. direction = 'inbound'
  317. _q += f''' dst="{user}"'''
  318. elif direction in ('out', False, '0', 'outgoing', 'outbound'):
  319. direction = 'outbound'
  320. _q += f''' src="{user}"'''
  321. else:
  322. direction = None
  323. _q += f''' (src="{user}" or dst="{user}")'''
  324. if end is None:
  325. end = dt.now()
  326. if start is None:
  327. start=(end - td(hours=24))
  328. _q += f''' AND calldate BETWEEN "{start}" AND "{end}" GROUP BY linkedid'''
  329. if None not in (limit, offset):
  330. _q += f''' LIMIT {offset},{limit}'''
  331. _q += f''') AS c2 ON c.linkedid = c2.linkedid;'''
  332. app.logger.warning('SQL: {}'.format(_q))
  333. _cdr = {}
  334. async for row in db.iterate(query=_q):
  335. if (row['disposition']=='FAILED' and row['lastapp']=='Queue'):
  336. continue
  337. if row['linkedid'] in _cdr:
  338. _cdr[row['linkedid']].events.add(row)
  339. else:
  340. _cdr[row['linkedid']]=CdrUserCall(user, row)
  341. cdr = []
  342. for _id in sorted(_cdr.keys(), reverse = True if (order.lower() == 'desc') else False):
  343. record = _cdr[_id].simple
  344. if (direction is not None) and (record['src'] == record['dst']) and (record['direction'] != direction):
  345. record['direction'] = direction
  346. if record['file'] is not None:
  347. record['file'] = '/static/records/{d.year}/{d.month:02}/{d.day:02}/{filename}'.format(d=record['start'],
  348. filename=record['file'])
  349. cdr.append(record)
  350. return cdr
  351. async def getCEL(start=None, end=None, table='cel', field='eventtime', sort='id'):
  352. return await getCDR(start, end, table, field, sort)
  353. async def doCallback(entity, msg):
  354. row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device', values={'device': entity})
  355. if (row is not None) and (row['url'].startswith('http')):
  356. app.logger.warning(f'''POST {row['url']} data: {str(msg)}''')
  357. else:
  358. app.logger.warning('No callback url defined for {}'.format(entity))
  359. return None
  360. @app.route('/openapi.json')
  361. async def openapi():
  362. '''Generates JSON that conforms OpenAPI Specification
  363. '''
  364. schema = app.__schema__
  365. schema['servers'] = [{'url':'http://aster.rrt.ru:8000'},
  366. {'url':'{}://{}:{}'.format(app.config['SCHEME'],
  367. app.config['FQDN'],
  368. app.config['PORT'])}]
  369. if app.config['EXTRA_API_URL'] is not None:
  370. schema['servers'].append({'url':app.config['EXTRA_API_URL']})
  371. schema['components'] = {'securitySchemes':{'ApiKey':{'type': 'apiKey',
  372. 'name': app.config['AUTH_HEADER'],
  373. 'in': 'header'}}}
  374. schema['security'] = [{'ApiKey':[]}]
  375. return jsonify(schema)
  376. @app.route('/ui')
  377. async def ui():
  378. '''Swagger UI
  379. '''
  380. return await render_template_string(SWAGGER_TEMPLATE,
  381. title=app.config['TITLE'],
  382. js_url=app.config['SWAGGER_JS_URL'],
  383. css_url=app.config['SWAGGER_CSS_URL'])
  384. async def action():
  385. _payload = await request.get_data()
  386. reply = await manager.send_action(json.loads(_payload))
  387. return str(reply)
  388. async def amiGetVar(variable):
  389. '''AMI GetVar
  390. Returns value of requested variable using AMI action GetVar in background.
  391. Parameters:
  392. variable (string): Variable to query for
  393. Returns:
  394. string: Variable value or empty string if variable not found
  395. '''
  396. reply = await manager.send_action({'Action': 'GetVar',
  397. 'Variable': variable})
  398. app.logger.warning('GetVar({})->{}'.format(variable, reply.value))
  399. return reply.value
  400. @app.route('/ami/auths')
  401. @authRequired
  402. async def amiPJSIPShowAuths():
  403. if not request.admin:
  404. abort(401)
  405. return successReply(app.cache['devices'])
  406. @app.route('/blackhole', methods=['GET','POST'])
  407. async def blackhole():
  408. return ''
  409. @app.route('/ami/aors')
  410. @authRequired
  411. async def amiPJSIPShowAors():
  412. if not request.admin:
  413. abort(401)
  414. aors = {}
  415. reply = await manager.send_action({'Action':'PJSIPShowAors'})
  416. if len(reply) >= 2:
  417. for message in reply:
  418. if ((message.event == 'AorList') and
  419. ('objecttype' in message) and
  420. (message.objecttype == 'aor') and
  421. (int(message.maxcontacts) > 0)):
  422. aors[message.objectname] = message.contacts
  423. app.logger.warning('AorsList: {}'.format(','.join(aors.keys())))
  424. return successReply(aors)
  425. async def amiUserEvent(name, data):
  426. '''AMI UserEvent
  427. Generates AMI Event using AMI action UserEvent with name and data supplied.
  428. Parameters:
  429. name (string): UserEvent name
  430. data (dict): UserEvent data
  431. Returns:
  432. string: None if UserEvent was successfull, error message overwise
  433. '''
  434. reply = await manager.send_action({**{'Action': 'UserEvent',
  435. 'UserEvent': name},
  436. **data})
  437. app.logger.warning('UserEvent({})'.format(name))
  438. if isinstance(reply, Message):
  439. if reply.success:
  440. return None
  441. else:
  442. return reply.message
  443. return 'AMI error'
  444. async def amiSetVar(variable, value):
  445. '''AMI SetVar
  446. Sets variable using AMI action SetVar to value in background.
  447. Parameters:
  448. variable (string): Variable to set
  449. value (string): Value to set for variable
  450. Returns:
  451. string: None if SetVar was successfull, error message overwise
  452. '''
  453. reply = await manager.send_action({'Action': 'SetVar',
  454. 'Variable': variable,
  455. 'Value': value})
  456. app.logger.warning('SetVar({}, {})'.format(variable, value))
  457. if isinstance(reply, Message):
  458. if reply.success:
  459. return None
  460. else:
  461. return reply.message
  462. return 'AMI error'
  463. async def amiDBGet(family, key):
  464. '''AMI DBGet
  465. Returns value of requested astdb key using AMI action DBGet in background.
  466. Parameters:
  467. family (string): astdb key family to query for
  468. key (string): astdb key to query for
  469. Returns:
  470. string: Value or empty string if variable not found
  471. '''
  472. reply = await manager.send_action({'Action': 'DBGet',
  473. 'Family': family,
  474. 'Key': key})
  475. if (isinstance(reply, list) and
  476. (len(reply) > 1)):
  477. for message in reply:
  478. if (message.event == 'DBGetResponse'):
  479. app.logger.warning('DBGet(/{}/{})->{}'.format(family, key, message.val))
  480. return message.val
  481. app.logger.warning('DBGet(/{}/{})->Error!'.format(family, key))
  482. return None
  483. async def amiDBPut(family, key, value):
  484. '''AMI DBPut
  485. Writes value to astdb by family and key using AMI action DBPut in background.
  486. Parameters:
  487. family (string): astdb key family to write to
  488. key (string): astdb key to write to
  489. value (string): value to write
  490. Returns:
  491. boolean: True if DBPut action was successfull, False overwise
  492. '''
  493. reply = await manager.send_action({'Action': 'DBPut',
  494. 'Family': family,
  495. 'Key': key,
  496. 'Val': value})
  497. app.logger.warning('DBPut(/{}/{}, {})'.format(family, key, value))
  498. if (isinstance(reply, Message) and reply.success):
  499. return True
  500. return False
  501. async def amiDBDel(family, key):
  502. '''AMI DBDel
  503. Deletes key from family in astdb using AMI action DBDel in background.
  504. Parameters:
  505. family (string): astdb key family
  506. key (string): astdb key to delete
  507. Returns:
  508. boolean: True if DBDel action was successfull, False overwise
  509. '''
  510. reply = await manager.send_action({'Action': 'DBDel',
  511. 'Family': family,
  512. 'Key': key})
  513. app.logger.warning('DBDel(/{}/{})'.format(family, key))
  514. if (isinstance(reply, Message) and reply.success):
  515. return True
  516. return False
  517. async def amiSetHint(context, user, hint):
  518. '''AMI SetHint
  519. Sets hint for user in context using AMI action DialplanUserAdd with Replace=true in background.
  520. Parameters:
  521. context (string): dialplan context
  522. user (string): user
  523. hint (string): hint for user
  524. Returns:
  525. boolean: True if DialplanUserAdd action was successfull, False overwise
  526. '''
  527. reply = await manager.send_action({'Action': 'DialplanExtensionAdd',
  528. 'Context': context,
  529. 'Extension': user,
  530. 'Priority': 'hint',
  531. 'Application': hint,
  532. 'Replace': 'yes'})
  533. app.logger.warning('SetHint({},{},{})'.format(context, user, hint))
  534. if (isinstance(reply, Message) and reply.success):
  535. return True
  536. return False
  537. async def amiPresenceState(user):
  538. '''AMI PresenceState request for CustomPresence provider
  539. Parameters:
  540. user (string): user
  541. Returns:
  542. boolean, string: True and state or False and error message
  543. '''
  544. reply = await manager.send_action({'Action': 'PresenceState',
  545. 'Provider': 'CustomPresence:{}'.format(user)})
  546. app.logger.warning('PresenceState({})'.format(user))
  547. if isinstance(reply, Message):
  548. if reply.success:
  549. return True, reply.state
  550. else:
  551. return False, reply.message
  552. return False, 'AMI error'
  553. async def amiPresenceStateList():
  554. states = {}
  555. reply = await manager.send_action({'Action':'PresenceStateList'})
  556. if len(reply) >= 2:
  557. for message in reply:
  558. if message.event == 'PresenceStateChange':
  559. user = re.search('CustomPresence:(\d+)', message.presentity).group(1)
  560. states[user] = message.status
  561. app.logger.warning('PresenceStateList: {}'.format(','.join(states.keys())))
  562. return states
  563. async def amiExtensionStateList():
  564. states = {}
  565. reply = await manager.send_action({'Action':'ExtensionStateList'})
  566. if len(reply) >= 2:
  567. for message in reply:
  568. if ((message.event == 'ExtensionStatus') and
  569. (message.context == 'ext-local')):
  570. states[message.exten] = message.statustext.lower()
  571. app.logger.warning('ExtensionStateList: {}'.format(','.join(states.keys())))
  572. return states
  573. async def amiCommand(command):
  574. '''AMI Command
  575. Runs specified command using AMI action Command in background.
  576. Parameters:
  577. command (string): command to run
  578. Returns:
  579. boolean, list: tuple representing the boolean result of request and list of lines of command output
  580. '''
  581. reply = await manager.send_action({'Action': 'Command',
  582. 'Command': command})
  583. result = []
  584. if (isinstance(reply, Message) and reply.success):
  585. if isinstance(reply.output, list):
  586. result = reply.output
  587. else:
  588. result = reply.output.split('\n')
  589. app.logger.warning('Command({})->{}'.format(command, '\n'.join(result)))
  590. return True, result
  591. app.logger.warning('Command({})->Error!'.format(command))
  592. return False, result
  593. async def amiReload(module='core'):
  594. '''AMI Reload
  595. Reload specified asterisk module using AMI action reload in background.
  596. Parameters:
  597. module (string): module to reload, defaults to core
  598. Returns:
  599. boolean: True if Reload action was successfull, False overwise
  600. '''
  601. reply = await manager.send_action({'Action': 'Reload',
  602. 'Module': module})
  603. app.logger.warning('Reload({})'.format(module))
  604. if (isinstance(reply, Message) and reply.success):
  605. return True
  606. return False
  607. async def getGlobalVars():
  608. globalVars = GlobalVars()
  609. for _var in globalVars.d():
  610. setattr(globalVars, _var, await amiGetVar(_var))
  611. return globalVars
  612. async def setUserHint(user, dial, ast):
  613. if dial in NONEs:
  614. hint = 'CustomPresence:{}'.format(user)
  615. else:
  616. _dial= [dial]
  617. if (ast.DNDDEVSTATE == 'TRUE'):
  618. _dial.append('Custom:DND{}'.format(user))
  619. hint = '{},CustomPresence:{}'.format('&'.join(_dial), user)
  620. return await amiSetHint('ext-local', user, hint)
  621. async def amiQueues():
  622. queues = {}
  623. reply = await manager.send_action({'Action':'QueueStatus'})
  624. if len(reply) >= 2:
  625. for message in reply:
  626. if message.event == 'QueueMember':
  627. _qm = QueueMember(re.search('Local\/(\d+)', message.location).group(1))
  628. queues.setdefault(message.queue, []).append(_qm.fromMessage(message))
  629. app.logger.warning('QueuesList: {}'.format(','.join(queues.keys())))
  630. return queues
  631. async def amiDeviceChannel(device):
  632. reply = await manager.send_action({'Action':'CoreShowChannels'})
  633. if len(reply) >= 2:
  634. for message in reply:
  635. if message.event == 'CoreShowChannel':
  636. if message.calleridnum == device:
  637. return message.channel
  638. return None
  639. async def getUserChannel(user):
  640. device = await getUserDevice(user)
  641. if device in NONEs:
  642. return False
  643. channel = await amiDeviceChannel(device)
  644. if channel in NONEs:
  645. return False
  646. return channel
  647. async def setQueueStates(user, device, state):
  648. for queue in [_q for _q, _ma in app.cache['queues'].items() for _m in _ma if _m.user == user]:
  649. await amiSetVar('DEVICE_STATE(Custom:QUEUE{}*{})'.format(device, queue), state)
  650. async def getDeviceUser(device):
  651. return await amiDBGet('DEVICE', '{}/user'.format(device))
  652. async def getDeviceType(device):
  653. return await amiDBGet('DEVICE', '{}/type'.format(device))
  654. async def getDeviceDial(device):
  655. return await amiDBGet('DEVICE', '{}/dial'.format(device))
  656. async def getUserCID(user):
  657. return await amiDBGet('AMPUSER', '{}/cidnum'.format(user))
  658. async def setDeviceUser(device, user):
  659. return await amiDBPut('DEVICE', '{}/user'.format(device), user)
  660. async def getUserDevice(user):
  661. return await amiDBGet('AMPUSER', '{}/device'.format(user))
  662. async def setUserDevice(user, device):
  663. if device is None:
  664. return await amiDBDel('AMPUSER', '{}/device'.format(user))
  665. else:
  666. return await amiDBPut('AMPUSER', '{}/device'.format(user), device)
  667. async def unbindOtherDevices(user, newDevice, ast):
  668. '''Unbinds user from all devices except newDevice and sets
  669. all required device states.
  670. '''
  671. devices = await amiDBGet('AMPUSER', '{}/device'.format(user))
  672. if devices not in NONEs:
  673. for _device in sorted(set(devices.split('&')), key=int):
  674. if _device == user:
  675. continue
  676. if _device != newDevice:
  677. if ast.FMDEVSTATE == 'TRUE':
  678. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(_device), 'INVALID')
  679. if ast.QUEDEVSTATE == 'TRUE':
  680. await setQueueStates(user, _device, 'NOT_INUSE')
  681. if ast.DNDDEVSTATE:
  682. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(_device), 'NOT_INUSE')
  683. if ast.CFDEVSTATE:
  684. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(_device), 'NOT_INUSE')
  685. await amiDBPut('DEVICE', '{}/user'.format(_device), 'none')
  686. async def setUserDeviceStates(user, device, ast):
  687. if ast.FMDEVSTATE == 'TRUE':
  688. _followMe = await amiDBGet('AMPUSER', '{}/followme/ddial'.format(user))
  689. if _followMe is not None:
  690. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(device), followMe2DevState(_followMe))
  691. if ast.QUEDEVSTATE == 'TRUE':
  692. await setQueueStates(user, device, 'INUSE')
  693. if ast.DNDDEVSTATE:
  694. _dnd = await amiDBGet('DND', user)
  695. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(device), 'INUSE' if _dnd == 'YES' else 'NOT_INUSE')
  696. if ast.CFDEVSTATE:
  697. _cf = await amiDBGet('CF', user)
  698. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(device), 'INUSE' if _cf != '' else 'NOT_INUSE')
  699. async def refreshStatesCache():
  700. app.cache['ustates'] = await amiExtensionStateList()
  701. app.cache['pstates'] = await amiPresenceStateList()
  702. return len(app.cache['ustates'])
  703. async def refreshDevicesCache():
  704. auths = {}
  705. reply = await manager.send_action({'Action':'PJSIPShowAuths'})
  706. if len(reply) >= 2:
  707. for message in reply:
  708. if ((message.event == 'AuthList') and
  709. ('objecttype' in message) and
  710. (message.objecttype == 'auth')):
  711. auths[message.username] = message.password
  712. app.cache['devices'] = auths
  713. return len(app.cache['devices'])
  714. async def refreshQueuesCache():
  715. app.cache['queues'] = await amiQueues()
  716. return len(app.cache['queues'])
  717. async def rebindLostDevices():
  718. app.cache['usermap'] = {}
  719. app.cache['devicemap'] = {}
  720. ast = await getGlobalVars()
  721. for device in app.cache['devices']:
  722. user = await getDeviceUser(device)
  723. deviceType = await getDeviceType(device)
  724. if (deviceType != 'fixed') and (user != 'none') and (user in app.cache['ustates'].keys()):
  725. _device = await getUserDevice(user)
  726. if _device != device:
  727. app.logger.warning('Fixing bind user {} to device {}'.format(user, device))
  728. dial = await getDeviceDial(device)
  729. await setUserHint(user, dial, ast) # Set hints for user on new device
  730. await setUserDeviceStates(user, device, ast) # Set device states for users device
  731. await setUserDevice(user, device) # Bind device to user
  732. app.cache['usermap'][device] = user
  733. if user != 'none':
  734. app.cache['devicemap'][user] = device
  735. async def userStateChangeCallback(user, state, prevState = None):
  736. app.logger.warning('{} changed state to: {}'.format(user, state))
  737. return ''
  738. def getUserStateCombined(user):
  739. _uCache = app.cache['ustates']
  740. _pCache = app.cache['pstates']
  741. return combinedStates[_uCache.get(user, 'unavailable')][_pCache.get(user, 'not_set')]
  742. def getUsersStatesCombined():
  743. return {user:getUserStateCombined(user) for user in app.cache['ustates']}
  744. @app.route('/atxfer/<userA>/<userB>')
  745. class AtXfer(Resource):
  746. @authRequired
  747. @app.param('userA', 'User initiating the attended transfer', 'path')
  748. @app.param('userB', 'Transfer destination user', 'path')
  749. @app.response(HTTPStatus.OK, 'Json reply')
  750. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  751. async def get(self, userA, userB):
  752. '''Attended call transfer
  753. '''
  754. if (userA != request.user) and (not request.admin):
  755. abort(401)
  756. channel = await getUserChannel(userA)
  757. if not channel:
  758. return noUserChannel(userA)
  759. reply = await manager.send_action({'Action':'Atxfer',
  760. 'Channel':channel,
  761. 'async':'false',
  762. 'Exten':userB})
  763. if isinstance(reply, Message):
  764. if reply.success:
  765. return successfullyTransfered(userA, userB)
  766. else:
  767. return errorReply(reply.message)
  768. @app.route('/bxfer/<userA>/<userB>')
  769. class BXfer(Resource):
  770. @authRequired
  771. @app.param('userA', 'User initiating the blind transfer', 'path')
  772. @app.param('userB', 'Transfer destination user', 'path')
  773. @app.response(HTTPStatus.OK, 'Json reply')
  774. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  775. async def get(self, userA, userB):
  776. '''Blind call transfer
  777. '''
  778. if (userA != request.user) and (not request.admin):
  779. abort(401)
  780. channel = await getUserChannel(userA)
  781. if not channel:
  782. return noUserChannel(userA)
  783. reply = await manager.send_action({'Action':'BlindTransfer',
  784. 'Channel':channel,
  785. 'async':'false',
  786. 'Exten':userB})
  787. if isinstance(reply, Message):
  788. if reply.success:
  789. return successfullyTransfered(userA, userB)
  790. else:
  791. return errorReply(reply.message)
  792. @app.route('/originate/<user>/<number>')
  793. class Originate(Resource):
  794. @authRequired
  795. @app.param('user', 'User initiating the call', 'path')
  796. @app.param('number', 'Destination number', 'path')
  797. @app.response(HTTPStatus.OK, 'Json reply')
  798. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  799. async def get(self, user, number):
  800. '''Originate call
  801. '''
  802. if (user != request.user) and (not request.admin):
  803. abort(401)
  804. device = await getUserDevice(user)
  805. if device in NONEs:
  806. return noUserDevice(user)
  807. device = device.replace('{}&'.format(user), '')
  808. _act = { 'Action':'Originate',
  809. 'Channel':'PJSIP/{}'.format(device),
  810. 'Context':'from-internal',
  811. 'Exten':number,
  812. 'Priority': '1',
  813. 'async':'false',
  814. 'Callerid': '{} <{}>'.format(user, user)}
  815. app.logger.warning(_act)
  816. reply = await manager.send_action(_act)
  817. if isinstance(reply, Message):
  818. if reply.success:
  819. return successfullyOriginated(user, number)
  820. else:
  821. return errorReply(reply.message)
  822. @app.route('/hangup/<user>')
  823. class Hangup(Resource):
  824. @authRequired
  825. @app.param('user', 'User to hangup', 'path')
  826. @app.response(HTTPStatus.OK, 'Json reply')
  827. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  828. async def get(self, user):
  829. '''Call hangup
  830. '''
  831. if (user != request.user) and (not request.admin):
  832. abort(401)
  833. channel = await getUserChannel(user)
  834. if not channel:
  835. return noUserChannel(user)
  836. reply = await manager.send_action({'Action':'Hangup',
  837. 'Channel':channel})
  838. if isinstance(reply, Message):
  839. if reply.success:
  840. return successfullyHungup(user)
  841. else:
  842. return errorReply(reply.message)
  843. @app.route('/users/states')
  844. class UsersStates(Resource):
  845. @authRequired
  846. @app.response(HTTPStatus.OK, 'JSON reply with user:state map or error message')
  847. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  848. async def get(self):
  849. '''Returns all users with their combined states.
  850. Possible states are: available, away, dnd, inuse, busy, unavailable, ringing
  851. '''
  852. if not request.admin:
  853. abort(401)
  854. #app.logger.warning('request device: {}'.format(request.device))
  855. #usersCount = await refreshStatesCache()
  856. #if usersCount == 0:
  857. # return stateCacheEmpty()
  858. return successReply(getUsersStatesCombined())
  859. @app.route('/users/states/<users_list>')
  860. class UsersStatesSelected(Resource):
  861. @authRequired
  862. @app.param('users_list', 'Comma separated list of users to query for combined states', 'path')
  863. @app.response(HTTPStatus.OK, 'JSON reply with user:state map or error message')
  864. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  865. async def get(self, users_list):
  866. '''Returns selected users with their combined states.
  867. Possible states are: available, away, dnd, inuse, busy, unavailable, ringing
  868. '''
  869. if not request.admin:
  870. abort(401)
  871. users = users_list.split(',')
  872. states = getUsersStatesCombined()
  873. result={}
  874. for user in states:
  875. if user in users:
  876. result[user] = states[user]
  877. return successReply(result)
  878. @app.route('/user/<user>/state')
  879. class UserState(Resource):
  880. @authRequired
  881. @app.param('user', 'User to query for combined state', 'path')
  882. @app.response(HTTPStatus.OK, 'JSON data {"user":user,"state":state}')
  883. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  884. async def get(self, user):
  885. '''Returns user's combined state.
  886. One of: available, away, dnd, inuse, busy, unavailable, ringing
  887. '''
  888. if (user != request.user) and (not request.admin):
  889. abort(401)
  890. if user not in app.cache['ustates']:
  891. return noUser(user)
  892. return successReply({'user':user,'state':getUserStateCombined(user)})
  893. @app.route('/user/<user>/presence')
  894. class PresenceState(Resource):
  895. @authRequired
  896. @app.param('user', 'User to query for presence state', 'path')
  897. @app.response(HTTPStatus.OK, 'JSON data {"user":user,"state":state}')
  898. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  899. async def get(self, user):
  900. '''Returns user's presence state.
  901. One of: not_set, unavailable, available, away, xa, chat, dnd
  902. '''
  903. if (user != request.user) and (not request.admin):
  904. abort(401)
  905. if user not in app.cache['ustates']:
  906. return noUser(user)
  907. return successReply({'user':user,'state':app.cache['pstates'].get(user, 'not_set')})
  908. @app.route('/user/<user>/presence/<state>')
  909. class SetPresenceState(Resource):
  910. @authRequired
  911. @app.param('user', 'Target user to set the presence state', 'path')
  912. @app.param('state',
  913. 'The presence state for user, one of: not_set, unavailable, available, away, xa, chat or dnd',
  914. 'path')
  915. @app.response(HTTPStatus.OK, 'Json reply')
  916. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  917. async def get(self, user, state):
  918. '''Sets user's presence state.
  919. Allowed states: not_set | unavailable | available | away | xa | chat | dnd
  920. '''
  921. if (user != request.user) and (not request.admin):
  922. abort(401)
  923. if state not in presenceStates:
  924. return invalidState(state)
  925. if user not in app.cache['ustates']:
  926. return noUser(user)
  927. # app.logger.warning('state={}, getUserStateCombined({})={}'.format(state, user, getUserStateCombined(user)))
  928. if (state.lower() in ('available','away','not_set','xa','chat')) and (getUserStateCombined(user) in ('dnd')):
  929. result = await amiDBDel('DND', '{}'.format(user))
  930. result = await amiSetVar('PRESENCE_STATE(CustomPresence:{})'.format(user), state)
  931. if result is not None:
  932. return errorReply(result)
  933. if state.lower() in ('dnd'):
  934. result = await amiDBPut('DND', '{}'.format(user), 'YES')
  935. return successfullySetState(user, state)
  936. @app.route('/users/devices')
  937. class UsersDevices(Resource):
  938. @authRequired
  939. @app.response(HTTPStatus.OK, 'JSON reply with user:device map or error message')
  940. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  941. async def get(self):
  942. '''Returns users to device maping.
  943. '''
  944. if not request.admin:
  945. abort(401)
  946. data = {}
  947. for user in app.cache['ustates']:
  948. device = await getUserDevice(user)
  949. if ((device in NONEs) or (device == user)):
  950. device = None
  951. else:
  952. device = device.replace('{}&'.format(user), '')
  953. data[user]= device
  954. return successReply(data)
  955. @app.route('/device/<device>/<user>/on')
  956. @app.route('/user/<user>/<device>/on')
  957. class UserDeviceBind(Resource):
  958. @authRequired
  959. @app.param('device', 'Device number to bind to', 'path')
  960. @app.param('user', 'User to bind to device', 'path')
  961. @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
  962. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  963. async def get(self, device, user):
  964. '''Binds user to device.
  965. Both user and device numbers are checked for existance.
  966. Any device user was previously bound to, is unbound.
  967. Any user previously bound to device is unbound also.
  968. '''
  969. if (device != request.device) and (not request.admin):
  970. abort(401)
  971. if user not in app.cache['ustates']:
  972. return noUser(user)
  973. dial = await getDeviceDial(device) # Check if device exists in astdb
  974. if dial is None:
  975. return noDevice(device)
  976. currentUser = await getDeviceUser(device) # Check if any user is already bound to device
  977. if currentUser == user:
  978. return alreadyBound(user, device)
  979. ast = await getGlobalVars()
  980. if currentUser not in NONEs: # If any other user is bound to device, unbind him,
  981. result = await amiSetVar('PRESENCE_STATE(CustomPresence:{})'.format(user), 'available')
  982. result = await amiDBDel('DND', '{}'.format(user))
  983. await setUserDevice(currentUser, None)
  984. if ast.QUEDEVSTATE == 'TRUE': # set device states for previous user queues
  985. await setQueueStates(currentUser, device, 'NOT_INUSE')
  986. await setUserHint(currentUser, None, ast) # set hints for previous user
  987. await setDeviceUser(device, user) # Bind user to device
  988. # If user is bound to some other devices, unbind him and set
  989. # device states for those devices
  990. await unbindOtherDevices(user, device, ast)
  991. if not (await setUserHint(user, dial, ast)): # Set hints for user on new device
  992. return hintError(user, device)
  993. await setUserDeviceStates(user, device, ast) # Set device states for users new device
  994. if not (await setUserDevice(user, device)): # Bind device to user
  995. return bindError(user, device)
  996. app.cache['usermap'][device] = user
  997. app.cache['devicemap'][user] = device
  998. await amiUserEvent('DeviceBound',{'device': device, 'newUser': user, 'oldUser': currentUser})
  999. return successfullyBound(user, device)
  1000. @app.route('/device/<device>/off')
  1001. class DeviceUnBind(Resource):
  1002. @authRequired
  1003. @app.param('device', 'Device number to unbind', 'path')
  1004. @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
  1005. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1006. async def get(self, device):
  1007. '''Unbinds any user from device.
  1008. Device is checked for existance.
  1009. '''
  1010. if (device != request.device) and (not request.admin):
  1011. abort(401)
  1012. dial = await getDeviceDial(device) # Check if device exists in astdb
  1013. if dial is None:
  1014. return noDevice(device)
  1015. currentUser = await getDeviceUser(device) # Check if any user is bound to device
  1016. if currentUser in NONEs:
  1017. return noUserBound(device)
  1018. else:
  1019. result = await amiSetVar('PRESENCE_STATE(CustomPresence:{})'.format(currentUser), 'available')
  1020. result = await amiDBDel('DND', '{}'.format(currentUser))
  1021. ast = await getGlobalVars()
  1022. await setUserDevice(currentUser, None) # Unbind device from current user
  1023. if ast.QUEDEVSTATE == 'TRUE': # set device states for current user queues
  1024. await setQueueStates(currentUser, device, 'NOT_INUSE')
  1025. await setUserHint(currentUser, None, ast) # set hints for current user
  1026. await setDeviceUser(device, 'none') # Unbind user from device
  1027. del app.cache['usermap'][device]
  1028. del app.cache['devicemap'][currentUser]
  1029. await amiUserEvent('DeviceUnbound',{'device': device, 'oldUser': currentUser})
  1030. return successfullyUnbound(currentUser, device)
  1031. @app.route('/cdr')
  1032. class CDR(Resource):
  1033. @authRequired
  1034. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  1035. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  1036. @app.response(HTTPStatus.OK, 'JSON reply')
  1037. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1038. async def get(self):
  1039. '''Returns CDR data, groupped by logical call id.
  1040. All request arguments are optional.
  1041. '''
  1042. if not request.admin:
  1043. abort(401)
  1044. start = parseDatetime(request.args.get('start'))
  1045. end = parseDatetime(request.args.get('end'))
  1046. cdr = await getCDR(start, end)
  1047. return successReply(cdr)
  1048. @app.route('/cel')
  1049. class CEL(Resource):
  1050. @authRequired
  1051. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  1052. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  1053. @app.response(HTTPStatus.OK, 'JSON reply')
  1054. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1055. async def get(self):
  1056. '''Returns CEL data, groupped by logical call id.
  1057. All request arguments are optional.
  1058. '''
  1059. if not request.admin:
  1060. abort(401)
  1061. start = parseDatetime(request.args.get('start'))
  1062. end = parseDatetime(request.args.get('end'))
  1063. cel = await getCEL(start, end)
  1064. return successReply(cel)
  1065. @app.route('/calls')
  1066. class Calls(Resource):
  1067. @authRequired
  1068. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 and YYYYMMDDhhmmss', 'query')
  1069. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 and YYYYMMDDhhmmss', 'query')
  1070. @app.response(HTTPStatus.OK, 'JSON reply')
  1071. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1072. async def get(self):
  1073. '''Returns aggregated call data JSON. Draft implementation.
  1074. All request arguments are optional.
  1075. '''
  1076. if not request.admin:
  1077. abort(401)
  1078. calls = []
  1079. start = parseDatetime(request.args.get('start'))
  1080. end = parseDatetime(request.args.get('end'))
  1081. cdr = await getCDR(start, end)
  1082. for c in cdr:
  1083. _call = {'id':c.linkedid,
  1084. 'start':c.start,
  1085. 'type': c.direction,
  1086. 'numberA': c.src,
  1087. 'numberB': c.dst,
  1088. 'line': c.did,
  1089. 'duration': c.duration,
  1090. 'waiting': c.waiting,
  1091. 'status':c.disposition,
  1092. 'url': c.file }
  1093. calls.append(_call)
  1094. return successReply(calls)
  1095. @app.route('/user/<user>/calls')
  1096. class UserCalls(Resource):
  1097. @authRequired
  1098. @app.param('user', 'User to query for call stats', 'path')
  1099. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 and YYYYMMDDhhmmss', 'query')
  1100. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 and YYYYMMDDhhmmss', 'query')
  1101. @app.param('direction', 'Calls direction, in or out. If not specified both are returned', 'query')
  1102. @app.param('limit', 'Max number of returned records, defaults to unlimited. Use offset parameter together with limit', 'query')
  1103. @app.param('offset', 'If limit is specified use offset parameter to request more results', 'query')
  1104. @app.param('order', 'Calls sort order for datetime field. ASC or DESC. Defaults to ASC', 'query')
  1105. @app.response(HTTPStatus.OK, 'JSON data {"status":status,"data":data,"message":message}')
  1106. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1107. async def get(self, user):
  1108. '''Returns user's call stats.
  1109. '''
  1110. if (user != request.user) and (not request.admin):
  1111. abort(401)
  1112. if user not in app.cache['ustates']:
  1113. return noUser(user)
  1114. cdr = await getUserCDR(user,
  1115. parseDatetime(request.args.get('start')),
  1116. parseDatetime(request.args.get('end')),
  1117. request.args.get('direction', None),
  1118. request.args.get('limit', None),
  1119. request.args.get('offset', None),
  1120. request.args.get('order', 'ASC'))
  1121. return successReply(cdr)
  1122. @app.route('/device/<device>/callback')
  1123. class DeviceCallback(Resource):
  1124. @authRequired
  1125. @app.param('device', 'Device to get/set the callback url for', 'path')
  1126. @app.param('url', 'used to set the Callback url for the device', 'query')
  1127. @app.response(HTTPStatus.OK, 'JSON data {"user":user,"state":state}')
  1128. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1129. async def get(self, device):
  1130. '''Returns and sets device's callback url.
  1131. '''
  1132. if (device != request.device) and (not request.admin):
  1133. abort(401)
  1134. url = request.args.get('url', None)
  1135. if url is not None:
  1136. await db.execute(query='REPLACE INTO callback_urls (device, url) VALUES (:device, :url)',
  1137. values={'device': device,'url': url})
  1138. else:
  1139. row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
  1140. values={'device': device})
  1141. if row is not None:
  1142. url = row['url']
  1143. return successCallbackURL(device, url)
  1144. @app.route('/group/ringing/callback')
  1145. class GroupRingingCallback(Resource):
  1146. @authRequired
  1147. @app.param('url', 'used to set the Callback url for the group ringing callback', 'query')
  1148. @app.response(HTTPStatus.OK, 'JSON data {"url":url}')
  1149. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1150. async def get(self):
  1151. '''Returns and sets groupRinging callback url.
  1152. '''
  1153. if not request.admin:
  1154. abort(401)
  1155. url = request.args.get('url', None)
  1156. if url is not None:
  1157. await db.execute(query='REPLACE INTO callback_urls (device, url) VALUES (:device, :url)',
  1158. values={'device': 'groupRinging','url': url})
  1159. else:
  1160. row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
  1161. values={'device': 'groupRinging'})
  1162. if row is not None:
  1163. url = row['url']
  1164. return successCommonCallbackURL('groupRinging', url)
  1165. @app.route('/group/answered/callback')
  1166. class GroupAnsweredCallback(Resource):
  1167. @authRequired
  1168. @app.param('url', 'used to set the Callback url for the group answered callback', 'query')
  1169. @app.response(HTTPStatus.OK, 'JSON data {"url":url}')
  1170. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1171. async def get(self):
  1172. '''Returns and sets groupAnswered callback url.
  1173. '''
  1174. if not request.admin:
  1175. abort(401)
  1176. url = request.args.get('url', None)
  1177. if url is not None:
  1178. await db.execute(query='REPLACE INTO callback_urls (device, url) VALUES (:device, :url)',
  1179. values={'device': 'groupAnswered','url': url})
  1180. else:
  1181. row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
  1182. values={'device': 'groupAnswered'})
  1183. if row is not None:
  1184. url = row['url']
  1185. return successCommonCallbackURL('groupAnswered', url)
  1186. @app.route('/queue/enter/callback')
  1187. class QueueEnterCallback(Resource):
  1188. @authRequired
  1189. @app.param('url', 'used to set the Callback url for the queue enter callback', 'query')
  1190. @app.response(HTTPStatus.OK, 'JSON data {"url":url}')
  1191. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1192. async def get(self):
  1193. '''Returns and sets queueEnter callback url.
  1194. '''
  1195. if not request.admin:
  1196. abort(401)
  1197. url = request.args.get('url', None)
  1198. if url is not None:
  1199. await db.execute(query='REPLACE INTO callback_urls (device, url) VALUES (:device, :url)',
  1200. values={'device': 'queueEnter','url': url})
  1201. else:
  1202. row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
  1203. values={'device': 'queueEnter'})
  1204. if row is not None:
  1205. url = row['url']
  1206. return successCommonCallbackURL('queueEnter', url)
  1207. @app.route('/queue/leave/callback')
  1208. class QueueLeaveCallback(Resource):
  1209. @authRequired
  1210. @app.param('url', 'used to set the Callback url for the queue leave callback', 'query')
  1211. @app.response(HTTPStatus.OK, 'JSON data {"url":url}')
  1212. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1213. async def get(self):
  1214. '''Returns and sets queueLeave callback url.
  1215. '''
  1216. if not request.admin:
  1217. abort(401)
  1218. url = request.args.get('url', None)
  1219. if url is not None:
  1220. await db.execute(query='REPLACE INTO callback_urls (device, url) VALUES (:device, :url)',
  1221. values={'device': 'queueLeave','url': url})
  1222. else:
  1223. row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
  1224. values={'device': 'queueLeave'})
  1225. if row is not None:
  1226. url = row['url']
  1227. return successCommonCallbackURL('queueLeave', url)
  1228. manager.connect()
  1229. app.run(loop=main_loop, host='0.0.0.0', port=app.config['PORT'])