|
| 1 | +package org.togetherjava.tjbot.commands.github; |
| 2 | + |
| 3 | +import net.dv8tion.jda.api.EmbedBuilder; |
| 4 | +import net.dv8tion.jda.api.entities.Message; |
| 5 | +import net.dv8tion.jda.api.entities.MessageEmbed; |
| 6 | +import net.dv8tion.jda.api.entities.channel.ChannelType; |
| 7 | +import net.dv8tion.jda.api.entities.channel.concrete.ThreadChannel; |
| 8 | +import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel; |
| 9 | +import net.dv8tion.jda.api.events.message.MessageReceivedEvent; |
| 10 | +import org.apache.commons.collections4.ListUtils; |
| 11 | +import org.kohsuke.github.*; |
| 12 | + |
| 13 | +import org.togetherjava.tjbot.config.Config; |
| 14 | +import org.togetherjava.tjbot.features.MessageReceiverAdapter; |
| 15 | + |
| 16 | +import java.awt.*; |
| 17 | +import java.io.FileNotFoundException; |
| 18 | +import java.io.IOException; |
| 19 | +import java.io.UncheckedIOException; |
| 20 | +import java.time.Instant; |
| 21 | +import java.time.ZoneOffset; |
| 22 | +import java.time.format.DateTimeFormatter; |
| 23 | +import java.util.ArrayList; |
| 24 | +import java.util.List; |
| 25 | +import java.util.Optional; |
| 26 | +import java.util.function.Predicate; |
| 27 | +import java.util.regex.Matcher; |
| 28 | +import java.util.regex.Pattern; |
| 29 | +import java.util.stream.Collectors; |
| 30 | + |
| 31 | +/** |
| 32 | + * GitHub Referencing feature. If someone sends #id of an issue (e.g. #207) in specified channel, |
| 33 | + * the bot replies with an embed that contains info on the issue/PR. |
| 34 | + */ |
| 35 | +public final class GitHubReference extends MessageReceiverAdapter { |
| 36 | + static final String ID_GROUP = "id"; |
| 37 | + |
| 38 | + /** |
| 39 | + * The pattern(#123) used to determine whether a message is referencing an issue. |
| 40 | + */ |
| 41 | + static final Pattern ISSUE_REFERENCE_PATTERN = |
| 42 | + Pattern.compile("#(?<%s>\\d+)".formatted(ID_GROUP)); |
| 43 | + private static final int ISSUE_OPEN = Color.green.getRGB(); |
| 44 | + private static final int ISSUE_CLOSE = Color.red.getRGB(); |
| 45 | + |
| 46 | + /** |
| 47 | + * A constant representing the date and time formatter used for formatting the creation date of |
| 48 | + * an issue. The pattern "dd MMM, yyyy" represents the format "09 Oct, 2023". |
| 49 | + */ |
| 50 | + static final DateTimeFormatter FORMATTER = |
| 51 | + DateTimeFormatter.ofPattern("dd MMM, yyyy").withZone(ZoneOffset.UTC); |
| 52 | + private final Predicate<String> hasGithubIssueReferenceEnabled; |
| 53 | + private final Config config; |
| 54 | + |
| 55 | + /** |
| 56 | + * The repositories that are searched when looking for an issue. |
| 57 | + */ |
| 58 | + private List<GHRepository> repositories; |
| 59 | + |
| 60 | + public GitHubReference(Config config) { |
| 61 | + this.config = config; |
| 62 | + this.hasGithubIssueReferenceEnabled = |
| 63 | + Pattern.compile(config.getGitHubReferencingEnabledChannelPattern()) |
| 64 | + .asMatchPredicate(); |
| 65 | + acquireRepositories(); |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * Acquires the list of repositories to use as a source for lookup. |
| 70 | + */ |
| 71 | + private void acquireRepositories() { |
| 72 | + try { |
| 73 | + repositories = new ArrayList<>(); |
| 74 | + |
| 75 | + GitHub githubApi = GitHub.connectUsingOAuth(config.getGitHubApiKey()); |
| 76 | + |
| 77 | + for (long repoId : config.getGitHubRepositories()) { |
| 78 | + repositories.add(githubApi.getRepositoryById(repoId)); |
| 79 | + } |
| 80 | + } catch (IOException ex) { |
| 81 | + throw new UncheckedIOException(ex); |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + @Override |
| 86 | + public void onMessageReceived(MessageReceivedEvent event) { |
| 87 | + if (event.getAuthor().isBot() || !isAllowedChannelOrChildThread(event)) { |
| 88 | + return; |
| 89 | + } |
| 90 | + |
| 91 | + Message message = event.getMessage(); |
| 92 | + String content = message.getContentRaw(); |
| 93 | + Matcher matcher = ISSUE_REFERENCE_PATTERN.matcher(content); |
| 94 | + List<MessageEmbed> embeds = new ArrayList<>(); |
| 95 | + |
| 96 | + while (matcher.find()) { |
| 97 | + long defaultRepoId = config.getGitHubRepositories().get(0); |
| 98 | + findIssue(Integer.parseInt(matcher.group(ID_GROUP)), defaultRepoId) |
| 99 | + .ifPresent(issue -> embeds.add(generateReply(issue))); |
| 100 | + } |
| 101 | + |
| 102 | + replyBatchEmbeds(embeds, message, false); |
| 103 | + } |
| 104 | + |
| 105 | + /** |
| 106 | + * Replies to the given message with the given embeds in "batches", sending |
| 107 | + * {@value Message#MAX_EMBED_COUNT} embeds at a time (the discord limit) |
| 108 | + */ |
| 109 | + private void replyBatchEmbeds(List<MessageEmbed> embeds, Message message, |
| 110 | + boolean mentionRepliedUser) { |
| 111 | + List<List<MessageEmbed>> partition = ListUtils.partition(embeds, Message.MAX_EMBED_COUNT); |
| 112 | + boolean isFirstBatch = true; |
| 113 | + |
| 114 | + MessageChannel sourceChannel = message.getChannelType() == ChannelType.GUILD_PUBLIC_THREAD |
| 115 | + ? message.getChannel().asThreadChannel() |
| 116 | + : message.getChannel().asTextChannel(); |
| 117 | + |
| 118 | + for (List<MessageEmbed> messageEmbeds : partition) { |
| 119 | + if (isFirstBatch) { |
| 120 | + message.replyEmbeds(messageEmbeds).mentionRepliedUser(mentionRepliedUser).queue(); |
| 121 | + |
| 122 | + isFirstBatch = false; |
| 123 | + } else { |
| 124 | + sourceChannel.sendMessageEmbeds(messageEmbeds).queue(); |
| 125 | + } |
| 126 | + } |
| 127 | + } |
| 128 | + |
| 129 | + /** |
| 130 | + * Generates the embed to reply with when someone references an issue. |
| 131 | + */ |
| 132 | + MessageEmbed generateReply(GHIssue issue) throws UncheckedIOException { |
| 133 | + try { |
| 134 | + String title = "[#%d] %s".formatted(issue.getNumber(), issue.getTitle()); |
| 135 | + String titleUrl = issue.getHtmlUrl().toString(); |
| 136 | + String description = issue.getBody(); |
| 137 | + |
| 138 | + String labels = issue.getLabels() |
| 139 | + .stream() |
| 140 | + .map(GHLabel::getName) |
| 141 | + .collect(Collectors.joining(", ")); |
| 142 | + |
| 143 | + String assignees = issue.getAssignees() |
| 144 | + .stream() |
| 145 | + .map(this::getUserNameOrThrow) |
| 146 | + .collect(Collectors.joining(", ")); |
| 147 | + |
| 148 | + Instant createdAt = issue.getCreatedAt().toInstant(); |
| 149 | + String dateOfCreation = FORMATTER.format(createdAt); |
| 150 | + |
| 151 | + String footer = "%s • %s • %s".formatted(labels, assignees, dateOfCreation); |
| 152 | + |
| 153 | + return new EmbedBuilder() |
| 154 | + .setColor(issue.getState() == GHIssueState.OPEN ? ISSUE_OPEN : ISSUE_CLOSE) |
| 155 | + .setTitle(title, titleUrl) |
| 156 | + .setDescription(description) |
| 157 | + .setAuthor(issue.getUser().getName(), null, issue.getUser().getAvatarUrl()) |
| 158 | + .setFooter(footer) |
| 159 | + .build(); |
| 160 | + |
| 161 | + } catch (IOException ex) { |
| 162 | + throw new UncheckedIOException(ex); |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + /** |
| 167 | + * Either properly gathers the name of a user or throws a UncheckedIOException. |
| 168 | + */ |
| 169 | + private String getUserNameOrThrow(GHUser user) throws UncheckedIOException { |
| 170 | + try { |
| 171 | + return user.getName(); |
| 172 | + } catch (IOException ex) { |
| 173 | + throw new UncheckedIOException(ex); |
| 174 | + } |
| 175 | + } |
| 176 | + |
| 177 | + /** |
| 178 | + * Looks through all of the given repositories for an issue/pr with the given id. |
| 179 | + */ |
| 180 | + Optional<GHIssue> findIssue(int id, String targetIssueTitle) { |
| 181 | + return repositories.stream().map(repository -> { |
| 182 | + try { |
| 183 | + GHIssue issue = repository.getIssue(id); |
| 184 | + if (issue.getTitle().equals(targetIssueTitle)) { |
| 185 | + return Optional.of(issue); |
| 186 | + } |
| 187 | + } catch (FileNotFoundException ignored) { |
| 188 | + return Optional.<GHIssue>empty(); |
| 189 | + } catch (IOException ex) { |
| 190 | + throw new UncheckedIOException(ex); |
| 191 | + } |
| 192 | + return Optional.<GHIssue>empty(); |
| 193 | + }).filter(Optional::isPresent).findFirst().orElse(Optional.empty()); |
| 194 | + } |
| 195 | + |
| 196 | + Optional<GHIssue> findIssue(int id, long defaultRepoId) { |
| 197 | + return repositories.stream() |
| 198 | + .filter(repository -> repository.getId() == defaultRepoId) |
| 199 | + .map(repository -> { |
| 200 | + try { |
| 201 | + return Optional.of(repository.getIssue(id)); |
| 202 | + } catch (FileNotFoundException ignored) { |
| 203 | + return Optional.<GHIssue>empty(); |
| 204 | + } catch (IOException ex) { |
| 205 | + throw new UncheckedIOException(ex); |
| 206 | + } |
| 207 | + }) |
| 208 | + .filter(Optional::isPresent) |
| 209 | + .map(Optional::orElseThrow) |
| 210 | + .findAny(); |
| 211 | + } |
| 212 | + |
| 213 | + /** |
| 214 | + * All repositories monitored by this instance. |
| 215 | + */ |
| 216 | + List<GHRepository> getRepositories() { |
| 217 | + return repositories; |
| 218 | + } |
| 219 | + |
| 220 | + private boolean isAllowedChannelOrChildThread(MessageReceivedEvent event) { |
| 221 | + if (event.getChannelType().isThread()) { |
| 222 | + ThreadChannel threadChannel = event.getChannel().asThreadChannel(); |
| 223 | + String rootChannel = threadChannel.getParentChannel().getName(); |
| 224 | + return this.hasGithubIssueReferenceEnabled.test(rootChannel); |
| 225 | + } |
| 226 | + |
| 227 | + String textChannel = event.getChannel().asTextChannel().getName(); |
| 228 | + return this.hasGithubIssueReferenceEnabled.test(textChannel); |
| 229 | + } |
| 230 | +} |
0 commit comments