app.py 54 KB

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