-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathringcentral.py
138 lines (131 loc) · 4.92 KB
/
ringcentral.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import requests
import base64
import urllib
import time
import json
import os, sys
if sys.hexversion >= 0x3000000:
from dotenv import load_dotenv
load_dotenv()
if os.getenv("ENVIRONMENT") == "sandbox":
tokens_file = "tokens_sb.txt"
dotenv = load_dotenv("./environment/.env-sandbox")
else:
tokens_file = "tokens_pd.txt"
dotenv = load_dotenv("./environment/.env-production")
else:
from dotenv import Dotenv
dotenv = Dotenv(".env")
if os.getenv("ENVIRONMENT") == "sandbox":
tokens_file = "tokens_sb.txt"
dotenv = Dotenv("./environment/.env-sandbox")
else:
tokens_file = "tokens_pd.txt"
dotenv = Dotenv("./environment/.env-production")
os.environ.update(dotenv)
class RingCentral(object):
access_token = ""
def authenticate(self):
url = os.getenv("RC_SERVER_URL") + "/restapi/oauth/token"
basic = "%s:%s" % (os.getenv("RC_CLIENT_ID"), os.getenv("RC_CLIENT_SECRET"))
headers = {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept': 'application/json',
'Authorization': 'Basic ' + base64.b64encode(basic.encode('utf-8')).decode('utf-8'),
}
body = {
'grant_type': 'password',
'username': os.getenv("RC_USERNAME"),
'password': os.getenv("RC_PASSWORD")
}
if os.path.isfile(tokens_file):
file = open(tokens_file, 'r')
tokenObj = json.loads(file.read())
file.close()
expire_time = time.time() - tokenObj['timestamp']
if expire_time < tokenObj['tokens']['expires_in']:
print ("access_token not expired")
self.access_token = tokenObj['tokens']['access_token']
return
else:
print ("access_token expired")
if expire_time < tokenObj['tokens']['refresh_token_expires_in']:
print ("refresh_token not expired")
body = {
'grant_type': 'refresh_token',
'refresh_token': tokenObj['tokens']['refresh_token']
}
# authenticate
if sys.hexversion >= 0x3000000:
body = urllib.parse.urlencode(body)
else:
body = urllib.urlencode(body)
try:
res = requests.post(url, headers=headers, data=body)
if res.status_code == 200:
jsonObj = json.loads(res._content)
tokensObj = {
"tokens": jsonObj,
"timestamp": time.time()
}
file = open(tokens_file,'w')
file.write(json.dumps(tokensObj))
file.close()
self.access_token = jsonObj['access_token']
return
else:
raise ValueError(res._content)
except Exception as e:
raise ValueError(e)
# Implement GET request
def get(self, endpoint, params=None, callback=None):
try:
self.authenticate()
url = os.getenv("RC_SERVER_URL") + endpoint
if params != None:
url += "?"
for key, value in params.items():
url += "&%s=%s" % (key, value)
headers = {
'Accept': 'application/json',
'Authorization': 'Bearer ' + self.access_token
}
try:
response = requests.get(url, headers=headers)
if response.status_code == 200:
if callback is None:
return response._content
else:
callback(response._content)
else:
raise ValueError(response._content)
except Exception as e:
raise ValueError(e)
except Exception as e:
raise ValueError(e)
# Implement POST request
def post(self, endpoint, params=None, callback=None):
try:
self.authenticate()
url = os.getenv("RC_SERVER_URL") + endpoint
body = None
if params != None:
body = json.dumps(params)
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer ' + self.access_token
}
try:
response = requests.post(url, headers=headers, data=body)
if response.status_code == 200:
if callback is None:
return response._content
else:
callback(response._content)
else:
raise ValueError(response._content)
except Exception as e:
raise ValueError(e)
except Exception as e:
raise ValueError(e)