Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapi.py
More file actions
Latest commit
260 lines (215 loc) · 7.42 KB
/
Copy pathapi.py
File metadata and controls
260 lines (215 loc) · 7.42 KB
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
importsys
importjson
importsubprocess
importtraceback
importos.path
fromfunctoolsimportwraps
try:
frombase64importencodebytes
exceptImportError:
frombase64importencodestringasencodebytes
try:
importssl
exceptImportError:
ssl=False
PY2=sys.version_info< (3, 0)
try:
import__builtin__
str_instances= (str, __builtin__.basestring)
exceptException:
str_instances= (str, )
try:
importurllib
fromurllib.requestimportRequest, urlopen
HTTPError=urllib.error.HTTPError
URLError=urllib.error.URLError
except (AttributeError, ImportError, ValueError):
importurllib2
fromurllib2importRequest, urlopen
HTTPError=urllib2.HTTPError
URLError=urllib2.URLError
try:
from .. importeditor
from . importcert, msg, sharedasG, utils
exceptImportError:
importcert
importeditor
importmsg
importsharedasG
importutils
defget_basic_auth(host):
username=G.AUTH.get(host, {}).get('username')
secret=G.AUTH.get(host, {}).get('secret')
ifusernameisNoneorsecretisNone:
return
basic_auth= ('%s:%s'% (username, secret)).encode('utf-8')
basic_auth=encodebytes(basic_auth)
returnbasic_auth.decode('ascii').replace('\n', '')
classAPIResponse():
def__init__(self, r):
self.body=None
ifisinstance(r, bytes):
r=r.decode('utf-8')
ifisinstance(r, str_instances):
lines=r.split('\n')
self.code=int(lines[0])
ifself.code!=204:
self.body=json.loads('\n'.join(lines[1:]))
elifhasattr(r, 'code'):
# Hopefully this is an HTTPError
self.code=r.code
ifself.code!=204:
self.body=json.loads(r.read().decode("utf-8"))
elifhasattr(r, 'reason'):
# Hopefully this is a URLError
# horrible hack, but lots of other stuff checks the response code :/
self.code=500
self.body=r.reason
else:
# WFIO
self.code=500
self.body=r
msg.debug('code: %s'%self.code)
defproxy_api_request(host, url, data, method):
args= ['python', '-m', 'floo.proxy', '--host', host, '--url', url]
ifdata:
args+= ["--data", json.dumps(data)]
ifmethod:
args+= ["--method", method]
msg.log('Running ', ' '.join(args), ' (', G.PLUGIN_PATH, ')')
proc=subprocess.Popen(args, cwd=G.PLUGIN_PATH, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
(stdout, stderr) =proc.communicate()
ifstderr:
raiseIOError(stderr)
ifproc.poll() !=0:
raiseIOError(stdout)
r=APIResponse(stdout)
returnr
defuser_agent():
return'Floobits Plugin %s %s %s py-%s.%s'% (
editor.name(),
G.__PLUGIN_VERSION__,
editor.platform(),
sys.version_info[0],
sys.version_info[1]
)
defhit_url(host, url, data, method):
ifdata:
data=json.dumps(data).encode('utf-8')
msg.debug('url: ', url, ' method: ', method, ' data: ', data)
r=Request(url, data=data)
r.method=method
r.get_method=lambda: method
auth=get_basic_auth(host)
ifauth:
r.add_header('Authorization', 'Basic %s'%auth)
r.add_header('Accept', 'application/json')
r.add_header('Content-type', 'application/json')
r.add_header('User-Agent', user_agent())
cafile=os.path.join(G.BASE_DIR, 'floobits.pem')
withopen(cafile, 'wb') ascert_fd:
cert_fd.write(cert.CA_CERT.encode('utf-8'))
ifG.INSECURE_SSL:
cafile=None
returnurlopen(r, timeout=10, cafile=cafile)
defapi_request(host, url, data=None, method=None):
ifdata:
method=methodor'POST'
else:
method=methodor'GET'
ifsslisFalse:
returnproxy_api_request(host, url, data, method)
try:
r=hit_url(host, url, data, method)
exceptHTTPErrorase:
r=e
exceptURLErrorase:
msg.warn('Error hitting url ', url, ': ', e)
r=e
ifnotPY2:
msg.warn('Retrying using system python...')
returnproxy_api_request(host, url, data, method)
returnAPIResponse(r)
defcreate_workspace(host, post_data):
api_url='https://%s/api/workspace'%host
returnapi_request(host, api_url, post_data)
defdelete_workspace(host, owner, workspace):
api_url='https://%s/api/workspace/%s/%s'% (host, owner, workspace)
returnapi_request(host, api_url, method='DELETE')
defupdate_workspace(workspace_url, data):
result=utils.parse_url(workspace_url)
api_url='https://%s/api/workspace/%s/%s'% (result['host'], result['owner'], result['workspace'])
returnapi_request(result['host'], api_url, data, method='PUT')
defget_workspace_by_url(url):
result=utils.parse_url(url)
api_url='https://%s/api/workspace/%s/%s'% (result['host'], result['owner'], result['workspace'])
returnapi_request(result['host'], api_url)
defget_workspace(host, owner, workspace):
api_url='https://%s/api/workspace/%s/%s'% (host, owner, workspace)
returnapi_request(host, api_url)
defget_workspaces(host):
api_url='https://%s/api/workspaces/can/view'% (host)
returnapi_request(host, api_url)
defget_orgs(host):
api_url='https://%s/api/orgs'% (host)
returnapi_request(host, api_url)
defget_orgs_can_admin(host):
api_url='https://%s/api/orgs/can/admin'% (host)
returnapi_request(host, api_url)
defrequest_review(host, owner, workspace, description):
api_url='https://%s/api/workspace/%s/%s/review'% (host, owner, workspace)
returnapi_request(host, api_url, data={'description': description})
defsend_error(description=None, exception=None):
G.ERROR_COUNT+=1
data= {
'jsondump': {
'error_count': G.ERROR_COUNT
},
'message': {},
'dir': G.COLAB_DIR,
}
stack=''
ifG.AGENT:
data['owner'] =getattr(G.AGENT, "owner", None)
data['username'] =getattr(G.AGENT, "username", None)
data['workspace'] =getattr(G.AGENT, "workspace", None)
ifexception:
exc_info=sys.exc_info()
try:
stack=traceback.format_exception(*exc_info)
exceptException:
ifexc_info[0] isNone:
stack='No sys.exc_info()'
else:
stack="Python is rtardd"
try:
description=str(exception)
exceptException:
description="Python is rtadd"
data['message'] = {
'description': description,
'stack': stack
}
msg.log('Floobits plugin error! Sending exception report: ', data['message'])
ifdescription:
data['message']['description'] =description
ifG.ERRORS_SENT>=G.MAX_ERROR_REPORTS:
msg.warn('Already sent ', G.ERRORS_SENT, ' errors this session. Not sending any more.\n', description, exception, stack)
return
try:
# TODO: use G.AGENT.proto.host?
api_url='https://%s/api/log'% (G.DEFAULT_HOST)
r=api_request(G.DEFAULT_HOST, api_url, data)
G.ERRORS_SENT+=1
returnr
exceptExceptionase:
print(e)
defsend_errors(f):
@wraps(f)
defwrapped(*args, **kwargs):
try:
returnf(*args, **kwargs)
exceptExceptionase:
send_error(None, e)
raise
returnwrapped