app.py 56 KB

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