-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathscratchapi.py
More file actions
executable file
·399 lines (370 loc) · 18.8 KB
/
scratchapi.py
File metadata and controls
executable file
·399 lines (370 loc) · 18.8 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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright (c) 2015 Dylan Beswick
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
# ScratchAPI 1.0
# Written by Dylan5797 [http://dylan4.com]
# _____ _ _____ ______ ___ ______
# | __ \ | | | ____|____ / _ \____ |
# | | | |_ _| | __ _ _ __ | |__ / / (_) | / /
# | | | | | | | |/ _ | _ \|___ \ / / \__ | / /
# | |__| | |_| | | (_| | | | |___) | / / / / / /
# |_____/ \__ |_|\__|_|_| |_|____/ /_/ /_/ /_/
# __/ |
# |___/
import requests as _requests
import json as _json
import socket as _socket
import hashlib as _hashlib
import os as _os
import time as _time
import webbrowser as _web
class ScratchUserSession:
def __init__(self, username, password, remember_password=False):
self.SERVER = 'scratch.mit.edu'
self.API_SERVER = 'api.scratch.mit.edu'
self.PROJECTS_SERVER = 'projects.scratch.mit.edu'
self.ASSETS_SERVER = 'assets.scratch.mit.edu'
self.CDN_SERVER = 'cdn.scratch.mit.edu'
self.CLOUD = 'cloud.scratch.mit.edu'
self.CLOUD_PORT = 531
self.lib.utils.request = self._request
self.lib.set.username = username
self.lib.set.password = None
self.lib.set.password_remembered = remember_password
if remember_password:
self.lib.set.password = password
self.lib.utils.session = _requests.session()
self.tools.verify_session = self._tools_verifySession
self.tools.update = self._tools_update
self.tools.reload_session = self._tools_reload_session
self.projects.get = self._projects_getProject
self.projects.set = self._projects_setProject
self.projects.comment = self._projects_comment
self.projects.get_meta = self._projects_get_meta
self.projects.get_remix_data = self._projects_get_remixtree
self.backpack.get = self._backpack_getBackpack
self.backpack.set = self._backpack_setBackpack
self.userpage.set_bio = self._userpage_setBio
self.userpage.set_status = self._userpage_setStatus
self.userpage.toggle_comments = self._userpage_toggleComments
self.users.follow = self._users_follow
self.users.unfollow = self._users_unfollow
self.users.get_message_count = self._users_get_message_count
self.users.comment = self._users_comment
self.messages.get_message_count = self._users_get_message_count
self.messages.get_message_html = self._get_message_html
self.studios.comment = self._studios_comment
self.studios.get_meta = self._studios_get_meta
self.cloud.set_var = self._cloud_setvar
self.cloud.create_var = self._cloud_makevar
self.cloud.get_var = self._cloud_getvar
self.cloud.get_vars = self._cloud_getvars
self.cloud.rename_var = self._cloud_rename_var
self.cloud.delete_var = self._cloud_delete_var
self.HEADERS = {'X-Requested-With': 'XMLHttpRequest', 'Referer':'https://scratch.mit.edu/'}
self.lib.utils.request(path='/csrf_token/', update=False)
self.HEADERS['Cookie'] = 'scratchcsrftoken=' + self.lib.utils.session.cookies.get('scratchcsrftoken') + '; scratchlanguage=en'
self.HEADERS['X-CSRFToken'] = self.lib.utils.session.cookies.get('scratchcsrftoken')
self.lib.utils.request(path='/login/', method='post', update=False, payload=_json.dumps({'username': username, 'password': password, 'csrftoken':self.lib.utils.session.cookies.get('scratchcsrftoken'), 'csrfmiddlewaretoken':self.lib.utils.session.cookies.get('scratchcsrftoken'),'captcha_challenge':'','captcha_response':'','embed_captcha':False,'timezone':'America/New_York'}))
self.tools.update()
def _projects_getProject(self, projectId):
return self.lib.utils.request(path='/internalapi/project/' + projectId + '/get/', server=self.PROJECTS_SERVER).json()
def _projects_setProject(self, projectId, payload):
return self.lib.utils.request(server=self.PROJECTS_SERVER, path='/internalapi/project/' + projectId + '/set/', payload=_json.dumps(payload), method='post')
def _projects_get_meta(self, projid):
return self.lib.utils.request(path='/api/v1/project/' + str(projid) + '/?format=json').json()
def _projects_get_remixtree(self, projid):
return self.lib.utils.request(path='/projects/' + str(projid) + '/remixtree/bare/').json()
def _tools_verifySession(self):
return self.lib.utils.request(path='/messages/ajax/get-message-count/', port=None).status_code == 200
def _tools_reload_session(self, password=None, remember_password=None):
if remember_password == None:
remember_password = self.lib.set.password_remembered
if (password == None) and (not self.lib.set.password_remembered):
raise AttributeError('Password not stored in class (use ScratchUserSesssion(\'User\', \'Password\', remember_password=True) to remember password, or supply your password in ScratchUserSession.tools.reload_session())')
if password == None:
password = self.lib.set.password
self.__init__(self.lib.set.username, password, remember_password=remember_password)
def _backpack_getBackpack(self):
return self.lib.utils.request(path='/internalapi/backpack/' + self.lib.set.username + '/get/').json()
def _backpack_setBackpack(self, payload):
return self.lib.utils.request(server=self.CDN_SERVER, path='/internalapi/backpack/' + self.lib.set.username + '/set/', method="post", payload=payload)
def _userpage_setStatus(self, payload):
p2 = self.lib.utils.request(path='/site-api/users/all/' + self.lib.set.username).json()
p = {}
for i in p2:
if i in ['comments_allowed', 'id', 'status', 'thumbnail_url', 'userId', 'username']:
p[i] = p2[i]
p['status'] = payload
return self.lib.utils.request(path='/site-api/users/all/' + self.lib.set.username, method="put", payload=_json.dumps(p))
def _userpage_toggleComments(self):
return self.lib.utils.request(path='/site-api/comments/user/' + self.lib.set.username + '/toggle-comments/', method="put", payload=_json.dumps(p))
def _userpage_setBio(self, payload):
p2 = self.lib.utils.request(path='/site-api/users/all/' + self.lib.set.username).json()
p = {}
for i in p2:
if i in ['comments_allowed', 'id', 'bio', 'thumbnail_url', 'userId', 'username']:
p[i] = p2[i]
p['bio'] = payload
return self.lib.utils.request(path='/site-api/users/all/' + self.lib.set.username, method="put", payload=_json.dumps(p))
def _users_get_meta(self, usr):
return self.lib.utils.request(path='/users/' + usr, server=self.API_SERVER).json()
def _users_follow(self, usr):
return self.lib.utils.request(path='/site-api/users/followers/' + usr + '/add/?usernames=' + self.lib.set.username, method='PUT')
def _users_unfollow(self, usr):
return self.lib.utils.request(path='/site-api/users/followers/' + usr + '/remove/?usernames=' + self.lib.set.username, method='PUT')
def _users_comment(self, user, comment):
return self.lib.utils.request(path='/site-api/comments/user/' + user + '/add/', method='POST', payload=_json.dumps({"content":comment,"parent_id":'',"commentee_id":''}))
def _studios_comment(self, studioid, comment):
return self.lib.utils.request(path='/site-api/comments/gallery/' + str(studioid) + '/add/', method='POST', payload=_json.dumps({"content":comment,"parent_id":'',"commentee_id":''}))
def _studios_get_meta(self, studioid):
return self.lib.utils.request(path='/site-api/galleries/all/' + str(studioid)).json()
def _studios_invite(self, studioid, user):
return self.lib.utils.request(path='/site-api/users/curators-in/' + str(studioid) + '/invite_curator/?usernames=' + user, method='PUT')
def _projects_comment(self, projid, comment):
return self.lib.utils.request(path='/site-api/comments/project/' + str(projid) + '/add/', method='POST', payload=_json.dumps({"content":comment,"parent_id":'',"commentee_id":''}))
def _cloud_setvar(self, var, value, projId):
return self._cloud_send('set', projId, {'name': '☁ ' + var, 'value': value})
def _cloud_makevar(self, var, value, projId):
return self._cloud_send('create', projId, {'name': '☁ ' + var})
def _cloud_rename_var(self, oldname, newname, projId):
self._cloud_send('rename', projId, {'name': '☁ ' + oldname, 'new_name': '☁ ' + newname})
def _cloud_delete_var(self, name, projId):
self._cloud_send('delete', projId, {'name':'☁ ' + name})
def _cloud_getvar(self, var, projId):
return self._cloud_getvars(projId)[var]
def _cloud_getvars(self, projId):
dt = self.lib.utils.request(path='/varserver/' + str(projId)).json()['variables']
vardict = {}
for x in dt:
xn = x['name']
if xn.startswith('☁ '):
vardict[xn[2:]] = x['value']
else:
vardict[xn] = x['value']
return vardict
def _cloud_send(self, method, projId, options):
cloudToken = self.lib.utils.request(method='GET', path='/projects/' + str(projId) + '/cloud-data.js').text.rsplit('\n')[-28].replace(' ', '')[13:49]
bc = _hashlib.md5()
bc.update(cloudToken.encode())
data = {
"token": cloudToken,
"token2": bc.hexdigest(),
"project_id": str(projId),
"method": str(method),
"user": self.lib.set.username,
}
data.update(options)
return self.lib.utils.request(method='POST', path='/varserver', payload=_json.dumps(data))
def _tools_update(self):
self.lib.set.csrf_token = self.lib.utils.session.cookies.get('scratchcsrftoken')
self.lib.set.sessions_id = self.lib.utils.session.cookies.get('scratchsessionsid')
self.HEADERS['Cookie'] = 'scratchcsrftoken=' + self.lib.utils.session.cookies.get_dict()['scratchcsrftoken'] + '; scratchsessionsid=' + self.lib.utils.session.cookies.get('scratchsessionsid') + '; scratchlanguage=en'
self.HEADERS['X-CSRFToken'] = self.lib.utils.session.cookies.get('scratchcsrftoken')
def _assets_get(self, md5):
return self.lib.utils.request(path='/internalapi/asset/' + md5 + '/get/', server=self.ASSETS_SERVER).content
def _assets_set(self, md5, content, content_type=None):
if not content_type:
if _os.path.splitext(md5)[-1] == '.png':
content_type = 'image/png'
elif _os.path.splitext(md5)[-1] == '.svg':
content_type = 'image/svg+xml'
elif _os.path.splitext(md5)[-1] == '.wav':
content_type = 'audio/wav'
else:
content_type = 'text/plain'
headers = {'Content-Length':str(len(content)),
'Origin':'https://cdn.scratch.mit.edu',
'Content-Type':content_type,
'Referer':'https://cdn.scratch.mit.edu/scratchr2/static/__cc77646ad8a4b266f015616addd66756__/Scratch.swf'}
return self.lib.utils.request(path='/internalapi/asset/' + md5 + '/set/', method='POST', server=self.ASSETS_SERVER, payload=content)
def _users_get_message_count(self, user=None):
if user == None:
user = self.lib.set.username
return self.lib.utils.request(path='/proxy/users/' + user + '/activity/count', server=self.API_SERVER).json()['msg_count']
def _get_message_html(self):
return self.lib.utils.request(path='/messages/')
def _request(self, **options):
headers = {}
for x in self.HEADERS:
headers[x] = self.HEADERS[x]
method = "get"
server = self.SERVER
port = ''
update = True
retry = 3
if 'method' in options:
method = options['method']
if 'server' in options:
server = options['server']
if 'payload' in options:
headers['Content-Length'] = len(str(options['payload']))
if 'port' in options:
if options['port'] == None:
port = ''
else:
port = ':' + str(options['port'])
if 'update' in options:
if options['update'] == True:
self.tools.update()
else:
update = False
else:
self.tools.update()
if 'headers' in options:
headers.update(options['headers'])
if 'retry' in options:
retry = options['retry']
server = 'https://' + server
headers = {x:str(headers[x]) for x in headers}
def request():
if 'payload' in options:
return getattr(self.lib.utils.session, method.lower())(server + port + options['path'], data=options['payload'], headers=headers)
else:
return getattr(self.lib.utils.session, method.lower())(server + port + options['path'], headers=headers)
success = False
for x in range(0, retry):
try:
r = request()
except _requests.exceptions.BaseHTTPError:
continue
except AttributeError:
raise ValueError('Unknown HTTP method')
else:
success = True
break
if not success:
raise ConnectionError('Connection failed on all ' + str(retry) + ' attempts')
if update:
self.tools.update()
return r
class lib:
class set: pass
class utils: pass
class tools: pass
class projects: pass
class backpack: pass
class userpage: pass
class users: pass
class messages: pass
class studios: pass
class cloud: pass
class CloudSession:
def __init__(self, projectId, session):
if type(session) == ScratchUserSession:
self._scratch = session
else:
self._scratch = ScratchUserSession(session[0], session[1])
self._user = self._scratch.lib.set.username
self._projectId = projectId
self._cloudId = self._scratch.lib.set.sessions_id
self._token = self._scratch.lib.utils.request(method='GET', path='/projects/' + str(self._projectId) + '/cloud-data.js').text.rsplit('\n')[-28].replace(' ', '')[13:49]
md5 = _hashlib.md5()
md5.update(self._cloudId.encode())
self._reset_last = _time.time()
self._reset = True
self._reset_interval = 300
self._rollover = []
self._md5token = md5.hexdigest()
self._connection = _socket.create_connection((self._scratch.CLOUD, self._scratch.CLOUD_PORT))
self._send('handshake', {})
def _send(self, method, options):
if self._reset:
if _time.time() > (self._reset_last + self._reset_interval):
reset_interval = self._reset_interval
self.__init__(self._projectId, self._scratch)
self._reset_interval = reset_interval
obj = {
'token': self._token,
'token2': self._md5token,
'user': self._user,
'project_id': str(self._projectId),
'method': method
}
obj.update(options)
ob = (_json.dumps(obj) + '\r\n').encode('utf-8')
try:
self._connection.send(ob)
except BrokenPipeError:
self.__init__(self._projectId, self._scratch)
self._connection.send(ob)
md5 = _hashlib.md5()
md5.update(self._md5token.encode())
self._md5token = md5.hexdigest()
def set_var(self, name, value):
self._send('set', {'name': '☁ ' + name, 'value': value})
def create_var(self, name, value=None):
if value == None:
value = 0
self._send('create', {'name': '☁ ' + name, 'value':value})
def rename_var(self, oldname, newname):
self._send('rename', {'name': '☁ ' + oldname, 'new_name': '☁ ' + newname})
def delete_var(self, name):
self._send('delete', {'name':'☁ ' + name})
def get_var(self, name):
return self._scratch.cloud.get_var(name, self._projectId)
def get_vars(self):
return self._scratch.cloud.get_vars(self._projectId)
def get_updates(self, timeout, max_count=10):
count = 0
updates = []
self._connection.settimeout(timeout)
while count < max_count:
data = ''.encode('utf-8')
while True:
try:
data = data + self._connection.recv(4096)
if data[-1] == 10:
break
self._connection.settimeout(0.1)
except:
break
if not data:
break
self._connection.settimeout(0.01)
if data[0] == 123:
self._rollover = []
data = self._rollover + data.decode('utf-8').split('\n')
if data[-1]:
self._rollover = [data[-1]]
else:
self._rollover = []
data = data[:-1]
for line in data:
if line:
try:
line = _json.loads(line)
name = line['name']
value = line['value']
if name.startswith('☁ '):
updates.append((name[2:], value))
else:
updates.append((name, value))
count = count + 1
except:
continue
self._connection.settimeout(None)
return updates
def get_new_values(self, timeout, max_values=10):
nv = {}
for x in self.get_updates(timeout, max_values):
nv[x[0]] = x[1]
return nv
class _docs_view():
def __call__(self):
_web.open("https://github.com/Dylan5797/scratchapi/wiki/")
def __repr__(self):
return "See https://github.com/Dylan5797/scratchapi/wiki/ or call scratchapi.__doc__()"
__doc__ = _docs_view()