app.py 53 KB

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