-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmodels.py
More file actions
317 lines (246 loc) · 9.22 KB
/
models.py
File metadata and controls
317 lines (246 loc) · 9.22 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
from __future__ import annotations
from abc import abstractmethod
from typing import List
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.db import models
from files.models import UserFile
from projects.models import Project
from users.models import CustomUser
User = get_user_model()
class BaseChat(models.Model):
"""
Base Chat model
Attributes:
created_at: A DateTimeField indicating date of creation.
"""
created_at = models.DateTimeField(auto_now_add=True)
def get_last_message(self) -> BaseMessage:
return self.messages.last()
def get_users_str(self) -> str:
"""Returns string of users separated by a comma, who are in chat
Returns:
str: string of users, who are in chat
"""
users = self.get_users()
return ", ".join([user.get_full_name() for user in users])
@abstractmethod
def get_users(self) -> List[CustomUser]:
"""
Returns all collaborators and leader of the project.
Returns:
List[CustomUser]: list of users, who are collaborators or leader of the project
"""
pass
@abstractmethod
def get_avatar(self, user: CustomUser) -> str:
"""
Returns avatar of the chat for given user
Args:
user: User who will see the avatar
Returns:
str: link to avatar of the chat for given user
"""
pass
@abstractmethod
def get_last_messages(self, message_count: int) -> List[BaseMessage]:
"""
Returns last messages of the chat
Args:
message_count: number of messages to return
Returns:
List[Message]: list of messages
"""
pass
def __str__(self):
return f"BaseChat<{self.pk}>"
class Meta:
abstract = True
class ProjectChat(BaseChat):
"""
ProjectChat model
Attributes:
project: A ForeignKey to Project model, indicating project, which chat belongs to.
created_at: A DateTimeField indicating date of creation.
"""
id = models.PositiveIntegerField(primary_key=True, unique=True)
project = models.ForeignKey(
Project, on_delete=models.CASCADE, related_name="project_chats"
)
def get_users(self) -> List[CustomUser]:
collaborators = self.project.collaborator_set.all()
users = [collaborator.user for collaborator in collaborators]
return users + [self.project.leader]
def get_avatar(self, user: CustomUser) -> str:
return self.project.image_address
def get_last_messages(self, message_count: int) -> List[BaseMessage]:
return self.messages.order_by("-created_at")[:message_count]
def __str__(self) -> str:
return f"ProjectChat<{self.project.id}> - {self.project.name}"
def save(
self, force_insert=False, force_update=False, using=None, update_fields=None
):
self.id = self.project.id
super().save(force_insert, force_update, using, update_fields)
class Meta:
verbose_name = "Чат проекта"
verbose_name_plural = "Чаты проектов"
class DirectChat(BaseChat):
"""
DirectChat model
Attributes:
created_at: A DateTimeField indicating date of creation.
Methods:
get_users: returns list of users, who are in chat
"""
id = models.CharField(primary_key=True, max_length=64)
users = models.ManyToManyField(User, related_name="direct_chats")
def get_users(self) -> List[CustomUser]:
return self.users.all()
def get_avatar(self, user) -> str:
other_user = self.get_users().exclude(pk=user.pk).first()
return other_user.avatar
@classmethod
def get_chat(cls, user1: CustomUser, user2: CustomUser) -> "DirectChat":
"""
Returns chat between two users.
Args:
user1 (CustomUser): first user, who is in chat
user2 (CustomUser): second user, who is in chat
Returns:
DirectChat: chat between two users
"""
pk = cls.get_chat_id_from_users(user1, user2)
try:
return cls.objects.get(pk=pk)
except cls.DoesNotExist:
chat = cls.objects.create(pk=pk)
chat.users.set([user1, user2])
return chat
def get_last_messages(self, message_count: int) -> BaseMessage:
return self.messages.order_by("-created_at")[:message_count]
def get_other_user(self, user: CustomUser) -> User:
return self.users.exclude(pk=user.pk).first()
@classmethod
def create_from_two_users(cls, user1: CustomUser, user2: CustomUser) -> DirectChat:
chat = cls.objects.create(pk=cls.get_chat_id_from_users(user1, user2))
chat.users.set([user1, user2])
return chat
@classmethod
def get_chat_id_from_users(cls, user1: CustomUser, user2: CustomUser) -> str:
first_user = user1 if user1.pk < user2.pk else user2
second_user = user2 if user1.pk < user2.pk else user1
return f"{first_user.pk}_{second_user.pk}"
def __str__(self) -> str:
return f"DirectChat with {self.get_users_str()}"
class Meta:
verbose_name = "Личный чат"
verbose_name_plural = "Личные чаты"
class BaseMessage(models.Model):
"""
Base message model
Attributes:
text: A TextField containing message text.
is_read: A BooleanField indicating whether message is read.
is_deleted: A BooleanField indicating whether message is deleted.
created_at: A DateTimeField indicating date of creation.
"""
text = models.TextField(max_length=8192)
is_read = models.BooleanField(default=False)
is_deleted = models.BooleanField(default=False)
is_edited = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self) -> str:
return f"Message<{self.pk}>"
class Meta:
verbose_name = "Сообщение"
verbose_name_plural = "Сообщения"
ordering = ["-created_at"]
abstract = True
class ProjectChatMessage(BaseMessage):
"""
ProjectMessage model
Attributes:
chat: A ForeignKey to ProjectChat model, indicating chat, which message belongs to.
author: A ForeignKey referring to the User model.
text: A TextField containing message text.
created_at: A DateTimeField indicating date of creation.
"""
chat = models.ForeignKey(
ProjectChat, on_delete=models.CASCADE, related_name="messages"
)
author = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="project_messages"
)
reply_to = models.ForeignKey(
"self",
on_delete=models.CASCADE,
null=True,
blank=True,
related_name="project_replies",
)
def clean(self):
# check that replied message is in the same chat
if self.reply_to and self.reply_to.chat != self.chat:
raise ValidationError("Reply to message from another chat")
def __str__(self) -> str:
return f"ProjectChatMessage<{self.pk}>"
class Meta:
verbose_name = "Сообщение в чате проекта"
verbose_name_plural = "Сообщения в чатах проектов"
class DirectChatMessage(BaseMessage):
"""
DirectChatMessage model
Attributes:
chat: A ForeignKey to DirectChat model, indicating chat, which message belongs to.
author: A ForeignKey referring to the User model.
text: A TextField containing message text.
created_at: A DateTimeField indicating date of creation.
"""
chat = models.ForeignKey(
DirectChat, on_delete=models.CASCADE, related_name="messages"
)
author = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="direct_messages"
)
reply_to = models.ForeignKey(
"self",
on_delete=models.CASCADE,
null=True,
blank=True,
related_name="direct_replies",
)
def clean(self):
# check that replied message is in the same chat
if self.reply_to and self.reply_to.chat != self.chat:
raise ValidationError("Reply to message from another chat")
def __str__(self) -> str:
return f"DirectChatMessage<{self.pk}>"
class Meta:
verbose_name = "Сообщение в личном чате"
verbose_name_plural = "Сообщения в личных чатах"
class FileToMessage(models.Model):
file = models.OneToOneField(
UserFile,
on_delete=models.CASCADE,
related_name="file_to_message",
primary_key=True,
null=False,
)
direct_message = models.ForeignKey(
DirectChatMessage,
on_delete=models.CASCADE,
related_name="file_to_message",
null=True,
)
project_message = models.ForeignKey(
ProjectChatMessage,
on_delete=models.CASCADE,
related_name="file_to_message",
null=True,
)
def __str__(self) -> str:
return f"FileToMessage<{self.file}>"
class Meta:
verbose_name = "Связка файла и сообщения"
verbose_name_plural = "Связки файлов и сообщений"