formatting changes (blackening)

master
Marek Isalski 3 years ago
parent bf13265261
commit 016df8873b

@ -1,7 +1,7 @@
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2015 Sipcentric Ltd. Copyright (c) 2015 Sipcentric Ltd.
Copyright (c) 2022 Faelix Limited Copyright (c) 2022 Faelix Limited.
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

@ -1,4 +1,4 @@
#!/usr/bin/env python3 0 #!/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# sipcentric/__init__.py # sipcentric/__init__.py
@ -20,242 +20,208 @@ logger = logging.getLogger(__name__)
class Sipcentric(object): class Sipcentric(object):
def __init__(
def __init__(self, username, password, base='https://pbx.sipcentric.com/api/v1', customer='me'): self,
username,
self.username = username # Account username password,
self.password = password # Account password base="https://pbx.sipcentric.com/api/v1",
self.base = base # Base API URL (default: https://pbx.sipcentric.com/api/v1) customer="me",
self.customer = customer # Customer (default: me) ):
self.username = username # Account username
# Resources self.password = password # Account password
self.account = Account(self) self.base = base # Base API URL (default: https://pbx.sipcentric.com/api/v1)
self.callBundles = CallBundles(self) self.customer = customer # Customer (default: me)
self.recordings = Recordings(self)
self.phoneBook = PhoneBook(self) # Resources
self.timeIntervals = TimeIntervals(self) self.account = Account(self)
self.endpoints = Endpoints(self) self.callBundles = CallBundles(self)
self.phoneNumbers = PhoneNumbers(self) self.recordings = Recordings(self)
self.sms = Sms(self) self.phoneBook = PhoneBook(self)
self.creditStatus = CreditStatus(self) self.timeIntervals = TimeIntervals(self)
self.calls = Calls(self) self.endpoints = Endpoints(self)
self.sounds = Sounds(self) self.phoneNumbers = PhoneNumbers(self)
self.outgoingCallerIds = OutgoingCallerIds(self) self.sms = Sms(self)
self.creditStatus = CreditStatus(self)
self.Stream = Stream(self) self.calls = Calls(self)
self.sounds = Sounds(self)
def _request(self, uri, method='GET', data=None, params=None): self.outgoingCallerIds = OutgoingCallerIds(self)
url = self.base + '/customers/' + self.customer + '/' + uri self.stream = Stream(self)
auth = requests.auth.HTTPBasicAuth(self.username, self.password) # Basic auth def _request(self, uri, method="GET", data=None, params=None):
url = self.base + "/customers/" + self.customer + "/" + uri
if method == 'GET': auth = requests.auth.HTTPBasicAuth(self.username, self.password) # Basic auth
if params: if method == "GET":
r = requests.get(url, auth=auth, params=params, verify=True, timeout=3.000) if params:
else: r = requests.get(
r = requests.get(url, auth=auth, verify=True, timeout=3.000) url, auth=auth, params=params, verify=True, timeout=3.000
)
elif method == 'POST': else:
r = requests.get(url, auth=auth, verify=True, timeout=3.000)
headers = {'content-type': 'application/json'}
elif method == "POST":
if params: headers = {"content-type": "application/json"}
r = requests.post(url, auth=auth, headers=headers, data=json.dumps(data), params=params, verify=True, timeout=3.000) if params:
else: r = requests.post(
r = requests.post(url, auth=auth, headers=headers, data=json.dumps(data), verify=True, timeout=3.000) url,
auth=auth,
if (r.status_code == 200) or (r.status_code == 201): headers=headers,
data=json.dumps(data),
try: params=params,
verify=True,
response = r.json() timeout=3.000,
return response )
else:
except: r = requests.post(
url,
return True auth=auth,
headers=headers,
elif r.status_code == 401: data=json.dumps(data),
verify=True,
raise AuthenticationException('We couldn\'t authenticate you with the API. Make sure you are using the correct credentials from the \'Web Users\' section of the control panel. If you dont have an account, sign up for one at https://my.nimvelo.com/signup') timeout=3.000,
)
return False
if (r.status_code == 200) or (r.status_code == 201):
else: try:
response = r.json()
if r.json(): return response
except:
raise Exception('HTTP Error ' + str(r.status_code), r.json()) return True
else: elif r.status_code == 401:
raise AuthenticationException(
raise Exception('HTTP Error ' + str(r.status_code), 'Something went wrong with the request') "We couldn't authenticate you with the API. Make sure you are using the correct credentials from the 'Web Users' section of the control panel. If you dont have an account, sign up for one at https://my.nimvelo.com/signup"
)
return False return False
else:
if r.json():
raise Exception("HTTP Error " + str(r.status_code), r.json())
else:
raise Exception(
"HTTP Error " + str(r.status_code),
"Something went wrong with the request",
)
return False
class Account(object): class Account(object):
def __init__(self, parent):
self.parent = parent
self.uri = "" # Not needed for the base of the customer
def __init__(self, parent): def get(self):
return self.parent._request(self.uri)
self.parent = parent
self.uri = '' # Not needed for the base of the customer
def get(self):
return self.parent._request(self.uri)
class CallBundles(object): class CallBundles(object):
def __init__(self, parent):
self.parent = parent
self.uri = "callbundles"
def __init__(self, parent): def get(self):
return self.parent._request(self.uri)
self.parent = parent
self.uri = 'callbundles'
def get(self):
return self.parent._request(self.uri)
class Recordings(object): class Recordings(object):
def __init__(self, parent):
self.parent = parent
self.uri = "recordings"
def __init__(self, parent): def get(self):
return self.parent._request(self.uri)
self.parent = parent
self.uri = 'recordings'
def get(self):
return self.parent._request(self.uri)
class PhoneBook(object): class PhoneBook(object):
def __init__(self, parent):
self.parent = parent
self.uri = "phonebook"
def __init__(self, parent): def get(self):
return self.parent._request(self.uri)
self.parent = parent
self.uri = 'phonebook'
def get(self):
return self.parent._request(self.uri)
class TimeIntervals(object): class TimeIntervals(object):
def __init__(self, parent):
self.parent = parent
self.uri = "timeintervals"
def __init__(self, parent): def get(self):
return self.parent._request(self.uri)
self.parent = parent
self.uri = 'timeintervals'
def get(self):
return self.parent._request(self.uri)
class Endpoints(object): class Endpoints(object):
def __init__(self, parent):
self.parent = parent
self.uri = "endpoints"
def __init__(self, parent): def get(self):
return self.parent._request(self.uri)
self.parent = parent
self.uri = 'endpoints'
def get(self):
return self.parent._request(self.uri)
class PhoneNumbers(object): class PhoneNumbers(object):
def __init__(self, parent):
self.parent = parent
self.uri = "phonenumbers"
def __init__(self, parent): def get(self):
return self.parent._request(self.uri)
self.parent = parent
self.uri = 'phonenumbers'
def get(self):
return self.parent._request(self.uri)
class Sms(object): class Sms(object):
def __init__(self, parent):
self.parent = parent
self.uri = "sms"
def __init__(self, parent): def get(self):
return self.parent._request(self.uri)
self.parent = parent
self.uri = 'sms'
def get(self):
return self.parent._request(self.uri) def post(self, to=None, _from=None, body=None):
data = {"type": "smsmessage", "to": to, "from": _from, "body": body}
def post(self, to=None, _from=None, body=None): return self.parent._request(self.uri, method="POST", data=data)
data = {
'type': 'smsmessage',
'to': to,
'from': _from,
'body': body
}
return self.parent._request(self.uri, method='POST', data=data)
class CreditStatus(object): class CreditStatus(object):
def __init__(self, parent):
self.parent = parent
self.uri = "creditstatus"
def __init__(self, parent): def get(self):
return self.parent._request(self.uri)
self.parent = parent
self.uri = 'creditstatus'
def get(self):
return self.parent._request(self.uri)
class Calls(object): class Calls(object):
def __init__(self, parent):
self.parent = parent
self.uri = "calls"
def __init__(self, parent): def get(self):
return self.parent._request(self.uri)
self.parent = parent
self.uri = 'calls'
def get(self):
return self.parent._request(self.uri)
class Sounds(object): class Sounds(object):
def __init__(self, parent):
self.parent = parent
self.uri = "sounds"
def __init__(self, parent): def get(self):
return self.parent._request(self.uri)
self.parent = parent
self.uri = 'sounds'
def get(self):
return self.parent._request(self.uri)
class OutgoingCallerIds(object): class OutgoingCallerIds(object):
def __init__(self, parent):
self.parent = parent
self.uri = "outgoingcallerids"
def __init__(self, parent): def get(self):
return self.parent._request(self.uri)
self.parent = parent
self.uri = 'outgoingcallerids'
def get(self):
return self.parent._request(self.uri)
class AuthenticationException(Exception): class AuthenticationException(Exception):
pass
pass
if __name__ == '__main__': if __name__ == "__main__":
logging.error('Do not run directly, import module first!') logging.error("Do not run directly, import module first!")
sys.exit() sys.exit()

@ -10,108 +10,96 @@ import multiprocessing
import requests import requests
import time import time
import logging import logging
import simplejson as json import simplejson as json
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class Stream(object): class Stream(object):
'''Allows you to connect to the Nimvelo (Sipcentric) streaming API """Allows you to connect to the Nimvelo (Sipcentric) streaming API
and register callbacks to your own functions. and register callbacks to your own functions.
''' """
def __init__(self, parent): def __init__(self, parent):
self.parent = parent
self.parent = parent self.process = multiprocessing.Process(target=self.__run)
self.username = self.parent.username # Account username
self.process = multiprocessing.Process(target=self.__run) self.password = self.parent.password # Account password
self.base = (
self.username = self.parent.username # Account username self.parent.base + "/stream"
self.password = self.parent.password # Account password ) # Base streaming URL (default: https://pbx.sipcentric.com/api/v1/stream)
self.base = self.parent.base + '/stream' # Base streaming URL (default: https://pbx.sipcentric.com/api/v1/stream) self.heartbeat = None
self.eventsCallback = None
self.heartbeat = None self.incomingcallCallback = None
self.smsreceivedCallback = None
self.eventsCallback = None
self.incomingcallCallback = None def __proccess(self, event):
self.smsreceivedCallback = None event = json.loads(event)
logger.info("Processing event")
def __proccess(self, event): logger.debug(event)
event = json.loads(event) if event["event"] == "heartbeat":
self.heartbeat = time.time()
logger.info('Processing event') return True
logger.debug(event)
elif event["event"] == "incomingcall":
if event['event'] == 'heartbeat': if self.incomingcallCallback:
self.incomingcallCallback(event["values"])
self.heartbeat = time.time() return True
return True
elif event["event"] == "smsreceived":
elif event['event'] == 'incomingcall': if self.smsreceivedCallback:
self.smsreceivedCallback(event["values"])
if self.incomingcallCallback: return True
self.incomingcallCallback(event['values'])
return True if self.eventsCallback:
self.eventsCallback(event)
elif event['event'] == 'smsreceived': return True
if self.smsreceivedCallback: def __run(self):
self.smsreceivedCallback(event['values']) stream = "" # Used as a buffer for the stream data
return True data = False # Data is not JSON until we detect it
level = 0 # JSON object depth
if self.eventsCallback:
r = requests.get(
self.eventsCallback(event) self.base, verify=True, auth=(self.username, self.password), stream=True
return True )
def __run(self): for i in r.iter_content():
if i == "{":
stream = '' # Used as a buffer for the stream data stream += i
data = False # Data is not JSON until we detect it level += 1
level = 0 # JSON object depth data = True
r = requests.get(self.base, verify=True, auth=(self.username, self.password), stream=True) elif i == "}":
stream += i
for i in r.iter_content(): data = False
if i == '{': level -= 1
stream += i
level += 1 if level <= 0:
data = True self.__proccess(stream)
stream = ""
elif i == '}':
stream += i elif data is True:
data = False stream += i
level -= 1
def register(self, type, callback):
if level <= 0: # Register a function to a callback in the class
self.__proccess(stream) if type == "incomingcall":
stream = '' self.incomingcallCallback = callback
elif type == "smsreceived":
elif data is True: self.smsreceivedCallback = callback
stream += i elif type == "events":
self.eventsCallback = callback
def register(self, type, callback):
logger.info("Callback registered")
# Register a function to a callback in the class
if type == 'incomingcall': def connect(self):
self.incomingcallCallback = callback # Start multiprocessing thread
elif type == 'smsreceived': self.process.start()
self.smsreceivedCallback = callback logger.info("Connected")
elif type == 'events':
self.eventsCallback = callback def disconnect(self):
# Terminate multiprocessing thread
logger.info('Callback registered') self.process.terminate()
logger.info("Disconnected")
def connect(self):
# Start multiprocessing thread
self.process.start()
logger.info('Connected')
def disconnect(self):
# Terminate multiprocessing thread
self.process.terminate()
logger.info('Disconnected')

Loading…
Cancel
Save