This repository has been archived by the owner on May 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 78
/
models.py
545 lines (435 loc) · 19.9 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
from enum import Enum
from uuid import uuid4
from PIL import Image, UnidentifiedImageError
from dateutil.relativedelta import relativedelta
from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.db.models import Count, F, IntegerField, Q
from django.db.models.manager import BaseManager
from django.utils import timezone
from versatileimagefield.fields import VersatileImageField
from config.settings import USERNAME_MENTION_RE
from karrot.base.base_models import BaseModel, UpdatedAtMixin
from karrot.conversations.signals import new_conversation_message, new_thread_message, conversation_marked_seen, \
thread_marked_seen
from karrot.utils import markdown
from karrot.utils.image_utils import resize_image, is_supported_content_type
class ConversationQuerySet(models.QuerySet):
def create(self, **kwargs):
target = kwargs.get('target', None)
if target is not None:
kwargs['group'] = target.group
return super().create(**kwargs)
def get_for_target(self, target):
return self.filter_for_target(target).first()
def get_or_create_for_target(self, target):
return self.get_for_target(target) or self.create(target=target)
def get_or_create_for_two_users(self, user1, user2):
if user1.id == user2.id:
raise Exception('Users need to be different')
conv = self.filter(is_private=True, participants=user1) \
.filter(participants=user2) \
.first()
if not conv:
conv = self.create(is_private=True)
conv.sync_users([user1, user2])
return conv
def filter_for_target(self, target):
return self.filter(
target_id=target.id,
target_type=ContentType.objects.get_for_model(target),
)
def with_access(self, user):
return self.filter(Q(participants=user) | Q(group__groupmembership__user=user, group__isnull=False)).distinct()
class Conversation(BaseModel, UpdatedAtMixin):
"""A conversation between one or more users."""
class Meta:
unique_together = ('target_type', 'target_id')
objects = ConversationQuerySet.as_manager()
participants = models.ManyToManyField(settings.AUTH_USER_MODEL, through='ConversationParticipant')
is_private = models.BooleanField(default=False)
is_closed = models.BooleanField(default=False)
# conversation belongs to this group
group = models.ForeignKey('groups.Group', on_delete=models.CASCADE, null=True)
target_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True)
target_id = models.PositiveIntegerField(null=True)
target = GenericForeignKey('target_type', 'target_id')
latest_message = models.ForeignKey(
'conversations.ConversationMessage',
on_delete=models.SET_NULL,
null=True,
related_name='conversation_latest_message'
)
def make_participant(self, **kwargs):
defaults = {
'updated_at': self.updated_at,
}
defaults.update(kwargs)
return ConversationParticipant(conversation=self, **defaults)
def join(self, user, **kwargs):
participant = self.conversationparticipant_set.filter(user=user).first()
if participant is None:
participant = self.make_participant(user=user, **kwargs)
participant.save()
return participant
def leave(self, user):
if self.target and self.target.conversation_supports_threads:
ConversationThreadParticipant.objects.filter(user=user, thread__conversation=self).delete()
self.conversationparticipant_set.filter(user=user).delete()
def sync_users(self, desired_users):
"""Pass in a set of users and we ensure the Conversation will end up with the right participants."""
existing_users = self.participants.all()
for user in desired_users:
if user not in existing_users:
self.join(user)
for user in existing_users:
if user not in desired_users:
self.leave(user)
def can_access(self, user):
if self.conversationparticipant_set.filter(user=user).exists():
return True
if self.group is not None and self.group.is_member(user):
return True
return False
def type(self):
if self.is_private:
return 'private'
if self.target_type_id is None:
return None
type = str(self.target_type.model)
if type == 'activity':
return 'activity'
return type
def find_group(self):
if self.is_private or self.target_type_id is None:
return None
return self.target.group
def supports_mentions(self):
# no mentions for private conversations (and those without a type/group...)
return self.type() is not None and self.type() != 'private' and self.group is not None
class ConversationMeta(BaseModel):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
conversations_marked_at = models.DateTimeField()
threads_marked_at = models.DateTimeField()
class ConversationParticipantQuerySet(models.QuerySet):
def annotate_unread_message_count(self):
exclude_replies = (
Q(conversation__messages__thread_id=None) |
Q(conversation__messages__id=F('conversation__messages__thread_id'))
)
unread_messages = Q(seen_up_to=None) | Q(conversation__messages__id__gt=F('seen_up_to'))
filter = unread_messages & exclude_replies
return self.annotate(unread_message_count=Count('conversation__messages', filter=filter, distinct=True))
class ConversationNotificationStatus(Enum):
ALL = 'all'
MUTED = 'muted'
NONE = 'none'
class ConversationParticipant(BaseModel, UpdatedAtMixin):
"""The join table between Conversation and User."""
class Meta:
unique_together = (('user', 'conversation'), )
objects = ConversationParticipantQuerySet.as_manager()
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE)
seen_up_to = models.ForeignKey(
'ConversationMessage',
null=True,
on_delete=models.SET_NULL,
related_name='conversationparticipants_seen_up_to',
)
notified_up_to = models.ForeignKey(
'ConversationMessage',
null=True,
on_delete=models.SET_NULL,
related_name='conversationparticipants_notified_up_to',
)
muted = models.BooleanField(default=False)
@property
def notifications(self):
if self.id is None:
# participant does not exist in database
return ConversationNotificationStatus.NONE.value
if self.muted:
return ConversationNotificationStatus.MUTED.value
return ConversationNotificationStatus.ALL.value
def unseen_and_unnotified_messages(self):
messages = self.conversation.messages.exclude_replies()
if self.seen_up_to_id is not None:
messages = messages.filter(id__gt=self.seen_up_to_id)
if self.notified_up_to_id is not None:
messages = messages.filter(id__gt=self.notified_up_to_id)
return messages
def save(self, **kwargs):
old = type(self).objects.get(pk=self.pk) if self.pk else None
seen_up_to_changed = False
if old is not None and old.seen_up_to != self.seen_up_to:
seen_up_to_changed = True
super().save(**kwargs)
if seen_up_to_changed:
# We use a custom signal here because the receiver needs to know whether seen_up_to changed
# Django's post_save signal doesn't provide this.
# A pre_save signal would be called too early for our purposes.
# Actually, it might be better to not use signals at all and call the logic from Model.save directly.
conversation_marked_seen.send(sender=self.__class__, participant=self)
class ConversationMessageQuerySet(models.QuerySet):
def exclude_replies(self):
return self.filter(Q(thread_id=None) | Q(id=F('thread_id')))
def only_threads_with_user(self, user):
return self.filter(participants__user=user)
def only_threads_and_replies(self):
return self.exclude(thread_id=None)
def only_replies(self):
return self.filter(~Q(thread_id=None) & ~Q(id=F('thread_id')))
def annotate_replies_count(self):
return self.annotate(
replies_count=Count('thread_messages', filter=~Q(thread_messages__id=F('thread_id')), distinct=True)
)
def annotate_unread_replies_count_for(self, user):
# see also ConversationThreadParticipantQuerySet.annotate_unread_replies_count
unread_replies_filter = Q(
participants__user=user,
) & ~Q(thread_messages__id=F('thread_id') # replies have id != thread_id
) & (Q(participants__seen_up_to=None) | Q(thread_messages__id__gt=F('participants__seen_up_to')))
return self.annotate(
unread_replies_count=Count('thread_messages', filter=unread_replies_filter, distinct=True)
)
def with_conversation_access(self, user):
# Note: this is needed if ConversationQuerySet.with_access is too slow
# should contain the same logic
return self.filter(
Q(conversation__participants=user) |
Q(conversation__group__groupmembership__user=user, conversation__group__isnull=False)
)
class ConversationMessageManager(BaseManager.from_queryset(ConversationMessageQuerySet)):
def create(self, **kwargs):
if 'thread' not in kwargs:
# make sure author is participant (to receive notifications)
conversation = kwargs.get('conversation')
author = kwargs.get('author')
conversation.conversationparticipant_set.get_or_create(user=author)
obj = super().create(**kwargs)
# clear cached value
if obj.thread and hasattr(obj.thread, '_replies_count'):
del obj.thread._replies_count
return obj
class ConversationMessage(BaseModel, UpdatedAtMixin):
"""A message in the conversation by a particular user."""
objects = ConversationMessageManager()
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
conversation = models.ForeignKey(Conversation, related_name='messages', on_delete=models.CASCADE)
thread = models.ForeignKey('self', related_name='thread_messages', null=True, on_delete=models.CASCADE)
content = models.TextField()
received_via = models.CharField(max_length=40, blank=True)
edited_at = models.DateTimeField(null=True)
latest_message = models.ForeignKey(
'self',
on_delete=models.SET_NULL,
null=True,
related_name='thread_latest_message',
)
def save(self, **kwargs):
creating = self.pk is None
old = type(self).objects.get(pk=self.pk) if self.pk else None
if old is not None and old.content != self.content:
self.edited_at = timezone.now()
super().save(**kwargs)
self.update_mentions()
if creating:
# keep latest_message reference up-to-date
if self.is_thread_reply():
# update thread
thread = self.thread
thread.latest_message = self
thread.save()
new_thread_message.send(sender=self.__class__, message=self)
else:
# update conversation
conversation = self.conversation
conversation.latest_message = self
conversation.save()
new_conversation_message.send(sender=self.__class__, message=self)
def content_rendered(self, **kwargs):
return markdown.render(self.content, mentions=self.mentions.all(), **kwargs)
def is_recent(self):
return self.created_at >= timezone.now() - relativedelta(days=settings.MESSAGE_EDIT_DAYS)
def is_first_in_thread(self):
return self.id == self.thread_id
def is_thread_reply(self):
return self.thread_id is not None and self.id != self.thread_id
@property
def replies_count(self):
if hasattr(self, '_replies_count'):
return self._replies_count
else:
return self.thread_messages.only_replies().count()
@replies_count.setter
def replies_count(self, value):
self._replies_count = value
def update_mentions(self):
if not self.conversation.supports_mentions():
return
usernames = USERNAME_MENTION_RE.findall(self.content)
# add in the new ones
newly_mentioned_users = self.conversation.group.members \
.filter(username__in=usernames) \
.exclude(id__in=self.mentions.values('user__id'))
created = [self.mentions.create(user=user) for user in newly_mentioned_users]
# clear out the old ones
removed = self.mentions.exclude(user__username__in=usernames).delete()
return created, removed
class ConversationMessageMention(BaseModel, UpdatedAtMixin):
message = models.ForeignKey(ConversationMessage, related_name='mentions', on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='mentions', on_delete=models.CASCADE)
class ConversationThreadParticipantQuerySet(models.QuerySet):
def annotate_unread_replies_count(self):
# see also ConversationMessageQuerySet.annotate_unread_replies_count_for
unread_replies_filter = (
~Q(thread__thread_messages__id=F('thread_id')) &
(Q(seen_up_to=None) | Q(thread__thread_messages__id__gt=F('seen_up_to')))
)
return self.annotate(
unread_replies_count=Count('thread__thread_messages', filter=unread_replies_filter, distinct=True)
)
class ConversationThreadParticipant(BaseModel, UpdatedAtMixin):
objects = ConversationThreadParticipantQuerySet.as_manager()
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
thread = models.ForeignKey(ConversationMessage, related_name='participants', on_delete=models.CASCADE)
seen_up_to = models.ForeignKey(
ConversationMessage,
null=True,
on_delete=models.SET_NULL,
related_name='threadparticipants_seen_up_to',
)
notified_up_to = models.ForeignKey(
ConversationMessage,
null=True,
on_delete=models.SET_NULL,
related_name='threadparticipants_notified_up_to',
)
muted = models.BooleanField(default=False)
class Meta:
unique_together = ['user', 'thread']
def unseen_and_unnotified_messages(self):
messages = self.thread.thread_messages.only_replies()
if self.seen_up_to_id is not None:
messages = messages.filter(id__gt=self.seen_up_to_id)
if self.notified_up_to_id is not None:
messages = messages.filter(id__gt=self.notified_up_to_id)
return messages
def save(self, **kwargs):
old = type(self).objects.get(pk=self.pk) if self.pk else None
seen_up_to_changed = False
if old is not None and old.seen_up_to != self.seen_up_to:
seen_up_to_changed = True
super().save(**kwargs)
if seen_up_to_changed:
# We use a custom signal here because the receiver needs to know whether seen_up_to changed
# Django's post_save signal doesn't provide this.
# A pre_save signal would be called too early for our purposes.
# Actually, it might be better to not use signals at all and call the logic from Model.save directly.
thread_marked_seen.send(sender=self.__class__, participant=self)
class ConversationMixin(object):
# TODO: including this should automatically wireup a signal to create/destroy with target
@property
def conversation(self):
return Conversation.objects.get_or_create_for_target(self)
@property
def ended_at(self):
"""Override this property if the conversation should be closed after the target has ended"""
return None
@property
def conversation_supports_threads(self):
"""Override this property if the conversation supports threaded replies"""
return False
@property
def group(self):
"""Returns the group that the target belongs to
Override this property if you have the group at another location
"""
return self.group
class ConversationMessageReaction(BaseModel):
"""Emoji reactions to messages."""
# User who gave the reaction
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
message = models.ForeignKey(ConversationMessage, related_name='reactions', on_delete=models.CASCADE)
# Name of the emoji
name = models.CharField(max_length=100)
class Meta:
unique_together = ['user', 'name', 'message']
class ConversationMessageImage(BaseModel):
class Meta:
ordering = ['position']
message = models.ForeignKey(
ConversationMessage,
related_name='images',
on_delete=models.CASCADE,
)
image = VersatileImageField(
'ConversationMessage Image',
upload_to='conversation_message_images',
null=False,
)
position = IntegerField(default=0)
class ConversationMessageAttachmentQuerySet(models.QuerySet):
def with_conversation_access(self, user):
# Note: this is needed if ConversationQuerySet.with_access is too slow
# should contain the same logic
return self.filter(
Q(message__conversation__participants=user) |
Q(message__conversation__group__groupmembership__user=user, message__conversation__group__isnull=False)
)
class ConversationMessageAttachment(BaseModel):
class Meta:
ordering = ['position']
objects = ConversationMessageAttachmentQuerySet.as_manager()
message = models.ForeignKey(
ConversationMessage,
related_name='attachments',
on_delete=models.CASCADE,
)
file = models.FileField(
'ConversationMessage Attachment',
upload_to='conversation_message_attachment_files',
null=False,
)
preview = models.ImageField(
upload_to='conversation_message_attachment_previews',
null=True,
)
thumbnail = models.ImageField(
upload_to='conversation_message_attachment_thumbnails',
null=True,
)
filename = models.CharField(
max_length=255,
null=True,
)
position = IntegerField(default=0)
content_type = models.CharField(
max_length=120,
null=True,
)
def save(self, update_fields=None, **kwargs):
self.ensure_images(save=False) # about to save, so don't save here
return super().save(**kwargs)
def ensure_images(self, *, save: bool):
"""Ensure we have the preview and thumbnail images if possible
You can pass the "save" parameter to decide whether to also save
the underlying model. If it is part of an existing call to save, you want false.
"""
if (self.file and (not self.preview or not self.thumbnail) and is_supported_content_type(self.content_type)):
try:
preview_size = settings.PREVIEW_SIZE
thumbnail_size = settings.THUMBNAIL_SIZE
with Image.open(self.file.file) as image:
width, height = image.size
if not self.preview and (width > preview_size or height > preview_size):
self.preview.save(f'{uuid4()}.jpg', resize_image(image, (preview_size, preview_size)), save)
if not self.thumbnail and (width > thumbnail_size or height > thumbnail_size):
self.thumbnail.save(
f'{uuid4()}.jpg', resize_image(image, (thumbnail_size, thumbnail_size)), save
)
except UnidentifiedImageError:
pass