forked from TimMcCool/scratchattach
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser.py
More file actions
1275 lines (1087 loc) · 47.2 KB
/
user.py
File metadata and controls
1275 lines (1087 loc) · 47.2 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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""User class"""
from __future__ import annotations
import json
import random
import re
import string
import warnings
from typing import Union, cast, Optional, TypedDict
from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum
from typing_extensions import deprecated
from bs4 import BeautifulSoup, Tag
from ._base import BaseSiteComponent
from scratchattach.eventhandlers import message_events
from scratchattach.utils import commons
from scratchattach.utils import exceptions
from scratchattach.utils.commons import headers
from scratchattach.utils.requests import requests
from . import project
from . import studio
from . import forum
from . import comment
from . import activity
from . import classroom
from . import typed_dicts
from . import session
class Rank(Enum):
"""
Possible ranks in scratch
"""
NEW_SCRATCHER = 0
SCRATCHER = 1
SCRATCH_TEAM = 2
class _OcularStatusMeta(TypedDict):
updated: str
updatedBy: str
class _OcularStatus(TypedDict):
_id: str
name: str
status: str
color: str
meta: _OcularStatusMeta
class Verificator:
def __init__(self, user: User, project_id: int):
self.project = user._make_linked_object(
"id", project_id, project.Project, exceptions.ProjectNotFound
)
self.projecturl = self.project.url
self.code = "".join(random.choices(string.ascii_letters + string.digits, k=8))
self.username = user.username
def check(self) -> bool:
return bool(
list(
filter(
lambda x: x.author_name == self.username
and (
x.content == self.code
or x.content.startswith(self.code)
or x.content.endswith(self.code)
),
self.project.comments(),
)
)
)
@dataclass
class User(BaseSiteComponent[typed_dicts.UserDict]):
"""
Represents a Scratch user.
Attributes:
:.join_date:
:.about_me:
:.wiwo: Returns the user's 'What I'm working on' section
:.country: Returns the country from the user profile
:.icon_url: Returns the link to the user's pfp (90x90)
:.id: Returns the id of the user
:.scratchteam: Retuns True if the user is in the Scratch team
:.update(): Updates the attributes
"""
username: str = field(kw_only=True, default="")
join_date: str = field(kw_only=True, default="")
about_me: str = field(kw_only=True, default="")
wiwo: str = field(kw_only=True, default="")
country: str = field(kw_only=True, default="")
icon_url: str = field(kw_only=True, default="")
id: int = field(kw_only=True, default=0)
scratchteam: bool = field(kw_only=True, repr=False, default=False)
is_member: bool = field(kw_only=True, repr=False, default=False)
has_ears: bool = field(kw_only=True, repr=False, default=False)
_classroom: tuple[bool, Optional[classroom.Classroom]] = field(
init=False, default=(False, None)
)
_headers: dict[str, str] = field(init=False, default_factory=headers.copy)
_cookies: dict[str, str] = field(init=False, default_factory=dict)
_json_headers: dict[str, str] = field(init=False, default_factory=dict)
_session: Optional[session.Session] = field(kw_only=True, default=None)
def __str__(self):
return f"-U {self.username}"
@property
def status(self) -> str:
return self.wiwo
@property
def bio(self) -> str:
return self.about_me
@property
def icon(self) -> bytes:
with requests.no_error_handling():
return requests.get(self.icon_url).content
@property
def name(self) -> str:
return self.username
def __post_init__(self):
# Info on how the .update method has to fetch the data:
self.update_function = requests.get
self.update_api = f"https://api.scratch.mit.edu/users/{self.username}"
# cache value for classroom getter method (using @property)
# first value is whether the cache has actually been set (because it can be None), second is the value itself
# self._classroom
# Headers and cookies:
if self._session is not None:
self._headers = self._session.get_headers()
self._cookies = self._session.get_cookies()
# Headers for operations that require accept and Content-Type fields:
self._json_headers = dict(self._headers)
self._json_headers["accept"] = "application/json"
self._json_headers["Content-Type"] = "application/json"
def _update_from_dict(self, data: Union[dict, typed_dicts.UserDict]):
data = cast(typed_dicts.UserDict, data)
self.id = data.get("id", self.id)
self.username = data.get("username", self.username)
self.scratchteam = data.get("scratchteam", self.scratchteam)
if history := data.get("history"):
self.join_date = history["joined"]
if profile := data.get("profile"):
self.about_me = profile["bio"]
self.wiwo = profile["status"]
self.country = profile["country"]
self.icon_url = profile["images"]["90x90"]
self.is_member = bool(profile.get("membership_label", False))
self.has_ears = bool(profile.get("membership_avatar_badge", False))
return True
def _assert_permission(self):
self._assert_auth()
if self._session.username != self.username:
raise exceptions.Unauthorized(
"You need to be authenticated as the profile owner to do this."
)
@property
def url(self):
return f"https://scratch.mit.edu/users/{self.username}"
def __rich__(self):
from rich.panel import Panel
from rich.table import Table
from rich import box
from rich.markup import escape
featured_data = self.featured_data() or {}
ocular_data = self.ocular_status()
ocular = "No ocular status"
if status := ocular_data.get("status"):
color_str = ""
color_data = ocular_data.get("color")
if color_data is not None:
color_str = f"[{color_data}] ⬤ [/]"
ocular = f"[i]{escape(status)}[/]{color_str}"
_classroom = self.classroom
url = f"[link={self.url}]{escape(self.username)}[/]"
info = Table(box=box.SIMPLE)
info.add_column(url, overflow="fold")
info.add_column(f"#{self.id}", overflow="fold")
info.add_row("Joined", escape(self.join_date))
info.add_row("Country", escape(self.country))
info.add_row("Messages", str(self.message_count()))
info.add_row(
"Class", str(_classroom.title if _classroom is not None else "None")
)
desc = Table("Profile", ocular, box=box.SIMPLE)
desc.add_row("About me", escape(self.about_me))
desc.add_row("Wiwo", escape(self.wiwo))
desc.add_row(
escape(featured_data.get("label", "Featured Project")),
escape(str(self.connect_featured_project())),
)
ret = Table.grid(expand=True)
ret.add_column(ratio=1)
ret.add_column(ratio=3)
ret.add_row(Panel(info, title=url), Panel(desc, title="Description"))
return ret
def connect_featured_project(self) -> Optional[project.Project]:
data = self.featured_data() or {}
if pid := data.get("id"):
return self._session.connect_project(int(pid))
if projs := self.projects(limit=1):
return projs[0]
return None
@property
def classroom(self) -> classroom.Classroom | None:
"""
Get a user's associated classroom, and return it as a `scratchattach.classroom.Classroom` object.
If there is no associated classroom, returns `None`
"""
if not self._classroom[0]:
with requests.no_error_handling():
resp = requests.get(f"https://scratch.mit.edu/users/{self.username}/")
soup = BeautifulSoup(resp.text, "html.parser")
details = soup.find("p", {"class": "profile-details"})
if details is None:
# No details, e.g. if the user is banned
return None
assert isinstance(details, Tag)
class_name, class_id, is_closed = None, None, False
for a in details.find_all("a"):
if not isinstance(a, Tag):
continue
href = str(a.get("href"))
if re.match(r"/classes/\d*/", href):
class_name = a.text.strip()[len("Student of: ") :]
is_closed = bool(
re.search(r"\n *\(ended\)", class_name)
) # as this has a \n, we can be sure
if is_closed:
class_name = re.sub(r"\n *\(ended\)", "", class_name).strip()
class_id = int(href.split("/")[2])
break
if class_name:
self._classroom = True, classroom.Classroom(
_session=self._session,
id=class_id or 0,
title=class_name,
is_closed=is_closed,
)
else:
self._classroom = True, None
return self._classroom[1]
def does_exist(self) -> Optional[bool]:
"""
Returns:
boolean : True if the user exists, False if the user is deleted, None if an error occured
"""
with requests.no_error_handling():
status_code = requests.get(
f"https://scratch.mit.edu/users/{self.username}/"
).status_code
if status_code == 200:
return True
elif status_code == 404:
return False
return None
# Will maybe be deprecated later, but for now still has its own purpose.
# @deprecated("This function is partially deprecated. Use user.rank() instead.")
def is_new_scratcher(self):
"""
Returns:
boolean : True if the user has the New Scratcher status, else False
"""
try:
with requests.no_error_handling():
res = requests.get(
f"https://scratch.mit.edu/users/{self.username}/"
).text
group = res[res.rindex('<span class="group">') :][:70]
return "new scratcher" in group.lower()
except Exception as e:
warnings.warn(f"Caught exception {e=}")
return None
def message_count(self):
return json.loads(
requests.get(
f"https://api.scratch.mit.edu/users/{self.username}/messages/count/?cachebust={random.randint(0,10000)}",
headers={
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.3c6 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36",
},
).text
)["count"]
def featured_data(self):
"""
Returns:
dict: Gets info on the user's featured project and featured label (like "Featured project", "My favorite things", etc.)
"""
try:
response = requests.get(
f"https://scratch.mit.edu/site-api/users/all/{self.username}/"
).json()
return {
"label": response["featured_project_label_name"],
"project": dict(
id=str(response["featured_project_data"]["id"]),
author=response["featured_project_data"]["creator"],
thumbnail_url="https://"
+ response["featured_project_data"]["thumbnail_url"][2:],
title=response["featured_project_data"]["title"],
),
}
except Exception:
return None
def unfollowers(self) -> list[User]:
"""
Get all unfollowers by comparing API response and HTML response.
NOTE: This method can take a long time to run.
Based on https://juegostrower.github.io/unfollowers/
"""
follower_count = self.follower_count()
# regular followers
usernames = []
for i in range(1, 2 + follower_count // 60):
with requests.no_error_handling():
resp = requests.get(
f"https://scratch.mit.edu/users/{self.username}/followers/",
params={"page": i},
)
soup = BeautifulSoup(resp.text, "html.parser")
usernames.extend(span.text.strip() for span in soup.select("span.title"))
# api response contains all-time followers, including deleted and unfollowed
unfollowers = []
for offset in range(0, follower_count, 40):
unfollowers.extend(
user
for user in self.followers(offset=offset, limit=40)
if user.username not in usernames
)
return unfollowers
def unfollower_usernames(self) -> list[str]:
return [user.username for user in self.unfollowers()]
def follower_count(self):
with requests.no_error_handling():
text = requests.get(
f"https://scratch.mit.edu/users/{self.username}/followers/",
headers=self._headers,
).text
return commons.webscrape_count(text, "Followers (", ")")
def following_count(self):
with requests.no_error_handling():
text = requests.get(
f"https://scratch.mit.edu/users/{self.username}/following/",
headers=self._headers,
).text
return commons.webscrape_count(text, "Following (", ")")
def followers(self, *, limit=40, offset=0):
"""
Returns:
list<scratchattach.user.User>: The user's followers as list of scratchattach.user.User objects
"""
response = commons.api_iterative(
f"https://api.scratch.mit.edu/users/{self.username}/followers/",
limit=limit,
offset=offset,
)
return commons.parse_object_list(response, User, self._session, "username")
def follower_names(self, *, limit=40, offset=0):
"""
Returns:
list<str>: The usernames of the user's followers
"""
return [i.name for i in self.followers(limit=limit, offset=offset)]
def following(self, *, limit=40, offset=0):
"""
Returns:
list<scratchattach.user.User>: The users that the user is following as list of scratchattach.user.User objects
"""
response = commons.api_iterative(
f"https://api.scratch.mit.edu/users/{self.username}/following/",
limit=limit,
offset=offset,
)
return commons.parse_object_list(response, User, self._session, "username")
def following_names(self, *, limit=40, offset=0):
"""
Returns:
list<str>: The usernames of the users the user is following
"""
return [i.name for i in self.following(limit=limit, offset=offset)]
def is_following(self, user: str):
"""
Returns:
boolean: Whether the user is following the user provided as argument
"""
offset = 0
following = False
while True:
try:
following_names = self.following_names(limit=20, offset=offset)
if user in following_names:
following = True
break
if not following_names:
break
offset += 20
except Exception as e:
print(f"Warning: API error when performing following check: {e=}")
return following
return following
def is_followed_by(self, user):
"""
Returns:
boolean: Whether the user is followed by the user provided as argument
"""
offset = 0
followed = False
while True:
try:
followed_names = self.follower_names(limit=20, offset=offset)
if user in followed_names:
followed = True
break
if not followed_names:
break
offset += 20
except Exception as e:
print(f"Warning: API error when performing following check: {e=}")
return followed
return followed
def is_followed_by_me(self):
"""
You can only use this function if this object was created using :meth:`scratchattach.session.Session.connect_user`
Returns:
boolean: Whether the user is followed by the user currently logged in.
"""
self._assert_auth()
with requests.no_error_handling():
resp = requests.get(
f"https://scratch.mit.edu/users/{self.username}/",
headers=self._headers,
cookies=self._cookies,
)
soup = BeautifulSoup(resp.text, "html.parser")
follow_btn = soup.select_one("div.follow-button")
if not follow_btn:
print("Warning: follow button not found in page.")
return False # defualt to not followed
data_control = follow_btn.get("data-control")
return data_control == 'unfollow' # True if unfollow, False if not
def project_count(self):
with requests.no_error_handling():
text = requests.get(
f"https://scratch.mit.edu/users/{self.username}/projects/",
headers=self._headers,
).text
return commons.webscrape_count(text, "Shared Projects (", ")")
def studio_count(self):
with requests.no_error_handling():
text = requests.get(
f"https://scratch.mit.edu/users/{self.username}/studios/",
headers=self._headers,
).text
return commons.webscrape_count(text, "Studios I Curate (", ")")
def studios_following_count(self):
with requests.no_error_handling():
text = requests.get(
f"https://scratch.mit.edu/users/{self.username}/studios_following/",
headers=self._headers,
).text
return commons.webscrape_count(text, "Studios I Follow (", ")")
def studios(self, *, limit=40, offset=0) -> list[studio.Studio]:
_studios = commons.api_iterative(
f"https://api.scratch.mit.edu/users/{self.username}/studios/curate",
limit=limit,
offset=offset,
)
studios = []
for studio_dict in _studios:
_studio = studio.Studio(_session=self._session, id=studio_dict["id"])
_studio._update_from_dict(studio_dict)
studios.append(_studio)
return studios
def projects(self, *, limit=40, offset=0) -> list[project.Project]:
"""
Returns:
list<projects.projects.Project>: The user's shared projects
"""
_projects = commons.api_iterative(
f"https://api.scratch.mit.edu/users/{self.username}/projects/",
limit=limit,
offset=offset,
_headers=self._headers,
)
for p in _projects:
p["author"] = {"username": self.username}
return commons.parse_object_list(_projects, project.Project, self._session)
def loves(
self, *, limit=40, offset=0, get_full_project: bool = False
) -> list[project.Project]:
"""
Returns:
list<projects.projects.Project>: The user's loved projects
"""
# We need to use beautifulsoup webscraping so we cant use the api_iterative function
if offset < 0:
raise exceptions.BadRequest("offset parameter must be >= 0")
if limit < 0:
raise exceptions.BadRequest("limit parameter must be >= 0")
# There are 40 projects on display per page
# So the first page you need to view is 1 + offset // 40
# (You have to add one because the first page is idx 1 instead of 0)
# The final project to view is at idx offset + limit - 1
# (You have to -1 because the index starts at 0)
# So the page number for this is 1 + (offset + limit - 1) // 40
# But this is a range so we have to add another 1 for the second argument
pages = range(1 + offset // 40, 2 + (offset + limit - 1) // 40)
_projects = []
for page in pages:
# The index of the first project on page #n is just (n-1) * 40
first_idx = (page - 1) * 40
with requests.no_error_handling():
page_content = requests.get(
f"https://scratch.mit.edu/projects/all/{self.username}/loves/"
f"?page={page}",
headers=self._headers,
).content
soup = BeautifulSoup(page_content, "html.parser")
# We need to check if we are out of bounds
# If we are, we can jump out early
# This is detectable if Scratch gives you a '404'
# We can't just detect if the 404 text is within the whole of the page content
# because it would break if someone made a project with that name
# This page only uses <h1> tags for the 404 text, so we can just use a soup for those
h1_tag = soup.find("h1")
if h1_tag is not None:
# Just to confirm that it's a 404, in case I am wrong. It can't hurt
if "Whoops! Our server is Scratch'ing its head" in h1_tag.text:
break
# Each project element is a list item with the class name 'project thumb item' so we can just use that
for i, project_element in enumerate(
soup.find_all("li", {"class": "project thumb item"})
):
# Remember we only want certain projects:
# The current project idx = first_idx + i
# We want to start at {offset} and end at {offset + limit}
# So the offset <= current project idx <= offset + limit
if offset <= first_idx + i <= offset + limit:
# Each of these elements provides:
# A project id
# A thumbnail link (no need to webscrape this)
# A title
# An Author (called an owner for some reason)
assert isinstance(project_element, Tag)
project_anchors = project_element.find_all("a")
# Each list item has three <a> tags, the first two linking the project
# 1st contains <img> tag
# 2nd contains project title
# 3rd links to the author & contains their username
# This function is pretty handy!
# I'll use it for an id from a string like: /projects/1070616180/
first_anchor = project_anchors[0]
second_anchor = project_anchors[1]
third_anchor = project_anchors[2]
assert isinstance(first_anchor, Tag)
assert isinstance(second_anchor, Tag)
assert isinstance(third_anchor, Tag)
project_id = commons.webscrape_count(
first_anchor.attrs["href"], "/projects/", "/"
)
title = second_anchor.contents[0]
author = third_anchor.contents[0]
# Instantiating a project with the properties that we know
# This may cause issues (see below)
_project = project.Project(
id=project_id,
_session=self._session,
title=title,
author_name=author,
url=f"https://scratch.mit.edu/projects/{project_id}/",
)
if get_full_project:
# Put this under an if statement since making api requests for every single
# project will cause the function to take a lot longer
_project.update()
_projects.append(_project)
return _projects
def loves_count(self):
with requests.no_error_handling():
text = requests.get(
f"https://scratch.mit.edu/projects/all/{self.username}/loves/",
headers=self._headers,
).text
# If there are no loved projects, then Scratch doesn't actually display the number - so we have to catch this
soup = BeautifulSoup(text, "html.parser")
if not soup.find("li", {"class": "project thumb item"}):
# There are no projects, so there are no projects loved
return 0
return commons.webscrape_count(text, "»\n\n (", ")")
def favorites(self, *, limit=40, offset=0):
"""
Returns:
list<projects.projects.Project>: The user's favorite projects
"""
_projects = commons.api_iterative(
f"https://api.scratch.mit.edu/users/{self.username}/favorites/",
limit=limit,
offset=offset,
_headers=self._headers,
)
return commons.parse_object_list(_projects, project.Project, self._session)
def favorites_count(self):
with requests.no_error_handling():
text = requests.get(
f"https://scratch.mit.edu/users/{self.username}/favorites/",
headers=self._headers,
).text
return commons.webscrape_count(text, "Favorites (", ")")
def has_badge(self) -> bool:
"""
Returns:
bool: Whether the user has a scratch membership badge on their profile (located next to the follow button)
"""
with requests.no_error_handling():
resp = requests.get(self.url)
soup = BeautifulSoup(resp.text, "html.parser")
head = soup.find("div", {"class": "box-head"})
if not head:
return False
for child in head.children:
if child.name == "img":
if "membership-badge.svg" in child["src"]:
return True
return False
def toggle_commenting(self):
"""
You can only use this function if this object was created using :meth:`scratchattach.session.Session.connect_user`
"""
self._assert_permission()
requests.post(
f"https://scratch.mit.edu/site-api/comments/user/{self.username}/toggle-comments/",
headers=headers,
cookies=self._cookies,
)
def viewed_projects(self, limit=24, offset=0):
"""
Returns:
list<projects.projects.Project>: The user's recently viewed projects
You can only use this function if this object was created using :meth:`scratchattach.session.Session.connect_user`
"""
self._assert_permission()
_projects = commons.api_iterative(
f"https://api.scratch.mit.edu/users/{self.username}/projects/recentlyviewed",
limit=limit,
offset=offset,
_headers=self._headers,
)
return commons.parse_object_list(_projects, project.Project, self._session)
def set_pfp(self, image: bytes):
"""
Sets the user's profile picture. You can only use this function if this object was created using :meth:`scratchattach.session.Session.connect_user`
"""
# Teachers can set pfp! - Should update this method to check for that
# self._assert_permission()
requests.post(
f"https://scratch.mit.edu/site-api/users/all/{self.username}/",
headers=self._headers,
cookies=self._cookies,
files={"file": image},
)
def set_bio(self, text):
"""
Sets the user's "About me" section. You can only use this function if this object was created using :meth:`scratchattach.session.Session.connect_user`
"""
# Teachers can set bio! - Should update this method to check for that
# self._assert_permission()
requests.put(
f"https://scratch.mit.edu/site-api/users/all/{self.username}/",
headers=self._json_headers,
cookies=self._cookies,
json={"bio": text},
)
def set_wiwo(self, text):
"""
Sets the user's "What I'm working on" section. You can only use this function if this object was created using :meth:`scratchattach.session.Session.connect_user`
"""
# Teachers can also change your wiwo
# self._assert_permission()
requests.put(
f"https://scratch.mit.edu/site-api/users/all/{self.username}/",
headers=self._json_headers,
cookies=self._cookies,
json={"status": text},
)
def set_featured(self, project_id, *, label=""):
"""
Sets the user's featured project. You can only use this function if this object was created using :meth:`scratchattach.session.Session.connect_user`
Args:
project_id: Project id of the project that should be set as featured
Keyword Args:
label: The label that should appear above the featured project on the user's profile (Like "Featured project", "Featured tutorial", "My favorite things", etc.)
"""
self._assert_permission()
requests.put(
f"https://scratch.mit.edu/site-api/users/all/{self.username}/",
headers=self._json_headers,
cookies=self._cookies,
json={"featured_project": int(project_id), "featured_project_label": label},
)
def set_forum_signature(self, text):
"""
Sets the user's discuss forum signature. You can only use this function if this object was created using :meth:`scratchattach.session.Session.connect_user`
"""
self._assert_permission()
headers = {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
"content-type": "application/x-www-form-urlencoded",
"origin": "https://scratch.mit.edu",
"referer": "https://scratch.mit.edu/discuss/settings/TimMcCool/",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
}
data = {
"csrfmiddlewaretoken": "a",
"signature": text,
"update": "",
}
response = requests.post(
f"https://scratch.mit.edu/discuss/settings/{self.username}/",
cookies=self._cookies,
headers=headers,
data=data,
)
def post_comment(self, content, *, parent_id="", commentee_id=""):
"""
Posts a comment on the user's profile. You can only use this function if this object was created using :meth:`scratchattach.session.Session.connect_user`
Args:
:param content: Content of the comment that should be posted
Keyword Arguments:
:param commentee_id: ID of the comment you want to reply to. If you don't want to mention a user, don't put the argument.
:param parent_id: ID of the user that will be mentioned in your comment and will receive a message about your comment. If you don't want to mention a user, don't put the argument.
Returns:
scratchattach.comment.Comment: An object representing the created comment.
"""
self._assert_auth()
data = {
"commentee_id": commentee_id,
"content": str(content),
"parent_id": parent_id,
}
r = requests.post(
f"https://scratch.mit.edu/site-api/comments/user/{self.username}/add/",
headers=headers,
cookies=self._cookies,
data=json.dumps(data),
)
if r.status_code != 200:
if "Looks like we are having issues with our servers!" in r.text:
raise exceptions.BadRequest("Invalid arguments passed")
else:
raise exceptions.CommentPostFailure(r.text)
text = r.text
try:
data = {
"id": text.split('<div id="comments-')[1].split('" class="comment')[0],
"author": {
"username": text.split('" data-comment-user="')[1].split(
'"><img class'
)[0]
},
"content": text.split('<div class="content">')[1]
.split("</div>")[0]
.strip(),
"reply_count": 0,
"cached_replies": [],
}
_comment = comment.Comment(
source=comment.CommentSource.USER_PROFILE,
parent_id=None if parent_id == "" else parent_id,
commentee_id=commentee_id,
source_id=self.username,
id=data["id"],
_session=self._session,
datetime=datetime.now(),
)
_comment._update_from_dict(data)
return _comment
except Exception as e:
if '{"error": "isFlood"}' in text:
raise (
exceptions.CommentPostFailure(
"You are being rate-limited for running this operation too often. Implement a cooldown of about 10 seconds."
)
) from e
elif '<script id="error-data" type="application/json">' in text:
raw_error_data = text.split(
'<script id="error-data" type="application/json">'
)[1].split("</script>")[0]
error_data = json.loads(raw_error_data)
expires = error_data["mute_status"]["muteExpiresAt"]
expires = datetime.fromtimestamp(expires, timezone.utc)
raise (
exceptions.CommentPostFailure(
f"You have been muted. Mute expires on {expires}"
)
) from e
else:
raise (
exceptions.FetchError(f"Couldn't parse API response: {r.text!r}")
) from e
def reply_comment(self, content, *, parent_id, commentee_id=""):
"""
Replies to a comment given by its id
Warning:
Only replies to top-level comments are shown on the Scratch website. Replies to replies are actually replies to the corresponding top-level comment in the API.
Therefore, parent_id should be the comment id of a top level comment.
Args:
:param content: Content of the comment that should be posted
Keyword Arguments:
:param parent_id: ID of the comment you want to reply to
:param commentee_id: ID of the user that will be mentioned in your comment and will receive a message about your comment. If you don't want to mention a user, don't put the argument.
"""
return self.post_comment(
content, parent_id=parent_id, commentee_id=commentee_id
)
def activity(self, *, limit=1000):
"""
Returns:
list<scratchattach.Activity>: The user's activity data as parsed list of scratchattach.activity.Activity objects
"""
with requests.no_error_handling():
soup = BeautifulSoup(
requests.get(
f"https://scratch.mit.edu/messages/ajax/user-activity/?user={self.username}&max={limit}"
).text,
"html.parser",
)
activities = []
source = soup.find_all("li")
for data in source:
_activity = activity.Activity(_session=self._session, raw=data)
_activity._update_from_html(data)
activities.append(_activity)
return activities
def activity_html(self, *, limit=1000):
"""
Returns:
str: The raw user activity HTML data
"""
with requests.no_error_handling():
return requests.get(
f"https://scratch.mit.edu/messages/ajax/user-activity/?user={self.username}&max={limit}"
).text
def follow(self):
"""
Follows the user represented by the User object. You can only use this function if this object was created using :meth:`scratchattach.session.Session.connect_user`
"""
self._assert_auth()
requests.put(
f"https://scratch.mit.edu/site-api/users/followers/{self.username}/add/?usernames={self._session._username}",
headers=headers,
cookies=self._cookies,
)
def unfollow(self):
"""
Unfollows the user represented by the User object. You can only use this function if this object was created using :meth:`scratchattach.session.Session.connect_user`
"""
self._assert_auth()
requests.put(
f"https://scratch.mit.edu/site-api/users/followers/{self.username}/remove/?usernames={self._session._username}",
headers=headers,
cookies=self._cookies,
)
def delete_comment(self, *, comment_id):
"""
Deletes a comment by its ID. You can only use this function if this object was created using :meth:`scratchattach.session.Session.connect_user`