diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java index dd5694792e..556ea519d2 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java @@ -7,6 +7,7 @@ import org.togetherjava.tjbot.commands.free.FreeCommand; import org.togetherjava.tjbot.commands.mathcommands.TeXCommand; import org.togetherjava.tjbot.commands.moderation.*; +import org.togetherjava.tjbot.commands.moderation.temp.TemporaryModerationRoutine; import org.togetherjava.tjbot.commands.tags.TagCommand; import org.togetherjava.tjbot.commands.tags.TagManageCommand; import org.togetherjava.tjbot.commands.tags.TagSystem; @@ -46,6 +47,7 @@ public enum Commands { // TODO This should be moved into some proper command system instead (see GH issue #235 // which adds support for routines) new ModAuditLogRoutine(jda, database).start(); + new TemporaryModerationRoutine(jda, actionsStore).start(); // TODO This should be moved into some proper command system instead (see GH issue #236 // which adds support for listeners) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ActionRecord.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ActionRecord.java index dbfb81fa24..b568a2e0d2 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ActionRecord.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ActionRecord.java @@ -21,8 +21,8 @@ * @param reason the reason why this action was executed */ public record ActionRecord(int caseId, @NotNull Instant issuedAt, long guildId, long authorId, - long targetId, @NotNull ModerationUtils.Action actionType, - @Nullable Instant actionExpiresAt, @NotNull String reason) { + long targetId, @NotNull ModerationAction actionType, @Nullable Instant actionExpiresAt, + @NotNull String reason) { /** * Creates the action record that corresponds to the given action entry from the database table. @@ -34,7 +34,7 @@ public record ActionRecord(int caseId, @NotNull Instant issuedAt, long guildId, static @NotNull ActionRecord of(@NotNull ModerationActionsRecord action) { return new ActionRecord(action.getCaseId(), action.getIssuedAt(), action.getGuildId(), action.getAuthorId(), action.getTargetId(), - ModerationUtils.Action.valueOf(action.getActionType()), action.getActionExpiresAt(), + ModerationAction.valueOf(action.getActionType()), action.getActionExpiresAt(), action.getReason()); } } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java index e33f3feded..a9391a5871 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java @@ -71,12 +71,12 @@ public AuditCommand(@NotNull ModerationActionsStore actionsStore) { String shortSummary = "There are **%d actions** against the user.".formatted(actionAmount); // Summary of all actions with their count, like "- Warn: 5", descending - Map actionTypeToCount = actions.stream() + Map actionTypeToCount = actions.stream() .collect(Collectors.groupingBy(ActionRecord::actionType, Collectors.counting())); String typeCountSummary = actionTypeToCount.entrySet() .stream() .filter(typeAndCount -> typeAndCount.getValue() > 0) - .sorted(Map.Entry.comparingByValue().reversed()) + .sorted(Map.Entry.comparingByValue().reversed()) .map(typeAndCount -> "- **%s**: %d".formatted(typeAndCount.getKey(), typeAndCount.getValue())) .collect(Collectors.joining("\n")); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java index 5e48064647..f11d15772c 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java @@ -22,6 +22,8 @@ import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.config.Config; +import java.time.Instant; +import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; @@ -38,10 +40,14 @@ public final class BanCommand extends SlashCommandAdapter { private static final Logger logger = LoggerFactory.getLogger(BanCommand.class); private static final String TARGET_OPTION = "user"; + private static final String DURATION_OPTION = "duration"; private static final String DELETE_HISTORY_OPTION = "delete-history"; private static final String REASON_OPTION = "reason"; private static final String COMMAND_NAME = "ban"; private static final String ACTION_VERB = "ban"; + @SuppressWarnings("StaticCollection") + private static final List DURATIONS = List.of(ModerationUtils.PERMANENT_DURATION, + "1 hour", "3 hours", "1 day", "2 days", "3 days", "7 days", "30 days"); private final Predicate hasRequiredRole; private final ModerationActionsStore actionsStore; @@ -53,7 +59,12 @@ public final class BanCommand extends SlashCommandAdapter { public BanCommand(@NotNull ModerationActionsStore actionsStore) { super(COMMAND_NAME, "Bans the given user from the server", SlashCommandVisibility.GUILD); + OptionData durationData = new OptionData(OptionType.STRING, DURATION_OPTION, + "the duration of the ban, permanent or temporary", true); + DURATIONS.forEach(duration -> durationData.addChoice(duration, duration)); + getData().addOption(OptionType.USER, TARGET_OPTION, "The user who you want to ban", true) + .addOptions(durationData) .addOption(OptionType.STRING, REASON_OPTION, "Why the user should be banned", true) .addOptions(new OptionData(OptionType.INTEGER, DELETE_HISTORY_OPTION, "the amount of days of the message history to delete, none means no messages are deleted.", @@ -75,53 +86,37 @@ private static RestAction handleAlreadyBanned(@NotNull Guild.Ba return event.reply(message).setEphemeral(true); } - @SuppressWarnings("MethodWithTooManyParameters") - private RestAction banUserFlow(@NotNull User target, @NotNull Member author, - @NotNull String reason, int deleteHistoryDays, @NotNull Guild guild, - @NotNull SlashCommandEvent event) { - return sendDm(target, reason, guild, event) - .flatMap(hasSentDm -> banUser(target, author, reason, deleteHistoryDays, guild) - .map(banResult -> hasSentDm)) - .map(hasSentDm -> sendFeedback(hasSentDm, target, author, reason)) - .flatMap(event::replyEmbeds); - } - - private static RestAction sendDm(@NotNull ISnowflake target, @NotNull String reason, + private static RestAction sendDm(@NotNull ISnowflake target, + @Nullable ModerationUtils.TemporaryData temporaryData, @NotNull String reason, @NotNull Guild guild, @NotNull GenericEvent event) { + String durationMessage = + temporaryData == null ? "permanently" : "for " + temporaryData.duration(); + String dmMessage = + """ + Hey there, sorry to tell you but unfortunately you have been banned %s from the server %s. + If you think this was a mistake, please contact a moderator or admin of the server. + The reason for the ban is: %s + """ + .formatted(durationMessage, guild.getName(), reason); + return event.getJDA() .openPrivateChannelById(target.getId()) - .flatMap(channel -> channel.sendMessage( - """ - Hey there, sorry to tell you but unfortunately you have been banned from the server %s. - If you think this was a mistake, please contact a moderator or admin of the server. - The reason for the ban is: %s - """ - .formatted(guild.getName(), reason))) + .flatMap(channel -> channel.sendMessage(dmMessage)) .mapToResult() .map(Result::isSuccess); } - private AuditableRestAction banUser(@NotNull User target, @NotNull Member author, - @NotNull String reason, int deleteHistoryDays, @NotNull Guild guild) { - logger.info( - "'{}' ({}) banned the user '{}' ({}) from guild '{}' and deleted their message history of the last {} days, for reason '{}'.", - author.getUser().getAsTag(), author.getId(), target.getAsTag(), target.getId(), - guild.getName(), deleteHistoryDays, reason); - - actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), - ModerationUtils.Action.BAN, null, reason); - - return guild.ban(target, deleteHistoryDays, reason); - } - private static @NotNull MessageEmbed sendFeedback(boolean hasSentDm, @NotNull User target, - @NotNull Member author, @NotNull String reason) { + @NotNull Member author, @Nullable ModerationUtils.TemporaryData temporaryData, + @NotNull String reason) { + String durationText = "The ban duration is: " + + (temporaryData == null ? "permanent" : temporaryData.duration()); String dmNoticeText = ""; if (!hasSentDm) { - dmNoticeText = "(Unable to send them a DM.)"; + dmNoticeText = "\n(Unable to send them a DM.)"; } - return ModerationUtils.createActionResponse(author.getUser(), ModerationUtils.Action.BAN, - target, dmNoticeText, reason); + return ModerationUtils.createActionResponse(author.getUser(), ModerationAction.BAN, target, + durationText + dmNoticeText, reason); } private static Optional> handleNotAlreadyBannedResponse( @@ -147,6 +142,35 @@ private static Optional> handleNotAlreadyBannedRespo .setEphemeral(true)); } + @SuppressWarnings("MethodWithTooManyParameters") + private RestAction banUserFlow(@NotNull User target, @NotNull Member author, + @Nullable ModerationUtils.TemporaryData temporaryData, @NotNull String reason, + int deleteHistoryDays, @NotNull Guild guild, @NotNull SlashCommandEvent event) { + return sendDm(target, temporaryData, reason, guild, event) + .flatMap(hasSentDm -> banUser(target, author, temporaryData, reason, deleteHistoryDays, + guild).map(banResult -> hasSentDm)) + .map(hasSentDm -> sendFeedback(hasSentDm, target, author, temporaryData, reason)) + .flatMap(event::replyEmbeds); + } + + @SuppressWarnings("MethodWithTooManyParameters") + private AuditableRestAction banUser(@NotNull User target, @NotNull Member author, + @Nullable ModerationUtils.TemporaryData temporaryData, @NotNull String reason, + int deleteHistoryDays, @NotNull Guild guild) { + String durationMessage = + temporaryData == null ? "permanently" : "for " + temporaryData.duration(); + logger.info( + "'{}' ({}) banned the user '{}' ({}) {} from guild '{}' and deleted their message history of the last {} days, for reason '{}'.", + author.getUser().getAsTag(), author.getId(), target.getAsTag(), target.getId(), + durationMessage, guild.getName(), deleteHistoryDays, reason); + + Instant expiresAt = temporaryData == null ? null : temporaryData.expiresAt(); + actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), + ModerationAction.BAN, expiresAt, reason); + + return guild.ban(target, deleteHistoryDays, reason); + } + @SuppressWarnings({"BooleanMethodNameMustStartWithQuestion", "MethodWithTooManyParameters"}) private boolean handleChecks(@NotNull Member bot, @NotNull Member author, @Nullable Member target, @NotNull CharSequence reason, @NotNull Guild guild, @@ -178,9 +202,14 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { Member author = Objects.requireNonNull(event.getMember(), "The author is null"); String reason = Objects.requireNonNull(event.getOption(REASON_OPTION), "The reason is null") .getAsString(); + String duration = + Objects.requireNonNull(event.getOption(DURATION_OPTION), "The duration is null") + .getAsString(); Guild guild = Objects.requireNonNull(event.getGuild()); Member bot = guild.getSelfMember(); + Optional temporaryData = + ModerationUtils.computeTemporaryData(duration); if (!handleChecks(bot, author, targetOption.getAsMember(), reason, guild, event)) { return; @@ -195,9 +224,10 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { return handleAlreadyBanned(alreadyBanned.get(), event); } - return handleNotAlreadyBannedResponse(Objects - .requireNonNull(alreadyBanned.getFailure()), event, guild, target).orElseGet( - () -> banUserFlow(target, author, reason, deleteHistoryDays, guild, event)); + return handleNotAlreadyBannedResponse( + Objects.requireNonNull(alreadyBanned.getFailure()), event, guild, target) + .orElseGet(() -> banUserFlow(target, author, temporaryData.orElse(null), + reason, deleteHistoryDays, guild, event)); }).queue(); } } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java index 731e3ef83d..8c9fcf5dfe 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java @@ -92,7 +92,7 @@ private AuditableRestAction kickUser(@NotNull Member target, @NotNull Memb target.getId(), guild.getName(), reason); actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), - ModerationUtils.Action.KICK, null, reason); + ModerationAction.KICK, null, reason); return guild.kick(target, reason).reason(reason); } @@ -103,7 +103,7 @@ private AuditableRestAction kickUser(@NotNull Member target, @NotNull Memb if (!hasSentDm) { dmNoticeText = "(Unable to send them a DM.)"; } - return ModerationUtils.createActionResponse(author.getUser(), ModerationUtils.Action.KICK, + return ModerationUtils.createActionResponse(author.getUser(), ModerationAction.KICK, target.getUser(), dmNoticeText, reason); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationAction.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationAction.java new file mode 100644 index 0000000000..505830864e --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationAction.java @@ -0,0 +1,56 @@ +package org.togetherjava.tjbot.commands.moderation; + +import org.jetbrains.annotations.NotNull; + +/** + * All available moderation actions. + */ +public enum ModerationAction { + /** + * When a user bans another user. + */ + BAN("banned"), + /** + * When a user unbans another user. + */ + UNBAN("unbanned"), + /** + * When a user kicks another user. + */ + KICK("kicked"), + /** + * When a user warns another user. + */ + WARN("warned"), + /** + * When a user mutes another user. + */ + MUTE("muted"), + /** + * When a user unmutes another user. + */ + UNMUTE("unmuted"); + + private final String verb; + + /** + * Creates an instance with the given verb + * + * @param verb the verb of the action, as it would be used in a sentence, such as "banned" or + * "kicked" + */ + ModerationAction(@NotNull String verb) { + this.verb = verb; + } + + /** + * Gets the verb of the action, as it would be used in a sentence. + *

+ * Such as "banned" or "kicked" + * + * @return the verb of this action + */ + public @NotNull String getVerb() { + return verb; + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationActionsStore.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationActionsStore.java index 27555e3097..3ee603b93a 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationActionsStore.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationActionsStore.java @@ -15,16 +15,15 @@ /** * Store for moderation actions, e.g. as banning users. Can be used to retrieve information about * past events, such as when a user has been banned the last time. - * + *

* Actions have to be added to the store using - * {@link #addAction(long, long, long, ModerationUtils.Action, Instant, String)} at the time they - * are executed and can then be retrieved by methods such as - * {@link #getActionsByTypeAscending(long, ModerationUtils.Action)} or - * {@link #findActionByCaseId(int)}. - * + * {@link #addAction(long, long, long, ModerationAction, Instant, String)} at the time they are + * executed and can then be retrieved by methods such as + * {@link #getActionsByTypeAscending(long, ModerationAction)} or {@link #findActionByCaseId(int)}. + *

* Be aware that timestamps associated with actions, such as {@link ActionRecord#issuedAt()} are * slightly off the timestamps used by Discord. - * + *

* The store persists the actions and is thread safe. */ @SuppressWarnings("ClassCanBeRecord") @@ -33,24 +32,37 @@ public final class ModerationActionsStore { /** * Creates a new instance which writes and retrieves actions from a given database. - * + * * @param database the database to write and retrieve actions from */ public ModerationActionsStore(@NotNull Database database) { this.database = Objects.requireNonNull(database); } + /** + * Gets all already expired actions, measured by the current time, which have been written to + * the store, chronologically ascending with the action issued the earliest first. + * + * @return a list of all expired actions, chronologically ascending + */ + public @NotNull List getExpiredActionsAscending() { + return getActionsAscendingWhere( + ModerationActions.MODERATION_ACTIONS.ACTION_EXPIRES_AT.isNotNull() + .and(ModerationActions.MODERATION_ACTIONS.ACTION_EXPIRES_AT + .lessOrEqual(Instant.now()))); + } + /** * Gets all actions of a given type that have been written to the store, chronologically * ascending with the earliest action first. - * + * * @param guildId the id of the guild, only actions that happened in the context of that guild * will be retrieved * @param actionType the type of action to filter for * @return a list of all actions with the given type, chronologically ascending */ public @NotNull List getActionsByTypeAscending(long guildId, - @NotNull ModerationUtils.Action actionType) { + @NotNull ModerationAction actionType) { Objects.requireNonNull(actionType); return getActionsFromGuildAscending(guildId, @@ -60,7 +72,7 @@ public ModerationActionsStore(@NotNull Database database) { /** * Gets all actions executed against a given target that have been written to the store, * chronologically ascending with the earliest action first. - * + * * @param guildId the id of the guild, only actions that happened in the context of that guild * will be retrieved * @param targetId the id of the target user to filter for @@ -74,7 +86,7 @@ public ModerationActionsStore(@NotNull Database database) { /** * Gets all actions executed by a given author that have been written to the store, * chronologically ascending with the earliest action first. - * + * * @param guildId the id of the guild, only actions that happened in the context of that guild * will be retrieved * @param authorId the id of the author user to filter for @@ -86,23 +98,46 @@ public ModerationActionsStore(@NotNull Database database) { } /** - * Gets the action with the given case id from the store, if present. + * Gets the action of the given type that was issued the latest against the given target, if + * present. * + * @param guildId the id of the guild, only actions that happened in the context of that guild + * will be retrieved + * @param targetId the id of the target user to filter for + * @param actionType the type of the action + * @return the last action issued against the given user of the given type, if present + */ + public @NotNull Optional findLastActionAgainstTargetByType(long guildId, + long targetId, @NotNull ModerationAction actionType) { + return database + .read(context -> context.selectFrom(ModerationActions.MODERATION_ACTIONS) + .where(ModerationActions.MODERATION_ACTIONS.GUILD_ID.eq(guildId) + .and(ModerationActions.MODERATION_ACTIONS.TARGET_ID.eq(targetId)) + .and(ModerationActions.MODERATION_ACTIONS.ACTION_TYPE.eq(actionType.name()))) + .orderBy(ModerationActions.MODERATION_ACTIONS.ISSUED_AT.desc()) + .limit(1) + .fetchOptional()) + .map(ActionRecord::of); + } + + /** + * Gets the action with the given case id from the store, if present. + * * @param caseId the actions' case id to search for * @return the action with the given case id, if present */ public @NotNull Optional findActionByCaseId(int caseId) { - return Optional - .of(database.read(context -> context.selectFrom(ModerationActions.MODERATION_ACTIONS) + return database + .read(context -> context.selectFrom(ModerationActions.MODERATION_ACTIONS) .where(ModerationActions.MODERATION_ACTIONS.CASE_ID.eq(caseId)) - .fetchOne())) + .fetchOptional()) .map(ActionRecord::of); } /** * Adds the given action to the store. A unique case id will be associated to the action and * returned. - * + *

* It is assumed that the action is issued at the point in time this method is called. It is not * possible to assign a different timestamp, especially not an earlier point in time. * Consequently, this causes the timestamps to be slightly off from the timestamps recorded by @@ -119,7 +154,7 @@ public ModerationActionsStore(@NotNull Database database) { */ @SuppressWarnings("MethodWithTooManyParameters") public int addAction(long guildId, long authorId, long targetId, - @NotNull ModerationUtils.Action actionType, @Nullable Instant actionExpiresAt, + @NotNull ModerationAction actionType, @Nullable Instant actionExpiresAt, @NotNull String reason) { Objects.requireNonNull(actionType); Objects.requireNonNull(reason); @@ -143,8 +178,15 @@ public int addAction(long guildId, long authorId, long targetId, @NotNull Condition condition) { Objects.requireNonNull(condition); + return getActionsAscendingWhere( + ModerationActions.MODERATION_ACTIONS.GUILD_ID.eq(guildId).and(condition)); + } + + private @NotNull List getActionsAscendingWhere(@NotNull Condition condition) { + Objects.requireNonNull(condition); + return database.read(context -> context.selectFrom(ModerationActions.MODERATION_ACTIONS) - .where(ModerationActions.MODERATION_ACTIONS.GUILD_ID.eq(guildId).and(condition)) + .where(condition) .orderBy(ModerationActions.MODERATION_ACTIONS.ISSUED_AT.asc()) .stream() .map(ActionRecord::of) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java index 524d72ee1e..fcb916be95 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java @@ -12,6 +12,8 @@ import java.awt.*; import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.time.temporal.TemporalUnit; import java.util.Optional; import java.util.function.Predicate; import java.util.regex.Pattern; @@ -28,7 +30,20 @@ public enum ModerationUtils { * {@link Guild#ban(User, int, String)}. */ private static final int REASON_MAX_LENGTH = 512; + /** + * Human-readable text representing the duration of a permanent action, will be shown to the + * user as option for selection. + */ + static final String PERMANENT_DURATION = "permanent"; + /** + * The ambient color used by moderation actions, often used to streamline the color theme of + * embeds. + */ static final Color AMBIENT_COLOR = Color.decode("#895FE8"); + /** + * Matches the name of the role that is used to mute users, as used by {@link MuteCommand} and + * similar. + */ public static final Predicate isMuteRole = Pattern.compile(Config.getInstance().getMutedRolePattern()).asMatchPredicate(); @@ -298,8 +313,9 @@ static boolean handleHasAuthorRole(@NotNull String actionVerb, * @param reason an optional reason for why the action is executed, {@code null} if not desired * @return the created response */ - static @NotNull MessageEmbed createActionResponse(@NotNull User author, @NotNull Action action, - @NotNull User target, @Nullable String extraMessage, @Nullable String reason) { + static @NotNull MessageEmbed createActionResponse(@NotNull User author, + @NotNull ModerationAction action, @NotNull User target, @Nullable String extraMessage, + @Nullable String reason) { String description = "%s **%s** (id: %s).".formatted(action.getVerb(), target.getAsTag(), target.getId()); if (extraMessage != null && !extraMessage.isBlank()) { @@ -326,56 +342,40 @@ static boolean handleHasAuthorRole(@NotNull String actionVerb, } /** - * All available moderation actions. + * Computes a temporary data wrapper representing the action with the given duration. + * + * @param durationText the duration of the action, either {@code "permanent"} or a time window + * such as {@code 1 day} or {@code 2 minutes}. Supports all units supported by + * {@link Instant#plus(long, TemporalUnit)}. + * @return the temporary data represented by the given duration or empty if the duration is + * {@code "permanent"} */ - enum Action { - /** - * When a user bans another user. - */ - BAN("banned"), - /** - * When a user unbans another user. - */ - UNBAN("unbanned"), - /** - * When a user kicks another user. - */ - KICK("kicked"), - /** - * When a user warns another user. - */ - WARN("warned"), - /** - * When a user mutes another user. - */ - MUTE("muted"), - /** - * When a user unmutes another user. - */ - UNMUTE("unmuted"); + static @NotNull Optional computeTemporaryData(@NotNull String durationText) { + if (PERMANENT_DURATION.equals(durationText)) { + return Optional.empty(); + } - private final String verb; + // 1 minute, 1 day, 2 days, ... + String[] data = durationText.split(" ", 2); + int duration = Integer.parseInt(data[0]); + ChronoUnit unit = switch (data[1]) { + case "minute", "minutes" -> ChronoUnit.MINUTES; + case "hour", "hours" -> ChronoUnit.HOURS; + case "day", "days" -> ChronoUnit.DAYS; + default -> throw new IllegalArgumentException( + "Unsupported mute duration: " + durationText); + }; - /** - * Creates an instance with the given verb - * - * @param verb the verb of the action, as it would be used in a sentence, such as "banned" - * or "kicked" - */ - Action(@NotNull String verb) { - this.verb = verb; - } + return Optional.of(new TemporaryData(Instant.now().plus(duration, unit), durationText)); + } - /** - * Gets the verb of the action, as it would be used in a sentence. - *

- * Such as "banned" or "kicked" - * - * @return the verb of this action - */ - @NotNull - String getVerb() { - return verb; - } + /** + * Wrapper to hold data relevant to temporary actions, for example the time it expires. + * + * @param expiresAt the time the temporary action expires + * @param duration a human-readable text representing the duration of the temporary action, such + * as {@code "1 day"}. + */ + record TemporaryData(@NotNull Instant expiresAt, @NotNull String duration) { } } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java index cb363190fc..f10606c8a4 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java @@ -5,6 +5,7 @@ import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.interactions.Interaction; import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.interactions.commands.build.OptionData; import net.dv8tion.jda.api.requests.RestAction; import net.dv8tion.jda.api.requests.restaction.AuditableRestAction; import net.dv8tion.jda.api.utils.Result; @@ -16,7 +17,10 @@ import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.config.Config; +import java.time.Instant; +import java.util.List; import java.util.Objects; +import java.util.Optional; import java.util.function.Predicate; import java.util.regex.Pattern; @@ -30,9 +34,13 @@ public final class MuteCommand extends SlashCommandAdapter { private static final Logger logger = LoggerFactory.getLogger(MuteCommand.class); private static final String TARGET_OPTION = "user"; + private static final String DURATION_OPTION = "duration"; private static final String REASON_OPTION = "reason"; private static final String COMMAND_NAME = "mute"; private static final String ACTION_VERB = "mute"; + @SuppressWarnings("StaticCollection") + private static final List DURATIONS = List.of("10 minutes", "30 minutes", "1 hour", + "3 hours", "1 day", "3 days", "7 days", ModerationUtils.PERMANENT_DURATION); private final Predicate hasRequiredRole; private final ModerationActionsStore actionsStore; @@ -45,7 +53,12 @@ public MuteCommand(@NotNull ModerationActionsStore actionsStore) { super(COMMAND_NAME, "Mutes the given user so that they can not send messages anymore", SlashCommandVisibility.GUILD); + OptionData durationData = new OptionData(OptionType.STRING, DURATION_OPTION, + "the duration of the mute, permanent or temporary", true); + DURATIONS.forEach(duration -> durationData.addChoice(duration, duration)); + getData().addOption(OptionType.USER, TARGET_OPTION, "The user who you want to mute", true) + .addOptions(durationData) .addOption(OptionType.STRING, REASON_OPTION, "Why the user should be muted", true); hasRequiredRole = Pattern.compile(Config.getInstance().getSoftModerationRolePattern()) @@ -57,16 +70,19 @@ private static void handleAlreadyMutedTarget(@NotNull Interaction event) { event.reply("The user is already muted.").setEphemeral(true).queue(); } - private static RestAction sendDm(@NotNull ISnowflake target, @NotNull String reason, + private static RestAction sendDm(@NotNull ISnowflake target, + @Nullable ModerationUtils.TemporaryData temporaryData, @NotNull String reason, @NotNull Guild guild, @NotNull GenericEvent event) { + String durationMessage = + temporaryData == null ? "permanently" : "for " + temporaryData.duration(); String dmMessage = """ - Hey there, sorry to tell you but unfortunately you have been muted in the server %s. + Hey there, sorry to tell you but unfortunately you have been muted %s in the server %s. This means you can no longer send any messages in the server until you have been unmuted again. If you think this was a mistake, please contact a moderator or admin of the server. The reason for the mute is: %s """ - .formatted(guild.getName(), reason); + .formatted(durationMessage, guild.getName(), reason); return event.getJDA() .openPrivateChannelById(target.getId()) .flatMap(channel -> channel.sendMessage(dmMessage)) @@ -75,34 +91,43 @@ private static RestAction sendDm(@NotNull ISnowflake target, @NotNull S } private static @NotNull MessageEmbed sendFeedback(boolean hasSentDm, @NotNull Member target, - @NotNull Member author, @NotNull String reason) { + @NotNull Member author, @Nullable ModerationUtils.TemporaryData temporaryData, + @NotNull String reason) { + String durationText = "The mute duration is: " + + (temporaryData == null ? "permanent" : temporaryData.duration()); String dmNoticeText = ""; if (!hasSentDm) { - dmNoticeText = "(Unable to send them a DM.)"; + dmNoticeText = "\n(Unable to send them a DM.)"; } - return ModerationUtils.createActionResponse(author.getUser(), ModerationUtils.Action.MUTE, - target.getUser(), dmNoticeText, reason); + return ModerationUtils.createActionResponse(author.getUser(), ModerationAction.MUTE, + target.getUser(), durationText + dmNoticeText, reason); } private AuditableRestAction muteUser(@NotNull Member target, @NotNull Member author, - @NotNull String reason, @NotNull Guild guild) { - logger.info("'{}' ({}) muted the user '{}' ({}) in guild '{}' for reason '{}'.", + @Nullable ModerationUtils.TemporaryData temporaryData, @NotNull String reason, + @NotNull Guild guild) { + String durationMessage = + temporaryData == null ? "permanently" : "for " + temporaryData.duration(); + logger.info("'{}' ({}) muted the user '{}' ({}) {} in guild '{}' for reason '{}'.", author.getUser().getAsTag(), author.getId(), target.getUser().getAsTag(), - target.getId(), guild.getName(), reason); + target.getId(), durationMessage, guild.getName(), reason); + Instant expiresAt = temporaryData == null ? null : temporaryData.expiresAt(); actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), - ModerationUtils.Action.MUTE, null, reason); + ModerationAction.MUTE, expiresAt, reason); return guild.addRoleToMember(target, ModerationUtils.getMutedRole(guild).orElseThrow()) .reason(reason); } + @SuppressWarnings("MethodWithTooManyParameters") private void muteUserFlow(@NotNull Member target, @NotNull Member author, - @NotNull String reason, @NotNull Guild guild, @NotNull SlashCommandEvent event) { - sendDm(target, reason, guild, event) - .flatMap(hasSentDm -> muteUser(target, author, reason, guild) + @Nullable ModerationUtils.TemporaryData temporaryData, @NotNull String reason, + @NotNull Guild guild, @NotNull SlashCommandEvent event) { + sendDm(target, temporaryData, reason, guild, event) + .flatMap(hasSentDm -> muteUser(target, author, temporaryData, reason, guild) .map(banResult -> hasSentDm)) - .map(hasSentDm -> sendFeedback(hasSentDm, target, author, reason)) + .map(hasSentDm -> sendFeedback(hasSentDm, target, author, temporaryData, reason)) .flatMap(event::replyEmbeds) .queue(); } @@ -134,14 +159,20 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { Member author = Objects.requireNonNull(event.getMember(), "The author is null"); String reason = Objects.requireNonNull(event.getOption(REASON_OPTION), "The reason is null") .getAsString(); + String duration = + Objects.requireNonNull(event.getOption(DURATION_OPTION), "The duration is null") + .getAsString(); Guild guild = Objects.requireNonNull(event.getGuild()); Member bot = guild.getSelfMember(); + Optional temporaryData = + ModerationUtils.computeTemporaryData(duration); if (!handleChecks(bot, author, target, reason, guild, event)) { return; } - muteUserFlow(Objects.requireNonNull(target), author, reason, guild, event); + muteUserFlow(Objects.requireNonNull(target), author, temporaryData.orElse(null), reason, + guild, event); } } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/RejoinMuteListener.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/RejoinMuteListener.java index 0278ce1c7c..2fa0ff438f 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/RejoinMuteListener.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/RejoinMuteListener.java @@ -10,6 +10,7 @@ import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; +import java.time.Instant; import java.util.*; /** @@ -45,6 +46,11 @@ private static void muteMember(@NotNull Member member) { .queue(); } + private static boolean isActionEffective(@NotNull ActionRecord action) { + // Effective if permanent or expires in the future + return action.actionExpiresAt() == null || action.actionExpiresAt().isAfter(Instant.now()); + } + @Override public void onGuildMemberJoin(@Nonnull GuildMemberJoinEvent event) { Member member = event.getMember(); @@ -55,27 +61,24 @@ public void onGuildMemberJoin(@Nonnull GuildMemberJoinEvent event) { } private boolean shouldMemberBeMuted(@NotNull IPermissionHolder member) { - List actions = new ArrayList<>(actionsStore - .getActionsByTargetAscending(member.getGuild().getIdLong(), member.getIdLong())); - Collections.reverse(actions); - - Optional lastMute = actions.stream() - .filter(action -> action.actionType() == ModerationUtils.Action.MUTE) - .findFirst(); + Optional lastMute = actionsStore.findLastActionAgainstTargetByType( + member.getGuild().getIdLong(), member.getIdLong(), ModerationAction.MUTE); if (lastMute.isEmpty()) { // User was never muted return false; } - Optional lastUnmute = actions.stream() - .filter(action -> action.actionType() == ModerationUtils.Action.UNMUTE) - .findFirst(); + Optional lastUnmute = actionsStore.findLastActionAgainstTargetByType( + member.getGuild().getIdLong(), member.getIdLong(), ModerationAction.UNMUTE); if (lastUnmute.isEmpty()) { // User was never unmuted - return true; + return isActionEffective(lastMute.orElseThrow()); } // The last issued action takes priority - return lastMute.orElseThrow().issuedAt().isAfter(lastUnmute.orElseThrow().issuedAt()); + if (lastMute.orElseThrow().issuedAt().isAfter(lastUnmute.orElseThrow().issuedAt())) { + return isActionEffective(lastMute.orElseThrow()); + } + return false; } } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnbanCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnbanCommand.java index b44daa3730..516ee88183 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnbanCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnbanCommand.java @@ -53,7 +53,7 @@ private void unban(@NotNull User target, @NotNull Member author, @NotNull String @NotNull Guild guild, @NotNull Interaction event) { guild.unban(target).reason(reason).queue(result -> { MessageEmbed message = ModerationUtils.createActionResponse(author.getUser(), - ModerationUtils.Action.UNBAN, target, null, reason); + ModerationAction.UNBAN, target, null, reason); event.replyEmbeds(message).queue(); logger.info("'{}' ({}) unbanned the user '{}' ({}) from guild '{}' for reason '{}'.", @@ -61,7 +61,7 @@ private void unban(@NotNull User target, @NotNull Member author, @NotNull String guild.getName(), reason); actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), - ModerationUtils.Action.UNBAN, null, reason); + ModerationAction.UNBAN, null, reason); }, unbanFailure -> handleFailure(unbanFailure, target, event)); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java index 6828981c68..fcd0f66a31 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java @@ -78,7 +78,7 @@ private static RestAction sendDm(@NotNull ISnowflake target, @NotNull S if (!hasSentDm) { dmNoticeText = "(Unable to send them a DM.)"; } - return ModerationUtils.createActionResponse(author.getUser(), ModerationUtils.Action.UNMUTE, + return ModerationUtils.createActionResponse(author.getUser(), ModerationAction.UNMUTE, target.getUser(), dmNoticeText, reason); } @@ -89,7 +89,7 @@ private AuditableRestAction unmuteUser(@NotNull Member target, @NotNull Me target.getId(), guild.getName(), reason); actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), - ModerationUtils.Action.UNMUTE, null, reason); + ModerationAction.UNMUTE, null, reason); return guild.removeRoleFromMember(target, ModerationUtils.getMutedRole(guild).orElseThrow()) .reason(reason); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index b7943a065f..2b2c8265c2 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -84,7 +84,7 @@ private void warnUser(@NotNull User target, @NotNull Member author, @NotNull Str reason); actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), - ModerationUtils.Action.WARN, null, reason); + ModerationAction.WARN, null, reason); } private static @NotNull MessageEmbed sendFeedback(boolean hasSentDm, @NotNull User target, @@ -93,8 +93,8 @@ private void warnUser(@NotNull User target, @NotNull Member author, @NotNull Str if (!hasSentDm) { dmNoticeText = "(Unable to send them a DM.)"; } - return ModerationUtils.createActionResponse(author.getUser(), ModerationUtils.Action.WARN, - target, dmNoticeText, reason); + return ModerationUtils.createActionResponse(author.getUser(), ModerationAction.WARN, target, + dmNoticeText, reason); } @Override diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/RevocableModerationAction.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/RevocableModerationAction.java new file mode 100644 index 0000000000..b2cedc3007 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/RevocableModerationAction.java @@ -0,0 +1,72 @@ +package org.togetherjava.tjbot.commands.moderation.temp; + +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.requests.RestAction; +import org.jetbrains.annotations.NotNull; +import org.togetherjava.tjbot.commands.moderation.ModerationAction; + +/** + * Represents revocable moderation actions, such as temporary bans. Primarily used by + * {@link TemporaryModerationRoutine} to identify and revoke such actions. + */ +interface RevocableModerationAction { + /** + * Classification of a revocation failure. + */ + @SuppressWarnings("PublicInnerClass") + enum FailureIdentification { + /** + * Acknowledges that the failure is known and has been handled. Hence, further error + * handling should not be continued. + */ + KNOWN, + /** + * The failure is unknown and has not been handled. Hence, further error handling should be + * continued. + */ + UNKNOWN + } + + /** + * The type to apply the temporary action, such as + * {@link net.dv8tion.jda.api.audit.ActionType#BAN}. + * + * @return the type to apply the temporary action + */ + @NotNull + ModerationAction getApplyType(); + + /** + * The type to revoke the temporary action, such as + * {@link net.dv8tion.jda.api.audit.ActionType#UNBAN}. + * + * @return the type to revoke the temporary action + */ + @NotNull + ModerationAction getRevokeType(); + + /** + * Revokes the temporary action against the given target. + * + * @param guild the guild the user belongs to + * @param target the target to revoke the action against + * @param reason why the action is revoked + * @return the unsubmitted revocation action + */ + @NotNull + RestAction revokeAction(@NotNull Guild guild, @NotNull User target, + @NotNull String reason); + + /** + * Handle a failure that might occur during revocation, i.e. execution of the action returned by + * {@link #revokeAction(Guild, User, String)}. + * + * @param failure the failure to handle + * @param targetId the id of the user who is targeted by the revocation + * @return a classification of the failure, decides whether the surrounding flow will continue + * to handle the error further or not + */ + @NotNull + FailureIdentification handleRevokeFailure(@NotNull Throwable failure, long targetId); +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryBanAction.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryBanAction.java new file mode 100644 index 0000000000..0941224872 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryBanAction.java @@ -0,0 +1,62 @@ +package org.togetherjava.tjbot.commands.moderation.temp; + +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.exceptions.ErrorResponseException; +import net.dv8tion.jda.api.requests.ErrorResponse; +import net.dv8tion.jda.api.requests.RestAction; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.moderation.ModerationAction; + +/** + * Action to revoke temporary bans, as applied by + * {@link org.togetherjava.tjbot.commands.moderation.BanCommand} and executed by + * {@link TemporaryModerationRoutine}. + */ +final class TemporaryBanAction implements RevocableModerationAction { + private static final Logger logger = LoggerFactory.getLogger(TemporaryBanAction.class); + + @Override + public @NotNull ModerationAction getApplyType() { + return ModerationAction.BAN; + } + + @Override + public @NotNull ModerationAction getRevokeType() { + return ModerationAction.UNBAN; + } + + @Override + public @NotNull RestAction revokeAction(@NotNull Guild guild, @NotNull User target, + @NotNull String reason) { + return guild.unban(target).reason(reason); + } + + @Override + public @NotNull FailureIdentification handleRevokeFailure(@NotNull Throwable failure, + long targetId) { + if (failure instanceof ErrorResponseException errorResponseException) { + if (errorResponseException.getErrorResponse() == ErrorResponse.UNKNOWN_USER) { + logger.debug( + "Attempted to revoke a temporary ban but user '{}' does not exist anymore.", + targetId); + return FailureIdentification.KNOWN; + } + + if (errorResponseException.getErrorResponse() == ErrorResponse.UNKNOWN_BAN) { + logger.debug( + "Attempted to revoke a temporary ban but the user '{}' is not banned anymore.", + targetId); + return FailureIdentification.KNOWN; + } + + if (errorResponseException.getErrorResponse() == ErrorResponse.MISSING_PERMISSIONS) { + logger.warn("Attempted to revoke a temporary ban but the bot lacks permission."); + return FailureIdentification.KNOWN; + } + } + return FailureIdentification.UNKNOWN; + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java new file mode 100644 index 0000000000..78428742aa --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryModerationRoutine.java @@ -0,0 +1,169 @@ +package org.togetherjava.tjbot.commands.moderation.temp; + +import net.dv8tion.jda.api.JDA; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.requests.RestAction; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.moderation.ActionRecord; +import org.togetherjava.tjbot.commands.moderation.ModerationAction; +import org.togetherjava.tjbot.commands.moderation.ModerationActionsStore; + +import java.time.Instant; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Routine that revokes temporary moderation actions, such as temporary bans, as listed by + * {@link ModerationActionsStore}. + *

+ * The routine is started by using {@link #start()} and then automatically executes on a schedule. + *

+ * Revoked actions are compatible with {@link ModerationActionsStore} and commands such as + * {@link org.togetherjava.tjbot.commands.moderation.UnbanCommand} and + * {@link org.togetherjava.tjbot.commands.moderation.AuditCommand}. + */ +public final class TemporaryModerationRoutine { + private static final Logger logger = LoggerFactory.getLogger(TemporaryModerationRoutine.class); + + private final ModerationActionsStore actionsStore; + private final JDA jda; + private final ScheduledExecutorService checkExpiredActionsService = + Executors.newSingleThreadScheduledExecutor(); + private final Map typeToRevocableAction; + + /** + * Creates a new instance. + * + * @param jda the JDA instance to use to send messages and retrieve information + * @param actionsStore the store used to retrieve temporary moderation actions + */ + public TemporaryModerationRoutine(@NotNull JDA jda, + @NotNull ModerationActionsStore actionsStore) { + this.actionsStore = actionsStore; + this.jda = jda; + + typeToRevocableAction = Stream.of(new TemporaryBanAction(), new TemporaryMuteAction()) + .collect( + Collectors.toMap(RevocableModerationAction::getApplyType, Function.identity())); + } + + private void checkExpiredActions() { + logger.debug("Checking expired temporary moderation actions to revoke..."); + + actionsStore.getExpiredActionsAscending() + .stream() + .filter(action -> typeToRevocableAction.containsKey(action.actionType())) + .map(RevocationGroupIdentifier::of) + .collect(Collectors.toSet()) + .forEach(this::processGroupedActions); + + logger.debug("Finished checking expired temporary moderation actions to revoke."); + } + + private void processGroupedActions(@NotNull RevocationGroupIdentifier groupIdentifier) { + // Do not revoke an action which was overwritten by a permanent action that was issued + // afterwards + // For example if a user was perm-banned after being temp-banned + ActionRecord lastApplyAction = actionsStore + .findLastActionAgainstTargetByType(groupIdentifier.guildId, groupIdentifier.targetId, + groupIdentifier.type) + .orElseThrow(); + if (lastApplyAction.actionExpiresAt() == null) { + return; + } + + // Do not revoke an action which was already revoked by another action issued afterwards + // For example if a user was unbanned manually after being temp-banned, + // but also if the system automatically revoked a temp-ban already itself + ModerationAction revokeActionType = + getRevocableActionByType(groupIdentifier.type).getRevokeType(); + Optional lastRevokeActionOpt = actionsStore.findLastActionAgainstTargetByType( + groupIdentifier.guildId, groupIdentifier.targetId, revokeActionType); + if (lastRevokeActionOpt.isPresent()) { + ActionRecord lastRevokeAction = lastRevokeActionOpt.orElseThrow(); + if (lastRevokeAction.issuedAt().isAfter(lastApplyAction.issuedAt()) + && (lastRevokeAction.actionExpiresAt() == null + || lastRevokeAction.actionExpiresAt().isAfter(Instant.now()))) { + return; + } + } + + revokeAction(groupIdentifier); + } + + private void revokeAction(@NotNull RevocationGroupIdentifier groupIdentifier) { + Guild guild = jda.getGuildById(groupIdentifier.guildId); + if (guild == null) { + logger.debug( + "Attempted to revoke a temporary moderation action but the bot is not connected to the guild '{}' anymore, skipping revoking.", + groupIdentifier.guildId); + return; + } + + jda.retrieveUserById(groupIdentifier.targetId) + .flatMap(target -> executeRevocation(guild, target, groupIdentifier.type)) + .queue(result -> { + }, failure -> handleFailure(failure, groupIdentifier)); + } + + private @NotNull RestAction executeRevocation(@NotNull Guild guild, @NotNull User target, + @NotNull ModerationAction actionType) { + logger.info("Revoked temporary action {} against user '{}' ({}).", actionType, + target.getAsTag(), target.getId()); + + String reason = "Automatic revocation of temporary action."; + actionsStore.addAction(guild.getIdLong(), jda.getSelfUser().getIdLong(), target.getIdLong(), + actionType, null, reason); + + return getRevocableActionByType(actionType).revokeAction(guild, target, reason); + } + + private void handleFailure(@NotNull Throwable failure, + @NotNull RevocationGroupIdentifier groupIdentifier) { + if (getRevocableActionByType(groupIdentifier.type).handleRevokeFailure(failure, + groupIdentifier.targetId) == RevocableModerationAction.FailureIdentification.KNOWN) { + return; + } + + logger.warn( + "Attempted to revoke a temporary moderation action for user '{}' but something unexpected went wrong.", + groupIdentifier.targetId, failure); + } + + private @NotNull RevocableModerationAction getRevocableActionByType( + @NotNull ModerationAction type) { + return Objects.requireNonNull(typeToRevocableAction.get(type), + "Action type is not revocable: " + type); + } + + /** + * Starts the routine, automatically checking expired temporary moderation actions on a + * schedule. + */ + public void start() { + // TODO This should be registered at some sort of routine system instead (see GH issue #235 + // which adds support for routines) + // TODO The initial run has to be delayed until after the guild cache has been updated + // (during CommandSystem startup) + checkExpiredActionsService.scheduleWithFixedDelay(this::checkExpiredActions, 5, 5, + TimeUnit.MINUTES); + } + + private record RevocationGroupIdentifier(long guildId, long targetId, + @NotNull ModerationAction type) { + static RevocationGroupIdentifier of(@NotNull ActionRecord actionRecord) { + return new RevocationGroupIdentifier(actionRecord.guildId(), actionRecord.targetId(), + actionRecord.actionType()); + } + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryMuteAction.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryMuteAction.java new file mode 100644 index 0000000000..0edd9f3308 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/TemporaryMuteAction.java @@ -0,0 +1,72 @@ +package org.togetherjava.tjbot.commands.moderation.temp; + +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.exceptions.ErrorResponseException; +import net.dv8tion.jda.api.requests.ErrorResponse; +import net.dv8tion.jda.api.requests.RestAction; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.moderation.ModerationAction; +import org.togetherjava.tjbot.commands.moderation.ModerationUtils; + +/** + * Action to revoke temporary mutes, as applied by + * {@link org.togetherjava.tjbot.commands.moderation.MuteCommand} and executed by + * {@link TemporaryModerationRoutine}. + */ +final class TemporaryMuteAction implements RevocableModerationAction { + private static final Logger logger = LoggerFactory.getLogger(TemporaryMuteAction.class); + + @Override + public @NotNull ModerationAction getApplyType() { + return ModerationAction.MUTE; + } + + @Override + public @NotNull ModerationAction getRevokeType() { + return ModerationAction.UNMUTE; + } + + @Override + public @NotNull RestAction revokeAction(@NotNull Guild guild, @NotNull User target, + @NotNull String reason) { + return guild + .removeRoleFromMember(target.getIdLong(), + ModerationUtils.getMutedRole(guild).orElseThrow()) + .reason(reason); + } + + @Override + public @NotNull FailureIdentification handleRevokeFailure(@NotNull Throwable failure, + long targetId) { + if (failure instanceof ErrorResponseException errorResponseException) { + if (errorResponseException.getErrorResponse() == ErrorResponse.UNKNOWN_USER) { + logger.debug( + "Attempted to revoke a temporary mute but user '{}' does not exist anymore.", + targetId); + return FailureIdentification.KNOWN; + } + + if (errorResponseException.getErrorResponse() == ErrorResponse.UNKNOWN_MEMBER) { + logger.debug( + "Attempted to revoke a temporary mute but user '{}' is not a member of the guild anymore.", + targetId); + return FailureIdentification.KNOWN; + } + + if (errorResponseException.getErrorResponse() == ErrorResponse.UNKNOWN_ROLE) { + logger.warn( + "Attempted to revoke a temporary mute but the mute role can not be found."); + return FailureIdentification.KNOWN; + } + + if (errorResponseException.getErrorResponse() == ErrorResponse.MISSING_PERMISSIONS) { + logger.warn("Attempted to revoke a temporary mute but the bot lacks permission."); + return FailureIdentification.KNOWN; + } + } + return FailureIdentification.UNKNOWN; + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/package-info.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/package-info.java new file mode 100644 index 0000000000..ba0fe1bbe9 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/temp/package-info.java @@ -0,0 +1,4 @@ +/** + * This package offers classes dealing with temporary moderation actions, such as temporary bans. + */ +package org.togetherjava.tjbot.commands.moderation.temp;