cleanups and improvements to api

This commit is contained in:
Matthew Connelly 2019-05-21 11:18:33 +01:00
parent 90fe289a1d
commit 87a1fdce4f
1 changed files with 272 additions and 199 deletions

View File

@ -1,199 +1,272 @@
# Environment var definitions # Environment var definitions
ENV_URI='TCX_SITE_URI' ENV_URI='TCX_SITE_URI'
ENV_AUTH_USER='TCX_API_AUTH_USERNAME' ENV_AUTH_USER='TCX_API_AUTH_USERNAME'
ENV_AUTH_PASS='TCX_API_AUTH_PASSWORD' ENV_AUTH_PASS='TCX_API_AUTH_PASSWORD'
class APIError(Exception): class APIError(Exception):
pass pass
class ValidationError(Exception): class ValidationError(Exception):
pass pass
class Request: class Request:
from requests import ConnectionError, exceptions from requests import ConnectionError, exceptions
def __init__(self, uri, verify): def __init__(self, uri, verify):
from requests import Session from requests import Session
self.uri=uri self.uri=uri
self.base="%s/api/{}" % uri self.base="%s/api/{}" % uri
self.last=None self.last=None
self.sess=Session() self.sess=Session()
self.sess.verify=verify self.sess.verify=verify
def get(self, api, params=None, expect=200): def get(self, api, params=None, expect=200):
try: try:
self.last=resp=self.sess.get(url=self.base.format(api), params=params) self.last=resp=self.sess.get(url=self.base.format(api), params=params)
assert (resp.status_code==expect) assert (resp.status_code==expect)
except AssertionError: except AssertionError:
raise APIError("Assertion error when handling API response; response code was %s, but expected response was %s" % (resp.status_code, expect)) raise APIError("Assertion error when handling API response; response code was %s, but expected response was %s" % (resp.status_code, expect))
except exceptions.SSLError as e: except self.exceptions.SSLError as e:
raise APIError("TLS error returned when communicating; use tls_verify=False or check leaf certs: %s" % str(e)) raise APIError("TLS error returned when communicating; use tls_verify=False or check leaf certs: %s" % str(e))
except exceptions.BaseHTTPError as e: except self.exceptions.BaseHTTPError as e:
raise APIError("HTTP error raised when communicating: %s" % str(e)) raise APIError("HTTP error raised when communicating: %s" % str(e))
except ConnectionError as e: except ConnectionError as e:
raise APIError("ConnectionError raised when communicating: %s" % str(e)) raise APIError("ConnectionError raised when communicating: %s" % str(e))
return resp return resp
def post(self, api, params, expect=200): def post(self, api, params, expect=200):
try: try:
self.last=resp=self.sess.post(url=self.base.format(api), json=params) self.last=resp=self.sess.post(url=self.base.format(api), json=params)
assert (resp.status_code==expect) assert (resp.status_code==expect)
except AssertionError: except AssertionError:
raise APIError("Assertion error when handling API response; response code was %s, but expected response was %s" % (resp.status_code, expect)) raise APIError("Assertion error when handling API response; response code was %s, but expected response was %s" % (resp.status_code, expect))
except exceptions.SSLError as e: except self.exceptions.SSLError as e:
raise APIError("TLS error returned when communicating; use tls_verify=False or check leaf certs: %s" % str(e)) raise APIError("TLS error returned when communicating; use tls_verify=False or check leaf certs: %s" % str(e))
except exceptions.BaseHTTPError as e: except self.exceptions.BaseHTTPError as e:
raise APIError("HTTP error raised when communicating: %s" % str(e)) raise APIError("HTTP error raised when communicating: %s" % str(e))
except ConnectionError as e: except ConnectionError as e:
raise APIError("ConnectionError raised when communicating: %s" % str(e)) raise APIError("ConnectionError raised when communicating: %s" % str(e))
except Exception as e: except Exception as e:
raise APIError("Other exception raised during API call: %s" % str(e)) raise APIError("Other exception raised during API call: %s" % str(e))
return resp return resp
class ReadOnlyObject(object): class BasicObject(object):
def __init__(self, parent, api): pass
self.tcx=parent class ReadOnlyObject(object):
self.api=api def __init__(self, parent, api):
def refresh(self, params={}): self.tcx=parent
self._result=self.tcx.rq.get(self.api, params=params) self.api=api
self.active=self._result.json() def refresh(self, params={}):
class TransactionalObject(object): self._result=self.tcx.rq.get(self.api, params=params)
def __init__(self, parent, api, submit='edit/save', discard='edit/cancel'): self.active=self._result.json()
self.tcx=parent class TransactionalObject(object):
self.api=api def __init__(self, parent, api, save='edit/save', discard='edit/cancel'):
self.submit=submit self.tcx=parent
self.discard=discard self.api=api
def create(self, params): self.save=save
self._result=self.tcx.rq.post(self.api, params=params) self.discard=discard
self._session=self._result.json()['Id'] def create(self, params):
self.active=self._result.json()['ActiveObject'] self._result=self.tcx.rq.post(self.api, params=params)
def submit(self, params): self._session=self._result.json()['Id']
raise ValidationError("NotImplemented error") self.active=self._result.json()['ActiveObject']
def cancel(self): def submit(self, params):
self.tcx.rq.post(self.discard, params={ raise ValidationError("NotImplemented error")
'Id':self._session}) def cancel(self):
self.tcx.rq.post(self.discard, params={
class User(TransactionalObject): 'Id':self._session})
def __init__(self, parent, params):
super().__init__(parent, 'ExtensionList/set') class Call(ReadOnlyObject):
self.params=params def __init__(self, tcx, callid):
self.load() super().__init__(tcx, 'activeCalls')
def load(self): self.params=callid
self.create(params={ def refresh(self):
'Id':self.params}) self.refresh()
parms=self.active self.timestamp=self._result.headers.get('date')
self.id=parms['Id'] res=list(filter(lambda cid: cid['Id'] == self.params, self._result.json()['list']))
self.enabled=not parms['Disabled']['_value'] assert (len(res)>0), "No call found in currently-active call list for ID %s" % self.params
self.sip_id=parms['SIPId']['_value'] assert(len(res)==1), "More than one active call found for ID %s" % self.params
#RecordCallsOption - enum res=res[0]
self.callrecs=parms['RecordCalls']['selected'] self.id=res['Id']
self.sip_host=parms['MyPhoneLocalInterface']['selected'] self.caller=res['Caller']
self.sip_host_addrs=parms['MyPhoneLocalInterface']['possibleValues'] self.callee=res['Callee']
self.sip_authid=parms['AuthId']['_value'] self.state=res['Status']
self.sip_authpw=parms['AuthPassword']['_value'] self.duration=res['Duration']
self.provision_uri=parms['MyPhoneProvLink']['_value'] self.since=res['LastChangeStatus']
self.webpw=parms['AccessPassword']['_value'] def hangup(self):
self.extension=Extension(self.tcx, self.params) self.tcx.rq.post('activeCalls/drop', params={
self.cancel() 'Id': self.params})
class Extension(ReadOnlyObject): self.params=None
def __init__(self, parent, params):
super().__init__(parent, api='ExtensionList') class User(TransactionalObject):
self.params=params def __init__(self, parent, params):
self.load() super().__init__(parent, 'ExtensionList/set')
def load(self): self.params=params
self.refresh(params=self.params) self.load()
res=self._result def load(self):
self.timestamp=res.headers.get('date') self.create(params={
res=list(filter(lambda ext: ext['Number'] == self.params, res.json()['list'])) 'Id':self.params})
assert (len(res)>0), "No extension found for: %s" % self.params parms=self.active
assert (len(res)==1), "More than one extension found for %s" % self.params self.id=parms['Id']
res=res[0] self.enabled=not parms['Disabled']['_value']
self.number=res['Number'] self.sip_id=parms['SIPId']['_value']
self.firstname=res['FirstName'] #RecordCallsOption - enum
self.surname=res['LastName'] self.callrecs=parms['RecordCalls']['selected']
self.name="%s %s" % (self.firstname, self.surname) self.sip_host=parms['MyPhoneLocalInterface']['selected']
self.dnd=res['DND'] self.sip_host_addrs=parms['MyPhoneLocalInterface']['possibleValues']
self.status=res['CurrentProfile'] self.sip_authid=parms['AuthId']['_value']
self.mail=res['Email'] self.sip_authpw=parms['AuthPassword']['_value']
self.cli=res['OutboundCallerId'] self.provision_uri=parms['MyPhoneProvLink']['_value']
self.mobile=res['MobileNumber'] self.webpw=parms['AccessPassword']['_value']
self.online=res['IsRegistered'] self.extension=Extension(self.tcx, self.params)
class PhoneSystem: self.cancel()
class System(object): class Extension(ReadOnlyObject):
class License(object): def __init__(self, parent, params, populate=True):
pass super().__init__(parent, api='ExtensionList')
class Status(object): self.params=params
pass if populate:
def __init__(self, tcx): self.load()
self.tcx=tcx def load(self):
def refresh_sysstat(self): self.refresh(params=self.params)
sysstat=self.tcx.rq.get('SystemStatus').json() res=self._result
addl=self.tcx.rq.get('SystemStatus/AdditionalStatus').json() self.timestamp=res.headers.get('date')
inroute=self.tcx.rq.get('InboundRulesList').json()['list'] res=list(filter(lambda ext: ext['Number'] == self.params, res.json()['list']))
hists=self.tcx.rq.post('SystemStatus/getDbInformation').json() assert (len(res)>0), "No extension found for: %s" % self.params
certstat=self.tcx.rq.get('SystemStatus/GetSingleStatus').json() assert (len(res)==1), "More than one extension found for %s" % self.params
self.Status.exts_online=sysstat['ExtensionsRegistered'] res=res[0]
self.Status.trunks_online=sysstat['TrunksRegistered'] self.number=res['Number']
self.Status.calls_active=sysstat['CallsActive'] self.firstname=res['FirstName']
self.Status.callrecs_bytes=addl['RecordingUsedSpace'] self.surname=res['LastName']
self.Status.diskbytes_free=sysstat['FreeDiskSpace'] self.name="%s %s" % (self.firstname, self.surname)
self.Status.membytes_free=sysstat['FreePhysicalMemory'] self.dnd=res['DND']
self.Status.banned_ips=sysstat['BlacklistedIpCount'] self.status=res['CurrentProfile']
self.Status.last_backup=sysstat['LastBackupDateTime'] self.mail=res['Email']
self.Status.sysexts_online=not sysstat['HasUnregisteredSystemExtensions'] self.cli=res['OutboundCallerId']
self.Status.services_online=not sysstat['HasNotRunningServices'] self.mobile=res['MobileNumber']
self.System.routes_out=sysstat['OutboundRules'] self.online=res['IsRegistered']
self.System.routes_in=len(inroute) class PhoneSystem:
self.System.fqdn=sysstat['FQDN'] class System(object):
self.System.webconf=sysstat['WebMeetingFQDN'] class License(object):
self.System.version=sysstat['Version'] pass
self.System.diskbytes_total=sysstat['TotalDiskSpace'] class Status(object):
self.System.membytes_total=sysstat['TotalPhysicalMemory'] pass
self.System.calls_total=hists['CallHistoryCount'] def __init__(self, tcx):
self.System.chats_total=hists['ChatMessagesCount'] self.tcx=tcx
self.System.callrecs_enabled=not addl['RecordingStopped'] self.extlist=None
self.System.callrecs_quota=addl['RecordingQuota'] def refresh_sysstat(self):
self.System.exts_total=sysstat['ExtensionsTotal'] sysstat=self.tcx.rq.get('SystemStatus').json()
self.System.trunks_total=sysstat['TrunksTotal'] self.Status.exts_online=sysstat['ExtensionsRegistered']
self.System.firebase_confed=sysstat['OwnPush'] self.Status.trunks_online=sysstat['TrunksRegistered']
self.System.backups_enabled=sysstat['BackupScheduled'] self.Status.calls_active=sysstat['CallsActive']
self.System.License.firewallsupported=certstat['Health']['Firewall'] self.Status.diskbytes_free=sysstat['FreeDiskSpace']
self.System.License.trunkssupported=certstat['Health']['Trunks'] self.Status.membytes_free=sysstat['FreePhysicalMemory']
self.System.License.phonessupported=certstat['Health']['Phones'] self.Status.banned_ips=sysstat['BlacklistedIpCount']
self.System.License.activated=sysstat['Activated'] self.Status.last_backup=sysstat['LastBackupDateTime']
self.System.License.calls=sysstat['MaxSimCalls'] self.Status.sysexts_online=not sysstat['HasUnregisteredSystemExtensions']
self.System.License.meetingcalls=sysstat['MaxSimMeetingParticipants'] self.Status.services_online=not sysstat['HasNotRunningServices']
self.System.License.supported=sysstat['Support'] self.System.routes_out=sysstat['OutboundRules']
self.System.License.expire=sysstat['ExpirationDate'] self.System.fqdn=sysstat['FQDN']
self.System.License.maintexpire=sysstat['MaintenanceExpiresAt'] self.System.webconf=sysstat['WebMeetingFQDN']
self.System.License.reseller=sysstat['ResellerName'] self.System.version=sysstat['Version']
self.System.License.key=sysstat['LicenseKey'] self.System.diskbytes_total=sysstat['TotalDiskSpace']
self.System.License.sku=sysstat['ProductCode'] self.System.membytes_total=sysstat['TotalPhysicalMemory']
self.System.License.spla=sysstat['IsSpla'] self.System.exts_total=sysstat['ExtensionsTotal']
self.System.trunks_total=sysstat['TrunksTotal']
self.System.firebase_confed=sysstat['OwnPush']
class Py3CX: self.System.backups_enabled=sysstat['BackupScheduled']
def __init__(self, uri=None, tls_verify=True): self.System.License.activated=sysstat['Activated']
from os import getenv self.System.License.calls=sysstat['MaxSimCalls']
self.uri=uri if uri is not None and uri.startswith('http') else getenv(ENV_URI, None) self.System.License.meetingcalls=sysstat['MaxSimMeetingParticipants']
assert (self.uri is not None and self.uri.startswith('http')), "Please provide URI" self.System.License.supported=sysstat['Support']
self.uname=getenv(ENV_AUTH_USER, None) self.System.License.expire=sysstat['ExpirationDate']
self.passw=getenv(ENV_AUTH_PASS, None) self.System.License.maintexpire=sysstat['MaintenanceExpiresAt']
self.rq=Request(uri=self.uri, verify=tls_verify) self.System.License.reseller=sysstat['ResellerName']
self.System.License.key=sysstat['LicenseKey']
def authenticate(self, username=None, password=None): self.System.License.sku=sysstat['ProductCode']
if username is not None and password is not None: self.System.License.spla=sysstat['IsSpla']
self.uname=username def refresh_addl(self):
self.passw=password addl=self.tcx.rq.get('SystemStatus/AdditionalStatus').json()
assert (self.uname is not None and self.passw is not None), "Authentication information needed" self.Status.callrecs_bytes=addl['RecordingUsedSpace']
rs=self.rq.post('login', params={ self.System.callrecs_enabled=not addl['RecordingStopped']
'Username': self.uname, self.System.callrecs_quota=addl['RecordingQuota']
'Password': self.passw}) def refresh_inroute(self):
self.rq.sess.headers.update({'x-xsrf-token':rs.cookies['XSRF-TOKEN']}) inroute=self.tcx.rq.get('InboundRulesList').json()['list']
self.System.routes_in=len(inroute)
@property def refresh_hists(self):
def authenticated(self): hists=self.tcx.rq.post('SystemStatus/getDbInformation', params={}).json()
try: self.System.calls_total=hists['CallHistoryCount']
self.rq.get('CurrentUser') self.System.chats_total=hists['ChatMessagesCount']
except APIError: def refresh_certified(self):
return False certstat=self.tcx.rq.get('SystemStatus/GetSingleStatus').json()
return True self.System.License.firewallsupported=certstat['Health']['Firewall']
self.System.License.trunkssupported=certstat['Health']['Trunks']
self.System.License.phonessupported=certstat['Health']['Phones']
def refresh(self):
self.refresh_addl()
self.refresh_certified()
self.refresh_hists()
self.refresh_inroute()
self.refresh_sysstat()
@property
def extensionlist(self):
if self.extlist is None:
self.extlist=ReadOnlyObject(self.tcx, api='ExtensionList')
self.extlist.refresh()
res=self.extlist._result.json()['list']
assert (len(res)>0), "No extensions found"
ret=[]
for extension in res:
this=Extension(self.tcx, params=extension['Number'], populate=False)
this.firstname=extension['FirstName']
this.surname=extension['LastName']
this.name="%s %s" % (this.firstname, this.surname)
this.dnd=extension['DND']
this.status=extension['CurrentProfile']
this.mail=extension['Email']
this.cli=extension['OutboundCallerId']
this.mobile=extension['MobileNumber']
this.online=extension['IsRegistered']
ret.append(this)
return ret
@property
def callslist(self):
if self.calllist is None:
self.calllist=ReadOnlyObject(self.tcx, api='activeCalls')
self.calllist.refresh()
res=self.calllist._result.json()['list']
if len(res)==0: return []
ret=[]
for call in res:
this=Call(self.tcx, call['Id'])
this.caller=call['Caller']
this.callee=call['Callee']
this.state=call['Status']
this.duration=res['Duration']
this.since=res['LastChangeStatus']
ret.append(this)
return ret
class Py3CX:
def __init__(self, uri=None, tls_verify=True):
from os import getenv
self.uri=uri if uri is not None and uri.startswith('http') else getenv(ENV_URI, None)
assert (self.uri is not None and self.uri.startswith('http')), "Please provide URI"
self.uname=getenv(ENV_AUTH_USER, None)
self.passw=getenv(ENV_AUTH_PASS, None)
self.rq=Request(uri=self.uri, verify=tls_verify)
def authenticate(self, username=None, password=None):
if username is not None and password is not None:
self.uname=username
self.passw=password
assert (self.uname is not None and self.passw is not None), "Authentication information needed"
rs=self.rq.post('login', params={
'Username': self.uname,
'Password': self.passw})
self.rq.sess.headers.update({'x-xsrf-token':rs.cookies['XSRF-TOKEN']})
@property
def authenticated(self):
try:
self.rq.get('CurrentUser')
except APIError:
return False
return True