|
| 1 | +package org.togetherjava.tjbot.commands.filesharing; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 4 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 5 | +import net.dv8tion.jda.api.entities.ChannelType; |
| 6 | +import net.dv8tion.jda.api.entities.Message; |
| 7 | +import net.dv8tion.jda.api.entities.ThreadChannel; |
| 8 | +import net.dv8tion.jda.api.entities.User; |
| 9 | +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; |
| 10 | +import net.dv8tion.jda.api.interactions.components.buttons.Button; |
| 11 | +import org.jetbrains.annotations.NotNull; |
| 12 | +import org.slf4j.Logger; |
| 13 | +import org.slf4j.LoggerFactory; |
| 14 | +import org.togetherjava.tjbot.commands.MessageReceiverAdapter; |
| 15 | +import org.togetherjava.tjbot.config.Config; |
| 16 | + |
| 17 | +import java.io.IOException; |
| 18 | +import java.io.InputStream; |
| 19 | +import java.io.UncheckedIOException; |
| 20 | +import java.net.HttpURLConnection; |
| 21 | +import java.net.URI; |
| 22 | +import java.net.http.HttpClient; |
| 23 | +import java.net.http.HttpRequest; |
| 24 | +import java.net.http.HttpResponse; |
| 25 | +import java.nio.charset.StandardCharsets; |
| 26 | +import java.util.*; |
| 27 | +import java.util.concurrent.CompletableFuture; |
| 28 | +import java.util.concurrent.ConcurrentHashMap; |
| 29 | +import java.util.function.Predicate; |
| 30 | +import java.util.regex.Pattern; |
| 31 | + |
| 32 | +/** |
| 33 | + * Listener that receives all sent help messages and uploads them to a share service if the message |
| 34 | + * contains a file with the given extension in the |
| 35 | + * {@link FileSharingMessageListener#extensionFilter}. |
| 36 | + */ |
| 37 | +public class FileSharingMessageListener extends MessageReceiverAdapter { |
| 38 | + |
| 39 | + private static final Logger LOGGER = LoggerFactory.getLogger(FileSharingMessageListener.class); |
| 40 | + private static final ObjectMapper JSON = new ObjectMapper(); |
| 41 | + |
| 42 | + private static final String SHARE_API = "https://api.github.com/gists"; |
| 43 | + private static final HttpClient CLIENT = HttpClient.newHttpClient(); |
| 44 | + |
| 45 | + private final String gistApiKey; |
| 46 | + private final Set<String> extensionFilter = Set.of("txt", "java", "gradle", "xml", "kt", "json", |
| 47 | + "fxml", "css", "c", "h", "cpp", "py", "yml"); |
| 48 | + |
| 49 | + private final Predicate<String> isStagingChannelName; |
| 50 | + private final Predicate<String> isOverviewChannelName; |
| 51 | + |
| 52 | + |
| 53 | + public FileSharingMessageListener(@NotNull Config config) { |
| 54 | + super(Pattern.compile(".*")); |
| 55 | + |
| 56 | + gistApiKey = config.getGistApiKey(); |
| 57 | + isStagingChannelName = Pattern.compile(config.getHelpSystem().getStagingChannelPattern()) |
| 58 | + .asMatchPredicate(); |
| 59 | + isOverviewChannelName = Pattern.compile(config.getHelpSystem().getOverviewChannelPattern()) |
| 60 | + .asMatchPredicate(); |
| 61 | + } |
| 62 | + |
| 63 | + @Override |
| 64 | + public void onMessageReceived(@NotNull MessageReceivedEvent event) { |
| 65 | + User author = event.getAuthor(); |
| 66 | + if (author.isBot() || event.isWebhookMessage()) { |
| 67 | + return; |
| 68 | + } |
| 69 | + |
| 70 | + if (!isHelpThread(event)) { |
| 71 | + return; |
| 72 | + } |
| 73 | + |
| 74 | + |
| 75 | + List<Message.Attachment> attachments = event.getMessage() |
| 76 | + .getAttachments() |
| 77 | + .stream() |
| 78 | + .filter(this::isAttachmentRelevant) |
| 79 | + .toList(); |
| 80 | + |
| 81 | + CompletableFuture.runAsync(() -> { |
| 82 | + try { |
| 83 | + processAttachments(event, attachments); |
| 84 | + } catch (Exception e) { |
| 85 | + LOGGER.error("Unknown error while processing attachments", e); |
| 86 | + } |
| 87 | + }); |
| 88 | + } |
| 89 | + |
| 90 | + private boolean isAttachmentRelevant(@NotNull Message.Attachment attachment) { |
| 91 | + String extension = attachment.getFileExtension(); |
| 92 | + if (extension == null) { |
| 93 | + return false; |
| 94 | + } |
| 95 | + return extensionFilter.contains(extension); |
| 96 | + } |
| 97 | + |
| 98 | + |
| 99 | + private void processAttachments(@NotNull MessageReceivedEvent event, |
| 100 | + @NotNull List<Message.Attachment> attachments) { |
| 101 | + |
| 102 | + Map<String, GistFile> nameToFile = new ConcurrentHashMap<>(); |
| 103 | + |
| 104 | + List<CompletableFuture<Void>> tasks = new ArrayList<>(); |
| 105 | + for (Message.Attachment attachment : attachments) { |
| 106 | + CompletableFuture<Void> task = attachment.retrieveInputStream() |
| 107 | + .thenApply(this::readAttachment) |
| 108 | + .thenAccept( |
| 109 | + content -> nameToFile.put(getNameOf(attachment), new GistFile(content))); |
| 110 | + |
| 111 | + tasks.add(task); |
| 112 | + } |
| 113 | + |
| 114 | + tasks.forEach(CompletableFuture::join); |
| 115 | + |
| 116 | + GistFiles files = new GistFiles(nameToFile); |
| 117 | + GistRequest request = new GistRequest(event.getAuthor().getName(), false, files); |
| 118 | + String url = uploadToGist(request); |
| 119 | + sendResponse(event, url); |
| 120 | + } |
| 121 | + |
| 122 | + private @NotNull String readAttachment(@NotNull InputStream stream) { |
| 123 | + try { |
| 124 | + return new String(stream.readAllBytes(), StandardCharsets.UTF_8); |
| 125 | + } catch (IOException e) { |
| 126 | + throw new UncheckedIOException(e); |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + private @NotNull String getNameOf(@NotNull Message.Attachment attachment) { |
| 131 | + String fileName = attachment.getFileName(); |
| 132 | + String fileExtension = attachment.getFileExtension(); |
| 133 | + |
| 134 | + if (fileExtension == null || fileExtension.equals("txt")) { |
| 135 | + fileExtension = "java"; |
| 136 | + } else if (fileExtension.equals("fxml")) { |
| 137 | + fileExtension = "xml"; |
| 138 | + } |
| 139 | + |
| 140 | + int extensionIndex = fileName.lastIndexOf('.'); |
| 141 | + if (extensionIndex != -1) { |
| 142 | + fileName = fileName.substring(0, extensionIndex); |
| 143 | + } |
| 144 | + |
| 145 | + fileName += "." + fileExtension; |
| 146 | + |
| 147 | + return fileName; |
| 148 | + } |
| 149 | + |
| 150 | + private @NotNull String uploadToGist(@NotNull GistRequest jsonRequest) { |
| 151 | + String body; |
| 152 | + try { |
| 153 | + body = JSON.writeValueAsString(jsonRequest); |
| 154 | + } catch (JsonProcessingException e) { |
| 155 | + throw new IllegalStateException( |
| 156 | + "Attempting to upload a file to gist, but unable to create the JSON request.", |
| 157 | + e); |
| 158 | + } |
| 159 | + |
| 160 | + HttpRequest request = HttpRequest.newBuilder() |
| 161 | + .uri(URI.create(SHARE_API)) |
| 162 | + .header("Accept", "application/json") |
| 163 | + .header("Authorization", "token " + gistApiKey) |
| 164 | + .POST(HttpRequest.BodyPublishers.ofString(body)) |
| 165 | + .build(); |
| 166 | + |
| 167 | + HttpResponse<String> apiResponse; |
| 168 | + try { |
| 169 | + apiResponse = CLIENT.send(request, HttpResponse.BodyHandlers.ofString()); |
| 170 | + } catch (IOException e) { |
| 171 | + throw new UncheckedIOException(e); |
| 172 | + } catch (InterruptedException e) { |
| 173 | + Thread.currentThread().interrupt(); |
| 174 | + throw new IllegalStateException( |
| 175 | + "Attempting to upload a file to gist, but the request got interrupted.", e); |
| 176 | + } |
| 177 | + |
| 178 | + int statusCode = apiResponse.statusCode(); |
| 179 | + |
| 180 | + if (statusCode < HttpURLConnection.HTTP_OK |
| 181 | + || statusCode >= HttpURLConnection.HTTP_MULT_CHOICE) { |
| 182 | + throw new IllegalStateException("Gist API unexpected response: " + apiResponse.body()); |
| 183 | + } |
| 184 | + |
| 185 | + GistResponse gistResponse; |
| 186 | + try { |
| 187 | + gistResponse = JSON.readValue(apiResponse.body(), GistResponse.class); |
| 188 | + } catch (JsonProcessingException e) { |
| 189 | + throw new IllegalStateException( |
| 190 | + "Attempting to upload file to gist, but unable to parse its JSON response.", e); |
| 191 | + } |
| 192 | + return gistResponse.getHtmlUrl(); |
| 193 | + } |
| 194 | + |
| 195 | + private void sendResponse(@NotNull MessageReceivedEvent event, @NotNull String url) { |
| 196 | + Message message = event.getMessage(); |
| 197 | + String messageContent = |
| 198 | + "I uploaded your attachments as **gist**. That way, they are easier to read for everyone, especially mobile users 👍"; |
| 199 | + |
| 200 | + message.reply(messageContent).setActionRow(Button.link(url, "gist")).queue(); |
| 201 | + } |
| 202 | + |
| 203 | + private boolean isHelpThread(@NotNull MessageReceivedEvent event) { |
| 204 | + if (event.getChannelType() != ChannelType.GUILD_PUBLIC_THREAD) { |
| 205 | + return false; |
| 206 | + } |
| 207 | + |
| 208 | + ThreadChannel thread = event.getThreadChannel(); |
| 209 | + String rootChannelName = thread.getParentChannel().getName(); |
| 210 | + return isStagingChannelName.test(rootChannelName) |
| 211 | + || isOverviewChannelName.test(rootChannelName); |
| 212 | + } |
| 213 | +} |
0 commit comments