-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
LogUploading.kt
458 lines (409 loc) · 15.7 KB
/
LogUploading.kt
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
package org.hyacinthbots.lilybot.extensions.events
import com.kotlindiscord.kord.extensions.DISCORD_GREEN
import com.kotlindiscord.kord.extensions.DISCORD_PINK
import com.kotlindiscord.kord.extensions.DISCORD_RED
import com.kotlindiscord.kord.extensions.checks.anyGuild
import com.kotlindiscord.kord.extensions.checks.channelFor
import com.kotlindiscord.kord.extensions.checks.hasPermission
import com.kotlindiscord.kord.extensions.commands.application.slash.ephemeralSubCommand
import com.kotlindiscord.kord.extensions.components.components
import com.kotlindiscord.kord.extensions.components.ephemeralButton
import com.kotlindiscord.kord.extensions.extensions.Extension
import com.kotlindiscord.kord.extensions.extensions.ephemeralSlashCommand
import com.kotlindiscord.kord.extensions.extensions.event
import com.kotlindiscord.kord.extensions.modules.extra.pluralkit.events.PKMessageCreateEvent
import com.kotlindiscord.kord.extensions.sentry.tag
import com.kotlindiscord.kord.extensions.types.respond
import com.kotlindiscord.kord.extensions.utils.download
import com.kotlindiscord.kord.extensions.utils.isNullOrBot
import dev.kord.common.entity.ButtonStyle
import dev.kord.common.entity.Permission
import dev.kord.common.entity.Permissions
import dev.kord.core.behavior.channel.createEmbed
import dev.kord.core.behavior.channel.createMessage
import dev.kord.core.behavior.edit
import dev.kord.core.behavior.getChannelOfOrNull
import dev.kord.core.entity.Message
import dev.kord.core.entity.channel.GuildMessageChannel
import dev.kord.core.entity.channel.MessageChannel
import dev.kord.core.entity.channel.thread.TextChannelThread
import dev.kord.rest.builder.message.create.embed
import dev.kord.rest.builder.message.modify.actionRow
import dev.kord.rest.builder.message.modify.embed
import io.ktor.client.HttpClient
import io.ktor.client.request.forms.FormDataContent
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.readBytes
import io.ktor.http.Parameters
import kotlinx.coroutines.delay
import kotlinx.datetime.Clock
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json
import org.hyacinthbots.lilybot.database.collections.AutoThreadingCollection
import org.hyacinthbots.lilybot.database.collections.LogUploadingBlacklistCollection
import org.hyacinthbots.lilybot.database.collections.ThreadsCollection
import org.hyacinthbots.lilybot.database.collections.UtilityConfigCollection
import org.hyacinthbots.lilybot.extensions.config.ConfigOptions
import org.hyacinthbots.lilybot.utils.HYACINTH_GITHUB
import org.hyacinthbots.lilybot.utils.botHasChannelPerms
import org.hyacinthbots.lilybot.utils.configIsUsable
import org.hyacinthbots.lilybot.utils.requiredConfigs
import java.io.ByteArrayInputStream
import java.io.IOException
import java.util.zip.GZIPInputStream
import kotlin.time.Duration.Companion.seconds
const val DEPRECATION_MESSAGE =
"**Log Uploading is deprecated in LilyBot. It has been implemented in [Allium]" +
"($HYACINTH_GITHUB/Allium) instead. It will be removed in 4.9.0**"
/**
* The class for the uploading of logs to mclo.gs.
*
* @since 2.0
*/
@Deprecated(
"Implemented in Allium",
level = DeprecationLevel.WARNING
)
class LogUploading : Extension() {
override val name = "log-uploading"
/** The file extensions that will be read and decoded by this system. */
private val logFileExtensions = setOf("log", "gz", "txt")
override suspend fun setup() {
/**
* Upload files that have the extensions specified in [logFileExtensions] to mclo.gs,
* giving a user confirmation.
*
* @author Caio_MGT, maximumpower55
* @since 2.0
*/
event<PKMessageCreateEvent> {
check {
anyGuild()
failIf {
event.message.author.isNullOrBot()
event.message.getChannelOrNull() !is MessageChannel
}
requiredConfigs(ConfigOptions.LOG_UPLOADS_ENABLED)
// I hate NullPointerExceptions. This is to prevent a null pointer exception if the message is a Pk one.
if (channelFor(event) == null) return@check
botHasChannelPerms(Permissions(Permission.SendMessages, Permission.EmbedLinks))
}
action {
if (LogUploadingBlacklistCollection().isChannelInUploadBlacklist(
event.guildId!!,
event.message.channelId
) != null
) {
return@action
}
var deferUploadUntilThread = false
val autoThreadingConfig = AutoThreadingCollection().getSingleAutoThread(event.message.channelId)
if (autoThreadingConfig != null && autoThreadingConfig.channelId == event.message.channelId) {
deferUploadUntilThread = true
}
val eventMessage = event.message.asMessageOrNull() // Get the message
var uploadChannel = eventMessage.channel.asChannelOrNull()
val eventMember = event.member ?: event.author
if (deferUploadUntilThread) {
delay(4.seconds) // Delay to allow for thread creation
ThreadsCollection().getOwnerThreads(eventMember!!.id).forEach {
val thread =
event.getGuildOrNull()?.getChannelOfOrNull<TextChannelThread>(it.threadId) ?: return@forEach
if (thread.parentId == autoThreadingConfig?.channelId) {
try {
uploadChannel =
event.getGuildOrNull()?.getChannelOfOrNull<GuildMessageChannel>(it.threadId)
?: return@forEach
} catch (_: IllegalArgumentException) {
return@forEach
}
return@forEach
}
}
}
eventMessage.attachments.forEach { attachment ->
val attachmentFileName = attachment.filename
val attachmentFileExtension = attachmentFileName.substring(
attachmentFileName.lastIndexOf(".") + 1
)
if (attachmentFileExtension in logFileExtensions) {
val logBytes = attachment.download()
val logContent: String = if (attachmentFileExtension != "gz") {
// If the file is not a gz log, we just decode it
logBytes.decodeToString()
} else {
// If the file is a gz log, we convert it to a byte array,
// and unzip it
val bis = ByteArrayInputStream(logBytes)
val gis = GZIPInputStream(bis)
gis.readAllBytes().decodeToString()
}
// Ask the user to remove NEC to ease the debugging on mobile users and others
val necText = "at Not Enough Crashes"
val indexOfNECText = logContent.indexOf(necText)
if (indexOfNECText != -1) {
uploadChannel?.createEmbed {
title = "Not Enough Crashes detected in logs"
description = "Not Enough Crashes (NEC) is well known to cause issues and often " +
"makes the debugging process more difficult. " +
"Please remove NEC, recreate the issue, and resend the relevant files " +
"(i.e. log or crash report) if the issue persists.\n\n$DEPRECATION_MESSAGE"
footer {
text = eventMessage.author?.tag ?: ""
icon = eventMessage.author?.avatar?.cdnUrl?.toUrl()
}
color = DISCORD_PINK
}
} else {
// Ask the user if they're ok with uploading their log to a paste site
var confirmationMessage: Message? = null
confirmationMessage = uploadChannel?.createMessage {
embed {
title = "Do you want to upload this file to mclo.gs?"
description =
"mclo.gs is a website that allows users to share minecraft logs " +
"through public posts.\nIt's easier for the mobile users to view " +
"the file on mclo.gs, do you want it to be uploaded?\n\n$DEPRECATION_MESSAGE"
footer {
text =
"Uploaded by ${eventMessage.author?.tag ?: eventMember?.asUserOrNull()?.tag}"
icon =
eventMessage.author?.avatar?.cdnUrl?.toUrl() ?: eventMember?.asUserOrNull()?.avatar?.cdnUrl?.toUrl()
}
color = DISCORD_PINK
}
components {
ephemeralButton(row = 0) {
label = "Yes"
style = ButtonStyle.Success
action {
// Make sure only the log uploader can confirm this
if (event.interaction.user.id == eventMember!!.id) {
// Delete the confirmation and proceed to upload
confirmationMessage!!.delete()
val uploadMessage = uploadChannel!!.createEmbed {
title = "Uploading `$attachmentFileName` to mclo.gs..."
footer {
text =
"Uploaded by ${eventMessage.author?.tag ?: eventMember.asUserOrNull()?.tag}"
icon = eventMessage.author?.avatar?.cdnUrl?.toUrl()
?: eventMember.asUserOrNull()?.avatar?.cdnUrl?.toUrl()
}
timestamp = Clock.System.now()
color = DISCORD_PINK
}
try {
val response = postToMCLogs(logContent)
uploadMessage.edit {
embed {
title = "`$attachmentFileName` uploaded to mclo.gs"
description = DEPRECATION_MESSAGE
footer {
text =
"Uploaded by ${eventMessage.author?.tag ?: eventMember.asUserOrNull()?.tag}"
icon = eventMessage.author?.avatar?.cdnUrl?.toUrl()
?: eventMember.asUserOrNull()?.avatar?.cdnUrl?.toUrl()
}
timestamp = Clock.System.now()
color = DISCORD_PINK
}
actionRow {
linkButton(response) {
label = "Click here to view"
}
}
}
} catch (e: IOException) {
// If the upload fails, we'll just show the error
uploadMessage.edit {
embed {
title =
"Failed to upload `$attachmentFileName` to mclo.gs"
description = "Error: $e\n\n$DEPRECATION_MESSAGE"
footer {
text =
"Uploaded by ${eventMessage.author?.tag ?: eventMember.asUserOrNull()?.tag}"
icon = eventMessage.author?.avatar?.cdnUrl?.toUrl()
?: eventMember.asUserOrNull()?.avatar?.cdnUrl?.toUrl()
}
timestamp = Clock.System.now()
color = DISCORD_RED
}
}
// Capture Exception to Sentry
sentry.captureException(e) {
tag("log_file_name", attachmentFileName)
tag("extension", extension.name)
tag("id", eventMessage.id.toString())
}
e.printStackTrace()
}
} else {
respond { content = "Only the uploader can use this menu." }
}
}
}
ephemeralButton(row = 0) {
label = "No"
style = ButtonStyle.Danger
action {
if (event.interaction.user.id == eventMember!!.id) {
confirmationMessage!!.delete()
} else {
respond { content = "Only the uploader can use this menu." }
}
}
}
}
}
}
}
}
}
}
ephemeralSlashCommand {
name = "log-uploading"
description = "The parent command for blacklisting channels from running the log uploading code"
ephemeralSubCommand {
name = "blacklist-add"
description = "Add a channel to the log uploading blacklist"
requirePermission(Permission.ModerateMembers)
check {
anyGuild()
hasPermission(Permission.ModerateMembers)
}
action {
val blacklist = LogUploadingBlacklistCollection().isChannelInUploadBlacklist(guild!!.id, channel.id)
val utilityConfig = UtilityConfigCollection().getConfig(guild!!.id)!!
if (blacklist != null) {
respond {
content = "This channel already blocks the log uploading"
}
return@action
}
LogUploadingBlacklistCollection().setLogUploadingBlacklist(guild!!.id, channel.id)
respond {
content = "Log uploading is now blocked in this channel!"
}
if (!configIsUsable(guild!!.id, ConfigOptions.UTILITY_LOG)) return@action
guild!!.getChannelOfOrNull<GuildMessageChannel>(utilityConfig.utilityLogChannel!!)?.createEmbed {
title = "Log uploading disabled"
description = "Log uploading was disabled in ${channel.mention}"
color = DISCORD_RED
footer {
text = "Disabled by ${user.asUserOrNull()?.tag}"
icon = user.asUserOrNull()?.avatar?.cdnUrl?.toUrl()
}
}
}
}
ephemeralSubCommand {
name = "blacklist-remove"
description = "Remove a channel from the log uploading blacklist"
requirePermission(Permission.ModerateMembers)
check {
anyGuild()
hasPermission(Permission.ModerateMembers)
}
action {
LogUploadingBlacklistCollection().isChannelInUploadBlacklist(guild!!.id, channel.id) ?: run {
respond {
content = "This channel does not block log uploading"
}
return@action
}
val utilityConfig = UtilityConfigCollection().getConfig(guild!!.id)!!
LogUploadingBlacklistCollection().removeLogUploadingBlacklist(guild!!.id, channel.id)
respond {
content = "Log uploading is no longer blocked in this channel!"
}
if (!configIsUsable(guild!!.id, ConfigOptions.UTILITY_LOG)) return@action
guild!!.getChannelOfOrNull<GuildMessageChannel>(utilityConfig.utilityLogChannel!!)?.createEmbed {
title = "Log uploading re-enabled"
description = "Log uploading was re-enabled in ${channel.mention}"
color = DISCORD_GREEN
footer {
text = "Enabled by ${user.asUserOrNull()?.tag}"
icon = user.asUserOrNull()?.avatar?.cdnUrl?.toUrl()
}
}
}
}
ephemeralSubCommand {
name = "blacklist-list"
description = "List all channels that block log uploading"
requirePermission(Permission.ModerateMembers)
check {
anyGuild()
hasPermission(Permission.ModerateMembers)
}
action {
var channels = ""
LogUploadingBlacklistCollection().getLogUploadingBlacklist(guild!!.id).forEach {
channels += "<#${it.channelId}>"
}
respond {
embed {
title = "Channels that blacklist uploading"
description = "The following channels do not run the log uploading code when a matching " +
"attachment is sent."
field {
name = "Channels:"
value = if (channels != "") {
channels.replace(" ", "\n")
} else {
"No channels found!"
}
}
}
}
}
}
}
}
/**
* This data class will store the data of the log being uploaded by [postToMCLogs].
*
* **NOTE:** Setting these to null is necessary in case a value is missing, which would cause an error.
*
* @param success Whether the log upload was a success or not
* @param id The ID of the log uploaded
* @param error Any errors that were returned by the upload
*
* @author CaioMGT
* @since 3.1.0
*/
@Serializable
data class LogData(val success: Boolean, val id: String? = null, val error: String? = null)
/**
* This function coordinates the uploading of a user provided log to mclo.gs, allowing support to view logs easily.
*
* @param text The content of the log
* @return The link to the log upload
* @author Maximumpower55, CaioMGT
* @since 3.1.0
*/
private suspend fun postToMCLogs(text: String): String {
val client = HttpClient()
val cleanText = text.replace("\r\n", "\n", true).replace("\r", "\n", true)
val response = client.post("https://api.mclo.gs/1/log") {
setBody(
FormDataContent(
Parameters.build {
append("content", cleanText)
}
)
)
}.readBytes().decodeToString()
client.close()
val json = Json { ignoreUnknownKeys = true } // to avoid causing any errors due to missing values in the JSON
val log = json.decodeFromString<LogData>(response)
if (log.success) {
return "https://mclo.gs/" + log.id
} else {
throw IOException("Failed to upload log: " + log.error)
}
}
}