Skip to content

Commit efa5b5b

Browse files
authored
sb2 json fetch (#417)
* edit: use typing_extensions * feat: correctly decode project data that is received as a zip file (sb2) * edit: comments
1 parent 473635d commit efa5b5b

File tree

2 files changed

+25
-8
lines changed

2 files changed

+25
-8
lines changed

scratchattach/site/browser_cookies.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
from typing import Optional, assert_never, TYPE_CHECKING
1+
from typing import Optional, TYPE_CHECKING
2+
from typing_extensions import assert_never
23
from http.cookiejar import CookieJar
34
from enum import Enum, auto
45
browsercookie_err = None

scratchattach/site/project.py

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55
import random
66
import base64
77
import time
8+
import zipfile
9+
from io import BytesIO
10+
811
from typing import Any
912
from . import user, comment, studio
1013
from ..utils import exceptions
@@ -307,17 +310,30 @@ def raw_json(self):
307310
"""
308311
try:
309312
self.update()
310-
return requests.get(
311-
f"https://projects.scratch.mit.edu/{self.id}?token={self.project_token}",
312-
timeout=10,
313-
).json()
314-
except Exception:
313+
314+
except Exception as e:
315315
raise (
316316
exceptions.FetchError(
317-
"Either the project was created with an old Scratch version, or you're not authorized for accessing it"
317+
f"You're not authorized for accessing {self}.\nException: {e}"
318318
)
319319
)
320-
320+
321+
with requests.no_error_handling():
322+
resp = requests.get(
323+
f"https://projects.scratch.mit.edu/{self.id}?token={self.project_token}",
324+
timeout=10,
325+
)
326+
327+
try:
328+
return resp.json()
329+
except json.JSONDecodeError:
330+
# I am not aware of any cases where this will not be a zip file
331+
# in the future, cache a projectbody object here and just return the json
332+
# that is fetched from there to not waste existing asset data from this zip file
333+
334+
with zipfile.ZipFile(BytesIO(resp.content)) as zipf:
335+
return json.load(zipf.open("project.json"))
336+
321337
def raw_json_or_empty(self):
322338
return self.raw_json()
323339

0 commit comments

Comments
 (0)