app.py 60 KB

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