app.py 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524
  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 (firstMessage.Context == 'from-pstn') or (firstMessage.get('groupCall',False)):
  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')):
  432. app.logger.warning(f'''POST {row['url']} data: {str(msg)}''')
  433. if not 'HTTP_CLIENT' in app.config:
  434. await initHttpClient()
  435. reply = await app.config['HTTP_CLIENT'].post(row['url'], json=msg)
  436. return reply
  437. else:
  438. app.logger.warning('No callback url defined for {}'.format(entity))
  439. return None
  440. @app.before_first_request
  441. async def initHttpClient():
  442. app.config['HTTP_CLIENT'] = aiohttp.ClientSession(loop=main_loop,
  443. connector=aiohttp.TCPConnector(verify_ssl=False,
  444. resolver=AsyncResolver(nameservers=['192.168.171.10','1.1.1.1'])))
  445. @app.route('/openapi.json')
  446. async def openapi():
  447. '''Generates JSON that conforms OpenAPI Specification
  448. '''
  449. schema = app.__schema__
  450. schema['servers'] = [{'url':'http://aster.rrt.ru:8000'},
  451. {'url':'{}://{}:{}'.format(app.config['SCHEME'],
  452. app.config['FQDN'],
  453. app.config['PORT'])}]
  454. if app.config['EXTRA_API_URL'] is not None:
  455. schema['servers'].append({'url':app.config['EXTRA_API_URL']})
  456. schema['components'] = {'securitySchemes':{'ApiKey':{'type': 'apiKey',
  457. 'name': app.config['AUTH_HEADER'],
  458. 'in': 'header'}}}
  459. schema['security'] = [{'ApiKey':[]}]
  460. return jsonify(schema)
  461. @app.route('/ui')
  462. async def ui():
  463. '''Swagger UI
  464. '''
  465. return await render_template_string(SWAGGER_TEMPLATE,
  466. title=app.config['TITLE'],
  467. js_url=app.config['SWAGGER_JS_URL'],
  468. css_url=app.config['SWAGGER_CSS_URL'])
  469. async def action():
  470. _payload = await request.get_data()
  471. reply = await manager.send_action(json.loads(_payload))
  472. return str(reply)
  473. async def amiGetVar(variable):
  474. '''AMI GetVar
  475. Returns value of requested variable using AMI action GetVar in background.
  476. Parameters:
  477. variable (string): Variable to query for
  478. Returns:
  479. string: Variable value or empty string if variable not found
  480. '''
  481. reply = await manager.send_action({'Action': 'GetVar',
  482. 'Variable': variable})
  483. #app.logger.warning('GetVar({})->{}'.format(variable, reply.value))
  484. return reply.value
  485. @app.route('/ami/auths')
  486. @authRequired
  487. async def amiPJSIPShowAuths():
  488. if not request.admin:
  489. abort(401)
  490. return successReply(app.cache['devices'])
  491. @app.route('/blackhole', methods=['GET','POST'])
  492. async def blackhole():
  493. return ''
  494. @app.route('/ami/aors')
  495. @authRequired
  496. async def amiPJSIPShowAors():
  497. if not request.admin:
  498. abort(401)
  499. aors = {}
  500. reply = await manager.send_action({'Action':'PJSIPShowAors'})
  501. if len(reply) >= 2:
  502. for message in reply:
  503. if ((message.event == 'AorList') and
  504. ('objecttype' in message) and
  505. (message.objecttype == 'aor') and
  506. (int(message.maxcontacts) > 0)):
  507. aors[message.objectname] = message.contacts
  508. app.logger.warning('AorsList: {}'.format(','.join(aors.keys())))
  509. return successReply(aors)
  510. async def amiStartMixMonitor(channel,filename):
  511. '''AMI MixMonitor
  512. Parameters:
  513. channel (string):channel to start mixmonitor
  514. filename (string): file name
  515. Returns:
  516. string: None if SetVar was successfull, error message overwise
  517. '''
  518. d = date.today()
  519. year = d.strftime("%Y")
  520. month = d.strftime("%m")
  521. day = d.strftime("%d")
  522. fullname = "{}/{}/{}/{}.wav".format(year,month,day,filename)
  523. reply = await manager.send_action({'Action': 'MixMonitor',
  524. 'Channel': channel,
  525. 'options': 'ai(LOCAL_MIXMON_ID)',
  526. 'Command': "/etc/asterisk/scripts/wav2mp3.sh {} {} {} {}".format(year,month,day,filename),
  527. 'File': fullname})
  528. #app.logger.warning('MixMonitor({}, {})'.format(channel, fullname))
  529. if isinstance(reply, Message):
  530. if reply.success:
  531. return None
  532. else:
  533. return reply.message
  534. return 'AMI error'
  535. async def amiStopMixMonitor(channel):
  536. '''AMI StopMixMonitor
  537. Parameters:
  538. channel (string):channel to stop mixmonitor
  539. Returns:
  540. string: None if SetVar was successfull, error message overwise
  541. '''
  542. reply = await manager.send_action({'Action': 'StopMixMonitor',
  543. 'Channel': channel})
  544. #app.logger.warning('StopMixMonitor({})'.format(channel))
  545. if isinstance(reply, Message):
  546. if reply.success:
  547. return None
  548. else:
  549. return reply.message
  550. return 'AMI error'
  551. async def amiUserEvent(name, data):
  552. '''AMI UserEvent
  553. Generates AMI Event using AMI action UserEvent with name and data supplied.
  554. Parameters:
  555. name (string): UserEvent name
  556. data (dict): UserEvent data
  557. Returns:
  558. string: None if UserEvent was successfull, error message overwise
  559. '''
  560. reply = await manager.send_action({**{'Action': 'UserEvent',
  561. 'UserEvent': name},
  562. **data})
  563. #app.logger.warning('UserEvent({})'.format(name))
  564. if isinstance(reply, Message):
  565. if reply.success:
  566. return None
  567. else:
  568. return reply.message
  569. return 'AMI error'
  570. async def amiChannelSetVar(channel,variable, value):
  571. '''AMI SetVar
  572. Sets variable using AMI action SetVar to value in background.
  573. Parameters:
  574. channel (string)
  575. variable (string): Variable to set
  576. value (string): Value to set for variable
  577. Returns:
  578. string: None if SetVar was successfull, error message overwise
  579. '''
  580. reply = await manager.send_action({'Action': 'SetVar',
  581. 'Variable': variable,
  582. 'Channel': channel,
  583. 'Value': value})
  584. #app.logger.warning('SetVar({},{}={})'.format(channel,variable, value))
  585. if isinstance(reply, Message):
  586. if reply.success:
  587. return None
  588. else:
  589. return reply.message
  590. return 'AMI error'
  591. async def amiSetVar(variable, value):
  592. '''AMI SetVar
  593. Sets variable using AMI action SetVar to value in background.
  594. Parameters:
  595. variable (string): Variable to set
  596. value (string): Value to set for variable
  597. Returns:
  598. string: None if SetVar was successfull, error message overwise
  599. '''
  600. reply = await manager.send_action({'Action': 'SetVar',
  601. 'Variable': variable,
  602. 'Value': value})
  603. #app.logger.warning('SetVar({}, {})'.format(variable, value))
  604. if isinstance(reply, Message):
  605. if reply.success:
  606. return None
  607. else:
  608. return reply.message
  609. return 'AMI error'
  610. async def amiDBGet(family, key):
  611. '''AMI DBGet
  612. Returns value of requested astdb key using AMI action DBGet in background.
  613. Parameters:
  614. family (string): astdb key family to query for
  615. key (string): astdb key to query for
  616. Returns:
  617. string: Value or empty string if variable not found
  618. '''
  619. reply = await manager.send_action({'Action': 'DBGet',
  620. 'Family': family,
  621. 'Key': key})
  622. if (isinstance(reply, list) and
  623. (len(reply) > 1)):
  624. for message in reply:
  625. if (message.event == 'DBGetResponse'):
  626. #app.logger.warning('DBGet(/{}/{})->{}'.format(family, key, message.val))
  627. return message.val
  628. app.logger.warning('DBGet(/{}/{})->Error!'.format(family, key))
  629. return None
  630. async def amiDBPut(family, key, value):
  631. '''AMI DBPut
  632. Writes value to astdb by family and key using AMI action DBPut in background.
  633. Parameters:
  634. family (string): astdb key family to write to
  635. key (string): astdb key to write to
  636. value (string): value to write
  637. Returns:
  638. boolean: True if DBPut action was successfull, False overwise
  639. '''
  640. reply = await manager.send_action({'Action': 'DBPut',
  641. 'Family': family,
  642. 'Key': key,
  643. 'Val': value})
  644. app.logger.warning('DBPut(/{}/{}, {})'.format(family, key, value))
  645. if (isinstance(reply, Message) and reply.success):
  646. return True
  647. return False
  648. async def amiDBDel(family, key):
  649. '''AMI DBDel
  650. Deletes key from family in astdb using AMI action DBDel in background.
  651. Parameters:
  652. family (string): astdb key family
  653. key (string): astdb key to delete
  654. Returns:
  655. boolean: True if DBDel action was successfull, False overwise
  656. '''
  657. reply = await manager.send_action({'Action': 'DBDel',
  658. 'Family': family,
  659. 'Key': key})
  660. app.logger.warning('DBDel(/{}/{})'.format(family, key))
  661. if (isinstance(reply, Message) and reply.success):
  662. return True
  663. return False
  664. async def amiSetHint(context, user, hint):
  665. '''AMI SetHint
  666. Sets hint for user in context using AMI action DialplanUserAdd with Replace=true in background.
  667. Parameters:
  668. context (string): dialplan context
  669. user (string): user
  670. hint (string): hint for user
  671. Returns:
  672. boolean: True if DialplanUserAdd action was successfull, False overwise
  673. '''
  674. reply = await manager.send_action({'Action': 'DialplanExtensionAdd',
  675. 'Context': context,
  676. 'Extension': user,
  677. 'Priority': 'hint',
  678. 'Application': hint,
  679. 'Replace': 'yes'})
  680. app.logger.warning('SetHint({},{},{})'.format(context, user, hint))
  681. if (isinstance(reply, Message) and reply.success):
  682. return True
  683. return False
  684. async def amiPresenceState(user):
  685. '''AMI PresenceState request for CustomPresence provider
  686. Parameters:
  687. user (string): user
  688. Returns:
  689. boolean, string: True and state or False and error message
  690. '''
  691. reply = await manager.send_action({'Action': 'PresenceState',
  692. 'Provider': 'CustomPresence:{}'.format(user)})
  693. #app.logger.warning('PresenceState({})'.format(user))
  694. if isinstance(reply, Message):
  695. if reply.success:
  696. return True, reply.state
  697. else:
  698. return False, reply.message
  699. return False, 'AMI error'
  700. async def amiPresenceStateList():
  701. states = {}
  702. reply = await manager.send_action({'Action':'PresenceStateList'})
  703. if len(reply) >= 2:
  704. for message in reply:
  705. if message.event == 'PresenceStateChange':
  706. user = re.search('CustomPresence:(\d+)', message.presentity).group(1)
  707. states[user] = message.status
  708. app.logger.warning('PresenceStateList: {}'.format(','.join(states.keys())))
  709. return states
  710. async def amiExtensionStateList():
  711. states = {}
  712. reply = await manager.send_action({'Action':'ExtensionStateList'})
  713. if len(reply) >= 2:
  714. for message in reply:
  715. if ((message.event == 'ExtensionStatus') and
  716. (message.context == 'ext-local')):
  717. states[message.exten] = message.statustext.lower()
  718. app.logger.warning('ExtensionStateList: {}'.format(','.join(states.keys())))
  719. return states
  720. async def amiCommand(command):
  721. '''AMI Command
  722. Runs specified command using AMI action Command in background.
  723. Parameters:
  724. command (string): command to run
  725. Returns:
  726. boolean, list: tuple representing the boolean result of request and list of lines of command output
  727. '''
  728. reply = await manager.send_action({'Action': 'Command',
  729. 'Command': command})
  730. result = []
  731. if (isinstance(reply, Message) and reply.success):
  732. if isinstance(reply.output, list):
  733. result = reply.output
  734. else:
  735. result = reply.output.split('\n')
  736. app.logger.warning('Command({})->{}'.format(command, '\n'.join(result)))
  737. return True, result
  738. app.logger.warning('Command({})->Error!'.format(command))
  739. return False, result
  740. async def amiReload(module='core'):
  741. '''AMI Reload
  742. Reload specified asterisk module using AMI action reload in background.
  743. Parameters:
  744. module (string): module to reload, defaults to core
  745. Returns:
  746. boolean: True if Reload action was successfull, False overwise
  747. '''
  748. reply = await manager.send_action({'Action': 'Reload',
  749. 'Module': module})
  750. app.logger.warning('Reload({})'.format(module))
  751. if (isinstance(reply, Message) and reply.success):
  752. return True
  753. return False
  754. async def getGlobalVars():
  755. globalVars = GlobalVars()
  756. for _var in globalVars.d():
  757. setattr(globalVars, _var, await amiGetVar(_var))
  758. return globalVars
  759. async def setUserHint(user, dial, ast):
  760. if dial in NONEs:
  761. hint = 'CustomPresence:{}'.format(user)
  762. else:
  763. _dial= [dial]
  764. if (ast.DNDDEVSTATE == 'TRUE'):
  765. _dial.append('Custom:DND{}'.format(user))
  766. hint = '{},CustomPresence:{}'.format('&'.join(_dial), user)
  767. return await amiSetHint('ext-local', user, hint)
  768. async def amiQueues():
  769. queues = {}
  770. reply = await manager.send_action({'Action':'QueueStatus'})
  771. if len(reply) >= 2:
  772. for message in reply:
  773. if message.event == 'QueueMember':
  774. _qm = QueueMember(re.search('Local\/(\d+)', message.location).group(1))
  775. queues.setdefault(message.queue, []).append(_qm.fromMessage(message))
  776. app.logger.warning('QueuesList: {}'.format(','.join(queues.keys())))
  777. return queues
  778. async def amiDeviceChannel(device):
  779. reply = await manager.send_action({'Action':'CoreShowChannels'})
  780. if len(reply) >= 2:
  781. for message in reply:
  782. if message.event == 'CoreShowChannel':
  783. if message.calleridnum == device:
  784. return message.channel
  785. return None
  786. async def getUserChannel(user):
  787. device = await getUserDevice(user)
  788. if device in NONEs:
  789. return False
  790. channel = await amiDeviceChannel(device)
  791. if channel in NONEs:
  792. return False
  793. return channel
  794. async def setQueueStates(user, device, state):
  795. for queue in [_q for _q, _ma in app.cache['queues'].items() for _m in _ma if _m.user == user]:
  796. await amiSetVar('DEVICE_STATE(Custom:QUEUE{}*{})'.format(device, queue), state)
  797. async def getDeviceUser(device):
  798. return await amiDBGet('DEVICE', '{}/user'.format(device))
  799. async def getDeviceType(device):
  800. return await amiDBGet('DEVICE', '{}/type'.format(device))
  801. async def getDeviceDial(device):
  802. return await amiDBGet('DEVICE', '{}/dial'.format(device))
  803. async def getUserCID(user):
  804. return await amiDBGet('AMPUSER', '{}/cidnum'.format(user))
  805. async def setDeviceUser(device, user):
  806. return await amiDBPut('DEVICE', '{}/user'.format(device), user)
  807. async def getUserDevice(user):
  808. return await amiDBGet('AMPUSER', '{}/device'.format(user))
  809. async def setUserDevice(user, device):
  810. if device is None:
  811. return await amiDBDel('AMPUSER', '{}/device'.format(user))
  812. else:
  813. return await amiDBPut('AMPUSER', '{}/device'.format(user), device)
  814. async def unbindOtherDevices(user, newDevice, ast):
  815. '''Unbinds user from all devices except newDevice and sets
  816. all required device states.
  817. '''
  818. devices = await amiDBGet('AMPUSER', '{}/device'.format(user))
  819. if devices not in NONEs:
  820. for _device in sorted(set(devices.split('&')), key=int):
  821. if _device == user:
  822. continue
  823. if _device != newDevice:
  824. if ast.FMDEVSTATE == 'TRUE':
  825. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(_device), 'INVALID')
  826. if ast.QUEDEVSTATE == 'TRUE':
  827. await setQueueStates(user, _device, 'NOT_INUSE')
  828. if ast.DNDDEVSTATE:
  829. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(_device), 'NOT_INUSE')
  830. if ast.CFDEVSTATE:
  831. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(_device), 'NOT_INUSE')
  832. await amiDBPut('DEVICE', '{}/user'.format(_device), 'none')
  833. async def setUserDeviceStates(user, device, ast):
  834. if ast.FMDEVSTATE == 'TRUE':
  835. _followMe = await amiDBGet('AMPUSER', '{}/followme/ddial'.format(user))
  836. if _followMe is not None:
  837. await amiSetVar('DEVICE_STATE(Custom:FOLLOWME{})'.format(device), followMe2DevState(_followMe))
  838. if ast.QUEDEVSTATE == 'TRUE':
  839. await setQueueStates(user, device, 'INUSE')
  840. if ast.DNDDEVSTATE:
  841. _dnd = await amiDBGet('DND', user)
  842. await amiSetVar('DEVICE_STATE(Custom:DEVDND{})'.format(device), 'INUSE' if _dnd == 'YES' else 'NOT_INUSE')
  843. if ast.CFDEVSTATE:
  844. _cf = await amiDBGet('CF', user)
  845. await amiSetVar('DEVICE_STATE(Custom:DEVCF{})'.format(device), 'INUSE' if _cf != '' else 'NOT_INUSE')
  846. async def refreshStatesCache():
  847. app.cache['ustates'] = await amiExtensionStateList()
  848. app.cache['pstates'] = await amiPresenceStateList()
  849. return len(app.cache['ustates'])
  850. async def refreshDevicesCache():
  851. auths = {}
  852. reply = await manager.send_action({'Action':'PJSIPShowAuths'})
  853. if len(reply) >= 2:
  854. for message in reply:
  855. if ((message.event == 'AuthList') and
  856. ('objecttype' in message) and
  857. (message.objecttype == 'auth')):
  858. auths[message.username] = message.password
  859. app.cache['devices'] = auths
  860. return len(app.cache['devices'])
  861. async def refreshQueuesCache():
  862. app.cache['queues'] = await amiQueues()
  863. return len(app.cache['queues'])
  864. async def rebindLostDevices():
  865. app.cache['usermap'] = {}
  866. app.cache['devicemap'] = {}
  867. ast = await getGlobalVars()
  868. for device in app.cache['devices']:
  869. user = await getDeviceUser(device)
  870. deviceType = await getDeviceType(device)
  871. if (deviceType != 'fixed') and (user != 'none') and (user in app.cache['ustates'].keys()):
  872. _device = await getUserDevice(user)
  873. if _device != device:
  874. app.logger.warning('Fixing bind user {} to device {}'.format(user, device))
  875. dial = await getDeviceDial(device)
  876. await setUserHint(user, dial, ast) # Set hints for user on new device
  877. await setUserDeviceStates(user, device, ast) # Set device states for users device
  878. await setUserDevice(user, device) # Bind device to user
  879. app.cache['usermap'][device] = user
  880. if user != 'none':
  881. app.cache['devicemap'][user] = device
  882. async def userStateChangeCallback(user, state, prevState = None):
  883. reply = None
  884. device = None
  885. if ('HTTP_CLIENT' in app.config) and (user in app.cache['devicemap']):
  886. device = app.cache['devicemap'][user]
  887. if device is not None:
  888. _cb = {'user': user,
  889. 'state': state,
  890. 'prev_state':prevState}
  891. reply = await doCallback(device, _cb)
  892. #app.logger.warning('{} changed state to: {}'.format(user, state))
  893. return reply
  894. def getUserStateCombined(user):
  895. _uCache = app.cache['ustates']
  896. _pCache = app.cache['pstates']
  897. return combinedStates[_uCache.get(user, 'unavailable')][_pCache.get(user, 'not_set')]
  898. def getUsersStatesCombined():
  899. return {user:getUserStateCombined(user) for user in app.cache['ustates']}
  900. @app.route('/atxfer/<userA>/<userB>')
  901. class AtXfer(Resource):
  902. @authRequired
  903. @app.param('userA', 'User initiating the attended transfer', 'path')
  904. @app.param('userB', 'Transfer destination user', 'path')
  905. @app.response(HTTPStatus.OK, 'Json reply')
  906. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  907. async def get(self, userA, userB):
  908. '''Attended call transfer
  909. '''
  910. if (userA != request.user) and (not request.admin):
  911. abort(401)
  912. channel = await getUserChannel(userA)
  913. if not channel:
  914. return noUserChannel(userA)
  915. reply = await manager.send_action({'Action':'Atxfer',
  916. 'Channel':channel,
  917. 'async':'false',
  918. 'Exten':userB})
  919. if isinstance(reply, Message):
  920. if reply.success:
  921. return successfullyTransfered(userA, userB)
  922. else:
  923. return errorReply(reply.message)
  924. @app.route('/bxfer/<userA>/<userB>')
  925. class BXfer(Resource):
  926. @authRequired
  927. @app.param('userA', 'User initiating the blind transfer', 'path')
  928. @app.param('userB', 'Transfer destination user', 'path')
  929. @app.response(HTTPStatus.OK, 'Json reply')
  930. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  931. async def get(self, userA, userB):
  932. '''Blind call transfer
  933. '''
  934. if (userA != request.user) and (not request.admin):
  935. abort(401)
  936. channel = await getUserChannel(userA)
  937. if not channel:
  938. return noUserChannel(userA)
  939. reply = await manager.send_action({'Action':'BlindTransfer',
  940. 'Channel':channel,
  941. 'async':'false',
  942. 'Exten':userB})
  943. if isinstance(reply, Message):
  944. if reply.success:
  945. return successfullyTransfered(userA, userB)
  946. else:
  947. return errorReply(reply.message)
  948. @app.route('/originate/<user>/<number>')
  949. class Originate(Resource):
  950. @authRequired
  951. @app.param('user', 'User initiating the call', 'path')
  952. @app.param('number', 'Destination number', 'path')
  953. @app.response(HTTPStatus.OK, 'Json reply')
  954. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  955. async def get(self, user, number):
  956. '''Originate call
  957. '''
  958. if (user != request.user) and (not request.admin):
  959. abort(401)
  960. device = await getUserDevice(user)
  961. if device in NONEs:
  962. return noUserDevice(user)
  963. device = device.replace('{}&'.format(user), '')
  964. _act = { 'Action':'Originate',
  965. 'Channel':'PJSIP/{}'.format(device),
  966. 'Context':'from-internal',
  967. 'Exten':number,
  968. 'Priority': '1',
  969. 'async':'false',
  970. 'Callerid': '{} <{}>'.format(user, user)}
  971. app.logger.warning(_act)
  972. reply = await manager.send_action(_act)
  973. if isinstance(reply, Message):
  974. if reply.success:
  975. return successfullyOriginated(user, number)
  976. else:
  977. return errorReply(reply.message)
  978. @app.route('/hangup/<user>')
  979. class Hangup(Resource):
  980. @authRequired
  981. @app.param('user', 'User to hangup', 'path')
  982. @app.response(HTTPStatus.OK, 'Json reply')
  983. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  984. async def get(self, user):
  985. '''Call hangup
  986. '''
  987. if (user != request.user) and (not request.admin):
  988. abort(401)
  989. channel = await getUserChannel(user)
  990. if not channel:
  991. return noUserChannel(user)
  992. reply = await manager.send_action({'Action':'Hangup',
  993. 'Channel':channel})
  994. if isinstance(reply, Message):
  995. if reply.success:
  996. return successfullyHungup(user)
  997. else:
  998. return errorReply(reply.message)
  999. @app.route('/users/states')
  1000. class UsersStates(Resource):
  1001. @authRequired
  1002. @app.response(HTTPStatus.OK, 'JSON reply with user:state map or error message')
  1003. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1004. async def get(self):
  1005. '''Returns all users with their combined states.
  1006. Possible states are: available, away, dnd, inuse, busy, unavailable, ringing
  1007. '''
  1008. if not request.admin:
  1009. abort(401)
  1010. #app.logger.warning('request device: {}'.format(request.device))
  1011. #usersCount = await refreshStatesCache()
  1012. #if usersCount == 0:
  1013. # return stateCacheEmpty()
  1014. return successReply(getUsersStatesCombined())
  1015. @app.route('/users/states/<users_list>')
  1016. class UsersStatesSelected(Resource):
  1017. @authRequired
  1018. @app.param('users_list', 'Comma separated list of users to query for combined states', 'path')
  1019. @app.response(HTTPStatus.OK, 'JSON reply with user:state map or error message')
  1020. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1021. async def get(self, users_list):
  1022. '''Returns selected users with their combined states.
  1023. Possible states are: available, away, dnd, inuse, busy, unavailable, ringing
  1024. '''
  1025. if not request.admin:
  1026. abort(401)
  1027. users = users_list.split(',')
  1028. states = getUsersStatesCombined()
  1029. result={}
  1030. for user in states:
  1031. if user in users:
  1032. result[user] = states[user]
  1033. return successReply(result)
  1034. @app.route('/user/<user>/state')
  1035. class UserState(Resource):
  1036. @authRequired
  1037. @app.param('user', 'User to query for combined state', 'path')
  1038. @app.response(HTTPStatus.OK, 'JSON data {"user":user,"state":state}')
  1039. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1040. async def get(self, user):
  1041. '''Returns user's combined state.
  1042. One of: available, away, dnd, inuse, busy, unavailable, ringing
  1043. '''
  1044. if (user != request.user) and (not request.admin):
  1045. abort(401)
  1046. if user not in app.cache['ustates']:
  1047. return noUser(user)
  1048. return successReply({'user':user,'state':getUserStateCombined(user)})
  1049. @app.route('/user/<user>/presence')
  1050. class PresenceState(Resource):
  1051. @authRequired
  1052. @app.param('user', 'User to query for presence state', 'path')
  1053. @app.response(HTTPStatus.OK, 'JSON data {"user":user,"state":state}')
  1054. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1055. async def get(self, user):
  1056. '''Returns user's presence state.
  1057. One of: not_set, unavailable, available, away, xa, chat, dnd
  1058. '''
  1059. if (user != request.user) and (not request.admin):
  1060. abort(401)
  1061. if user not in app.cache['ustates']:
  1062. return noUser(user)
  1063. return successReply({'user':user,'state':app.cache['pstates'].get(user, 'not_set')})
  1064. @app.route('/user/<user>/presence/<state>')
  1065. class SetPresenceState(Resource):
  1066. @authRequired
  1067. @app.param('user', 'Target user to set the presence state', 'path')
  1068. @app.param('state',
  1069. 'The presence state for user, one of: not_set, unavailable, available, away, xa, chat or dnd',
  1070. 'path')
  1071. @app.response(HTTPStatus.OK, 'Json reply')
  1072. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1073. async def get(self, user, state):
  1074. '''Sets user's presence state.
  1075. Allowed states: not_set | unavailable | available | away | xa | chat | dnd
  1076. '''
  1077. if (user != request.user) and (not request.admin):
  1078. abort(401)
  1079. if state not in presenceStates:
  1080. return invalidState(state)
  1081. if user not in app.cache['ustates']:
  1082. return noUser(user)
  1083. # app.logger.warning('state={}, getUserStateCombined({})={}'.format(state, user, getUserStateCombined(user)))
  1084. # if (state.lower() in ('available','away','not_set','xa','chat')) and (getUserStateCombined(user) in ('dnd')):
  1085. if (state.lower() not in ('dnd')):
  1086. result = await amiDBDel('DND', '{}'.format(user))
  1087. result = await amiSetVar('PRESENCE_STATE(CustomPresence:{})'.format(user), state)
  1088. if result is not None:
  1089. return errorReply(result)
  1090. if state.lower() in ('dnd'):
  1091. result = await amiDBPut('DND', '{}'.format(user), 'YES')
  1092. return successfullySetState(user, state)
  1093. @app.route('/users/devices')
  1094. class UsersDevices(Resource):
  1095. @authRequired
  1096. @app.response(HTTPStatus.OK, 'JSON reply with user:device map or error message')
  1097. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1098. async def get(self):
  1099. '''Returns users to device maping.
  1100. '''
  1101. if not request.admin:
  1102. abort(401)
  1103. data = {}
  1104. for user in app.cache['ustates']:
  1105. device = await getUserDevice(user)
  1106. if ((device in NONEs) or (device == user)):
  1107. device = None
  1108. else:
  1109. device = device.replace('{}&'.format(user), '')
  1110. data[user]= device
  1111. return successReply(data)
  1112. @app.route('/device/<device>/<user>/on')
  1113. @app.route('/user/<user>/<device>/on')
  1114. class UserDeviceBind(Resource):
  1115. @authRequired
  1116. @app.param('device', 'Device number to bind to', 'path')
  1117. @app.param('user', 'User to bind to device', 'path')
  1118. @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
  1119. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1120. async def get(self, device, user):
  1121. '''Binds user to device.
  1122. Both user and device numbers are checked for existance.
  1123. Any device user was previously bound to, is unbound.
  1124. Any user previously bound to device is unbound also.
  1125. '''
  1126. if (device != request.device) and (not request.admin):
  1127. abort(401)
  1128. if user not in app.cache['ustates']:
  1129. return noUser(user)
  1130. dial = await getDeviceDial(device) # Check if device exists in astdb
  1131. if dial is None:
  1132. return noDevice(device)
  1133. currentUser = await getDeviceUser(device) # Check if any user is already bound to device
  1134. if currentUser == user:
  1135. return alreadyBound(user, device)
  1136. ast = await getGlobalVars()
  1137. if currentUser not in NONEs: # If any other user is bound to device, unbind him,
  1138. result = await amiSetVar('PRESENCE_STATE(CustomPresence:{})'.format(user), 'available')
  1139. result = await amiDBDel('DND', '{}'.format(user))
  1140. await setUserDevice(currentUser, None)
  1141. if ast.QUEDEVSTATE == 'TRUE': # set device states for previous user queues
  1142. await setQueueStates(currentUser, device, 'NOT_INUSE')
  1143. await setUserHint(currentUser, None, ast) # set hints for previous user
  1144. await setDeviceUser(device, user) # Bind user to device
  1145. # If user is bound to some other devices, unbind him and set
  1146. # device states for those devices
  1147. await unbindOtherDevices(user, device, ast)
  1148. if not (await setUserHint(user, dial, ast)): # Set hints for user on new device
  1149. return hintError(user, device)
  1150. await setUserDeviceStates(user, device, ast) # Set device states for users new device
  1151. if not (await setUserDevice(user, device)): # Bind device to user
  1152. return bindError(user, device)
  1153. app.cache['usermap'][device] = user
  1154. app.cache['devicemap'][user] = device
  1155. await amiUserEvent('DeviceBound',{'device': device, 'newUser': user, 'oldUser': currentUser})
  1156. return successfullyBound(user, device)
  1157. @app.route('/device/<device>/off')
  1158. class DeviceUnBind(Resource):
  1159. @authRequired
  1160. @app.param('device', 'Device number to unbind', 'path')
  1161. @app.response(HTTPStatus.OK, 'JSON reply with fields "success" and "result"')
  1162. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1163. async def get(self, device):
  1164. '''Unbinds any user from device.
  1165. Device is checked for existance.
  1166. '''
  1167. if (device != request.device) and (not request.admin):
  1168. abort(401)
  1169. dial = await getDeviceDial(device) # Check if device exists in astdb
  1170. if dial is None:
  1171. return noDevice(device)
  1172. currentUser = await getDeviceUser(device) # Check if any user is bound to device
  1173. if currentUser in NONEs:
  1174. return noUserBound(device)
  1175. else:
  1176. result = await amiSetVar('PRESENCE_STATE(CustomPresence:{})'.format(currentUser), 'available')
  1177. result = await amiDBDel('DND', '{}'.format(currentUser))
  1178. ast = await getGlobalVars()
  1179. await setUserDevice(currentUser, None) # Unbind device from current user
  1180. if ast.QUEDEVSTATE == 'TRUE': # set device states for current user queues
  1181. await setQueueStates(currentUser, device, 'NOT_INUSE')
  1182. await setUserHint(currentUser, None, ast) # set hints for current user
  1183. await setDeviceUser(device, 'none') # Unbind user from device
  1184. del app.cache['usermap'][device]
  1185. del app.cache['devicemap'][currentUser]
  1186. await amiUserEvent('DeviceUnbound',{'device': device, 'oldUser': currentUser})
  1187. return successfullyUnbound(currentUser, device)
  1188. @app.route('/cdr')
  1189. class CDR(Resource):
  1190. @authRequired
  1191. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  1192. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  1193. @app.response(HTTPStatus.OK, 'JSON reply')
  1194. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1195. async def get(self):
  1196. '''Returns CDR data, groupped by logical call id.
  1197. All request arguments are optional.
  1198. '''
  1199. if not request.admin:
  1200. abort(401)
  1201. start = parseDatetime(request.args.get('start'))
  1202. end = parseDatetime(request.args.get('end'))
  1203. cdr = await getCDR(start, end)
  1204. return successReply(cdr)
  1205. @app.route('/cel')
  1206. class CEL(Resource):
  1207. @authRequired
  1208. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  1209. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 or YYYYMMDDhhmmss', 'query')
  1210. @app.response(HTTPStatus.OK, 'JSON reply')
  1211. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1212. async def get(self):
  1213. '''Returns CEL data, groupped by logical call id.
  1214. All request arguments are optional.
  1215. '''
  1216. if not request.admin:
  1217. abort(401)
  1218. start = parseDatetime(request.args.get('start'))
  1219. end = parseDatetime(request.args.get('end'))
  1220. cel = await getCEL(start, end)
  1221. return successReply(cel)
  1222. @app.route('/calls')
  1223. class Calls(Resource):
  1224. @authRequired
  1225. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 and YYYYMMDDhhmmss', 'query')
  1226. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 and YYYYMMDDhhmmss', 'query')
  1227. @app.response(HTTPStatus.OK, 'JSON reply')
  1228. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1229. async def get(self):
  1230. '''Returns aggregated call data JSON. Draft implementation.
  1231. All request arguments are optional.
  1232. '''
  1233. if not request.admin:
  1234. abort(401)
  1235. calls = []
  1236. start = parseDatetime(request.args.get('start'))
  1237. end = parseDatetime(request.args.get('end'))
  1238. cdr = await getCDR(start, end)
  1239. for c in cdr:
  1240. _call = {'id':c.linkedid,
  1241. 'start':c.start,
  1242. 'type': c.direction,
  1243. 'numberA': c.cnum,
  1244. 'numberB': c.dst,
  1245. 'line': c.did,
  1246. 'duration': c.duration,
  1247. 'waiting': c.waiting,
  1248. 'status':c.disposition,
  1249. 'url': c.file }
  1250. calls.append(_call)
  1251. return successReply(calls)
  1252. @app.route('/user/<user>/calls')
  1253. class UserCalls(Resource):
  1254. @authRequired
  1255. @app.param('user', 'User to query for call stats', 'path')
  1256. @app.param('end', 'End of datetime range. Defaults to now. Allowed formats are: timestamp, ISO 8601 and YYYYMMDDhhmmss', 'query')
  1257. @app.param('start', 'Start of datetime range. Defaults to end-24h. Allowed formats are: timestamp, ISO 8601 and YYYYMMDDhhmmss', 'query')
  1258. @app.param('direction', 'Calls direction, in or out. If not specified both are returned', 'query')
  1259. @app.param('limit', 'Max number of returned records, defaults to unlimited. Use offset parameter together with limit', 'query')
  1260. @app.param('offset', 'If limit is specified use offset parameter to request more results', 'query')
  1261. @app.param('order', 'Calls sort order for datetime field. ASC or DESC. Defaults to ASC', 'query')
  1262. @app.response(HTTPStatus.OK, 'JSON data {"status":status,"data":data,"message":message}')
  1263. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1264. async def get(self, user):
  1265. '''Returns user's call stats.
  1266. '''
  1267. if (user != request.user) and (not request.admin):
  1268. abort(401)
  1269. if user not in app.cache['ustates']:
  1270. return noUser(user)
  1271. cdr = await getUserCDR(user,
  1272. parseDatetime(request.args.get('start')),
  1273. parseDatetime(request.args.get('end')),
  1274. request.args.get('direction', None),
  1275. request.args.get('limit', None),
  1276. request.args.get('offset', None),
  1277. request.args.get('order', 'ASC'))
  1278. return successReply(cdr)
  1279. @app.route('/call/<call_id>')
  1280. class CallInfo(Resource):
  1281. @authRequired
  1282. @app.param('call_id', 'call_id for ', 'path')
  1283. @app.response(HTTPStatus.OK, 'JSON data {"status":status,"data":data,"message":message}')
  1284. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1285. async def get(self, call_id):
  1286. '''Returns call info.'''
  1287. call = await getCallInfo(call_id)
  1288. return successReply(call)
  1289. @app.route('/device/<device>/callback')
  1290. class DeviceCallback(Resource):
  1291. @authRequired
  1292. @app.param('device', 'Device to get/set the callback url for', 'path')
  1293. @app.param('url', 'used to set the Callback url for the device', 'query')
  1294. @app.response(HTTPStatus.OK, 'JSON data {"user":user,"state":state}')
  1295. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1296. async def get(self, device):
  1297. '''Returns and sets device's callback url.
  1298. '''
  1299. if (device != request.device) and (not request.admin):
  1300. abort(401)
  1301. url = request.args.get('url', None)
  1302. if url is not None:
  1303. await db.execute(query='REPLACE INTO callback_urls (device, url) VALUES (:device, :url)',
  1304. values={'device': device,'url': url})
  1305. else:
  1306. row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
  1307. values={'device': device})
  1308. if row is not None:
  1309. url = row['url']
  1310. return successCallbackURL(device, url)
  1311. @app.route('/group/ringing/callback')
  1312. class GroupRingingCallback(Resource):
  1313. @authRequired
  1314. @app.param('url', 'used to set the Callback url for the group ringing callback', 'query')
  1315. @app.response(HTTPStatus.OK, 'JSON data {"url":url}')
  1316. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1317. async def get(self):
  1318. '''Returns and sets groupRinging callback url.
  1319. '''
  1320. if not request.admin:
  1321. abort(401)
  1322. url = request.args.get('url', None)
  1323. if url is not None:
  1324. await db.execute(query='REPLACE INTO callback_urls (device, url) VALUES (:device, :url)',
  1325. values={'device': 'groupRinging','url': url})
  1326. else:
  1327. row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
  1328. values={'device': 'groupRinging'})
  1329. if row is not None:
  1330. url = row['url']
  1331. return successCommonCallbackURL('groupRinging', url)
  1332. @app.route('/group/answered/callback')
  1333. class GroupAnsweredCallback(Resource):
  1334. @authRequired
  1335. @app.param('url', 'used to set the Callback url for the group answered callback', 'query')
  1336. @app.response(HTTPStatus.OK, 'JSON data {"url":url}')
  1337. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1338. async def get(self):
  1339. '''Returns and sets groupAnswered callback url.
  1340. '''
  1341. if not request.admin:
  1342. abort(401)
  1343. url = request.args.get('url', None)
  1344. if url is not None:
  1345. await db.execute(query='REPLACE INTO callback_urls (device, url) VALUES (:device, :url)',
  1346. values={'device': 'groupAnswered','url': url})
  1347. else:
  1348. row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
  1349. values={'device': 'groupAnswered'})
  1350. if row is not None:
  1351. url = row['url']
  1352. return successCommonCallbackURL('groupAnswered', url)
  1353. @app.route('/queue/enter/callback')
  1354. class QueueEnterCallback(Resource):
  1355. @authRequired
  1356. @app.param('url', 'used to set the Callback url for the queue enter callback', 'query')
  1357. @app.response(HTTPStatus.OK, 'JSON data {"url":url}')
  1358. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1359. async def get(self):
  1360. '''Returns and sets queueEnter callback url.
  1361. '''
  1362. if not request.admin:
  1363. abort(401)
  1364. url = request.args.get('url', None)
  1365. if url is not None:
  1366. await db.execute(query='REPLACE INTO callback_urls (device, url) VALUES (:device, :url)',
  1367. values={'device': 'queueEnter','url': url})
  1368. else:
  1369. row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
  1370. values={'device': 'queueEnter'})
  1371. if row is not None:
  1372. url = row['url']
  1373. return successCommonCallbackURL('queueEnter', url)
  1374. @app.route('/queue/leave/callback')
  1375. class QueueLeaveCallback(Resource):
  1376. @authRequired
  1377. @app.param('url', 'used to set the Callback url for the queue leave callback', 'query')
  1378. @app.response(HTTPStatus.OK, 'JSON data {"url":url}')
  1379. @app.response(HTTPStatus.UNAUTHORIZED, 'Authorization required')
  1380. async def get(self):
  1381. '''Returns and sets queueLeave callback url.
  1382. '''
  1383. if not request.admin:
  1384. abort(401)
  1385. url = request.args.get('url', None)
  1386. if url is not None:
  1387. await db.execute(query='REPLACE INTO callback_urls (device, url) VALUES (:device, :url)',
  1388. values={'device': 'queueLeave','url': url})
  1389. else:
  1390. row = await db.fetch_one(query='SELECT url FROM callback_urls WHERE device = :device',
  1391. values={'device': 'queueLeave'})
  1392. if row is not None:
  1393. url = row['url']
  1394. return successCommonCallbackURL('queueLeave', url)
  1395. manager.connect()
  1396. app.run(loop=main_loop, host='0.0.0.0', port=app.config['PORT'])