-
Notifications
You must be signed in to change notification settings - Fork 4
Open
Description
hi,
I just made a working yet incomplete version for python3, this is very quick and dirty, but i thought it might be a starting base:
###
# THECALLR webservice communication library
###
import json
import urllib.request
import urllib.error
import urllib.parse
from base64 import encodestring
from random import randint
class TheCallR(object):
_login = False
_password = False
_headers = {
"Expect": "",
"Content-Type": "application/json-rpc; charset=utf-8"
}
API_URL = "https://api.thecallr.com/"
def __init__(self, login, password, options = None):
self._login = login
self._password = password
#self.set_options(options)
""" !! Non converti du python 2 au 3
def set_options(self, options):
if isinstance(options, dict):
if options.has_key("proxy"):
self.set_proxy(options["proxy"])
def set_proxy(self, proxy):
if isinstance(proxy, basestring):
proxy_handler = urllib2.ProxyHandler({'https': proxy})
opener = urllib2.build_opener(proxy_handler)
urllib2.install_opener(opener)
else:
raise ThecallrLocalException("PROXY_NOT_STRING", 1)
"""
###
# Send a request to THECALLR webservice
###
def call(self, method, *params):
""" Idem que send, renvoit sur send
"""
self.send(method, params)
###
# Send a request to THECALLR webservice
###
def send(self, method, params = [], id = None):
self._check_auth()
json_data = json.dumps({
"id": 12, # TODO ??
"jsonrpc": "2.0",
"method": method,
"params": params
}).encode('utf-8')
b = encodestring(("%s:%s" % (self._login, self._password)).encode('utf-8')).decode().replace('\n', '')
self._headers["Authorization"] = ("Basic %s" % b)
req = urllib.request.Request(self.API_URL, json_data, self._headers)
try:
res = urllib.request.urlopen(req)
if res.code != 200:
raise ThecallrException("HTTP_CODE_ERROR", -1, {"http_code": res.code, "http_message": res.msg})
return self._parse_response(res.read())
except urllib.error.HTTPError as e:
raise ThecallrException("HTTP_CODE_ERROR", -1, {"http_code": e.code, "http_message": e.msg})
except urllib.error.URLError as e:
raise ThecallrException("HTTP_EXCEPTION", -2, {"exception": e})
def _check_auth(self):
if self._login is False or len(self._login) == 0 or self._password is False or len(self._password) == 0:
raise ThecallrLocalException("CREDENTIALS_NOT_SET", 1)
###
# Response analysis
###
def _parse_response(self, body):
try:
data = json.loads(body.decode())
if data and "result" in data.keys() and data["result"]:
return data["result"]
elif data and "error" in data.keys() and data["error"]:
raise ThecallrException(data["error"]["message"], data["error"]["code"])
else:
raise ThecallrException("INVALID_RESPONSE", -2, {"response": body})
except ValueError as e:
raise ThecallrException("INVALID_RESPONSE", -2, {"response": body})
###
# Exceptions
###
class ThecallrException(Exception):
def __init__(self, msg, code = 0, data = None):
self.msg = msg
self.code = code
self.data = data
class ThecallrLocalException(ThecallrException):
pass # ??Metadata
Metadata
Assignees
Labels
No labels