Skip to content

Commit 5e85677

Browse files
fixed connection leaks in StarboardManager
1 parent 1cd1a98 commit 5e85677

File tree

3 files changed

+73
-113
lines changed

3 files changed

+73
-113
lines changed

src/main/java/net/javadiscord/javabot/Bot.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -137,11 +137,11 @@ public static void main(String[] args) throws Exception {
137137
.setCommandsPackage("net.javadiscord.javabot")
138138
.setDefaultCommandType(RegistrationType.GUILD)
139139
.build();
140-
addEventListeners(jda, dih4jda);
141-
addComponentHandler(dih4jda);
140+
customTagManager = new CustomTagManager(jda, dataSource);
142141
messageCache = new MessageCache();
143142
serverLockManager = new ServerLockManager(jda);
144-
customTagManager = new CustomTagManager(jda, dataSource);
143+
addEventListeners(jda, dih4jda);
144+
addComponentHandler(dih4jda);
145145
// initialize Sentry
146146
Sentry.init(options -> {
147147
options.setDsn(config.getSystems().getSentryDsn());

src/main/java/net/javadiscord/javabot/systems/moderation/AutoMod.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ public boolean hasAdvertisingLink(@NotNull Message message) {
228228
// Advertising
229229
Matcher matcher = INVITE_URL.matcher(cleanString(message.getContentRaw()));
230230
if (matcher.find()) {
231-
return Arrays.stream(Bot.config.get(message.getGuild()).getModerationConfig().getAutomodInviteExcludes()).noneMatch(message.getContentRaw()::contains);
231+
return Bot.config.get(message.getGuild()).getModerationConfig().getAutomodInviteExcludes().stream().noneMatch(message.getContentRaw()::contains);
232232
}
233233
return false;
234234
}

src/main/java/net/javadiscord/javabot/systems/starboard/StarboardManager.java

Lines changed: 69 additions & 109 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@
44
import net.dv8tion.jda.api.EmbedBuilder;
55
import net.dv8tion.jda.api.entities.*;
66
import net.dv8tion.jda.api.entities.emoji.Emoji;
7+
import net.dv8tion.jda.api.entities.emoji.UnicodeEmoji;
78
import net.dv8tion.jda.api.events.message.MessageDeleteEvent;
89
import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent;
910
import net.dv8tion.jda.api.events.message.react.MessageReactionRemoveEvent;
1011
import net.dv8tion.jda.api.hooks.ListenerAdapter;
12+
import net.dv8tion.jda.api.interactions.components.buttons.Button;
1113
import net.dv8tion.jda.api.requests.restaction.MessageAction;
1214
import net.javadiscord.javabot.Bot;
1315
import net.javadiscord.javabot.data.config.guild.StarboardConfig;
@@ -18,6 +20,7 @@
1820
import net.javadiscord.javabot.util.Responses;
1921
import org.jetbrains.annotations.NotNull;
2022

23+
import java.sql.Connection;
2124
import java.sql.SQLException;
2225
import java.util.concurrent.ExecutionException;
2326

@@ -28,76 +31,69 @@
2831
public class StarboardManager extends ListenerAdapter {
2932
@Override
3033
public void onMessageReactionAdd(@NotNull MessageReactionAddEvent event) {
31-
if (!validUser(event.getUser())) return;
32-
if (!isValidChannel(event.getChannel())) return;
34+
if (isInvalidUser(event.getUser())) return;
35+
if (isInvalidChannel(event.getChannel())) return;
3336
handleReactionEvent(event.getGuild(), event.getEmoji(), event.getChannel(), event.getMessageIdLong());
3437
}
3538

3639
@Override
3740
public void onMessageReactionRemove(@NotNull MessageReactionRemoveEvent event) {
38-
if (!validUser(event.getUser())) return;
39-
if (!isValidChannel(event.getGuildChannel())) return;
41+
if (isInvalidUser(event.getUser())) return;
42+
if (isInvalidChannel(event.getGuildChannel())) return;
4043
handleReactionEvent(event.getGuild(), event.getEmoji(), event.getChannel(), event.getMessageIdLong());
4144
}
4245

4346
private void handleReactionEvent(Guild guild, Emoji emoji, MessageChannel channel, long messageId) {
4447
Bot.asyncPool.submit(() -> {
45-
var config = Bot.config.get(guild).getStarboardConfig();
48+
StarboardConfig config = Bot.config.get(guild).getStarboardConfig();
4649
if (config.getStarboardChannel().equals(channel)) return;
4750
Emoji starEmote = config.getEmojis().get(0);
4851
if (!emoji.equals(starEmote)) return;
4952
channel.retrieveMessageById(messageId).queue(
5053
message -> {
5154
int stars = getReactionCountForEmote(starEmote, message);
52-
try (var con = Bot.dataSource.getConnection()) {
53-
var repo = new StarboardRepository(con);
54-
var entry = repo.getEntryByMessageId(message.getIdLong());
55+
DbHelper.doDaoAction(StarboardRepository::new, dao -> {
56+
StarboardEntry entry = dao.getEntryByMessageId(message.getIdLong());
5557
if (entry != null) {
5658
updateStarboardMessage(message, stars, config);
5759
} else if (stars >= config.getReactionThreshold()) {
5860
addMessageToStarboard(message, stars, config);
59-
} else if (stars < 1) {
60-
if (!removeMessageFromStarboard(message.getIdLong(), channel, config)) {
61-
log.error("Could not remove Message from Starboard");
62-
}
61+
} else if (stars < 1 && !removeMessageFromStarboard(message.getIdLong(), channel, config)) {
62+
log.error("Could not remove Message from Starboard");
6363
}
64-
} catch (SQLException e) {
65-
ExceptionLogger.capture(e, getClass().getSimpleName());
66-
}
64+
});
6765
}, e -> log.error("Could not add Message to Starboard", e)
6866
);
6967
});
7068
}
7169

72-
private boolean isValidChannel(@NotNull MessageChannel channel) {
73-
var type = channel.getType();
74-
return type == ChannelType.TEXT || type == ChannelType.GUILD_PUBLIC_THREAD;
70+
private boolean isInvalidChannel(@NotNull MessageChannel channel) {
71+
ChannelType type = channel.getType();
72+
return type != ChannelType.TEXT && type != ChannelType.GUILD_PUBLIC_THREAD;
7573
}
7674

7775
@Override
7876
public void onMessageDelete(@NotNull MessageDeleteEvent event) {
79-
if (!isValidChannel(event.getChannel())) return;
80-
try (var con = Bot.dataSource.getConnection()) {
81-
var repo = new StarboardRepository(con);
82-
var config = Bot.config.get(event.getGuild()).getStarboardConfig();
77+
if (isInvalidChannel(event.getChannel())) return;
78+
try (Connection con = Bot.dataSource.getConnection()) {
79+
StarboardRepository repo = new StarboardRepository(con);
80+
StarboardConfig config = Bot.config.get(event.getGuild()).getStarboardConfig();
8381
StarboardEntry entry;
8482
if (event.getChannel().equals(config.getStarboardChannel())) {
8583
entry = repo.getEntryByStarboardMessageId(event.getMessageIdLong());
8684
} else {
8785
entry = repo.getEntryByMessageId(event.getMessageIdLong());
8886
}
89-
if (entry != null) {
90-
if (!removeMessageFromStarboard(entry.getOriginalMessageId(), event.getChannel(), config)) {
91-
log.error("Could not remove Message from Starboard");
92-
}
87+
if (entry != null && !removeMessageFromStarboard(entry.getOriginalMessageId(), event.getChannel(), config)) {
88+
log.error("Could not remove Message from Starboard");
9389
}
9490
} catch (SQLException e) {
9591
ExceptionLogger.capture(e, getClass().getSimpleName());
9692
}
9793
}
9894

99-
private boolean validUser(User user) {
100-
return user != null && !user.isBot() && !user.isSystem();
95+
private boolean isInvalidUser(User user) {
96+
return user == null || user.isBot() || user.isSystem();
10197
}
10298

10399
/**
@@ -107,19 +103,20 @@ private boolean validUser(User user) {
107103
* @param message The message.
108104
* @return The amount of reactions.
109105
*/
110-
private int getReactionCountForEmote(Emoji emoji, Message message) {
106+
private int getReactionCountForEmote(Emoji emoji, @NotNull Message message) {
111107
return message.getReactions().stream()
112108
.filter(r -> r.getEmoji().equals(emoji))
113109
.findFirst()
114110
.map(MessageReaction::getCount)
115111
.orElse(0);
116112
}
117113

118-
private void addMessageToStarboard(Message message, int stars, StarboardConfig config) throws SQLException {
114+
private void addMessageToStarboard(Message message, int stars, @NotNull StarboardConfig config) throws SQLException {
119115
if (stars < config.getReactionThreshold()) return;
120116
MessageEmbed embed = buildStarboardEmbed(message);
121117
MessageAction action = config.getStarboardChannel()
122-
.sendMessage(String.format("%s %s | %s", config.getEmojis().get(0), stars, message.getChannel().getAsMention()))
118+
.sendMessage(String.format("%s %s", config.getEmojis().get(0), stars))
119+
.setActionRow(Button.link(message.getJumpUrl(), "Jump to Message"))
123120
.setEmbeds(embed);
124121
for (Message.Attachment a : message.getAttachments()) {
125122
try {
@@ -140,100 +137,63 @@ private void addMessageToStarboard(Message message, int stars, StarboardConfig c
140137
);
141138
}
142139

143-
private void updateStarboardMessage(Message message, int stars, StarboardConfig config) throws SQLException {
144-
var repo = new StarboardRepository(Bot.dataSource.getConnection());
145-
var starboardId = repo.getEntryByMessageId(message.getIdLong()).getStarboardMessageId();
146-
config.getStarboardChannel().retrieveMessageById(starboardId).queue(
147-
starboardMessage -> {
148-
if (stars < 1) {
149-
try {
150-
if (!removeMessageFromStarboard(message.getIdLong(), message.getChannel(), config)) {
151-
log.error("Could not remove Message from Starboard");
140+
private void updateStarboardMessage(@NotNull Message message, int stars, @NotNull StarboardConfig config) throws SQLException {
141+
try (Connection con = Bot.dataSource.getConnection()) {
142+
StarboardRepository repo = new StarboardRepository(con);
143+
long starboardId = repo.getEntryByMessageId(message.getIdLong()).getStarboardMessageId();
144+
config.getStarboardChannel().retrieveMessageById(starboardId).queue(
145+
starboardMessage -> {
146+
if (stars < 1) {
147+
try {
148+
if (!removeMessageFromStarboard(message.getIdLong(), message.getChannel(), config)) {
149+
log.error("Could not remove Message from Starboard");
150+
}
151+
} catch (SQLException e) {
152+
ExceptionLogger.capture(e, getClass().getSimpleName());
152153
}
153-
} catch (SQLException e) {
154-
ExceptionLogger.capture(e, getClass().getSimpleName());
154+
} else {
155+
UnicodeEmoji starEmote = config.getEmojis().get(0);
156+
if (stars > 10) starEmote = config.getEmojis().get(1);
157+
if (stars > 25) starEmote = config.getEmojis().get(2);
158+
starboardMessage.editMessage(
159+
String.format("%s %s | %s", starEmote, stars, message.getChannel().getAsMention()))
160+
.queue();
161+
}
162+
}, e -> {
163+
log.error("Could not retrieve original Message. Deleting corresponding Starboard Entry...");
164+
try {
165+
removeMessageFromStarboard(message.getIdLong(), message.getChannel(), config);
166+
} catch (SQLException ex) {
167+
ex.printStackTrace();
155168
}
156-
} else {
157-
var starEmote = config.getEmojis().get(0);
158-
if (stars > 10) starEmote = config.getEmojis().get(1);
159-
if (stars > 25) starEmote = config.getEmojis().get(2);
160-
starboardMessage.editMessage(
161-
String.format("%s %s | %s", starEmote, stars, message.getChannel().getAsMention()))
162-
.queue();
163-
}
164-
}, e -> {
165-
log.error("Could not retrieve original Message. Deleting corresponding Starboard Entry...");
166-
try {
167-
removeMessageFromStarboard(message.getIdLong(), message.getChannel(), config);
168-
} catch (SQLException ex) {
169-
ex.printStackTrace();
170169
}
171-
}
172-
);
173-
}
174-
175-
private boolean removeMessageFromStarboard(long messageId, MessageChannel channel, StarboardConfig config) throws SQLException {
176-
var repo = new StarboardRepository(Bot.dataSource.getConnection());
177-
var entry = repo.getEntryByMessageId(messageId);
178-
if (entry == null) return false;
179-
if (!channel.equals(config.getStarboardChannel())) {
180-
config.getStarboardChannel().retrieveMessageById(entry.getStarboardMessageId()).queue(
181-
starboardMessage -> starboardMessage.delete().queue(),
182-
Throwable::printStackTrace
183170
);
184171
}
185-
repo.delete(messageId);
186-
log.info("Removed Starboard Entry with message Id {}", messageId);
187-
return true;
188172
}
189173

190-
/**
191-
* Updates all Starboard Entries in the current guild.
192-
*
193-
* @param guild The current guild.
194-
*/
195-
public void updateAllStarboardEntries(Guild guild) {
196-
log.info("Updating all Starboard Entries");
197-
try (var con = Bot.dataSource.getConnection()) {
198-
var repo = new StarboardRepository(con);
199-
var entries = repo.getAllStarboardEntries(guild.getIdLong());
200-
var config = Bot.config.get(guild).getStarboardConfig();
201-
var starEmote = config.getEmojis().get(0);
202-
for (var entry : entries) {
203-
var channel = guild.getTextChannelById(entry.getChannelId());
204-
if (channel == null) {
205-
removeMessageFromStarboard(entry.getOriginalMessageId(), channel, config);
206-
return;
207-
}
208-
channel.retrieveMessageById(entry.getOriginalMessageId()).queue(
209-
message -> {
210-
try {
211-
updateStarboardMessage(message, getReactionCountForEmote(starEmote, message), config);
212-
} catch (SQLException ex) {
213-
ex.printStackTrace();
214-
}
215-
},
216-
e -> {
217-
try {
218-
removeMessageFromStarboard(entry.getOriginalMessageId(), channel, config);
219-
} catch (SQLException ex) {
220-
ex.printStackTrace();
221-
}
222-
}
174+
private boolean removeMessageFromStarboard(long messageId, MessageChannel channel, StarboardConfig config) throws SQLException {
175+
try (Connection con = Bot.dataSource.getConnection()) {
176+
StarboardRepository repo = new StarboardRepository(con);
177+
StarboardEntry entry = repo.getEntryByMessageId(messageId);
178+
if (entry == null) return false;
179+
if (!channel.equals(config.getStarboardChannel())) {
180+
config.getStarboardChannel().retrieveMessageById(entry.getStarboardMessageId()).queue(
181+
starboardMessage -> starboardMessage.delete().queue(), ExceptionLogger::capture
223182
);
224183
}
225-
} catch (SQLException e) {
226-
ExceptionLogger.capture(e, getClass().getSimpleName());
184+
repo.delete(messageId);
185+
log.info("Removed Starboard Entry with message Id {}", messageId);
186+
return true;
227187
}
228188
}
229189

230-
private MessageEmbed buildStarboardEmbed(Message message) {
190+
private @NotNull MessageEmbed buildStarboardEmbed(@NotNull Message message) {
231191
var author = message.getAuthor();
232192
return new EmbedBuilder()
233-
.setAuthor("Jump to Message", message.getJumpUrl())
234-
.setFooter(author.getAsTag(), author.getEffectiveAvatarUrl())
193+
.setAuthor(author.getAsTag(), message.getJumpUrl(), author.getEffectiveAvatarUrl())
235194
.setColor(Responses.Type.DEFAULT.getColor())
236195
.setDescription(message.getContentRaw())
196+
.setFooter("from: #" + message.getChannel().getName())
237197
.build();
238198
}
239199
}

0 commit comments

Comments
 (0)