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
|
from __future__ import annotations
import json
from collections.abc import Iterable
from django import urls
from django.contrib import admin
from django.db.models import QuerySet
from django.http import HttpRequest
from django.utils.html import SafeString, format_html
from .models import (
BotSetting,
DeletedMessage,
DocumentationLink,
Filter,
FilterList,
Infraction,
MessageDeletionContext,
Nomination,
OffTopicChannelName,
OffensiveMessage,
Role,
User
)
from .models.bot.nomination import NominationEntry
admin.site.site_header = "Python Discord | Administration"
admin.site.site_title = "Python Discord"
@admin.register(BotSetting)
class BotSettingAdmin(admin.ModelAdmin):
"""Admin formatting for the BotSetting model."""
fields = ("name", "data")
list_display = ("name",)
readonly_fields = ("name",)
def has_add_permission(self, *args) -> bool:
"""Prevent adding from django admin."""
return False
def has_delete_permission(self, *args) -> bool:
"""Prevent deleting from django admin."""
return False
@admin.register(DocumentationLink)
class DocumentationLinkAdmin(admin.ModelAdmin):
"""Admin formatting for the DocumentationLink model."""
fields = ("package", "inventory_url", "base_url")
list_display = ("package", "inventory_url", "base_url")
list_editable = ("base_url", "inventory_url")
search_fields = ("package",)
class InfractionActorFilter(admin.SimpleListFilter):
"""Actor Filter for Infraction Admin list page."""
title = "Actor"
parameter_name = "actor"
def lookups(self, request: HttpRequest, model: NominationAdmin) -> Iterable[tuple[int, str]]:
"""Selectable values for viewer to filter by."""
actor_ids = Infraction.objects.order_by().values_list("actor").distinct()
actors = User.objects.filter(id__in=actor_ids)
return ((a.id, a.username) for a in actors)
def queryset(self, request: HttpRequest, queryset: QuerySet) -> QuerySet | None:
"""Query to filter the list of Users against."""
if not self.value():
return None
return queryset.filter(actor__id=self.value())
@admin.register(Infraction)
class InfractionAdmin(admin.ModelAdmin):
"""Admin formatting for the Infraction model."""
fieldsets = (
("Members", {"fields": ("user", "actor")}),
("Action", {"fields": ("type", "hidden", "active")}),
("Dates", {"fields": ("inserted_at", "expires_at")}),
("Reason", {"fields": ("reason",)}),
)
readonly_fields = (
"user",
"actor",
"type",
"inserted_at",
"expires_at",
"active",
"hidden"
)
list_display = (
"type",
"active",
"user",
"inserted_at",
"reason",
)
search_fields = (
"id",
"user__name",
"user__id",
"actor__name",
"actor__id",
"reason",
"type"
)
list_filter = (
"type",
"hidden",
"active",
InfractionActorFilter
)
def has_add_permission(self, *args) -> bool:
"""Prevent adding from django admin."""
return False
@admin.register(DeletedMessage)
class DeletedMessageAdmin(admin.ModelAdmin):
"""Admin formatting for the DeletedMessage model."""
fields = (
"id",
"author",
"channel_id",
"content",
"embed_data",
"context",
"view_full_log"
)
exclude = ("embeds", "deletion_context")
search_fields = (
"id",
"content",
"author__name",
"author__id",
"deletion_context__actor__name",
"deletion_context__actor__id"
)
list_display = ("id", "author", "channel_id")
def embed_data(self, message: DeletedMessage) -> str | None:
"""Format embed data in a code block for better readability."""
if message.embeds:
return format_html(
"<pre style='word-wrap: break-word; white-space: pre-wrap; overflow-x: auto;'>"
"<code>{0}</code></pre>",
json.dumps(message.embeds, indent=4)
)
return None
embed_data.short_description = "Embeds"
@staticmethod
def context(message: DeletedMessage) -> str:
"""Provide full context info with a link through to context admin view."""
link = urls.reverse(
"admin:api_messagedeletioncontext_change",
args=[message.deletion_context.id]
)
details = (
f"Deleted by {message.deletion_context.actor} at "
f"{message.deletion_context.creation}"
)
return format_html("<a href='{0}'>{1}</a>", link, details)
@staticmethod
def view_full_log(message: DeletedMessage) -> str:
"""Provide a link to the message logs for the relevant context."""
return format_html(
"<a href='{0}'>Click to view full context log</a>",
message.deletion_context.log_url
)
def has_add_permission(self, *args) -> bool:
"""Prevent adding from django admin."""
return False
def has_change_permission(self, *args) -> bool:
"""Prevent editing from django admin."""
return False
class DeletedMessageInline(admin.TabularInline):
"""Tabular Inline Admin model for Deleted Message to be viewed within Context."""
model = DeletedMessage
@admin.register(FilterList)
class FilterListAdmin(admin.ModelAdmin):
"""Admin formatting for the FilterList model."""
@admin.register(Filter)
class FilterAdmin(admin.ModelAdmin):
"""Admin formatting for the Filter model."""
@admin.register(MessageDeletionContext)
class MessageDeletionContextAdmin(admin.ModelAdmin):
"""Admin formatting for the MessageDeletionContext model."""
fields = ("actor", "creation")
list_display = ("id", "creation", "actor")
inlines = (DeletedMessageInline,)
def has_add_permission(self, *args) -> bool:
"""Prevent adding from django admin."""
return False
def has_change_permission(self, *args) -> bool:
"""Prevent editing from django admin."""
return False
class NominationActorFilter(admin.SimpleListFilter):
"""Actor Filter for Nomination Admin list page."""
title = "Actor"
parameter_name = "actor"
def lookups(self, request: HttpRequest, model: NominationAdmin) -> Iterable[tuple[int, str]]:
"""Selectable values for viewer to filter by."""
actor_ids = NominationEntry.objects.order_by().values_list("actor").distinct()
actors = User.objects.filter(id__in=actor_ids)
return ((a.id, a.username) for a in actors)
def queryset(self, request: HttpRequest, queryset: QuerySet) -> QuerySet | None:
"""Query to filter the list of Users against."""
if not self.value():
return None
nomination_ids = NominationEntry.objects.filter(
actor__id=self.value()
).values_list("nomination_id").distinct()
return queryset.filter(id__in=nomination_ids)
@admin.register(Nomination)
class NominationAdmin(admin.ModelAdmin):
"""Admin formatting for the Nomination model."""
search_fields = (
"user__name",
"user__id",
"end_reason"
)
list_filter = ("active", NominationActorFilter)
list_display = (
"user",
"active",
"reviewed"
)
fields = (
"user",
"active",
"inserted_at",
"ended_at",
"end_reason",
"reviewed"
)
# only allow end reason field to be edited.
readonly_fields = (
"user",
"active",
"inserted_at",
"ended_at",
"reviewed"
)
def has_add_permission(self, *args) -> bool:
"""Prevent adding from django admin."""
return False
class NominationEntryActorFilter(admin.SimpleListFilter):
"""Actor Filter for NominationEntry Admin list page."""
title = "Actor"
parameter_name = "actor"
def lookups(self, request: HttpRequest, model: NominationAdmin) -> Iterable[tuple[int, str]]:
"""Selectable values for viewer to filter by."""
actor_ids = NominationEntry.objects.order_by().values_list("actor").distinct()
actors = User.objects.filter(id__in=actor_ids)
return ((a.id, a.username) for a in actors)
def queryset(self, request: HttpRequest, queryset: QuerySet) -> QuerySet | None:
"""Query to filter the list of Users against."""
if not self.value():
return None
return queryset.filter(actor__id=self.value())
@admin.register(NominationEntry)
class NominationEntryAdmin(admin.ModelAdmin):
"""Admin formatting for the NominationEntry model."""
search_fields = (
"actor__name",
"actor__id",
"reason",
)
list_filter = (NominationEntryActorFilter,)
list_display = (
"nomination",
"actor",
)
fields = (
"nomination",
"actor",
"reason",
"inserted_at",
)
# only allow reason field to be edited
readonly_fields = (
"nomination",
"actor",
"inserted_at",
)
def has_add_permission(self, request: HttpRequest) -> bool:
"""Disable adding new nomination entry from admin."""
return False
@admin.register(OffTopicChannelName)
class OffTopicChannelNameAdmin(admin.ModelAdmin):
"""Admin formatting for the OffTopicChannelName model."""
search_fields = ("name",)
list_filter = ("used",)
@admin.register(OffensiveMessage)
class OffensiveMessageAdmin(admin.ModelAdmin):
"""Admin formatting for the OffensiveMessage model."""
def message_jumplink(self, message: OffensiveMessage) -> SafeString:
"""Message ID hyperlinked to the direct discord jumplink."""
return format_html(
'<a href="https://canary.discordapp.com/channels/267624335836053506/{0}/{1}">{1}</a>',
message.channel_id,
message.id
)
message_jumplink.short_description = "Message ID"
search_fields = ("id", "channel_id")
list_display = ("id", "channel_id", "delete_date")
fields = ("message_jumplink", "channel_id", "delete_date")
readonly_fields = ("message_jumplink", "channel_id")
def has_add_permission(self, *args) -> bool:
"""Prevent adding from django admin."""
return False
@admin.register(Role)
class RoleAdmin(admin.ModelAdmin):
"""Admin formatting for the Role model."""
def coloured_name(self, role: Role) -> SafeString:
"""Role name with html style colouring."""
return format_html(
'<span style="color: {0}!important; font-weight: bold;">{1}</span>',
f"#{role.colour:06X}",
role.name
)
coloured_name.short_description = "Name"
def colour_with_preview(self, role: Role) -> SafeString:
"""Show colour value in both int and hex, in bolded and coloured style."""
return format_html(
"<span style='color: {0}; font-weight: bold;'>{0} ({1})</span>",
f"#{role.colour:06x}",
role.colour
)
colour_with_preview.short_description = "Colour"
def permissions_with_calc_link(self, role: Role) -> SafeString:
"""Show permissions with link to API permissions calculator page."""
return format_html(
"<a href='https://discordapi.com/permissions.html#{0}' target='_blank'>{0}</a>",
role.permissions
)
permissions_with_calc_link.short_description = "Permissions"
search_fields = ("name", "id")
list_display = ("coloured_name",)
fields = ("id", "name", "colour_with_preview", "permissions_with_calc_link", "position")
def has_add_permission(self, *args) -> bool:
"""Prevent adding from django admin."""
return False
def has_change_permission(self, *args) -> bool:
"""Prevent editing from django admin."""
return False
class UserRoleFilter(admin.SimpleListFilter):
"""List Filter for User list Admin page."""
title = "Role"
parameter_name = "role"
def lookups(self, request: HttpRequest, model: UserAdmin) -> Iterable[tuple[str, str]]:
"""Selectable values for viewer to filter by."""
roles = Role.objects.all()
return ((r.name, r.name) for r in roles)
def queryset(self, request: HttpRequest, queryset: QuerySet) -> QuerySet | None:
"""Query to filter the list of Users against."""
if not self.value():
return None
role = Role.objects.get(name=self.value())
return queryset.filter(roles__contains=[role.id])
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
"""Admin formatting for the User model."""
def top_role_coloured(self, user: User) -> SafeString:
"""Returns the top role of the user with html style matching role colour."""
return format_html(
'<span style="color: {0}; font-weight: bold;">{1}</span>',
f"#{user.top_role.colour:06X}",
user.top_role.name
)
top_role_coloured.short_description = "Top Role"
def all_roles_coloured(self, user: User) -> SafeString:
"""Returns all user roles with html style matching role colours."""
roles = Role.objects.filter(id__in=user.roles)
return format_html(
"</br>".join(
f'<span style="color: #{r.colour:06X}; font-weight: bold;">{r.name}</span>'
for r in roles
)
)
all_roles_coloured.short_description = "All Roles"
search_fields = ("name", "id", "roles")
list_filter = (UserRoleFilter, "in_guild")
list_display = ("username", "top_role_coloured", "in_guild")
fields = ("username", "id", "in_guild", "all_roles_coloured")
sortable_by = ("username",)
def has_add_permission(self, *args) -> bool:
"""Prevent adding from django admin."""
return False
def has_change_permission(self, *args) -> bool:
"""Prevent editing from django admin."""
return False
|