app.py 53 KB

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