Skip to content

Commit

Permalink
adds functions for managing participants in a conversation, and looki…
Browse files Browse the repository at this point in the history
…ng up existing conversations with a set of partipants
  • Loading branch information
jontsai committed May 25, 2024
1 parent f49285f commit bc4c6df
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions apps/conversations/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,33 @@ def __str__(self):
)
return value

@classmethod
def find_by_participants(cls, participants):
"""Finds a conversation by participants
This is useful for finding an existing conversation between a set of participants
"""

participant_ids = set([participant.id for participant in participants])
num_participants = len(participant_ids)

conversation = (
cls.objects.annotate(
n_participants=models.Count('participants'),
n_user_matches=models.Count(
'participants',
filter=models.Q(participants__user_id__in=participant_ids),
),
)
.filter(
n_participants=num_participants,
n_user_matches=num_participants,
)
.first()
)

return conversation

@property
def num_participants(self):
num = self.participants.count()
Expand All @@ -46,6 +73,15 @@ def num_messages(self):
num = self.messages.count()
return num

def add_participant(self, user):
"""Adds a participant to this conversation"""
self.participants.get_or_create(user=user)

def add_participants(self, users):
"""Adds several participants to this conversation"""
for user in users:
self.add_participant(user)


class BaseConversationParticipant(models.Model):
"""A participant in a conversation
Expand Down

0 comments on commit bc4c6df

Please sign in to comment.