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
|
"""Converters from Django models to data interchange formats and back."""
from django.db.models.query import QuerySet
from rest_framework.exceptions import NotFound
from rest_framework.serializers import (
IntegerField,
ListSerializer,
ModelSerializer,
PrimaryKeyRelatedField,
ValidationError
)
from rest_framework.validators import UniqueTogetherValidator
from .models import (
BotSetting,
DeletedMessage,
DocumentationLink,
FilterList,
Infraction,
LogEntry,
MessageDeletionContext,
Nomination,
OffTopicChannelName,
OffensiveMessage,
Reminder,
Role,
User
)
class BotSettingSerializer(ModelSerializer):
"""A class providing (de-)serialization of `BotSetting` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = BotSetting
fields = ('name', 'data')
class DeletedMessageSerializer(ModelSerializer):
"""
A class providing (de-)serialization of `DeletedMessage` instances.
The serializer generally requires a valid `deletion_context` to be
given, which should be created beforehand. See the `DeletedMessage`
model for more information.
"""
author = PrimaryKeyRelatedField(
queryset=User.objects.all()
)
deletion_context = PrimaryKeyRelatedField(
queryset=MessageDeletionContext.objects.all(),
# This will be overridden in the `create` function
# of the deletion context serializer.
required=False
)
class Meta:
"""Metadata defined for the Django REST Framework."""
model = DeletedMessage
fields = (
'id', 'author',
'channel_id', 'content',
'embeds', 'deletion_context',
'attachments'
)
class MessageDeletionContextSerializer(ModelSerializer):
"""A class providing (de-)serialization of `MessageDeletionContext` instances."""
actor = PrimaryKeyRelatedField(queryset=User.objects.all(), allow_null=True)
deletedmessage_set = DeletedMessageSerializer(many=True)
class Meta:
"""Metadata defined for the Django REST Framework."""
model = MessageDeletionContext
fields = ('actor', 'creation', 'id', 'deletedmessage_set')
depth = 1
def create(self, validated_data: dict) -> MessageDeletionContext:
"""
Return a `MessageDeletionContext` based on the given data.
In addition to the normal attributes expected by the `MessageDeletionContext` model
itself, this serializer also allows for passing the `deletedmessage_set` element
which contains messages that were deleted as part of this context.
"""
messages = validated_data.pop('deletedmessage_set')
deletion_context = MessageDeletionContext.objects.create(**validated_data)
for message in messages:
DeletedMessage.objects.create(
deletion_context=deletion_context,
**message
)
return deletion_context
class DocumentationLinkSerializer(ModelSerializer):
"""A class providing (de-)serialization of `DocumentationLink` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = DocumentationLink
fields = ('package', 'base_url', 'inventory_url')
class FilterListSerializer(ModelSerializer):
"""A class providing (de-)serialization of `FilterList` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = FilterList
fields = ('id', 'created_at', 'updated_at', 'type', 'allowed', 'content', 'comment')
# This validator ensures only one filterlist with the
# same content can exist. This means that we cannot have both an allow
# and a deny for the same item, and we cannot have duplicates of the
# same item.
validators = [
UniqueTogetherValidator(
queryset=FilterList.objects.all(),
fields=['content', 'type'],
message=(
"A filterlist for this item already exists. "
"Please note that you cannot add the same item to both allow and deny."
)
),
]
class InfractionSerializer(ModelSerializer):
"""A class providing (de-)serialization of `Infraction` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = Infraction
fields = (
'id', 'inserted_at', 'expires_at', 'active', 'user', 'actor', 'type', 'reason', 'hidden'
)
validators = [
UniqueTogetherValidator(
queryset=Infraction.objects.filter(active=True),
fields=['user', 'type', 'active'],
message='This user already has an active infraction of this type.',
)
]
def validate(self, attrs: dict) -> dict:
"""Validate data constraints for the given data and abort if it is invalid."""
infr_type = attrs.get('type')
active = attrs.get('active')
if active and infr_type in ('note', 'warning', 'kick'):
raise ValidationError({'active': [f'{infr_type} infractions cannot be active.']})
expires_at = attrs.get('expires_at')
if expires_at and infr_type in ('kick', 'warning'):
raise ValidationError({'expires_at': [f'{infr_type} infractions cannot expire.']})
hidden = attrs.get('hidden')
if hidden and infr_type in ('superstar', 'warning'):
raise ValidationError({'hidden': [f'{infr_type} infractions cannot be hidden.']})
if not hidden and infr_type in ('note', ):
raise ValidationError({'hidden': [f'{infr_type} infractions must be hidden.']})
return attrs
class ExpandedInfractionSerializer(InfractionSerializer):
"""
A class providing expanded (de-)serialization of `Infraction` instances.
In addition to the fields of `Infraction` objects themselves, this
serializer also attaches the `user` and `actor` fields when serializing.
"""
def to_representation(self, instance: Infraction) -> dict:
"""Return the dictionary representation of this infraction."""
ret = super().to_representation(instance)
user = User.objects.get(id=ret['user'])
user_data = UserSerializer(user).data
ret['user'] = user_data
actor = User.objects.get(id=ret['actor'])
actor_data = UserSerializer(actor).data
ret['actor'] = actor_data
return ret
class LogEntrySerializer(ModelSerializer):
"""A class providing (de-)serialization of `LogEntry` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = LogEntry
fields = (
'application', 'logger_name', 'timestamp',
'level', 'module', 'line', 'message'
)
class OffTopicChannelNameSerializer(ModelSerializer):
"""A class providing (de-)serialization of `OffTopicChannelName` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = OffTopicChannelName
fields = ('name',)
def to_representation(self, obj: OffTopicChannelName) -> str:
"""
Return the representation of this `OffTopicChannelName`.
This only returns the name of the off topic channel name. As the model
only has a single attribute, it is unnecessary to create a nested dictionary.
Additionally, this allows off topic channel name routes to simply return an
array of names instead of objects, saving on bandwidth.
"""
return obj.name
class ReminderSerializer(ModelSerializer):
"""A class providing (de-)serialization of `Reminder` instances."""
author = PrimaryKeyRelatedField(queryset=User.objects.all())
class Meta:
"""Metadata defined for the Django REST Framework."""
model = Reminder
fields = (
'active', 'author', 'jump_url', 'channel_id', 'content', 'expiration', 'id', 'mentions'
)
class RoleSerializer(ModelSerializer):
"""A class providing (de-)serialization of `Role` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = Role
fields = ('id', 'name', 'colour', 'permissions', 'position')
class UserListSerializer(ListSerializer):
"""List serializer for User model to handle bulk updates."""
def create(self, validated_data: list) -> list:
"""Override create method to optimize django queries."""
new_users = []
request_user_ids = [user["id"] for user in validated_data]
for user_dict in validated_data:
if request_user_ids.count(user_dict["id"]) > 1:
raise ValidationError({"id": f"User with ID {user_dict['id']} "
f"given multiple times."})
new_users.append(User(**user_dict))
return User.objects.bulk_create(new_users, ignore_conflicts=True)
def update(self, instance: QuerySet, validated_data: list) -> list:
"""
Override update method to support bulk updates.
ref:https://www.django-rest-framework.org/api-guide/serializers/#customizing-multiple-update
"""
instance_mapping = {user.id: user for user in instance}
updated = []
fields_to_update = set()
for user_data in validated_data:
for key in user_data:
fields_to_update.add(key)
try:
user = instance_mapping[user_data["id"]]
except KeyError:
raise NotFound({"id": f"User with id {user_data['id']} not found."})
user.__dict__.update(user_data)
updated.append(user)
fields_to_update.remove("id")
User.objects.bulk_update(updated, fields_to_update)
return updated
class UserSerializer(ModelSerializer):
"""A class providing (de-)serialization of `User` instances."""
# ID field must be explicitly set as the default id field is read-only.
id = IntegerField(min_value=0)
class Meta:
"""Metadata defined for the Django REST Framework."""
model = User
fields = ('id', 'name', 'discriminator', 'roles', 'in_guild')
depth = 1
list_serializer_class = UserListSerializer
class NominationSerializer(ModelSerializer):
"""A class providing (de-)serialization of `Nomination` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = Nomination
fields = (
'id', 'active', 'actor', 'reason', 'user',
'inserted_at', 'end_reason', 'ended_at')
class OffensiveMessageSerializer(ModelSerializer):
"""A class providing (de-)serialization of `OffensiveMessage` instances."""
class Meta:
"""Metadata defined for the Django REST Framework."""
model = OffensiveMessage
fields = ('id', 'channel_id', 'delete_date')
|