This repository has been archived by the owner on Nov 12, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
models.py
2430 lines (2097 loc) · 84.6 KB
/
models.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
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
import config
import datetime
import email.utils
import extensions
from flask import render_template, url_for
from flask_sqlalchemy import BaseQuery
import json
from passlib.hash import sha256_crypt
import patterns
import secrets
from sqlalchemy import case, desc, func, or_
from sqlalchemy.orm import aliased, Bundle
from sqlalchemy.sql import expression
from sqlalchemy.sql.expression import false, true, null
from typing import Any, Iterable, List, Optional, Tuple, Union
import utils
db = extensions.db
# This links Molts to Crabtags in a many-to-many relationship
crabtag_table = db.Table(
"crabtag_links",
db.Column("id", db.Integer, primary_key=True),
db.Column("molt_id", db.Integer, db.ForeignKey("molt.id")),
db.Column("tag_id", db.Integer, db.ForeignKey("crabtag.id")),
)
# This stores unidirectional follower-followee relationships
following_table = db.Table(
"following",
db.Column("id", db.Integer, primary_key=True),
db.Column("follower_id", db.Integer, db.ForeignKey("crab.id")),
db.Column("following_id", db.Integer, db.ForeignKey("crab.id")),
)
blocking_table = db.Table(
"blocking",
db.Column("id", db.Integer, primary_key=True),
db.Column("blocker_id", db.Integer, db.ForeignKey("crab.id")),
db.Column("blocked_id", db.Integer, db.ForeignKey("crab.id")),
)
class NotFoundInDatabase(BaseException):
"""Raised when requested item was not found in the database."""
pass
class Crab(db.Model):
"""A Crab is a user.
Create new with `Crab.create_new`.
"""
id = db.Column(db.Integer, primary_key=True)
# User info
username = db.Column(db.String(32), nullable=False)
email = db.Column(db.String(120), nullable=False)
display_name = db.Column(db.String(32), nullable=False)
password = db.Column(db.String(128), nullable=False)
description = db.Column(
db.String(1024), nullable=False, server_default="This user has no description."
)
raw_bio = db.Column(db.String(2048), nullable=False, server_default="{}")
location = db.Column(db.String(256), nullable=True)
website = db.Column(db.String(1024), nullable=True)
theme_song = db.Column(db.String(1024), nullable=True)
verified = db.Column(db.Boolean, nullable=False, default=False)
avatar = db.Column(
db.String(140),
nullable=False,
server_default="https://cdn.crabber.net/img/avatar.jpg",
)
banner = db.Column(
db.String(140),
nullable=False,
server_default="https://cdn.crabber.net/img/banner.png",
)
register_time = db.Column(
db.DateTime, nullable=False, default=datetime.datetime.utcnow
)
address = db.Column(db.String(64))
referrer_id = db.Column(db.Integer, db.ForeignKey("crab.id"))
referrer = db.relationship("Crab", remote_side=[id], backref="referrals")
deleted = db.Column(db.Boolean, nullable=False, default=False)
timezone = db.Column(db.String(8), nullable=False, default="-06.00")
lastfm = db.Column(db.String(128), nullable=True)
banned = db.Column(db.Boolean, nullable=False, default=False)
_password_reset_token = db.Column("password_reset_token", db.String(128))
# Content visibility
nsfw = db.Column(db.Boolean, nullable=False, default=False)
show_nsfw = db.Column(db.Boolean, nullable=False, default=False)
show_nsfw_thumbnails = db.Column(db.Boolean, nullable=False, default=False)
_muted_words = db.Column(
"muted_words", db.String(4096), nullable=False, server_default=""
)
# Dynamic relationships
_molts = db.relationship("Molt", back_populates="author")
_following = db.relationship(
"Crab",
secondary=following_table,
primaryjoin=id == following_table.c.follower_id,
secondaryjoin=id == following_table.c.following_id,
backref=db.backref("_followers"),
)
_blocked = db.relationship(
"Crab",
secondary=blocking_table,
primaryjoin=id == blocking_table.c.blocker_id,
secondaryjoin=id == blocking_table.c.blocked_id,
backref=db.backref("_blockers"),
)
_likes = db.relationship("Like")
_bookmarks = db.relationship("Bookmark")
pinned_molt_id = db.Column(db.Integer, nullable=True)
_preferences = db.Column(
"preferences", db.String(4096), nullable=False, default="{}"
)
# Used for efficient queries in templates
column_dict = dict(
id=id,
avatar=avatar,
username=username,
display_name=display_name,
verified=verified,
deleted=deleted,
banned=banned,
description=description,
raw_bio=raw_bio,
location=location,
website=website,
banner=banner,
register_time=register_time,
timezone=timezone,
lastfm=lastfm,
)
def __repr__(self):
return f"<Crab '@{self.username}'>"
@property
def register_timestamp(self):
"""Returns integer timestamp of user's registration."""
return int(self.register_time.timestamp())
@property
def rich_description(self):
"""Returns user's description parsed into rich HTML."""
return utils.parse_rich_content(
self.description, include_media=False, preserve_whitespace=False
)
@property
def bio(self):
"""Returns bio JSON as dictionary."""
return json.loads(self.raw_bio)
@property
def timedelta(self):
"""Returns time offset for user's timezone."""
return datetime.timedelta(hours=float(self.timezone))
@property
def is_admin(self) -> bool:
"""Returns whether the user is a website admin."""
return self.username.lower() in config.ADMINS
@property
def is_moderator(self) -> bool:
"""Returns whether the user is a website moderator."""
return self.username.lower() in [*config.MODERATORS, *config.ADMINS]
@property
def muted_words(self) -> List[str]:
"""Returns a list of the words this user has muted."""
return filter(lambda s: len(s), self._muted_words.split(","))
@property
def muted_words_string(self) -> List[str]:
"""Returns a comma-separated list of the words this user has muted."""
return ", ".join(self.muted_words)
@property
def bookmarks(self):
"""Returns all bookmarks the user has where the molt is still available."""
return self.query_bookmarks()
@property
def bookmark_count(self):
"""Returns number of molts the user has bookmarked that are still available."""
return self.query_bookmarks().count()
@property
def likes(self):
"""Returns all likes the user has where the molt is still available."""
return self.query_likes()
@property
def like_count(self):
"""Returns number of molts the user has liked that are still available."""
return self.query_likes().count()
@property
def molts(self):
"""Returns all molts the user has published that are still available."""
return self.query_molts()
@property
def molt_count(self):
"""Returns number of molts the user has published that are still available."""
return self.query_molts().count()
@property
def replies(self):
"""Returns all replies the user has published that are still available."""
return self.query_replies()
@property
def reply_count(self):
"""Returns number of replies the user has published that are still available."""
return self.query_replies().count()
@property
def blocked(self) -> List["Crab"]:
"""Returns this Crab's blocked Crabs without deleted/banned users."""
return self.query_blocked()
@property
def blockers(self) -> List["Crab"]:
"""Returns Crabs that have blocked this Crab without deleted/banned users."""
return self.query_blockers()
@property
def following(self) -> List["Crab"]:
"""Returns this Crab's following without deleted/banned users."""
return self.query_following()
@property
def followers(self) -> List["Crab"]:
"""Returns this Crab's followers without deleted/banned users."""
return self.query_followers()
@property
def following_count(self):
"""Returns this Crab's following count without deleted/banned users."""
return self.query_following().count()
@property
def follower_count(self):
"""Returns this Crab's follower count without deleted/banned users."""
return self.query_followers().count()
@property
def days_active(self):
"""Returns number of days since user signed up."""
return (datetime.datetime.utcnow() - self.register_time).days
@property
def trophy_count(self):
"""Returns amount of trophies user has earned."""
return TrophyCase.query.filter_by(owner_id=self.id).count()
@property
def unread_notifications(self):
"""Get the amount of unread notifications for this Crab."""
return Notification.query_all().filter_by(recipient=self, read=False).count()
@property
def pinned(self) -> Optional["Molt"]:
"""Return user's currently pinned molt."""
return Molt.query.filter_by(id=self.pinned_molt_id).first()
@property
def referral_code(self) -> "ReferralCode":
"""Return user's referral code."""
return ReferralCode.get(self)
@property
def referrals_count(self) -> int:
"""Return number of times this user's referral code has been used."""
return (
db.session.query(ReferralCode.uses).filter_by(crab_id=self.id).first()
or (0,)
)[0]
def generate_password_reset_token(self):
"""Generates and returns a new password reset token."""
new_token = dict(
token=secrets.token_hex(32),
timestamp=int(datetime.datetime.utcnow().timestamp()),
)
self._password_reset_token = json.dumps(new_token)
db.session.commit()
return new_token["token"]
def verify_password_reset_token(self, token: str) -> bool:
"""Verifies a given password reset token is still valid."""
if token and self._password_reset_token:
# Load from JSON
real_token = json.loads(self._password_reset_token)
# Check if expired
token_time = datetime.datetime.fromtimestamp(real_token["timestamp"])
elapsed_minutes = (
abs((token_time - datetime.datetime.utcnow()).total_seconds()) / 60
)
if elapsed_minutes < 10 and token == real_token["token"]:
return True
return False
def clear_password_reset_token(self):
"""Removes any existing password reset tokens."""
self._password_reset_token = None
db.session.commit()
def bookmark(self, molt):
"""Add `molt` to bookmarks."""
if not self.has_bookmarked(molt):
new_bookmark = Bookmark(crab=self, molt=molt)
db.session.add(new_bookmark)
db.session.commit()
def unbookmark(self, molt):
"""Remove `molt` from bookmarks."""
Bookmark.query.filter_by(crab_id=self.id, molt_id=molt.id).delete()
db.session.commit()
def get_mutuals_for(self, crab: "Crab"):
"""Returns a list of people you follow who also follow `crab`."""
self_following = (
db.session.query(Crab.id)
.join(following_table, Crab.id == following_table.c.following_id)
.filter(following_table.c.follower_id == self.id)
.filter(Crab.banned == false(), Crab.deleted == false())
)
crab_followers = (
db.session.query(Crab)
.join(following_table, Crab.id == following_table.c.follower_id)
.filter(following_table.c.following_id == crab.id)
.filter(Crab.banned == false(), Crab.deleted == false())
)
mutuals = crab_followers.filter(Crab.id.in_(self_following))
return mutuals
def get_preference(self, key: str, default: Optional[Any] = None):
"""Gets key from user's preferences."""
preferences_dict = json.loads(self._preferences)
return preferences_dict.get(key, default)
def set_preference(self, key: str, value: Any):
"""Sets a value in user's preferences."""
preferences_dict = json.loads(self._preferences)
preferences_dict[key] = value
self._preferences = json.dumps(preferences_dict)
db.session.commit()
def get_recommended_crabs(self, limit=3):
"""Returns recommended crabs based on this user's following."""
following_ids = (
db.session.query(Crab.id)
.join(following_table, Crab.id == following_table.c.following_id)
.filter(following_table.c.follower_id == self.id)
.filter(Crab.banned == false(), Crab.deleted == false())
)
if following_ids.count():
recommended = (
db.session.query(Crab)
.join(following_table, Crab.id == following_table.c.following_id)
.filter(following_table.c.follower_id.in_(following_ids))
.filter(following_table.c.following_id.notin_(following_ids))
.group_by(Crab.id)
.filter(Crab.banned == false(), Crab.deleted == false())
.filter(Crab.id != self.id)
.order_by(func.count(Crab.id).desc())
)
else:
recommended = (
Crab.query_most_popular().filter(Crab.id != self.id).with_entities(Crab)
)
recommended = self.filter_user_query_by_not_blocked(recommended)
return recommended.limit(limit)
def update_bio(self, updates: dict):
"""Update bio with keys from `new_bio`."""
self.description = updates.get("description") or self.description
self.location = updates.get("location") or self.location
self.website = updates.get("website") or self.website
valid_keys = (
"age",
"emoji",
"jam",
"obsession",
"pronouns",
"quote",
"remember",
)
# Load bio JSON from string
new_bio = json.loads(self.raw_bio)
# Update bio with new values
new_bio.update(updates)
# Remove empty fields
new_bio = {
k: v
for k, v in new_bio.items()
if (str(v.strip()) if v is not None else v) and k in valid_keys
}
# Convert bio back to JSON string and update in database
self.raw_bio = json.dumps(new_bio)
db.session.commit()
def verify(self):
"""Verify this user."""
self.verified = True
for crab in self.following:
crab.award(title="I Captivated the Guy")
db.session.commit()
def unverify(self):
"""Revoke this user's verification."""
self.verified = False
db.session.commit()
def clear_username(self):
"""Change this user's username to a randomly generated one."""
new_username = f"crab{utils.hexID(8)}"
while not utils.validate_username(new_username):
new_username = f"crab{utils.hexID(8)}"
self.username = new_username
db.session.commit()
def clear_display_name(self):
"""Change this user's display name to a generic one."""
self.display_name = "Unnamed Crab"
db.session.commit()
def clear_description(self, description="This user has no description."):
"""Change this user's description to a generic one."""
self.description = description
db.session.commit()
def clear_avatar(self):
"""Change this user's avatar to a generic one."""
self.avatar = utils.make_crabatar(self.username)
db.session.commit()
def clear_banner(self):
"""Change this user's banner to a generic one."""
self.banner = "https://cdn.crabber.net/img/banner.png"
db.session.commit()
def ban(self, reason=None):
"""Banish this user from the site."""
if not self.banned:
self.banned = True
db.session.commit()
if config.MAIL_ENABLED:
# Send ban notification email
body = render_template(
"user-banned-email.html", crab=self, ban_reason=reason
)
if config.is_debug_server:
print(f"\nEMAIL BODY:\n{body}\n")
else:
extensions.mail.send_mail(
self.email, subject="Your account has been banned", body=body
)
def unban(self):
"""Restore a banned user's access to the site."""
if self.banned:
self.banned = False
db.session.commit()
if config.MAIL_ENABLED:
# Send ban notification email
body = render_template("user-unbanned-email.html", crab=self)
if config.is_debug_server:
print(f"\nEMAIL BODY:\n{body}\n")
else:
extensions.mail.send_mail(
self.email, subject="Your account has been restored", body=body
)
def pin(self, molt):
"""Set `molt` as user's pinned molt."""
self.pinned_molt_id = molt.id
db.session.commit()
def unpin(self):
"""Unpin whatever molt user currently has pinned."""
self.pinned_molt_id = None
db.session.commit()
def get_notifications(self, paginated=False, page=1):
"""Return all valid notifications for user."""
blocker_ids = db.session.query(blocking_table.c.blocker_id).filter(
blocking_table.c.blocked_id == self.id
)
blocked_ids = db.session.query(blocking_table.c.blocked_id).filter(
blocking_table.c.blocker_id == self.id
)
block_ids = blocked_ids.union(blocker_ids)
notifs = (
Notification.query_all()
.filter(
db.or_(
Notification.sender_id == null(),
Notification.sender_id.notin_(block_ids),
)
)
.filter_by(recipient=self)
)
likes = (
notifs.with_entities(
Notification,
func.count(Notification.id),
func.max(Notification.timestamp),
)
.filter_by(type="like")
.group_by(Notification.molt_id)
)
remolts = (
notifs.with_entities(
Notification,
func.count(Notification.id),
func.max(Notification.timestamp),
)
.filter_by(type="remolt")
.join(Molt, Molt.id == Notification.molt_id)
.group_by(Molt.original_molt_id)
)
other = notifs.with_entities(
Notification,
expression.literal(1),
Notification.timestamp.label("timestamp"),
).filter(
Notification.type.in_(
("other", "warning", "trophy", "mention", "quote", "reply", "follow")
)
)
notifs = other.union(likes, remolts).order_by(Notification.timestamp.desc())
if paginated:
return notifs.paginate(page, config.NOTIFS_PER_PAGE, False)
else:
return notifs
def read_notifications(self):
"""Mark all of this user's notifications as read."""
notifs = (
Notification.query_all().filter_by(recipient=self).filter_by(read=False)
)
notifs.update({"read": True}, synchronize_session=False)
db.session.commit()
def award(self, title=None, trophy=None):
"""Award user trophy by object or by title."""
if trophy is None and title is None:
raise TypeError(
"You must specify one of either trophy object or trophy title."
)
# Query trophy by title
if trophy is None:
trophy_query = Trophy.query.filter(Trophy.title.ilike(title))
if trophy_query.count() == 0:
raise NotFoundInDatabase(f"Trophy with title: '{title}' not found.")
trophy = trophy_query.first()
# Check trophy hasn't already been awarded to user
if not TrophyCase.query.filter_by(owner=self, trophy=trophy).count():
new_trophy = TrophyCase(owner=self, trophy=trophy)
db.session.add(new_trophy)
# Notify of new award
self.notify(type="trophy", content=trophy.title)
db.session.commit()
return new_trophy
def block(self, crab):
"""Add `crab` to this Crab's block users."""
if crab not in self._blocked and crab is not self:
self.unfollow(crab)
crab.unfollow(self)
self._blocked.append(crab)
db.session.commit()
def unblock(self, crab):
"""Removes `crab` from this Crab's block users."""
if crab in self._blocked and crab is not self:
self._blocked.remove(crab)
db.session.commit()
def follow(self, crab):
"""Adds user to `crab`'s following."""
if crab not in self._following and crab is not self:
self._following.append(crab)
# Create follow notification
crab.notify(sender=self, type="follow")
# Award applicable trophies
self.check_follower_count_trophies()
crab.check_follower_count_trophies()
if self.verified:
crab.award(title="I Captivated the Guy")
db.session.commit()
def unfollow(self, crab):
"""Removes user from `crab`'s following."""
if crab in self._following and crab is not self:
self._following.remove(crab)
db.session.commit()
def verify_password(self, password):
"""Returns true if `password` matches user's password."""
return sha256_crypt.verify(password, self.password)
def molt(self, content, **kwargs):
"""Create and publish new Molt."""
kwargs["nsfw"] = kwargs.get("nsfw", self.nsfw)
content = Molt.conform_content(content)
new_molt = Molt.create(author=self, content=content, **kwargs)
# Award molt count trophies
molt_count = self.molt_count
if molt_count >= 10_000:
self.award(title="Please Stop")
if molt_count >= 1_000:
self.award(title="Loudmouth")
if molt_count == 1:
self.award(title="Baby Crab")
return new_molt
def delete(self):
"""Delete user. (Can be undone)."""
self.deleted = True
db.session.commit()
def restore(self):
"""Restore deleted user."""
self.deleted = False
db.session.commit()
def is_blocking(self, crab):
"""Returns True if user has blocked `crab`."""
return (
db.session.query(blocking_table)
.filter(
(blocking_table.c.blocker_id == self.id)
& (blocking_table.c.blocked_id == crab.id)
)
.count()
)
def is_blocked_by(self, crab):
"""Returns True if user has been blocked by `crab`."""
return (
db.session.query(blocking_table)
.filter(
(blocking_table.c.blocked_id == self.id)
& (blocking_table.c.blocker_id == crab.id)
)
.count()
)
def is_following(self, crab):
"""Returns True if user is following `crab`."""
return (
db.session.query(following_table)
.filter(
(following_table.c.follower_id == self.id)
& (following_table.c.following_id == crab.id)
)
.count()
)
def has_bookmarked(self, molt) -> Optional["Bookmark"]:
"""Returns bookmark if user has bookmarked `molt`."""
return Bookmark.query.filter_by(molt_id=molt.id, crab_id=self.id).first()
def has_liked(self, molt) -> Optional["Like"]:
"""Returns like if user has liked `molt`."""
return Like.query.filter_by(molt_id=molt.id, crab_id=self.id).first()
def has_remolted(self, molt) -> Optional["Molt"]:
"""Returns the Remolt if user has remolted `molt`, otherwise None."""
molt = Molt.query.filter_by(
is_remolt=True, original_molt_id=molt.id, author_id=self.id, deleted=False
).first()
return molt
def notify(self, **kwargs):
"""Create notification for user."""
is_duplicate = False
if kwargs.get("sender") is not self:
# Don't notify if either user is blocked
sender = kwargs.get("sender")
if sender is not None:
if self.is_blocked_by(sender) or self.is_blocking(sender):
return None
# Check for molt duplicates
molt = kwargs.get("molt")
if molt:
duplicate_notification = db.session.query(Notification.id).filter_by(
recipient=self,
sender=kwargs.get("sender"),
type=kwargs.get("type"),
molt=molt,
)
if duplicate_notification.first():
is_duplicate = True
# Check for notification spamming
if kwargs.get("type") in ("follow", "unfollow"):
now = datetime.datetime.utcnow()
yesterday = now - datetime.timedelta(days=1)
duplicate_notification = (
Notification.query_all()
.filter_by(
recipient=self,
sender=kwargs.get("sender"),
type=kwargs.get("type"),
molt=kwargs.get("molt"),
)
.filter(Notification.timestamp > yesterday)
)
if duplicate_notification.count():
is_duplicate = True
if not is_duplicate:
new_notif = Notification(recipient=self, **kwargs)
db.session.add(new_notif)
db.session.commit()
return new_notif
# Query methods
def query_blocked(self) -> BaseQuery:
"""Returns this Crab's blocked Crabs without deleted/banned users."""
blocked = (
db.session.query(Crab)
.join(blocking_table, Crab.id == blocking_table.c.blocked_id)
.filter(blocking_table.c.blocker_id == self.id)
.filter(Crab.banned == false(), Crab.deleted == false())
.order_by(Crab.username)
)
return blocked
def query_blocked_ids(self) -> BaseQuery:
"""Returns ids of valid and invalid crabs that have been blocked by this Crab."""
blocker_ids = (
db.session.query(Crab.id)
.join(blocking_table, Crab.id == blocking_table.c.blocked_id)
.filter(blocking_table.c.blocker_id == self.id)
)
return blocker_ids
def query_blockers(self) -> BaseQuery:
"""Returns Crabs that have blocked this Crab without deleted/banned users."""
blockers = (
db.session.query(Crab)
.join(blocking_table, Crab.id == blocking_table.c.blocker_id)
.filter(blocking_table.c.blocked_id == self.id)
.filter(Crab.banned == false(), Crab.deleted == false())
.order_by(Crab.username)
)
return blockers
def query_blocker_ids(self) -> BaseQuery:
"""Returns ids of valid and invalid crabs that have blocked this Crab."""
blocker_ids = (
db.session.query(Crab.id)
.join(blocking_table, Crab.id == blocking_table.c.blocker_id)
.filter(blocking_table.c.blocked_id == self.id)
)
return blocker_ids
def query_following(self) -> BaseQuery:
"""Returns this Crab's following without deleted/banned users."""
following = (
db.session.query(Crab)
.join(following_table, Crab.id == following_table.c.following_id)
.filter(following_table.c.follower_id == self.id)
.filter(Crab.banned == false(), Crab.deleted == false())
)
return following
def query_followers(self) -> BaseQuery:
"""Returns this Crab's followers without deleted/banned users."""
followers = (
db.session.query(Crab)
.join(following_table, Crab.id == following_table.c.follower_id)
.filter(following_table.c.following_id == self.id)
.filter(Crab.banned == false(), Crab.deleted == false())
)
return followers
def query_bookmarks(self) -> BaseQuery:
"""Returns all bookmarks the user has where the molt is still available."""
bookmarks = (
Bookmark.query.filter_by(crab=self)
.filter(Bookmark.molt.has(deleted=False))
.filter(Bookmark.molt.has(Molt.author.has(banned=False, deleted=False)))
.join(Molt, Bookmark.molt)
.order_by(Bookmark.timestamp.desc())
)
return bookmarks
def query_likes(self) -> BaseQuery:
"""Returns all likes the user has where the molt is still available."""
likes = (
Like.query.filter_by(crab=self)
.filter(Like.molt.has(deleted=False))
.filter(Like.molt.has(Molt.author.has(banned=False, deleted=False)))
.join(Molt, Like.molt)
.order_by(Molt.timestamp.desc())
)
return likes
def query_molts(self) -> BaseQuery:
"""Returns all molts the user has published that are still available."""
molts = Molt.query.filter_by(author=self, deleted=False).order_by(
Molt.timestamp.desc()
)
return Molt.filter_query_by_available(molts)
def query_replies(self) -> BaseQuery:
"""Returns all replies the user has published that are still available."""
molts = (
self.query_molts()
.filter_by(is_reply=True)
.filter(Molt.original_molt.has(deleted=False))
)
return molts
def query_profile_molts(self, current_user=None) -> BaseQuery:
"""Retrieves the fast-molt molts for this user's profile."""
query = Molt.query_fast_molts(current_user).filter(
Molt.author_id == self.id, Molt.is_reply == false()
)
return query
def query_profile_replies(self, current_user=None) -> BaseQuery:
"""Retrieves the fast-molt replies for this user's profile."""
query = Molt.query_fast_molts(current_user).filter(
Molt.author_id == self.id, Molt.is_reply == true()
)
return query
def query_timeline(self) -> BaseQuery:
"""Retrieves the molts in this user's timeline."""
query = (
Molt.query_fast_molts(self)
.join(following_table, following_table.c.following_id == Molt.author_id)
.filter(Molt.is_reply == false())
.filter(
db.or_(
following_table.c.follower_id == self.id, Molt.author_id == self.id
)
)
)
return query
def query_wild(self) -> BaseQuery:
"""Retrieves the molts in /wild for this user."""
query = Molt.query_fast_molts(self).filter(
Molt.is_reply == false(),
Molt.is_remolt == false(),
Molt.is_quote == false(),
)
return query
def change_password(self, password: str):
"""Updates this user's password hash."""
self.password = self.hash_pass(password)
db.session.commit()
def filter_molt_query(self, query: BaseQuery) -> BaseQuery:
"""Filters a Molt query for all user blocks and preferences."""
query = self.filter_molt_query_by_not_blocked(query)
if not self.show_nsfw:
query = self.filter_molt_query_by_not_nsfw(query)
query = self.filter_molt_query_by_muted_words(query)
return query
def filter_molt_query_by_muted_words(self, query: BaseQuery) -> BaseQuery:
"""Filters Molts containing muted words out of a query."""
original_molt = aliased(Molt)
query = query.outerjoin(
original_molt, original_molt.id == Molt.original_molt_id
)
for muted_word in self.muted_words:
query = query.filter(
db.or_(
Molt.author_id == self.id,
db.not_(Molt.content.ilike(f"%{muted_word}%")),
),
db.or_(
Molt.original_molt == null(),
db.not_(original_molt.content.ilike(f"%{muted_word}%")),
),
)
return query
def filter_molt_query_by_not_nsfw(self, query: BaseQuery) -> BaseQuery:
"""Filters NSFW Molts out of a query."""
query = query.filter(
db.or_(Molt.nsfw == false(), Molt.author_id == self.id)
).filter(
db.or_(
Molt.original_molt == null(),
Molt.original_molt.has(nsfw=False),
Molt.original_molt.has(author_id=self.id),
Molt.author_id == self.id,
)
)
return query
def filter_molt_query_by_not_blocked(self, query: BaseQuery) -> BaseQuery:
"""Filters a Molt query by authors who are not blocked."""
blocked_ids = db.session.query(blocking_table.c.blocked_id).filter(
blocking_table.c.blocker_id == self.id
)
blocker_ids = db.session.query(blocking_table.c.blocker_id).filter(
blocking_table.c.blocked_id == self.id
)
original_molt = aliased(Molt)
query = (
query.filter(Molt.author_id.notin_(blocker_ids))
.filter(Molt.author_id.notin_(blocked_ids))
.outerjoin(original_molt, original_molt.id == Molt.original_molt_id)
.filter(
db.or_(
Molt.original_molt == null(),
db.and_(
original_molt.author_id.notin_(blocked_ids),
original_molt.author_id.notin_(blocker_ids),
),
)
)
)
return query
def check_customization_trophies(self):
"""Awards applicable bio customization trophies."""
if all(
(
self.description != "This user has no description.",
"user_uploads" in self.banner,
"user_uploads" in self.avatar,
self.raw_bio != "{}",
)
):
self.award("I Want it That Way")
def check_follower_count_trophies(self):
"""Awards necessary follower/following trophies."""
following_count = self.following_count
follower_count = self.follower_count
if follower_count == 1:
self.award(title="Social Newbie")
elif follower_count == 10:
self.award(title="Mingler")
elif follower_count == 100:
self.award(title="Life of the Party")
elif follower_count == 1_000:
self.award(title="Celebrity")
if following_count >= 20:
follower_ratio = follower_count / following_count
if follower_ratio >= 20:
self.award(title="20/20")
if follower_ratio >= 100:
self.award(title="The Golden Ratio")
def filter_user_query_by_not_blocked(self, query: BaseQuery) -> BaseQuery:
"""Filters a Crab query by users who are not blocked."""
query = query.filter(
Crab.id.notin_(self.query_blocked_ids()),
Crab.id.notin_(self.query_blocker_ids()),