app.py 53 KB

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