mirror of
https://github.com/Sheldan/abstracto.git
synced 2026-04-05 00:53:04 +00:00
[AB-138] improving logging at various places fixing various issues regarding async commands and exception handling, fixing role role calculation being done twice
This commit is contained in:
@@ -30,12 +30,14 @@ public class DeleteNote extends AbstractConditionableCommand {
|
||||
@Autowired
|
||||
private TemplateService templateService;
|
||||
|
||||
|
||||
|
||||
@Override
|
||||
public CommandResult execute(CommandContext commandContext) {
|
||||
checkParameters(commandContext);
|
||||
Long id = (Long) commandContext.getParameters().getParameters().get(0);
|
||||
if(userNoteManagementService.noteExists(id)) {
|
||||
userNoteManagementService.deleteNote(id);
|
||||
if(userNoteManagementService.noteExists(id, commandContext.getUserInitiatedContext().getServer())) {
|
||||
userNoteManagementService.deleteNote(id, commandContext.getUserInitiatedContext().getServer());
|
||||
} else {
|
||||
// TODO replace with exception
|
||||
return CommandResult.fromError(templateService.renderSimpleTemplate(NOTE_NOT_FOUND_EXCEPTION_TEMPLATE));
|
||||
|
||||
@@ -28,7 +28,7 @@ public class UnMuteJob extends QuartzJobBean {
|
||||
|
||||
@Override
|
||||
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
|
||||
log.info("Executing unMute job for mute {}", muteId);
|
||||
log.info("Executing unMute job for mute {} in server {}", muteId, serverId);
|
||||
muteService.endMute(muteId, serverId);
|
||||
}
|
||||
|
||||
|
||||
@@ -39,9 +39,11 @@ public class WarnDecayJob extends QuartzJobBean {
|
||||
@Transactional
|
||||
public void executeInternal(JobExecutionContext context) throws JobExecutionException {
|
||||
List<AServer> allServers = serverManagementService.getAllServers();
|
||||
log.info("Executing warn decay job.");
|
||||
allServers.forEach(server -> {
|
||||
boolean featureEnabled = featureFlagService.isFeatureEnabled(warningDecayFeature, server);
|
||||
if(featureEnabled) {
|
||||
log.info("Executing warn decay for server {}.", server.getId());
|
||||
warnService.decayWarningsForServer(server);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -50,6 +50,7 @@ public class MessageDeleteLogListener implements MessageDeletedListener {
|
||||
MessageToSend message = templateService.renderEmbedTemplate(MESSAGE_DELETED_TEMPLATE, logModel);
|
||||
postTargetService.sendEmbedInPostTarget(message, LoggingPostTarget.DELETE_LOG, messageFromCache.getServerId());
|
||||
if(messageFromCache.getAttachmentUrls() != null){
|
||||
log.trace("Notifying about deletions of {} attachments.", messageFromCache.getAttachmentUrls().size());
|
||||
for (int i = 0; i < messageFromCache.getAttachmentUrls().size(); i++) {
|
||||
MessageDeletedAttachmentLog log = MessageDeletedAttachmentLog
|
||||
.builder()
|
||||
|
||||
@@ -5,11 +5,13 @@ import dev.sheldan.abstracto.core.models.database.AServer;
|
||||
import dev.sheldan.abstracto.core.service.management.ConfigManagementService;
|
||||
import dev.sheldan.abstracto.core.service.management.DefaultConfigManagementService;
|
||||
import dev.sheldan.abstracto.moderation.config.features.WarningDecayFeature;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
public class WarnDecayConfigListener implements ServerConfigListener {
|
||||
|
||||
@Autowired
|
||||
@@ -20,6 +22,7 @@ public class WarnDecayConfigListener implements ServerConfigListener {
|
||||
|
||||
@Override
|
||||
public void updateServerConfig(AServer server) {
|
||||
log.info("Updating decay day configuration for server {}.", server.getId());
|
||||
configManagementService.createIfNotExists(server.getId(), WarningDecayFeature.DECAY_DAYS_KEY, defaultConfigManagementService.getDefaultConfig(WarningDecayFeature.DECAY_DAYS_KEY).getLongValue());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,8 +19,9 @@ public interface UserNoteRepository extends JpaRepository<UserNote, Long> {
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
List<UserNote> findByUser_ServerReference(AServer server);
|
||||
|
||||
@Override
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
boolean existsById(@NonNull Long aLong);
|
||||
boolean existsByUserNoteId_IdAndUserNoteId_ServerId(@NonNull Long aLong, Long serverId);
|
||||
|
||||
void deleteByUserNoteId_IdAndUserNoteId_ServerId(@NonNull Long aLong, Long serverId);
|
||||
|
||||
}
|
||||
|
||||
@@ -54,7 +54,6 @@ public class BanServiceBean implements BanService {
|
||||
private CompletableFuture<Void> banUser(Long guildId, Long userId, String reason) {
|
||||
Optional<Guild> guildByIdOptional = botService.getGuildById(guildId);
|
||||
if(guildByIdOptional.isPresent()) {
|
||||
log.info("Banning user {} in guild {}.", userId, guildId);
|
||||
return banUser(guildByIdOptional.get(), userId, reason);
|
||||
} else {
|
||||
log.warn("Guild {} not found. Not able to ban user {}", guildId, userId);
|
||||
@@ -63,6 +62,7 @@ public class BanServiceBean implements BanService {
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> banUser(Guild guild, Long userId, String reason) {
|
||||
log.info("Banning user {} in guild {}.", userId, guild.getId());
|
||||
return guild.ban(userId.toString(), 0, reason).submit();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,12 +134,12 @@ public class MuteServiceBean implements MuteService {
|
||||
throw new MuteRoleNotSetupException();
|
||||
}
|
||||
Member memberBeingMuted = userBeingMuted.getMember();
|
||||
log.info("User {} mutes user {} until {}",
|
||||
memberBeingMuted.getIdLong(), userMuting.getMember().getIdLong(), unMuteDate);
|
||||
log.info("User {} mutes user {} in server {} until {}",
|
||||
memberBeingMuted.getIdLong(), message.getServerId(), userMuting.getMember().getIdLong(), unMuteDate);
|
||||
if(message.getMessageId() != null) {
|
||||
log.trace("because of message {} in channel {} in server {}", message.getMessageId(), message.getChannelId(), message.getServerId());
|
||||
log.info("because of message {} in channel {} in server {}", message.getMessageId(), message.getChannelId(), message.getServerId());
|
||||
} else {
|
||||
log.trace("This mute was not triggered by a message.");
|
||||
log.info("This mute was not triggered by a message.");
|
||||
}
|
||||
List<CompletableFuture<Void>> futures = new ArrayList<>();
|
||||
AUserInAServer userInServerBeingMuted = userBeingMuted.getAUserInAServer();
|
||||
@@ -159,15 +159,16 @@ public class MuteServiceBean implements MuteService {
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> sendMuteNotification(ServerChannelMessage message, Member memberBeingMuted, MuteNotification muteNotification) {
|
||||
log.trace("Notifying the user about the mute.");
|
||||
log.info("Notifying the user about the mute.");
|
||||
CompletableFuture<Void> notificationFuture = new CompletableFuture<>();
|
||||
String muteNotificationMessage = templateService.renderTemplate(MUTE_NOTIFICATION_TEMPLATE, muteNotification);
|
||||
CompletableFuture<Message> messageCompletableFuture = messageService.sendMessageToUser(memberBeingMuted.getUser(), muteNotificationMessage);
|
||||
messageCompletableFuture.exceptionally(throwable -> {
|
||||
TextChannel feedBackChannel = botService.getTextChannelFromServer(message.getServerId(), message.getChannelId());
|
||||
feedBackChannel.sendMessage(throwable.getMessage()).submit().whenComplete((exceptionMessage, innerThrowable) ->
|
||||
notificationFuture.complete(null)
|
||||
);
|
||||
feedBackChannel.sendMessage(throwable.getMessage()).submit().whenComplete((exceptionMessage, innerThrowable) -> {
|
||||
notificationFuture.complete(null);
|
||||
log.info("Successfully notified user {} in server {} about mute.", memberBeingMuted.getId(), memberBeingMuted.getGuild().getId());
|
||||
});
|
||||
return null;
|
||||
});
|
||||
messageCompletableFuture.thenAccept(message1 ->
|
||||
@@ -226,7 +227,7 @@ public class MuteServiceBean implements MuteService {
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> muteMemberWithLog(MuteContext context) {
|
||||
log.trace("Muting member with sending a mute log");
|
||||
log.trace("Muting member {} in server {} and sending a mute log.", context.getMutedUser().getId(), context.getMutedUser().getGuild().getId());
|
||||
AServer server = serverManagementService.loadOrCreate(context.getContext().getServerId());
|
||||
Long nextCounterValue = counterService.getNextCounterValue(server, MUTE_COUNTER_KEY);
|
||||
context.setMuteId(nextCounterValue);
|
||||
@@ -244,14 +245,14 @@ public class MuteServiceBean implements MuteService {
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> sendMuteLog(MuteContext muteLogModel) {
|
||||
log.trace("Sending mute log to the mute posttarget");
|
||||
log.trace("Sending mute log to the mute posttarget.");
|
||||
MessageToSend message = templateService.renderEmbedTemplate(MUTE_LOG_TEMPLATE, muteLogModel);
|
||||
List<CompletableFuture<Message>> completableFutures = postTargetService.sendEmbedInPostTarget(message, MutingPostTarget.MUTE_LOG, muteLogModel.getContext().getServerId());
|
||||
return FutureUtils.toSingleFutureGeneric(completableFutures);
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> sendUnMuteLog(UnMuteLog muteLogModel) {
|
||||
log.trace("Sending unMute log to the mute posttarget");
|
||||
log.trace("Sending unMute log to the mute posttarget.");
|
||||
MessageToSend message = templateService.renderEmbedTemplate(UN_MUTE_LOG_TEMPLATE, muteLogModel);
|
||||
List<CompletableFuture<Message>> completableFutures = postTargetService.sendEmbedInPostTarget(message, MutingPostTarget.MUTE_LOG, muteLogModel.getServer().getId());
|
||||
return FutureUtils.toSingleFutureGeneric(completableFutures);
|
||||
@@ -313,7 +314,7 @@ public class MuteServiceBean implements MuteService {
|
||||
@Override
|
||||
@Transactional
|
||||
public CompletableFuture<Void> endMute(Long muteId, Long serverId) {
|
||||
log.info("UnMuting the mute {}", muteId);
|
||||
log.info("UnMuting the mute {} in server {}", muteId, serverId);
|
||||
Optional<Mute> muteOptional = muteManagementService.findMute(muteId, serverId);
|
||||
if(muteOptional.isPresent()) {
|
||||
return endMute(muteOptional.get());
|
||||
@@ -324,6 +325,7 @@ public class MuteServiceBean implements MuteService {
|
||||
|
||||
@Override
|
||||
public void completelyUnMuteUser(AUserInAServer aUserInAServer) {
|
||||
log.info("Completely unmuting user {} in server {}.", aUserInAServer.getUserReference().getId(), aUserInAServer.getServerReference().getId());
|
||||
List<Mute> allMutesOfUser = muteManagementService.getAllMutesOf(aUserInAServer);
|
||||
allMutesOfUser.forEach(mute -> {
|
||||
mute.setMuteEnded(true);
|
||||
|
||||
@@ -25,6 +25,7 @@ import java.util.function.Consumer;
|
||||
@Slf4j
|
||||
public class PurgeServiceBean implements PurgeService {
|
||||
|
||||
public static final int PURGE_MAX_MESSAGES = 100;
|
||||
@Autowired
|
||||
private MessageService messageService;
|
||||
|
||||
@@ -39,12 +40,12 @@ public class PurgeServiceBean implements PurgeService {
|
||||
private CompletableFuture<Void> purgeMessages(Integer amountToDelete, TextChannel channel, Long startId, Member purgedMember, Integer totalCount, Integer currentCount, Long statusMessageId) {
|
||||
|
||||
int toDeleteInThisIteration;
|
||||
int messageLimit = 100;
|
||||
if(amountToDelete >= messageLimit){
|
||||
toDeleteInThisIteration = messageLimit;
|
||||
if(amountToDelete >= PURGE_MAX_MESSAGES){
|
||||
toDeleteInThisIteration = PURGE_MAX_MESSAGES;
|
||||
} else {
|
||||
toDeleteInThisIteration = amountToDelete % messageLimit;
|
||||
toDeleteInThisIteration = amountToDelete % PURGE_MAX_MESSAGES;
|
||||
}
|
||||
log.info("Purging {} this iteration ({}/{}) messages in channel {} in server {}.", toDeleteInThisIteration, currentCount, totalCount, channel.getId(), channel.getGuild().getId());
|
||||
|
||||
CompletableFuture<MessageHistory> historyFuture = channel.getHistoryBefore(startId, toDeleteInThisIteration).submit();
|
||||
CompletableFuture<Long> statusMessageFuture = getOrCreatedStatusMessage(channel, totalCount, statusMessageId);
|
||||
@@ -57,6 +58,7 @@ public class PurgeServiceBean implements PurgeService {
|
||||
List<Message> messagesToDeleteNow = filterMessagesToDelete(retrievedHistory, purgedMember);
|
||||
Long currentStatusMessageId = statusMessageFuture.get();
|
||||
if(messagesToDeleteNow.size() == 0) {
|
||||
log.warn("No messages found to delete, all were filtered.");
|
||||
deletionFuture.completeExceptionally(new NoMessageFoundException());
|
||||
channel.deleteMessageById(currentStatusMessageId).queueAfter(5, TimeUnit.SECONDS);
|
||||
return;
|
||||
@@ -64,7 +66,7 @@ public class PurgeServiceBean implements PurgeService {
|
||||
Message latestMessage = messagesToDeleteNow.get(messagesToDeleteNow.size() - 1);
|
||||
log.trace("Deleting {} messages directly", messagesToDeleteNow.size());
|
||||
int newCurrentCount = currentCount + messagesToDeleteNow.size();
|
||||
int newAmountToDelete = amountToDelete - messageLimit;
|
||||
int newAmountToDelete = amountToDelete - PURGE_MAX_MESSAGES;
|
||||
Consumer<Void> consumer = deletionConsumer(newAmountToDelete, channel, purgedMember, totalCount, newCurrentCount, deletionFuture, currentStatusMessageId, latestMessage);
|
||||
if (messagesToDeleteNow.size() > 1) {
|
||||
bulkDeleteMessages(channel, deletionFuture, messagesToDeleteNow, consumer);
|
||||
@@ -97,10 +99,12 @@ public class PurgeServiceBean implements PurgeService {
|
||||
private CompletableFuture<Long> getOrCreatedStatusMessage(TextChannel channel, Integer totalCount, Long statusMessageId) {
|
||||
CompletableFuture<Long> statusMessageFuture;
|
||||
if(statusMessageId == 0) {
|
||||
log.trace("Creating new status message in channel {} in server {} because of puring.", channel.getIdLong(), channel.getGuild().getId());
|
||||
PurgeStatusUpdateModel model = PurgeStatusUpdateModel.builder().currentlyDeleted(0).totalToDelete(totalCount).build();
|
||||
MessageToSend messageToSend = templateService.renderTemplateToMessageToSend("purge_status_update", model);
|
||||
statusMessageFuture = messageService.createStatusMessageId(messageToSend, channel);
|
||||
} else {
|
||||
log.trace("Using existing status message {}.", statusMessageId);
|
||||
statusMessageFuture = CompletableFuture.completedFuture(statusMessageId);
|
||||
}
|
||||
return statusMessageFuture;
|
||||
@@ -108,16 +112,20 @@ public class PurgeServiceBean implements PurgeService {
|
||||
|
||||
private List<Message> filterMessagesToDelete(List<Message> retrievedHistory, Member purgedMember) {
|
||||
long twoWeeksAgo = TimeUtil.getDiscordTimestamp((System.currentTimeMillis() - (14 * 24 * 60 * 60 * 1000)));
|
||||
log.trace("Filtering messages older than {}.", twoWeeksAgo);
|
||||
List<Message> messagesToDeleteNow = new ArrayList<>();
|
||||
for (Message messageObj : retrievedHistory) {
|
||||
if (MiscUtil.parseSnowflake(messageObj.getId()) > twoWeeksAgo) {
|
||||
if(purgedMember != null) {
|
||||
if(messageObj.getAuthor().getIdLong() == purgedMember.getIdLong()) {
|
||||
log.trace("Message {} is from filtered user {}. Purging.", messageObj.getId(), purgedMember.getIdLong());
|
||||
messagesToDeleteNow.add(messageObj);
|
||||
}
|
||||
} else {
|
||||
messagesToDeleteNow.add(messageObj);
|
||||
}
|
||||
} else {
|
||||
log.trace("Message {} was older than {}. Not purging.", messageObj.getId(), twoWeeksAgo);
|
||||
}
|
||||
}
|
||||
return messagesToDeleteNow;
|
||||
@@ -125,7 +133,8 @@ public class PurgeServiceBean implements PurgeService {
|
||||
|
||||
private Consumer<Void> deletionConsumer(Integer amountToDelete, TextChannel channel, Member purgedMember, Integer totalCount, Integer currentCount, CompletableFuture<Void> deletionFuture, Long currentStatusMessageId, Message earliestMessage) {
|
||||
return aVoid -> {
|
||||
if (amountToDelete > 1) {
|
||||
if (amountToDelete >= 1) {
|
||||
log.trace("Still more than 1 message to delete. Continuing.");
|
||||
purgeMessages(amountToDelete, channel, earliestMessage.getIdLong(), purgedMember, totalCount, currentCount, currentStatusMessageId).whenComplete((avoid, throwable) -> {
|
||||
if (throwable != null) {
|
||||
deletionFuture.completeExceptionally(throwable);
|
||||
@@ -135,10 +144,11 @@ public class PurgeServiceBean implements PurgeService {
|
||||
}
|
||||
);
|
||||
} else {
|
||||
log.trace("Completed purging of {} messages.", totalCount);
|
||||
channel.deleteMessageById(currentStatusMessageId).queueAfter(5, TimeUnit.SECONDS);
|
||||
deletionFuture.complete(null);
|
||||
}
|
||||
log.info("Setting status for {} out of {}", currentCount, totalCount);
|
||||
log.trace("Setting status for {} out of {}", currentCount, totalCount);
|
||||
PurgeStatusUpdateModel finalUpdateModel = PurgeStatusUpdateModel.builder().currentlyDeleted(currentCount).totalToDelete(totalCount).build();
|
||||
MessageToSend finalUpdateMessage = templateService.renderTemplateToMessageToSend("purge_status_update", finalUpdateModel);
|
||||
messageService.updateStatusMessage(channel, currentStatusMessageId, finalUpdateMessage);
|
||||
|
||||
@@ -98,6 +98,8 @@ public class WarnServiceBean implements WarnService {
|
||||
|
||||
@Transactional
|
||||
public void persistWarning(WarnContext context) {
|
||||
log.info("Persisting warning {} in server {} for user {} by user {}.",
|
||||
context.getWarnId(), context.getGuild().getId(), context.getWarnedMember().getId(), context.getMember().getId());
|
||||
AUserInAServer warnedUser = userInServerManagementService.loadUser(context.getWarnedMember());
|
||||
AUserInAServer warningUser = userInServerManagementService.loadUser(context.getMember());
|
||||
warnManagementService.createWarning(warnedUser, warningUser, context.getReason(), context.getWarnId());
|
||||
@@ -109,6 +111,7 @@ public class WarnServiceBean implements WarnService {
|
||||
public CompletableFuture<Void> decayWarningsForServer(AServer server) {
|
||||
Long days = configService.getLongValue(WarningDecayFeature.DECAY_DAYS_KEY, server.getId());
|
||||
Instant cutOffDay = Instant.now().minus(days, ChronoUnit.DAYS);
|
||||
log.info("Decaying warnings on server {} which are older than {}.", server.getId(), cutOffDay);
|
||||
List<Warning> warningsToDecay = warnManagementService.getActiveWarningsInServerOlderThan(server, cutOffDay);
|
||||
List<Long> warningIds = flattenWarnings(warningsToDecay);
|
||||
Long serverId = server.getId();
|
||||
@@ -129,6 +132,7 @@ public class WarnServiceBean implements WarnService {
|
||||
@Transactional
|
||||
public void decayWarnings(List<Long> warningIds, Long serverId) {
|
||||
Instant now = Instant.now();
|
||||
log.info("Decaying {} warnings.", warningIds.size());
|
||||
warningIds.forEach(warningId -> {
|
||||
Optional<Warning> warningOptional = warnManagementService.findById(warningId, serverId);
|
||||
warningOptional.ifPresent(warning ->
|
||||
@@ -142,11 +146,13 @@ public class WarnServiceBean implements WarnService {
|
||||
|
||||
@Override
|
||||
public void decayWarning(Warning warning, Instant now) {
|
||||
log.trace("Decaying warning {} in server {} with date {}.", warning.getWarnId().getId(), warning.getWarnId().getServerId(), now);
|
||||
warning.setDecayDate(now);
|
||||
warning.setDecayed(true);
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> logDecayedWarnings(AServer server, List<Warning> warningsToDecay) {
|
||||
log.trace("Logging decaying {} warnings in server {}.", warningsToDecay.size(), server.getId());
|
||||
List<WarnDecayWarning> warnDecayWarnings = new ArrayList<>();
|
||||
warningsToDecay.forEach(warning -> {
|
||||
WarnDecayWarning warnDecayWarning = WarnDecayWarning
|
||||
@@ -172,6 +178,7 @@ public class WarnServiceBean implements WarnService {
|
||||
public CompletableFuture<Void> decayAllWarningsForServer(AServer server, boolean logWarnings) {
|
||||
List<Warning> warningsToDecay = warnManagementService.getActiveWarningsInServerOlderThan(server, Instant.now());
|
||||
List<Long> warnIds = flattenWarnings(warningsToDecay);
|
||||
log.info("Decaying ALL warning in server {} with logging {}.", server.getId(), logWarnings);
|
||||
Long serverId = server.getId();
|
||||
if(logWarnings) {
|
||||
return logDecayedWarnings(server, warningsToDecay).thenAccept(aVoid ->
|
||||
|
||||
@@ -43,6 +43,7 @@ public class MuteRoleManagementServiceBean implements MuteRoleManagementService
|
||||
public MuteRole setMuteRoleForServer(AServer server, ARole role) {
|
||||
log.info("Setting muted role for server {} to role {}", server.getId(), role.getId());
|
||||
if(!muteRoleForServerExists(server)) {
|
||||
log.trace("Mute role did not exist yet, updating for server {}.", server.getId());
|
||||
return createMuteRoleForServer(server, role);
|
||||
} else {
|
||||
MuteRole existing = retrieveMuteRoleForServer(server);
|
||||
|
||||
@@ -6,12 +6,14 @@ import dev.sheldan.abstracto.core.models.database.AUserInAServer;
|
||||
import dev.sheldan.abstracto.core.service.CounterService;
|
||||
import dev.sheldan.abstracto.moderation.models.database.UserNote;
|
||||
import dev.sheldan.abstracto.moderation.repository.UserNoteRepository;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
public class UserNoteManagementServiceBean implements UserNoteManagementService {
|
||||
|
||||
@Autowired
|
||||
@@ -25,6 +27,7 @@ public class UserNoteManagementServiceBean implements UserNoteManagementService
|
||||
@Override
|
||||
public UserNote createUserNote(AUserInAServer aUserInAServer, String note) {
|
||||
Long id = counterService.getNextCounterValue(aUserInAServer.getServerReference(), USER_NOTE_COUNTER_KEY);
|
||||
log.info("Creating user note with id {} for user {} in server {}.", id, aUserInAServer.getUserReference().getId(), aUserInAServer.getServerReference().getId());
|
||||
ServerSpecificId userNoteId = new ServerSpecificId(aUserInAServer.getServerReference().getId(), id);
|
||||
UserNote newNote = UserNote
|
||||
.builder()
|
||||
@@ -38,13 +41,14 @@ public class UserNoteManagementServiceBean implements UserNoteManagementService
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteNote(Long id) {
|
||||
userNoteRepository.deleteById(id);
|
||||
public void deleteNote(Long id, AServer server) {
|
||||
log.info("Deleting user note with id {} in server {}.", id, server.getId());
|
||||
userNoteRepository.deleteByUserNoteId_IdAndUserNoteId_ServerId(id, server.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean noteExists(Long id) {
|
||||
return userNoteRepository.existsById(id);
|
||||
public boolean noteExists(Long id, AServer server) {
|
||||
return userNoteRepository.existsByUserNoteId_IdAndUserNoteId_ServerId(id, server.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -5,6 +5,7 @@ import dev.sheldan.abstracto.core.models.database.AServer;
|
||||
import dev.sheldan.abstracto.moderation.models.database.Warning;
|
||||
import dev.sheldan.abstracto.moderation.repository.WarnRepository;
|
||||
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@@ -13,6 +14,7 @@ import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
public class WarnManagementServiceBean implements WarnManagementService {
|
||||
|
||||
@Autowired
|
||||
@@ -20,6 +22,8 @@ public class WarnManagementServiceBean implements WarnManagementService {
|
||||
|
||||
@Override
|
||||
public Warning createWarning(AUserInAServer warnedAUser, AUserInAServer warningAUser, String reason, Long warnId) {
|
||||
log.info("Creating warning with id {} for user {} in server {} cast by user {}.",
|
||||
warnId, warnedAUser.getUserReference().getId(), warningAUser.getServerReference().getId(), warningAUser.getUserReference().getId());
|
||||
ServerSpecificId warningId = new ServerSpecificId(warnId, warningAUser.getServerReference().getId());
|
||||
Warning warning = Warning.builder()
|
||||
.reason(reason)
|
||||
@@ -66,6 +70,7 @@ public class WarnManagementServiceBean implements WarnManagementService {
|
||||
|
||||
@Override
|
||||
public void deleteWarning(Warning warning) {
|
||||
log.info("Deleting warning with id {} in server {}.", warning.getWarnId().getId(), warning.getWarnId().getServerId());
|
||||
warnRepository.delete(warning);
|
||||
}
|
||||
|
||||
|
||||
@@ -37,16 +37,16 @@ public class DeleteNoteTest {
|
||||
@Test
|
||||
public void testDeleteExistingNote() {
|
||||
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(NOTE_ID));
|
||||
when(userNoteManagementService.noteExists(NOTE_ID)).thenReturn(true);
|
||||
when(userNoteManagementService.noteExists(NOTE_ID, parameters.getUserInitiatedContext().getServer())).thenReturn(true);
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
verify(userNoteManagementService, times(1)).deleteNote(NOTE_ID);
|
||||
verify(userNoteManagementService, times(1)).deleteNote(NOTE_ID, parameters.getUserInitiatedContext().getServer());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteNotExistingNote() {
|
||||
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(NOTE_ID));
|
||||
when(userNoteManagementService.noteExists(NOTE_ID)).thenReturn(false);
|
||||
when(userNoteManagementService.noteExists(NOTE_ID, parameters.getUserInitiatedContext().getServer())).thenReturn(false);
|
||||
when(templateService.renderSimpleTemplate(DeleteNote.NOTE_NOT_FOUND_EXCEPTION_TEMPLATE)).thenReturn("error");
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
Assert.assertEquals(ResultState.ERROR, result.getResult());
|
||||
|
||||
@@ -10,6 +10,7 @@ import net.dv8tion.jda.api.requests.RestAction;
|
||||
import net.dv8tion.jda.api.requests.restaction.AuditableRestAction;
|
||||
import net.dv8tion.jda.api.utils.TimeUtil;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InjectMocks;
|
||||
@@ -77,6 +78,15 @@ public class PurgeServiceBeanTest {
|
||||
@Mock
|
||||
private AuditableRestAction deleteStatusAction;
|
||||
|
||||
@Mock
|
||||
private Guild guild;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
when(textChannel.getGuild()).thenReturn(guild);
|
||||
when(guild.getId()).thenReturn("1");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPurgeMessageViaStartMessage() {
|
||||
Integer amountToDelete = 50;
|
||||
|
||||
@@ -118,6 +118,7 @@ public class WarnServiceBeanTest {
|
||||
@Test
|
||||
public void testDecayWarning() {
|
||||
Instant date = Instant.now();
|
||||
when(firstWarning.getWarnId()).thenReturn(new ServerSpecificId(3L, 4L));
|
||||
testUnit.decayWarning(firstWarning, date);
|
||||
verify(firstWarning, times(1)).setDecayed(true);
|
||||
verify(firstWarning, times(1)).setDecayDate(date);
|
||||
|
||||
@@ -53,14 +53,14 @@ public class UserNoteManagementServiceBeanTest {
|
||||
|
||||
@Test
|
||||
public void testDeleteNote() {
|
||||
testUnit.deleteNote(NOTE_ID);
|
||||
verify(userNoteRepository, times(1)).deleteById(NOTE_ID);
|
||||
testUnit.deleteNote(NOTE_ID, server);
|
||||
verify(userNoteRepository, times(1)).deleteByUserNoteId_IdAndUserNoteId_ServerId(NOTE_ID, server.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNoteExists() {
|
||||
when(userNoteRepository.existsById(NOTE_ID)).thenReturn(true);
|
||||
Assert.assertTrue(testUnit.noteExists(NOTE_ID));
|
||||
when(userNoteRepository.existsByUserNoteId_IdAndUserNoteId_ServerId(NOTE_ID, server.getId())).thenReturn(true);
|
||||
Assert.assertTrue(testUnit.noteExists(NOTE_ID, server));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package dev.sheldan.abstracto.moderation.service.management;
|
||||
|
||||
import dev.sheldan.abstracto.core.models.ServerSpecificId;
|
||||
import dev.sheldan.abstracto.core.models.database.AServer;
|
||||
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
|
||||
import dev.sheldan.abstracto.moderation.models.database.Warning;
|
||||
@@ -130,6 +131,6 @@ public class WarnManagementServiceBeanTest {
|
||||
}
|
||||
|
||||
private Warning getWarning() {
|
||||
return Warning.builder().build();
|
||||
return Warning.builder().warnId(new ServerSpecificId(3L, 4L)).build();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user