mirror of
https://github.com/Sheldan/abstracto.git
synced 2026-06-24 09:40:27 +00:00
[AB-57] [AB-61] reworked commands and services to work with completable futures and moved the database operations to the very last operation so we have transaction safety in more areas
added some cache annotations to the default repository functions reworked how the undo cations are processed within commands, they are executed in a post command listener when the state is error added a counter id to generate ids to be unique within servers, changed a few tables to be unique within a server added future utils class for wrapping a list of futures into one moved abstracto tables to separate schema in the installer refactored experience gain to work with more futures and delayed database access
This commit is contained in:
@@ -7,6 +7,8 @@ import dev.sheldan.abstracto.assignableroles.models.database.AssignableRolePlace
|
||||
import dev.sheldan.abstracto.assignableroles.models.database.AssignedRoleUser;
|
||||
import dev.sheldan.abstracto.assignableroles.service.AssignableRolePlaceService;
|
||||
import dev.sheldan.abstracto.assignableroles.service.AssignableRoleServiceBean;
|
||||
import dev.sheldan.abstracto.assignableroles.service.management.AssignableRoleManagementService;
|
||||
import dev.sheldan.abstracto.assignableroles.service.management.AssignableRolePlaceManagementService;
|
||||
import dev.sheldan.abstracto.assignableroles.service.management.AssignableRolePlacePostManagementService;
|
||||
import dev.sheldan.abstracto.assignableroles.service.management.AssignedRoleUserManagementService;
|
||||
import dev.sheldan.abstracto.core.config.FeatureEnum;
|
||||
@@ -14,12 +16,15 @@ import dev.sheldan.abstracto.core.listener.ReactedAddedListener;
|
||||
import dev.sheldan.abstracto.core.models.cache.CachedMessage;
|
||||
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
|
||||
import dev.sheldan.abstracto.core.service.EmoteService;
|
||||
import dev.sheldan.abstracto.core.service.management.UserInServerManagementService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.dv8tion.jda.api.entities.MessageReaction;
|
||||
import net.dv8tion.jda.api.events.message.guild.react.GuildMessageReactionAddEvent;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@@ -42,6 +47,18 @@ public class AssignablePostReactionAdded implements ReactedAddedListener {
|
||||
@Autowired
|
||||
private AssignedRoleUserManagementService assignedRoleUserManagementService;
|
||||
|
||||
@Autowired
|
||||
private AssignableRolePlaceManagementService assignableRolePlaceManagementService;
|
||||
|
||||
@Autowired
|
||||
private AssignablePostReactionAdded self;
|
||||
|
||||
@Autowired
|
||||
private UserInServerManagementService userInServerManagementService;
|
||||
|
||||
@Autowired
|
||||
private AssignableRoleManagementService assignableRoleManagementService;
|
||||
|
||||
@Override
|
||||
public void executeReactionAdded(CachedMessage message, GuildMessageReactionAddEvent event, AUserInAServer userAdding) {
|
||||
Optional<AssignableRolePlacePost> messageOptional = service.findByMessageIdOptional(message.getMessageId());
|
||||
@@ -65,38 +82,41 @@ public class AssignablePostReactionAdded implements ReactedAddedListener {
|
||||
private void addAppropriateRoles(GuildMessageReactionAddEvent event, MessageReaction reaction, AssignableRolePlacePost assignablePlacePost, MessageReaction.ReactionEmote reactionEmote, AUserInAServer userAdding) {
|
||||
boolean validReaction = false;
|
||||
AssignableRolePlace assignableRolePlace = assignablePlacePost.getAssignablePlace();
|
||||
List<CompletableFuture<Void>> futures = new ArrayList<>();
|
||||
for (AssignableRole assignableRole : assignablePlacePost.getAssignableRoles()) {
|
||||
if (emoteService.isReactionEmoteAEmote(reactionEmote, assignableRole.getEmote())) {
|
||||
CompletableFuture<Void> future;
|
||||
if(assignableRolePlace.getUniqueRoles()) {
|
||||
Optional<AssignedRoleUser> byUserInServer = assignedRoleUserManagementService.findByUserInServerOptional(userAdding);
|
||||
if(byUserInServer.isPresent()){
|
||||
future = assignableRolePlaceService.removeExistingReactionsAndRoles(assignableRolePlace, byUserInServer.get());
|
||||
} else {
|
||||
future = CompletableFuture.completedFuture(null);
|
||||
}
|
||||
} else {
|
||||
future = CompletableFuture.completedFuture(null);
|
||||
byUserInServer.ifPresent(user -> futures.add(assignableRolePlaceService.removeExistingReactionsAndRoles(assignableRolePlace, user)));
|
||||
}
|
||||
|
||||
Long assignableRoleId = assignableRole.getId();
|
||||
future.whenComplete((aVoid, throwable) -> {
|
||||
if(throwable != null) {
|
||||
log.warn("Failed to remove previous role assignments for {} in server {} at place {}.",
|
||||
userAdding.getUserReference().getId(), userAdding.getServerReference().getId(), assignablePlacePost.getAssignablePlace().getKey());
|
||||
}
|
||||
assignableRoleServiceBean.assignAssignableRoleToUser(assignableRoleId, event.getMember()).exceptionally(innerThrowable -> {
|
||||
log.error("Failed to add new role assignment.", innerThrowable);
|
||||
return null;
|
||||
});
|
||||
});
|
||||
CompletableFuture<Void> roleAdditionFuture = assignableRoleServiceBean.assignAssignableRoleToUser(assignableRoleId, event.getMember());
|
||||
|
||||
futures.add(CompletableFuture.allOf(roleAdditionFuture));
|
||||
validReaction = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(!validReaction || assignableRolePlace.getAutoRemove()) {
|
||||
reaction.removeReaction(event.getUser()).submit();
|
||||
if(!validReaction) {
|
||||
futures.add(reaction.removeReaction(event.getUser()).submit());
|
||||
}
|
||||
Long assignableRolePlaceId = assignableRolePlace.getId();
|
||||
Long userInServerId = userAdding.getUserInServerId();
|
||||
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).thenAccept(aVoid ->
|
||||
self.updateStoredAssignableRoles(assignableRolePlaceId, userInServerId, reactionEmote)
|
||||
);
|
||||
}
|
||||
|
||||
private void updateStoredAssignableRoles(Long assignableRolePlaceId, Long userAdding, MessageReaction.ReactionEmote reactionEmote) {
|
||||
AssignableRolePlace place = assignableRolePlaceManagementService.findByPlaceId(assignableRolePlaceId);
|
||||
AUserInAServer userInAServer = userInServerManagementService.loadUser(userAdding);
|
||||
if(place.getUniqueRoles()) {
|
||||
assignableRoleServiceBean.clearAllRolesOfUserInPlace(place, userInAServer);
|
||||
}
|
||||
AssignableRole role = assignableRoleManagementService.getRoleForReactionEmote(reactionEmote, place);
|
||||
assignableRoleServiceBean.addRoleToUser(role.getId(), userInAServer);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -49,7 +49,7 @@ public class AssignablePostReactionRemoved implements ReactedRemovedListener {
|
||||
assignablePlacePost.getAssignableRoles().forEach(assignableRole -> {
|
||||
if(emoteService.isReactionEmoteAEmote(reactionEmote, assignableRole.getEmote())) {
|
||||
Long assignableRoleId = assignableRole.getId();
|
||||
assignableRoleService.removeAssignableRoleFromUser(assignableRole, event.getMember()).exceptionally(throwable -> {
|
||||
assignableRoleService.fullyRemoveAssignableRoleFromUser(assignableRole, event.getMember()).exceptionally(throwable -> {
|
||||
log.error("Failed to remove assignable role {} from user {}.", assignableRoleId, event.getMember(), throwable);
|
||||
return null;
|
||||
});
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
package dev.sheldan.abstracto.assignableroles.repository;
|
||||
|
||||
import dev.sheldan.abstracto.assignableroles.models.database.AssignableRolePlacePost;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.QueryHints;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import javax.persistence.QueryHint;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface AssignableRolePlacePostRepository extends JpaRepository<AssignableRolePlacePost, Long> {
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
Optional<AssignableRolePlacePost> findById(@NonNull Long aLong);
|
||||
}
|
||||
|
||||
@@ -2,15 +2,30 @@ package dev.sheldan.abstracto.assignableroles.repository;
|
||||
|
||||
import dev.sheldan.abstracto.assignableroles.models.database.AssignableRolePlace;
|
||||
import dev.sheldan.abstracto.core.models.database.AServer;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.QueryHints;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import javax.persistence.QueryHint;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface AssignableRolePlaceRepository extends JpaRepository<AssignableRolePlace, Long> {
|
||||
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
boolean existsByServerAndKey(AServer server, String key);
|
||||
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
Optional<AssignableRolePlace> findByServerAndKey(AServer server, String key);
|
||||
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
List<AssignableRolePlace> findByServer(AServer server);
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
Optional<AssignableRolePlace> findById(@NonNull Long aLong);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
package dev.sheldan.abstracto.assignableroles.repository;
|
||||
|
||||
import dev.sheldan.abstracto.assignableroles.models.database.AssignableRole;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.QueryHints;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import javax.persistence.QueryHint;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface AssignableRoleRepository extends JpaRepository<AssignableRole, Long> {
|
||||
@NotNull
|
||||
@Override
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
Optional<AssignableRole> findById(@NonNull Long aLong);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,23 @@
|
||||
package dev.sheldan.abstracto.assignableroles.repository;
|
||||
|
||||
import dev.sheldan.abstracto.assignableroles.models.database.AssignedRoleUser;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.QueryHints;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import javax.persistence.QueryHint;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface AssignedRoleUserRepository extends JpaRepository<AssignedRoleUser, Long> {
|
||||
@NotNull
|
||||
@Override
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
Optional<AssignedRoleUser> findById(@NonNull Long aLong);
|
||||
|
||||
@Override
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
boolean existsById(@NonNull Long aLong);
|
||||
}
|
||||
|
||||
@@ -150,12 +150,8 @@ public class AssignableRolePlaceServiceBean implements AssignableRolePlaceServic
|
||||
emoteUsable = emoteService.isEmoteUsableByBot(fakeEmote.getEmote()) && fakeEmote.getEmote().isAvailable();
|
||||
}
|
||||
if(emoteUsable) {
|
||||
AEmote createdEmote = emoteManagementService.createEmote(null, fakeEmote.getFakeEmote(), server.getId(), false);
|
||||
Integer emoteId = createdEmote.getId();
|
||||
|
||||
List<AssignableRolePlacePost> existingMessagePosts = assignableRolePlace.getMessagePosts();
|
||||
existingMessagePosts.sort(Comparator.comparingLong(AssignableRolePlacePost::getId));
|
||||
createdEmote.setChangeable(false);
|
||||
|
||||
if(!assignableRolePlace.getMessagePosts().isEmpty()){
|
||||
AssignableRolePlacePost latestPost = existingMessagePosts.get(assignableRolePlace.getMessagePosts().size() - 1);
|
||||
@@ -173,16 +169,16 @@ public class AssignableRolePlaceServiceBean implements AssignableRolePlaceServic
|
||||
if(channelOptional.isPresent()) {
|
||||
TextChannel textChannel = channelOptional.get();
|
||||
if(latestPost.getAssignableRoles().size() < 20) {
|
||||
return addReactionToExistingAssignableRolePlacePost(fakeEmote, description, assignableRolePlace, placeId, roleId, serverId, emoteId, latestPost, messageToSend, textChannel);
|
||||
return addReactionToExistingAssignableRolePlacePost(fakeEmote, description, assignableRolePlace, placeId, roleId, serverId, latestPost, messageToSend, textChannel, fakeEmote);
|
||||
} else {
|
||||
return addNewMessageToAssignableRolePlace(placeName, fakeEmote, description, roleId, serverId, emoteId, messageToSend, textChannel);
|
||||
return addNewMessageToAssignableRolePlace(placeName, fakeEmote, description, roleId, serverId, messageToSend, textChannel, fakeEmote);
|
||||
}
|
||||
} else {
|
||||
throw new ChannelNotFoundException(latestPost.getUsedChannel().getId());
|
||||
}
|
||||
} else {
|
||||
log.info("Added emote to assignable place {} in server {}, but no message post yet.", placeName, serverId);
|
||||
self.addAssignableRoleInstanceWithoutPost(placeId, roleId, emoteId, description);
|
||||
self.addAssignableRoleInstanceWithoutPost(placeId, roleId, fakeEmote, description);
|
||||
}
|
||||
} else {
|
||||
throw new EmoteNotUsableException(fakeEmote.getEmote());
|
||||
@@ -190,7 +186,8 @@ public class AssignableRolePlaceServiceBean implements AssignableRolePlaceServic
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> addReactionToExistingAssignableRolePlacePost(FullEmote fakeEmote, String description, AssignableRolePlace assignableRolePlace, Long placeId, Long roleId, Long serverId, Integer emoteId, AssignableRolePlacePost latestPost, MessageToSend messageToSend, TextChannel textChannel) {
|
||||
private CompletableFuture<Void> addReactionToExistingAssignableRolePlacePost(FullEmote fakeEmote, String description, AssignableRolePlace assignableRolePlace, Long placeId, Long roleId, Long serverId, AssignableRolePlacePost latestPost, MessageToSend messageToSend, TextChannel textChannel, FullEmote emote) {
|
||||
// TODO maybe refactor to use the same message object, so we dont need to retrieve it twice and do in parallel
|
||||
return textChannel.retrieveMessageById(latestPost.getId()).submit()
|
||||
.thenCompose(message -> messageService.addReactionToMessageWithFuture(fakeEmote.getFakeEmote(), serverId, message))
|
||||
.thenCompose(aVoid -> {
|
||||
@@ -198,26 +195,27 @@ public class AssignableRolePlaceServiceBean implements AssignableRolePlaceServic
|
||||
return channelService.editEmbedMessageInAChannel(embedToUse, textChannel, latestPost.getId());
|
||||
})
|
||||
.thenCompose(message -> {
|
||||
self.addAssignableRoleInstanceWithPost(message.getIdLong(), placeId, roleId, emoteId, description);
|
||||
self.addAssignableRoleInstanceWithPost(message.getIdLong(), placeId, roleId, description, emote);
|
||||
return CompletableFuture.completedFuture(null);
|
||||
});
|
||||
}
|
||||
|
||||
private CompletableFuture<Void> addNewMessageToAssignableRolePlace(String placeName, FullEmote fakeEmote, String description, Long roleId, Long serverId, Integer emoteId, MessageToSend messageToSend, TextChannel textChannel) {
|
||||
private CompletableFuture<Void> addNewMessageToAssignableRolePlace(String placeName, FullEmote fakeEmote, String description, Long roleId, Long serverId, MessageToSend messageToSend, TextChannel textChannel, FullEmote emote) {
|
||||
MessageEmbed embedToUse = messageToSend.getEmbeds().get(messageToSend.getEmbeds().size() - 1);
|
||||
return channelService.sendEmbedToChannel(embedToUse, textChannel)
|
||||
.thenCompose(message -> messageService.addReactionToMessageWithFuture(fakeEmote.getFakeEmote(), serverId, message).thenAccept(aVoid ->
|
||||
self.addNewlyCreatedAssignablePlacePost(placeName, description, roleId, serverId, emoteId, textChannel, message)
|
||||
self.addNewlyCreatedAssignablePlacePost(placeName, description, roleId, serverId, textChannel, message, emote)
|
||||
));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void addNewlyCreatedAssignablePlacePost(String placeName, String description,Long roleId, Long serverId, Integer emoteId, TextChannel textChannel, Message message) {
|
||||
public void addNewlyCreatedAssignablePlacePost(String placeName, String description,Long roleId, Long serverId, TextChannel textChannel, Message message, FullEmote fakeEmote) {
|
||||
AChannel loadedChannel = channelManagementService.loadChannel(textChannel.getIdLong());
|
||||
AServer loadedServer = serverManagementService.loadOrCreate(serverId);
|
||||
ARole role = roleManagementService.findRole(roleId);
|
||||
AEmote emote = emoteManagementService.loadEmote(emoteId);
|
||||
AssignableRolePlace loadedPlace = rolePlaceManagementService.findByServerAndKey(loadedServer, placeName);
|
||||
AEmote emote = emoteManagementService.createEmote(null, fakeEmote.getFakeEmote(), serverId, false);
|
||||
emote.setChangeable(false);
|
||||
|
||||
AssignableRolePlacePost newPost = AssignableRolePlacePost
|
||||
.builder()
|
||||
@@ -231,13 +229,17 @@ public class AssignableRolePlaceServiceBean implements AssignableRolePlaceServic
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void addAssignableRoleInstanceWithPost(Long messageId, Long placeId, Long roleId, Integer emoteId, String description) {
|
||||
assignableRoleManagementServiceBean.addRoleToPlace(placeId, emoteId, roleId, description, messageId);
|
||||
public void addAssignableRoleInstanceWithPost(Long messageId, Long placeId, Long roleId, String description, FullEmote fakeEmote) {
|
||||
AEmote emote = emoteManagementService.createEmote(null, fakeEmote.getFakeEmote(), fakeEmote.getEmote().getGuild().getIdLong(), false);
|
||||
emote.setChangeable(false);
|
||||
assignableRoleManagementServiceBean.addRoleToPlace(placeId, emote.getId(), roleId, description, messageId);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void addAssignableRoleInstanceWithoutPost(Long placeId, Long roleId, Integer emoteId, String description) {
|
||||
assignableRoleManagementServiceBean.addRoleToPlace(placeId, emoteId, roleId, description);
|
||||
public void addAssignableRoleInstanceWithoutPost(Long placeId, Long roleId, FullEmote fakeEmote, String description) {
|
||||
AEmote emote = emoteManagementService.createEmote(null, fakeEmote.getFakeEmote(), fakeEmote.getEmote().getGuild().getIdLong(), false);
|
||||
emote.setChangeable(false);
|
||||
assignableRoleManagementServiceBean.addRoleToPlace(placeId, emote.getId(), roleId, description);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package dev.sheldan.abstracto.assignableroles.service;
|
||||
|
||||
import dev.sheldan.abstracto.assignableroles.models.database.AssignableRole;
|
||||
import dev.sheldan.abstracto.assignableroles.models.database.AssignableRolePlace;
|
||||
import dev.sheldan.abstracto.assignableroles.models.database.AssignedRoleUser;
|
||||
import dev.sheldan.abstracto.assignableroles.service.management.AssignableRoleManagementServiceBean;
|
||||
import dev.sheldan.abstracto.assignableroles.service.management.AssignedRoleUserManagementService;
|
||||
import dev.sheldan.abstracto.assignableroles.service.management.AssignedRoleUserManagementServiceBean;
|
||||
@@ -38,30 +40,71 @@ public class AssignableRoleServiceBean implements AssignableRoleService {
|
||||
@Override
|
||||
public CompletableFuture<Void> assignAssignableRoleToUser(Long assignableRoleId, Member toAdd) {
|
||||
AssignableRole role = assignableRoleManagementServiceBean.getByAssignableRoleId(assignableRoleId);
|
||||
return roleService.addRoleToMemberFuture(toAdd, role.getRole()).thenApply(aVoid -> {
|
||||
self.persistRoleAssignment(assignableRoleId, toAdd);
|
||||
return null;
|
||||
return roleService.addRoleToMemberFuture(toAdd, role.getRole());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearAllRolesOfUserInPlace(AssignableRolePlace place, AUserInAServer userInAServer) {
|
||||
AssignedRoleUser user = assignedRoleUserManagementServiceBean.findByUserInServer(userInAServer);
|
||||
user.getRoles().forEach(assignableRole -> {
|
||||
if(assignableRole.getAssignablePlace().equals(place)) {
|
||||
assignableRole.getAssignedUsers().remove(user);
|
||||
}
|
||||
});
|
||||
user.getRoles().removeIf(assignableRole -> assignableRole.getAssignablePlace().equals(place));
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> fullyAssignAssignableRoleToUser(Long assignableRoleId, Member toAdd) {
|
||||
return this.assignAssignableRoleToUser(assignableRoleId, toAdd).thenAccept(aVoid ->
|
||||
self.addRoleToUser(assignableRoleId, toAdd)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> removeAssignableRoleFromUser(AssignableRole assignableRole, Member member) {
|
||||
return roleService.removeRoleFromMemberFuture(member, assignableRole.getRole());
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> fullyRemoveAssignableRoleFromUser(AssignableRole assignableRole, Member member) {
|
||||
Long assignableRoleId = assignableRole.getId();
|
||||
return roleService.removeRoleFromMemberFuture(member, assignableRole.getRole()).thenApply(aVoid -> {
|
||||
self.persistRoleRemoval(assignableRoleId, member);
|
||||
return null;
|
||||
});
|
||||
return this.removeAssignableRoleFromUser(assignableRole, member).thenAccept(aVoid ->
|
||||
self.removeRoleFromUser(assignableRoleId, member)
|
||||
);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void persistRoleAssignment(Long assignableRoleId, Member member) {
|
||||
public void addRoleToUser(Long assignableRoleId, AUserInAServer aUserInAServer) {
|
||||
AssignableRole role = assignableRoleManagementServiceBean.getByAssignableRoleId(assignableRoleId);
|
||||
addRoleToUser(role, aUserInAServer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addRoleToUser(AssignableRole assignableRole, AUserInAServer aUserInAServer) {
|
||||
assignedRoleUserManagementServiceBean.addAssignedRoleToUser(assignableRole, aUserInAServer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeRoleFromUser(AssignableRole assignableRole, AUserInAServer aUserInAServer) {
|
||||
assignedRoleUserManagementServiceBean.removeAssignedRoleFromUser(assignableRole, aUserInAServer);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void addRoleToUser(Long assignableRoleId, Member member) {
|
||||
AssignableRole role = assignableRoleManagementServiceBean.getByAssignableRoleId(assignableRoleId);
|
||||
AUserInAServer aUserInAServer = userInServerManagementService.loadUser(member);
|
||||
assignedRoleUserManagementServiceBean.addAssignedRoleToUser(role, aUserInAServer);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void persistRoleRemoval(Long assignableRoleId, Member member) {
|
||||
public void removeRoleFromUser(Long assignableRoleId, AUserInAServer aUserInAServer) {
|
||||
AssignableRole role = assignableRoleManagementServiceBean.getByAssignableRoleId(assignableRoleId);
|
||||
removeRoleFromUser(role, aUserInAServer);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void removeRoleFromUser(Long assignableRoleId, Member member) {
|
||||
AssignableRole role = assignableRoleManagementServiceBean.getByAssignableRoleId(assignableRoleId);
|
||||
AUserInAServer aUserInAServer = userInServerManagementService.loadUser(member);
|
||||
assignedRoleUserManagementServiceBean.removeAssignedRoleFromUser(role, aUserInAServer);
|
||||
|
||||
@@ -8,8 +8,10 @@ import dev.sheldan.abstracto.assignableroles.repository.AssignableRoleRepository
|
||||
import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException;
|
||||
import dev.sheldan.abstracto.core.models.database.AEmote;
|
||||
import dev.sheldan.abstracto.core.models.database.ARole;
|
||||
import dev.sheldan.abstracto.core.service.EmoteService;
|
||||
import dev.sheldan.abstracto.core.service.management.EmoteManagementService;
|
||||
import dev.sheldan.abstracto.core.service.management.RoleManagementService;
|
||||
import net.dv8tion.jda.api.entities.MessageReaction;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@@ -31,6 +33,9 @@ public class AssignableRoleManagementServiceBean implements AssignableRoleManage
|
||||
@Autowired
|
||||
private AssignableRoleRepository repository;
|
||||
|
||||
@Autowired
|
||||
private EmoteService emoteService;
|
||||
|
||||
@Override
|
||||
public AssignableRole addRoleToPlace(AssignableRolePlace place, AEmote emote, ARole role, String description, AssignableRolePlacePost post) {
|
||||
Integer maxPosition = place.getAssignableRoles().stream().map(AssignableRole::getPosition).max(Integer::compareTo).orElse(0);
|
||||
@@ -53,7 +58,7 @@ public class AssignableRoleManagementServiceBean implements AssignableRoleManage
|
||||
|
||||
@Override
|
||||
public AssignableRole addRoleToPlace(Long placeId, Integer emoteId, Long roleId, String description, Long messageId) {
|
||||
AssignableRolePlace place = rolePlaceManagementService.findByPlaceId(placeId).orElseThrow(() -> new AssignableRolePlaceNotFoundException(placeId));
|
||||
AssignableRolePlace place = rolePlaceManagementService.findByPlaceIdOptional(placeId).orElseThrow(() -> new AssignableRolePlaceNotFoundException(placeId));
|
||||
AEmote emote = emoteManagementService.loadEmote(emoteId);
|
||||
ARole role = roleManagementService.findRole(roleId);
|
||||
AssignableRolePlacePost post = postManagementService.findByMessageId(messageId);
|
||||
@@ -64,7 +69,7 @@ public class AssignableRoleManagementServiceBean implements AssignableRoleManage
|
||||
|
||||
@Override
|
||||
public AssignableRole addRoleToPlace(Long placeId, Integer emoteId, Long roleId, String description) {
|
||||
AssignableRolePlace place = rolePlaceManagementService.findByPlaceId(placeId).orElseThrow(() -> new AssignableRolePlaceNotFoundException(placeId));
|
||||
AssignableRolePlace place = rolePlaceManagementService.findByPlaceIdOptional(placeId).orElseThrow(() -> new AssignableRolePlaceNotFoundException(placeId));
|
||||
AEmote emote = emoteManagementService.loadEmote(emoteId);
|
||||
ARole role = roleManagementService.findRole(roleId);
|
||||
return addRoleToPlace(place, emote, role, description, null);
|
||||
@@ -74,4 +79,16 @@ public class AssignableRoleManagementServiceBean implements AssignableRoleManage
|
||||
public AssignableRole getByAssignableRoleId(Long assignableRoleId) {
|
||||
return repository.findById(assignableRoleId).orElseThrow(() -> new AbstractoRunTimeException("Assignable role not found"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssignableRole getRoleForReactionEmote(MessageReaction.ReactionEmote emote, AssignableRolePlace assignableRolePlace) {
|
||||
for (AssignableRolePlacePost post : assignableRolePlace.getMessagePosts()) {
|
||||
for (AssignableRole assignableRole : post.getAssignableRoles()) {
|
||||
if (emoteService.isReactionEmoteAEmote(emote, assignableRole.getEmote())) {
|
||||
return assignableRole;
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new AbstractoRunTimeException("Role for reaction was not found.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,10 +42,15 @@ public class AssignableRolePlaceManagementServiceBean implements AssignableRoleP
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<AssignableRolePlace> findByPlaceId(Long id) {
|
||||
public Optional<AssignableRolePlace> findByPlaceIdOptional(Long id) {
|
||||
return repository.findById(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssignableRolePlace findByPlaceId(Long id) {
|
||||
return findByPlaceIdOptional(id).orElseThrow(() -> new AssignableRolePlaceNotFoundException(id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void moveAssignableRolePlace(AServer server, String name, AChannel newChannel) {
|
||||
AssignableRolePlace assignablePlaceToChange = findByServerAndKey(server, name);
|
||||
|
||||
@@ -37,6 +37,15 @@ public class AssignedRoleUserManagementServiceBean implements AssignedRoleUserMa
|
||||
return repository.save(newUser);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearAllAssignedRolesOfUser(AUserInAServer userInAServer) {
|
||||
AssignedRoleUser user = findByUserInServer(userInAServer);
|
||||
user.getRoles().forEach(assignableRole ->
|
||||
assignableRole.getAssignedUsers().remove(user)
|
||||
);
|
||||
user.getRoles().clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean doesAssignedRoleUserExist(AUserInAServer aUserInAServer) {
|
||||
return repository.existsById(aUserInAServer.getUserInServerId());
|
||||
|
||||
@@ -49,6 +49,7 @@ public class AssignableRole implements Serializable {
|
||||
@Setter
|
||||
@ManyToMany(mappedBy = "roles")
|
||||
@Builder.Default
|
||||
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
|
||||
private List<AssignedRoleUser> assignedUsers = new ArrayList<>();
|
||||
|
||||
private String description;
|
||||
|
||||
@@ -59,6 +59,13 @@ public interface AssignableRolePlaceService {
|
||||
void changeAssignablePlaceDescription(AServer server, String name, String newDescription);
|
||||
CompletableFuture<Void> deleteAssignableRolePlace(AServer server, String name);
|
||||
CompletableFuture<Void> changeText(AServer server, String name, String newText);
|
||||
|
||||
/**
|
||||
* Removes the reactions and the roles from the user from the place, this does not touch the stored data
|
||||
* @param place The {@link AssignableRolePlace} to which remove the existing reactions and roles from
|
||||
* @param user The {@link AssignedRoleUser} to the remove *all* reactions and assigned roles from
|
||||
* @return A {@link CompletableFuture} which completes when both of these actions have been done for all {@link dev.sheldan.abstracto.assignableroles.models.database.AssignableRole}
|
||||
*/
|
||||
CompletableFuture<Void> removeExistingReactionsAndRoles(AssignableRolePlace place, AssignedRoleUser user);
|
||||
CompletableFuture<Void> changeConfiguration(AServer server, String name, AssignableRolePlaceParameterKey keyToChange, Object newValue);
|
||||
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
package dev.sheldan.abstracto.assignableroles.service;
|
||||
|
||||
import dev.sheldan.abstracto.assignableroles.models.database.AssignableRole;
|
||||
import dev.sheldan.abstracto.assignableroles.models.database.AssignableRolePlace;
|
||||
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
|
||||
import net.dv8tion.jda.api.entities.Member;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
public interface AssignableRoleService {
|
||||
CompletableFuture<Void> assignAssignableRoleToUser(Long assignableRoleId, Member toAdd);
|
||||
void clearAllRolesOfUserInPlace(AssignableRolePlace place, AUserInAServer user);
|
||||
CompletableFuture<Void> fullyAssignAssignableRoleToUser(Long assignableRoleId, Member toAdd);
|
||||
CompletableFuture<Void> removeAssignableRoleFromUser(AssignableRole assignableRole, Member member);
|
||||
CompletableFuture<Void> fullyRemoveAssignableRoleFromUser(AssignableRole assignableRole, Member member);
|
||||
void addRoleToUser(Long assignableRoleId, AUserInAServer aUserInAServer);
|
||||
void addRoleToUser(AssignableRole assignableRole, AUserInAServer aUserInAServer);
|
||||
void removeRoleFromUser(AssignableRole assignableRole, AUserInAServer aUserInAServer);
|
||||
void removeRoleFromUser(Long assignableRoleId, AUserInAServer aUserInAServer);
|
||||
}
|
||||
|
||||
@@ -5,10 +5,12 @@ import dev.sheldan.abstracto.assignableroles.models.database.AssignableRolePlace
|
||||
import dev.sheldan.abstracto.assignableroles.models.database.AssignableRolePlacePost;
|
||||
import dev.sheldan.abstracto.core.models.database.AEmote;
|
||||
import dev.sheldan.abstracto.core.models.database.ARole;
|
||||
import net.dv8tion.jda.api.entities.MessageReaction;
|
||||
|
||||
public interface AssignableRoleManagementService {
|
||||
AssignableRole addRoleToPlace(AssignableRolePlace place, AEmote emote, ARole role, String description, AssignableRolePlacePost post);
|
||||
AssignableRole addRoleToPlace(Long placeId, Integer emoteId, Long roleId, String description, Long messageId);
|
||||
AssignableRole addRoleToPlace(Long placeId, Integer emoteId, Long roleId, String description);
|
||||
AssignableRole getByAssignableRoleId(Long assignableRoleId);
|
||||
AssignableRole getRoleForReactionEmote(MessageReaction.ReactionEmote emote, AssignableRolePlace assignableRolePlace);
|
||||
}
|
||||
|
||||
@@ -11,7 +11,8 @@ public interface AssignableRolePlaceManagementService {
|
||||
AssignableRolePlace createPlace(AServer server, String name, AChannel channel, String text);
|
||||
boolean doesPlaceExist(AServer server, String name);
|
||||
AssignableRolePlace findByServerAndKey(AServer server, String name);
|
||||
Optional<AssignableRolePlace> findByPlaceId(Long id);
|
||||
Optional<AssignableRolePlace> findByPlaceIdOptional(Long id);
|
||||
AssignableRolePlace findByPlaceId(Long id);
|
||||
void moveAssignableRolePlace(AServer server, String name, AChannel newChannel);
|
||||
void changeAssignableRolePlaceDescription(AServer server, String name, String newDescription);
|
||||
void deleteAssignablePlace(AssignableRolePlace place);
|
||||
|
||||
@@ -10,6 +10,7 @@ public interface AssignedRoleUserManagementService {
|
||||
void addAssignedRoleToUser(AssignableRole assignableRole, AUserInAServer aUserInAServer);
|
||||
void removeAssignedRoleFromUser(AssignableRole assignableRole, AUserInAServer aUserInAServer);
|
||||
AssignedRoleUser createAssignedRoleUser(AUserInAServer aUserInAServer);
|
||||
void clearAllAssignedRolesOfUser(AUserInAServer userInAServer);
|
||||
boolean doesAssignedRoleUserExist(AUserInAServer aUserInAServer);
|
||||
Optional<AssignedRoleUser> findByUserInServerOptional(AUserInAServer aUserInAServer);
|
||||
AssignedRoleUser findByUserInServer(AUserInAServer aUserInAServer);
|
||||
|
||||
@@ -9,6 +9,7 @@ import dev.sheldan.abstracto.core.command.execution.CommandResult;
|
||||
import dev.sheldan.abstracto.core.command.execution.ContextConverter;
|
||||
import dev.sheldan.abstracto.core.config.FeatureEnum;
|
||||
import dev.sheldan.abstracto.core.service.ChannelService;
|
||||
import dev.sheldan.abstracto.core.utils.FutureUtils;
|
||||
import dev.sheldan.abstracto.experience.config.features.ExperienceFeature;
|
||||
import dev.sheldan.abstracto.experience.converter.LeaderBoardModelConverter;
|
||||
import dev.sheldan.abstracto.experience.models.LeaderBoard;
|
||||
@@ -23,6 +24,7 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* Shows the experience gain information of the top 10 users in the server, or if a page number is provided as a parameter, only the members which are on this page.
|
||||
@@ -46,7 +48,7 @@ public class LeaderBoardCommand extends AbstractConditionableCommand {
|
||||
|
||||
|
||||
@Override
|
||||
public CommandResult execute(CommandContext commandContext) {
|
||||
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
|
||||
checkParameters(commandContext);
|
||||
List<Object> parameters = commandContext.getParameters().getParameters();
|
||||
// parameter is optional, in case its not present, we default to the 0th page
|
||||
@@ -58,9 +60,9 @@ public class LeaderBoardCommand extends AbstractConditionableCommand {
|
||||
LeaderBoardEntry userRank = userExperienceService.getRankOfUserInServer(commandContext.getUserInitiatedContext().getAUserInAServer());
|
||||
leaderBoardModel.setUserExecuting(converter.fromLeaderBoardEntry(userRank));
|
||||
MessageToSend messageToSend = templateService.renderEmbedTemplate(LEADER_BOARD_POST_EMBED_TEMPLATE, leaderBoardModel);
|
||||
channelService.sendMessageToSendToChannel(messageToSend, commandContext.getChannel());
|
||||
return FutureUtils.toSingleFutureGeneric(channelService.sendMessageToSendToChannel(messageToSend, commandContext.getChannel()))
|
||||
.thenApply(aVoid -> CommandResult.fromSuccess());
|
||||
|
||||
return CommandResult.fromSuccess();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -72,6 +74,7 @@ public class LeaderBoardCommand extends AbstractConditionableCommand {
|
||||
.name("leaderboard")
|
||||
.module(ExperienceModule.EXPERIENCE)
|
||||
.templated(true)
|
||||
.async(true)
|
||||
.supportsEmbedException(true)
|
||||
.causesReaction(true)
|
||||
.parameters(parameters)
|
||||
|
||||
@@ -11,16 +11,19 @@ import dev.sheldan.abstracto.core.config.FeatureEnum;
|
||||
import dev.sheldan.abstracto.core.models.FullRole;
|
||||
import dev.sheldan.abstracto.core.service.ChannelService;
|
||||
import dev.sheldan.abstracto.core.service.RoleService;
|
||||
import dev.sheldan.abstracto.core.utils.FutureUtils;
|
||||
import dev.sheldan.abstracto.experience.config.features.ExperienceFeature;
|
||||
import dev.sheldan.abstracto.experience.models.database.ADisabledExpRole;
|
||||
import dev.sheldan.abstracto.experience.models.templates.DisabledExperienceRolesModel;
|
||||
import dev.sheldan.abstracto.experience.service.management.DisabledExpRoleManagementService;
|
||||
import net.dv8tion.jda.api.entities.Message;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* Creates an embed containing the roles for which the experience gain has been disabled.
|
||||
@@ -38,7 +41,7 @@ public class ListDisabledExperienceRoles extends AbstractConditionableCommand {
|
||||
private ChannelService channelService;
|
||||
|
||||
@Override
|
||||
public CommandResult execute(CommandContext commandContext) {
|
||||
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
|
||||
checkParameters(commandContext);
|
||||
List<ADisabledExpRole> disabledRolesForServer = disabledExpRoleManagementService.getDisabledRolesForServer(commandContext.getUserInitiatedContext().getServer());
|
||||
DisabledExperienceRolesModel disabledExperienceRolesModel = (DisabledExperienceRolesModel) ContextConverter.fromCommandContext(commandContext, DisabledExperienceRolesModel.class);
|
||||
@@ -50,8 +53,8 @@ public class ListDisabledExperienceRoles extends AbstractConditionableCommand {
|
||||
.build();
|
||||
disabledExperienceRolesModel.getRoles().add(role);
|
||||
});
|
||||
channelService.sendEmbedTemplateInChannel("list_disabled_experience_roles", disabledExperienceRolesModel, commandContext.getChannel());
|
||||
return CommandResult.fromSuccess();
|
||||
List<CompletableFuture<Message>> futures = channelService.sendEmbedTemplateInChannel("list_disabled_experience_roles", disabledExperienceRolesModel, commandContext.getChannel());
|
||||
return FutureUtils.toSingleFutureGeneric(futures).thenApply(aVoid -> CommandResult.fromSuccess());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -9,6 +9,7 @@ import dev.sheldan.abstracto.core.command.execution.CommandResult;
|
||||
import dev.sheldan.abstracto.core.command.execution.ContextConverter;
|
||||
import dev.sheldan.abstracto.core.config.FeatureEnum;
|
||||
import dev.sheldan.abstracto.core.service.ChannelService;
|
||||
import dev.sheldan.abstracto.core.utils.FutureUtils;
|
||||
import dev.sheldan.abstracto.experience.config.features.ExperienceFeature;
|
||||
import dev.sheldan.abstracto.experience.converter.LeaderBoardModelConverter;
|
||||
import dev.sheldan.abstracto.experience.models.LeaderBoardEntry;
|
||||
@@ -23,6 +24,7 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* Command used to show an embed containing information about the experience amount, level and message count of a ember on a server
|
||||
@@ -48,7 +50,7 @@ public class Rank extends AbstractConditionableCommand {
|
||||
|
||||
|
||||
@Override
|
||||
public CommandResult execute(CommandContext commandContext) {
|
||||
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
|
||||
checkParameters(commandContext);
|
||||
RankModel rankModel = (RankModel) ContextConverter.fromCommandContext(commandContext, RankModel.class);
|
||||
LeaderBoardEntry userRank = userExperienceService.getRankOfUserInServer(commandContext.getUserInitiatedContext().getAUserInAServer());
|
||||
@@ -56,9 +58,8 @@ public class Rank extends AbstractConditionableCommand {
|
||||
AUserExperience experienceObj = userRank.getExperience();
|
||||
rankModel.setExperienceToNextLevel(experienceLevelService.calculateExperienceToNextLevel(experienceObj.getCurrentLevel().getLevel(), experienceObj.getExperience()));
|
||||
MessageToSend messageToSend = templateService.renderEmbedTemplate(RANK_POST_EMBED_TEMPLATE, rankModel);
|
||||
channelService.sendMessageToSendToChannel(messageToSend, commandContext.getChannel());
|
||||
|
||||
return CommandResult.fromSuccess();
|
||||
return FutureUtils.toSingleFutureGeneric(channelService.sendMessageToSendToChannel(messageToSend, commandContext.getChannel()))
|
||||
.thenApply(aVoid -> CommandResult.fromSuccess());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -69,6 +70,7 @@ public class Rank extends AbstractConditionableCommand {
|
||||
.name("rank")
|
||||
.module(ExperienceModule.EXPERIENCE)
|
||||
.templated(true)
|
||||
.async(true)
|
||||
.supportsEmbedException(true)
|
||||
.causesReaction(true)
|
||||
.parameters(parameters)
|
||||
|
||||
@@ -19,6 +19,7 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* Command used to define which commands are to be awarded at which level
|
||||
@@ -34,7 +35,7 @@ public class SetExpRole extends AbstractConditionableCommand {
|
||||
private RoleService roleService;
|
||||
|
||||
@Override
|
||||
public CommandResult execute(CommandContext commandContext) {
|
||||
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
|
||||
checkParameters(commandContext);
|
||||
Integer level = (Integer) commandContext.getParameters().getParameters().get(0);
|
||||
ARole role = (ARole) commandContext.getParameters().getParameters().get(1);
|
||||
@@ -43,8 +44,8 @@ public class SetExpRole extends AbstractConditionableCommand {
|
||||
throw new RoleNotFoundInGuildException(role.getId(), server.getId());
|
||||
}
|
||||
log.info("Setting role {} to be used for level {} on server {}", role.getId(), level, server.getId());
|
||||
experienceRoleService.setRoleToLevel(role, level, commandContext.getUserInitiatedContext().getChannel());
|
||||
return CommandResult.fromSuccess();
|
||||
return experienceRoleService.setRoleToLevel(role, level, commandContext.getUserInitiatedContext().getChannel())
|
||||
.thenApply(aVoid -> CommandResult.fromSuccess());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -57,6 +58,7 @@ public class SetExpRole extends AbstractConditionableCommand {
|
||||
.name("setExpRole")
|
||||
.module(ExperienceModule.EXPERIENCE)
|
||||
.templated(true)
|
||||
.async(true)
|
||||
.supportsEmbedException(true)
|
||||
.causesReaction(true)
|
||||
.parameters(parameters)
|
||||
|
||||
@@ -16,6 +16,7 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* Command used to synchronize the actual awarded roles which what is defined to be awarded in the database.
|
||||
@@ -31,11 +32,11 @@ public class SyncRoles extends AbstractConditionableCommand {
|
||||
private AUserExperienceService userExperienceService;
|
||||
|
||||
@Override
|
||||
public CommandResult execute(CommandContext commandContext) {
|
||||
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
|
||||
AServer server = commandContext.getUserInitiatedContext().getServer();
|
||||
log.info("Synchronizing roles on server {}", server.getId());
|
||||
userExperienceService.syncUserRolesWithFeedback(server, commandContext.getUserInitiatedContext().getChannel());
|
||||
return CommandResult.fromSuccess();
|
||||
return userExperienceService.syncUserRolesWithFeedback(server, commandContext.getUserInitiatedContext().getChannel())
|
||||
.thenApply(aVoid -> CommandResult.fromSuccess());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -46,6 +47,7 @@ public class SyncRoles extends AbstractConditionableCommand {
|
||||
.name("syncExpRoles")
|
||||
.module(ExperienceModule.EXPERIENCE)
|
||||
.templated(true)
|
||||
.async(true)
|
||||
.supportsEmbedException(true)
|
||||
.causesReaction(true)
|
||||
.parameters(parameters)
|
||||
|
||||
@@ -15,6 +15,7 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* Command used to remove a role from the roles to be awarded at certain levels. If there are users with this role currently, their role
|
||||
@@ -27,13 +28,13 @@ public class UnSetExpRole extends AbstractConditionableCommand {
|
||||
private ExperienceRoleService experienceRoleService;
|
||||
|
||||
@Override
|
||||
public CommandResult execute(CommandContext commandContext) {
|
||||
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
|
||||
checkParameters(commandContext);
|
||||
ARole role = (ARole) commandContext.getParameters().getParameters().get(0);
|
||||
// do not check for the existence of the role, because if the role was deleted, users should be able
|
||||
// to get rid of it in the configuration
|
||||
experienceRoleService.unsetRole(role, commandContext.getUserInitiatedContext().getChannel());
|
||||
return CommandResult.fromSuccess();
|
||||
return experienceRoleService.unsetRole(role, commandContext.getUserInitiatedContext().getChannel())
|
||||
.thenApply(aVoid -> CommandResult.fromSuccess());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -45,6 +46,7 @@ public class UnSetExpRole extends AbstractConditionableCommand {
|
||||
.name("unSetExpRole")
|
||||
.module(ExperienceModule.EXPERIENCE)
|
||||
.templated(true)
|
||||
.async(true)
|
||||
.causesReaction(true)
|
||||
.supportsEmbedException(true)
|
||||
.parameters(parameters)
|
||||
|
||||
@@ -30,9 +30,12 @@ public class JoiningUserRoleListener implements JoinListener {
|
||||
@Override
|
||||
public void execute(Member member, Guild guild, AUserInAServer aUserInAServer) {
|
||||
AUserExperience userExperience = userExperienceManagementService.findUserInServer(aUserInAServer);
|
||||
Long userInServerId = aUserInAServer.getUserInServerId();
|
||||
if(userExperience != null) {
|
||||
log.info("User {} joined {} with previous experience. Setting up experience role again (if necessary).", member.getUser().getIdLong(), guild.getIdLong());
|
||||
userExperienceService.syncForSingleUser(userExperience);
|
||||
userExperienceService.syncForSingleUser(userExperience).thenAccept(result ->
|
||||
log.trace("Finished re-assigning experience for re-joning user {} in server {}.", userInServerId, guild.getIdLong())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,8 +4,10 @@ import dev.sheldan.abstracto.core.models.database.ARole;
|
||||
import dev.sheldan.abstracto.core.models.database.AServer;
|
||||
import dev.sheldan.abstracto.experience.models.database.ADisabledExpRole;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.QueryHints;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import javax.persistence.QueryHint;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
@@ -13,10 +15,15 @@ import java.util.List;
|
||||
*/
|
||||
@Repository
|
||||
public interface DisabledExpRoleRepository extends JpaRepository<ADisabledExpRole, Long> {
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
boolean existsByRole(ARole role);
|
||||
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
ADisabledExpRole findByRole(ARole role);
|
||||
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
void deleteByRole(ARole role);
|
||||
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
List<ADisabledExpRole> getByRole_Server(AServer server);
|
||||
}
|
||||
|
||||
@@ -1,12 +1,32 @@
|
||||
package dev.sheldan.abstracto.experience.repository;
|
||||
|
||||
import dev.sheldan.abstracto.experience.models.database.AExperienceLevel;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.QueryHints;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import javax.persistence.QueryHint;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Repository to manage the access to the table managed by {@link AExperienceLevel}
|
||||
*/
|
||||
@Repository
|
||||
public interface ExperienceLevelRepository extends JpaRepository<AExperienceLevel, Integer> {
|
||||
@NotNull
|
||||
@Override
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
Optional<AExperienceLevel> findById(@NonNull Integer aLong);
|
||||
|
||||
@Override
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
boolean existsById(@NonNull Integer aLong);
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
List<AExperienceLevel> findAll();
|
||||
}
|
||||
|
||||
@@ -4,12 +4,15 @@ import dev.sheldan.abstracto.core.models.database.ARole;
|
||||
import dev.sheldan.abstracto.core.models.database.AServer;
|
||||
import dev.sheldan.abstracto.experience.models.database.AExperienceLevel;
|
||||
import dev.sheldan.abstracto.experience.models.database.AExperienceRole;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.QueryHints;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import javax.persistence.QueryHint;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Repository to manage the access to the table managed by {@link AExperienceRole}
|
||||
@@ -22,7 +25,7 @@ public interface ExperienceRoleRepository extends JpaRepository<AExperienceRole,
|
||||
* @return The {@link AExperienceRole} found or null if the query did not return any results
|
||||
*/
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
AExperienceRole findByRole(ARole role);
|
||||
Optional<AExperienceRole> findByRole(ARole role);
|
||||
|
||||
/**
|
||||
* Finds a list of {@link AExperienceRole} (if there are multiple ones, because of misconfiguration) of the given
|
||||
@@ -41,4 +44,9 @@ public interface ExperienceRoleRepository extends JpaRepository<AExperienceRole,
|
||||
*/
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
List<AExperienceRole> findByRoleServer(AServer server);
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
Optional<AExperienceRole> findById(@NonNull Long aLong);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,12 @@ import dev.sheldan.abstracto.core.service.BotService;
|
||||
import dev.sheldan.abstracto.core.service.ConfigService;
|
||||
import dev.sheldan.abstracto.core.service.MessageService;
|
||||
import dev.sheldan.abstracto.core.service.RoleService;
|
||||
import dev.sheldan.abstracto.core.service.management.UserInServerManagementService;
|
||||
import dev.sheldan.abstracto.core.utils.CompletableFutureList;
|
||||
import dev.sheldan.abstracto.core.utils.FutureUtils;
|
||||
import dev.sheldan.abstracto.experience.config.features.ExperienceFeatureConfig;
|
||||
import dev.sheldan.abstracto.experience.models.ExperienceGainResult;
|
||||
import dev.sheldan.abstracto.experience.models.RoleCalculationResult;
|
||||
import dev.sheldan.abstracto.experience.models.database.*;
|
||||
import dev.sheldan.abstracto.experience.models.LeaderBoard;
|
||||
import dev.sheldan.abstracto.experience.models.LeaderBoardEntry;
|
||||
@@ -28,15 +33,16 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
public class AUserExperienceServiceBean implements AUserExperienceService {
|
||||
|
||||
|
||||
@Autowired
|
||||
private UserExperienceManagementService userExperienceManagementService;
|
||||
|
||||
@@ -64,12 +70,18 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
|
||||
@Autowired
|
||||
private DisabledExpRoleManagementService disabledExpRoleManagementService;
|
||||
|
||||
@Autowired
|
||||
private UserInServerManagementService userInServerManagementService;
|
||||
|
||||
@Autowired
|
||||
private BotService botService;
|
||||
|
||||
@Autowired
|
||||
private RunTimeExperienceService runTimeExperienceService;
|
||||
|
||||
@Autowired
|
||||
private AUserExperienceServiceBean self;
|
||||
|
||||
/**
|
||||
* Creates the user in the runtime experience, if the user was not in yet. Also creates an entry for the minute, if necessary.
|
||||
* @param userInAServer The {@link AUserInAServer} to be added to the list of users gaining experience
|
||||
@@ -104,17 +116,17 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
|
||||
|
||||
/**
|
||||
* Calculates the level of the given {@link AUserExperience} according to the given {@link AExperienceLevel} list
|
||||
* @param experience The {@link AUserExperience} to calculate the level for
|
||||
* @param levels The list of {@link AExperienceLevel} representing the level configuration, this must include the initial level 0
|
||||
* * This level will be taken as the initial value, and if no other level qualifies, this will be taken.
|
||||
* The levels must be ordered.
|
||||
* @param experienceCount
|
||||
* @return The appropriate level according to the level config
|
||||
*/
|
||||
@Override
|
||||
public AExperienceLevel calculateLevel(AUserExperience experience, List<AExperienceLevel> levels) {
|
||||
public AExperienceLevel calculateLevel(List<AExperienceLevel> levels, Long experienceCount) {
|
||||
AExperienceLevel lastLevel = levels.get(0);
|
||||
for (AExperienceLevel level : levels) {
|
||||
if(level.getExperienceNeeded() >= experience.getExperience()) {
|
||||
if(level.getExperienceNeeded() >= experienceCount) {
|
||||
return lastLevel;
|
||||
} else {
|
||||
lastLevel = level;
|
||||
@@ -124,9 +136,9 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean updateUserLevel(AUserExperience userExperience, List<AExperienceLevel> levels) {
|
||||
public boolean updateUserLevel(AUserExperience userExperience, List<AExperienceLevel> levels, Long experienceCount) {
|
||||
AUserInAServer user = userExperience.getUser();
|
||||
AExperienceLevel correctLevel = calculateLevel(userExperience, levels);
|
||||
AExperienceLevel correctLevel = calculateLevel(levels, experienceCount);
|
||||
Integer currentLevel = userExperience.getCurrentLevel() != null ? userExperience.getCurrentLevel().getLevel() : 0;
|
||||
if(!correctLevel.getLevel().equals(currentLevel)) {
|
||||
log.info("User {} leveled from {} to {}", user.getUserReference().getId(), currentLevel, correctLevel.getLevel());
|
||||
@@ -146,14 +158,17 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
|
||||
*/
|
||||
@Transactional
|
||||
@Override
|
||||
public void handleExperienceGain(List<AServer> servers) {
|
||||
public CompletableFuture<Void> handleExperienceGain(List<AServer> servers) {
|
||||
List<ExperienceGainResult> resultFutures = new ArrayList<>();
|
||||
List<CompletableFuture<RoleCalculationResult>> futures = new ArrayList<>();
|
||||
List<AExperienceLevel> levels = experienceLevelManagementService.getLevelConfig();
|
||||
// TODO what if there are a lot in here...., transaction size etc
|
||||
servers.forEach(serverExp -> {
|
||||
log.trace("Handling experience for server {}", serverExp.getId());
|
||||
int minExp = configService.getLongValue(ExperienceFeatureConfig.MIN_EXP_KEY, serverExp.getId()).intValue();
|
||||
int maxExp = configService.getLongValue(ExperienceFeatureConfig.MAX_EXP_KEY, serverExp.getId()).intValue();
|
||||
Double multiplier = configService.getDoubleValue(ExperienceFeatureConfig.EXP_MULTIPLIER_KEY, serverExp.getId());
|
||||
PrimitiveIterator.OfInt iterator = new Random().ints(serverExp.getUsers().size(), minExp, maxExp + 1).iterator();
|
||||
List<AExperienceLevel> levels = experienceLevelManagementService.getLevelConfig();
|
||||
levels.sort(Comparator.comparing(AExperienceLevel::getExperienceNeeded));
|
||||
List<AExperienceRole> roles = experienceRoleManagementService.getExperienceRolesForServer(serverExp);
|
||||
List<ADisabledExpRole> disabledExpRoles = disabledExpRoleManagementService.getDisabledRolesForServer(serverExp);
|
||||
@@ -165,11 +180,23 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
|
||||
Member member = botService.getMemberInServer(userInAServer);
|
||||
if(!roleService.hasAnyOfTheRoles(member, disabledRoles)) {
|
||||
log.trace("Handling {}. The user gains {}", userInAServer.getUserReference().getId(), gainedExperience);
|
||||
AUserExperience aUserExperience = userExperienceManagementService.incrementExpForUser(userInAServer, gainedExperience.longValue(), 1L);
|
||||
AUserExperience aUserExperience = userExperienceManagementService.findUserInServer(userInAServer);
|
||||
if(Boolean.FALSE.equals(aUserExperience.getExperienceGainDisabled())) {
|
||||
updateUserLevel(aUserExperience, levels);
|
||||
updateUserRole(aUserExperience, roles);
|
||||
userExperienceManagementService.saveUser(aUserExperience);
|
||||
Long newExperienceCount = aUserExperience.getExperience() + gainedExperience.longValue();
|
||||
AExperienceLevel newLevel = calculateLevel(levels, newExperienceCount);
|
||||
CompletableFuture<RoleCalculationResult> resultFuture = updateUserRole(aUserExperience, roles, newLevel.getLevel());
|
||||
Long newMessageCount = aUserExperience.getMessageCount() + 1L;
|
||||
ExperienceGainResult calculationResult =
|
||||
ExperienceGainResult
|
||||
.builder()
|
||||
.calculationResult(resultFuture)
|
||||
.newExperience(newExperienceCount)
|
||||
.newMessageCount(newMessageCount)
|
||||
.newLevel(newLevel.getLevel())
|
||||
.userInServerId(userInAServer.getUserInServerId())
|
||||
.build();
|
||||
resultFutures.add(calculationResult);
|
||||
futures.add(resultFuture);
|
||||
} else {
|
||||
log.trace("Experience gain was disabled. User did not gain any experience.");
|
||||
}
|
||||
@@ -178,6 +205,35 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return FutureUtils.toSingleFutureGeneric(futures).thenAccept(aVoid ->
|
||||
self.persistExperienceChanges(resultFutures)
|
||||
);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void persistExperienceChanges(List<ExperienceGainResult> resultFutures) {
|
||||
List<AExperienceLevel> levels = experienceLevelManagementService.getLevelConfig();
|
||||
HashMap<Long, List<AExperienceRole>> serverRoleMapping = new HashMap<>();
|
||||
resultFutures.forEach(experienceGainResult -> {
|
||||
AUserInAServer user = userInServerManagementService.loadUser(experienceGainResult.getUserInServerId());
|
||||
AUserExperience userExperience = userExperienceManagementService.findUserInServer(user);
|
||||
userExperience.setMessageCount(experienceGainResult.getNewMessageCount());
|
||||
userExperience.setExperience(experienceGainResult.getNewExperience());
|
||||
Optional<AExperienceLevel> foundLevel = levels.stream().filter(level -> level.getLevel().equals(experienceGainResult.getNewLevel())).findFirst();
|
||||
if(foundLevel.isPresent()) {
|
||||
userExperience.setCurrentLevel(foundLevel.get());
|
||||
} else {
|
||||
log.warn("User {} was present, but no level could be found.", userExperience.getUser().getUserReference().getId());
|
||||
}
|
||||
AServer server = user.getServerReference();
|
||||
if(!serverRoleMapping.containsKey(server.getId())) {
|
||||
serverRoleMapping.put(server.getId(), experienceRoleManagementService.getExperienceRolesForServer(server));
|
||||
}
|
||||
List<AExperienceRole> roleConfig = serverRoleMapping.get(server.getId());
|
||||
AExperienceRole role = experienceRoleService.calculateRole(roleConfig, userExperience.getLevelOrDefault());
|
||||
userExperience.setCurrentExperienceRole(role);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -189,28 +245,48 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
|
||||
* @param roles The list of {@link AExperienceRole} used as a role configuration
|
||||
*/
|
||||
@Override
|
||||
public void updateUserRole(AUserExperience userExperience, List<AExperienceRole> roles) {
|
||||
public CompletableFuture<RoleCalculationResult> updateUserRole(AUserExperience userExperience, List<AExperienceRole> roles, Integer currentLevel) {
|
||||
AUserInAServer user = userExperience.getUser();
|
||||
Function<Void, RoleCalculationResult> returnNullRole = aVoid -> RoleCalculationResult
|
||||
.builder()
|
||||
.userInServerId(user.getUserInServerId())
|
||||
.experienceRoleId(null)
|
||||
.build();
|
||||
if(!botService.isUserInGuild(userExperience.getUser())) {
|
||||
log.trace("User {} is not in server {} anymore. No role calculation done.", userExperience.getUser().getUserInServerId(), userExperience.getUser().getServerReference().getId());
|
||||
return CompletableFuture.completedFuture(returnNullRole.apply(null));
|
||||
}
|
||||
Long userInServerId = user.getUserInServerId();
|
||||
log.trace("Updating experience role for user {} in server {}", user.getUserReference().getId(), user.getServerReference().getId());
|
||||
AExperienceRole role = experienceRoleService.calculateRole(userExperience, roles);
|
||||
AExperienceRole role = experienceRoleService.calculateRole(roles, currentLevel);
|
||||
Member member = botService.getMemberInServer(user.getServerReference(), user.getUserReference());
|
||||
boolean currentlyHasNoExperienceRole = userExperience.getCurrentExperienceRole() == null;
|
||||
if(role == null) {
|
||||
if(!currentlyHasNoExperienceRole && botService.isUserInGuild(userExperience.getUser())){
|
||||
roleService.removeRoleFromUser(user, userExperience.getCurrentExperienceRole().getRole());
|
||||
if(!currentlyHasNoExperienceRole){
|
||||
return roleService.removeRoleFromUserFuture(user, userExperience.getCurrentExperienceRole().getRole())
|
||||
.thenApply(returnNullRole);
|
||||
}
|
||||
userExperience.setCurrentExperienceRole(null);
|
||||
return;
|
||||
return CompletableFuture.completedFuture(returnNullRole.apply(null));
|
||||
}
|
||||
boolean userHasRoleAlready = roleService.memberHasRole(member, role.getRole());
|
||||
Long experienceRoleId = role.getId();
|
||||
Function<Void, RoleCalculationResult> fullResult = aVoid -> RoleCalculationResult
|
||||
.builder()
|
||||
.experienceRoleId(experienceRoleId)
|
||||
.userInServerId(userInServerId)
|
||||
.build();
|
||||
if(!userHasRoleAlready && (currentlyHasNoExperienceRole || !role.getRole().getId().equals(userExperience.getCurrentExperienceRole().getRole().getId()))) {
|
||||
log.info("User {} in server {} gets a new role {}", user.getUserReference().getId(), user.getServerReference().getId(), role.getRole().getId());
|
||||
CompletableFuture<Void> removalFuture;
|
||||
if(!currentlyHasNoExperienceRole && botService.isUserInGuild(userExperience.getUser())) {
|
||||
roleService.removeRoleFromUser(user, userExperience.getCurrentExperienceRole().getRole());
|
||||
removalFuture = roleService.removeRoleFromUserFuture(user, userExperience.getCurrentExperienceRole().getRole());
|
||||
} else {
|
||||
removalFuture = CompletableFuture.completedFuture(null);
|
||||
}
|
||||
roleService.addRoleToUser(user, role.getRole());
|
||||
CompletableFuture<Void> addRoleFuture = roleService.addRoleToUserFuture(user, role.getRole());
|
||||
return CompletableFuture.allOf(removalFuture, addRoleFuture).thenApply(fullResult);
|
||||
}
|
||||
userExperience.setCurrentExperienceRole(role);
|
||||
return CompletableFuture.completedFuture(fullResult.apply(null));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -219,15 +295,17 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
|
||||
* @param server The {@link AServer} to update the users for
|
||||
*/
|
||||
@Override
|
||||
public void syncUserRoles(AServer server) {
|
||||
public List<CompletableFuture<RoleCalculationResult>> syncUserRoles(AServer server) {
|
||||
List<CompletableFuture<RoleCalculationResult>> results = new ArrayList<>();
|
||||
List<AUserExperience> aUserExperiences = userExperienceManagementService.loadAllUsers(server);
|
||||
log.info("Found {} users to synchronize", aUserExperiences.size());
|
||||
List<AExperienceRole> roles = experienceRoleManagementService.getExperienceRolesForServer(server);
|
||||
for (int i = 0; i < aUserExperiences.size(); i++) {
|
||||
AUserExperience userExperience = aUserExperiences.get(i);
|
||||
log.trace("Synchronizing {} out of {}", i, aUserExperiences.size());
|
||||
updateUserRole(userExperience, roles);
|
||||
results.add(updateUserRole(userExperience, roles, userExperience.getCurrentLevel().getLevel()));
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -236,11 +314,35 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
|
||||
* @param channel The {@link AChannel} in which the {@link dev.sheldan.abstracto.experience.models.templates.UserSyncStatusModel}
|
||||
*/
|
||||
@Override
|
||||
public void syncUserRolesWithFeedback(AServer server, AChannel channel) {
|
||||
public CompletableFuture<Void> syncUserRolesWithFeedback(AServer server, AChannel channel) {
|
||||
List<AUserExperience> aUserExperiences = userExperienceManagementService.loadAllUsers(server);
|
||||
log.info("Found {} users to synchronize", aUserExperiences.size());
|
||||
List<AExperienceRole> roles = experienceRoleManagementService.getExperienceRolesForServer(server);
|
||||
executeActionOnUserExperiencesWithFeedBack(aUserExperiences, channel, (AUserExperience experience) -> updateUserRole(experience, roles));
|
||||
CompletableFutureList<RoleCalculationResult> calculations = executeActionOnUserExperiencesWithFeedBack(aUserExperiences, channel, (AUserExperience experience) -> updateUserRole(experience, roles, experience.getLevelOrDefault()));
|
||||
return calculations.getMainFuture().thenAccept(aVoid ->
|
||||
self.syncRolesInStorage(calculations.getObjects())
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the actually stored experience roles in the database
|
||||
* @param results The list of {@link RoleCalculationResult} which should be applied
|
||||
*/
|
||||
@Transactional
|
||||
public void syncRolesInStorage(List<RoleCalculationResult> results) {
|
||||
results.forEach(result -> {
|
||||
if(result != null) {
|
||||
AUserInAServer user = userInServerManagementService.loadUser(result.getUserInServerId());
|
||||
AUserExperience userExperience = userExperienceManagementService.findUserInServer(user);
|
||||
log.trace("Updating experience role for {} in server {} to {}", user.getUserInServerId(), user.getServerReference(), result.getExperienceRoleId());
|
||||
if(result.getExperienceRoleId() != null) {
|
||||
AExperienceRole role = experienceRoleManagementService.getExperienceRoleById(result.getExperienceRoleId());
|
||||
userExperience.setCurrentExperienceRole(role);
|
||||
} else {
|
||||
userExperience.setCurrentExperienceRole(null);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -250,7 +352,8 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
|
||||
* @param toExecute The {@link Consumer} which should be executed on each element of the passed list
|
||||
*/
|
||||
@Override
|
||||
public void executeActionOnUserExperiencesWithFeedBack(List<AUserExperience> experiences, AChannel channel, Consumer<AUserExperience> toExecute) {
|
||||
public CompletableFutureList<RoleCalculationResult> executeActionOnUserExperiencesWithFeedBack(List<AUserExperience> experiences, AChannel channel, Function<AUserExperience, CompletableFuture<RoleCalculationResult>> toExecute) {
|
||||
List<CompletableFuture<RoleCalculationResult>> futures = new ArrayList<>();
|
||||
MessageToSend status = getUserSyncStatusUpdateModel(0, experiences.size());
|
||||
try {
|
||||
Message statusMessage = messageService.createStatusMessage(status, channel).get();
|
||||
@@ -261,7 +364,7 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
|
||||
status = getUserSyncStatusUpdateModel(i, experiences.size());
|
||||
messageService.updateStatusMessage(channel, statusMessage.getIdLong(), status);
|
||||
}
|
||||
toExecute.accept(experiences.get(i));
|
||||
futures.add(toExecute.apply(experiences.get(i)));
|
||||
log.trace("Synchronizing {} out of {}", i, experiences.size());
|
||||
}
|
||||
status = getUserSyncStatusUpdateModel(experiences.size(), experiences.size());
|
||||
@@ -270,6 +373,8 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
|
||||
log.info("Failed to synchronize users.", e);
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
|
||||
return new CompletableFutureList<>(futures);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -294,11 +399,11 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
|
||||
* @param userExperience The {@link AUserExperience} to synchronize the role for
|
||||
*/
|
||||
@Override
|
||||
public void syncForSingleUser(AUserExperience userExperience) {
|
||||
public CompletableFuture<RoleCalculationResult> syncForSingleUser(AUserExperience userExperience) {
|
||||
AUserInAServer user = userExperience.getUser();
|
||||
log.info("Synchronizing for user {} in server {}", user.getUserReference().getId(), user.getServerReference().getId());
|
||||
List<AExperienceRole> roles = experienceRoleManagementService.getExperienceRolesForServer(user.getServerReference());
|
||||
updateUserRole(userExperience, roles);
|
||||
return updateUserRole(userExperience, roles, userExperience.getLevelOrDefault());
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,6 +3,9 @@ package dev.sheldan.abstracto.experience.service;
|
||||
import dev.sheldan.abstracto.core.models.database.AChannel;
|
||||
import dev.sheldan.abstracto.core.models.database.ARole;
|
||||
import dev.sheldan.abstracto.core.models.database.AServer;
|
||||
import dev.sheldan.abstracto.core.service.management.RoleManagementService;
|
||||
import dev.sheldan.abstracto.core.utils.CompletableFutureList;
|
||||
import dev.sheldan.abstracto.experience.models.RoleCalculationResult;
|
||||
import dev.sheldan.abstracto.experience.models.database.AExperienceLevel;
|
||||
import dev.sheldan.abstracto.experience.models.database.AExperienceRole;
|
||||
import dev.sheldan.abstracto.experience.models.database.AUserExperience;
|
||||
@@ -11,9 +14,12 @@ import dev.sheldan.abstracto.experience.service.management.ExperienceRoleManagem
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
@@ -29,6 +35,12 @@ public class ExperienceRoleServiceBean implements ExperienceRoleService {
|
||||
@Autowired
|
||||
private AUserExperienceService userExperienceService;
|
||||
|
||||
@Autowired
|
||||
private ExperienceRoleServiceBean self;
|
||||
|
||||
@Autowired
|
||||
private RoleManagementService roleManagementService;
|
||||
|
||||
/**
|
||||
* UnSets the current configuration for the passed level, and sets the {@link ARole} to be used for this level
|
||||
* in the given {@link AServer}
|
||||
@@ -36,11 +48,19 @@ public class ExperienceRoleServiceBean implements ExperienceRoleService {
|
||||
* @param level The level the {@link ARole} should be awarded at
|
||||
*/
|
||||
@Override
|
||||
public void setRoleToLevel(ARole role, Integer level, AChannel feedbackChannel) {
|
||||
public CompletableFuture<Void> setRoleToLevel(ARole role, Integer level, AChannel feedbackChannel) {
|
||||
Long roleId = role.getId();
|
||||
return unsetRole(role, feedbackChannel).thenAccept(aVoid ->
|
||||
self.unsetRoleInDb(level, roleId)
|
||||
);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void unsetRoleInDb(Integer level, Long roleId) {
|
||||
AExperienceLevel experienceLevel = experienceLevelService.getLevel(level).orElseThrow(() -> new IllegalArgumentException(String.format("Could not find level %s", level)));
|
||||
unsetRole(role, feedbackChannel);
|
||||
experienceRoleManagementService.removeAllRoleAssignmentsForLevelInServer(experienceLevel, role.getServer());
|
||||
experienceRoleManagementService.setLevelToRole(experienceLevel, role);
|
||||
ARole loadedRole = roleManagementService.findRole(roleId);
|
||||
experienceRoleManagementService.removeAllRoleAssignmentsForLevelInServer(experienceLevel, loadedRole.getServer());
|
||||
experienceRoleManagementService.setLevelToRole(experienceLevel, loadedRole);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -50,35 +70,52 @@ public class ExperienceRoleServiceBean implements ExperienceRoleService {
|
||||
* configuration
|
||||
*/
|
||||
@Override
|
||||
public void unsetRole(ARole role, AChannel feedbackChannel) {
|
||||
AExperienceRole roleInServer = experienceRoleManagementService.getRoleInServer(role);
|
||||
if(roleInServer != null) {
|
||||
public CompletableFuture<Void> unsetRole(ARole role, AChannel feedbackChannel) {
|
||||
Optional<AExperienceRole> roleInServerOptional = experienceRoleManagementService.getRoleInServerOptional(role);
|
||||
if(roleInServerOptional.isPresent()) {
|
||||
AExperienceRole roleInServer = roleInServerOptional.get();
|
||||
if(!roleInServer.getUsers().isEmpty()) {
|
||||
log.info("Recalculating the roles for {} users, because their current role was removed from experience tracking.", roleInServer.getUsers().size());
|
||||
List<AExperienceRole> roles = experienceRoleManagementService.getExperienceRolesForServer(role.getServer());
|
||||
roles.removeIf(role1 -> role1.getId().equals(roleInServer.getId()));
|
||||
|
||||
userExperienceService.executeActionOnUserExperiencesWithFeedBack(roleInServer.getUsers(), feedbackChannel,
|
||||
(AUserExperience ex) -> userExperienceService.updateUserRole(ex, roles));
|
||||
Long roleId = role.getId();
|
||||
CompletableFutureList<RoleCalculationResult> calculationResults = userExperienceService.executeActionOnUserExperiencesWithFeedBack(roleInServer.getUsers(), feedbackChannel,
|
||||
(AUserExperience ex) -> userExperienceService.updateUserRole(ex, roles, ex.getLevelOrDefault()));
|
||||
return calculationResults.getMainFuture().thenAccept(aVoid ->
|
||||
self.persistData(calculationResults, roleId)
|
||||
);
|
||||
} else {
|
||||
experienceRoleManagementService.unsetRole(roleInServer);
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
experienceRoleManagementService.unsetRole(roleInServer);
|
||||
} else {
|
||||
log.info("Experience role is not define in server - skipping unset.");
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void persistData(CompletableFutureList<RoleCalculationResult> results, Long roleId) {
|
||||
AExperienceRole roleInServer = experienceRoleManagementService.getRoleInServer(roleId);
|
||||
experienceRoleManagementService.unsetRole(roleInServer);
|
||||
userExperienceService.syncRolesInStorage(results.getObjects());
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the best {@link AExperienceRole} for the level of the passed {@link AUserExperience}
|
||||
* @param userExperience The {@link AUserExperience} containing the level to calculate the {@link AExperienceRole}
|
||||
* Finds the best {@link AExperienceRole} for the level of the passed {@link AUserExperience}, returns null if the passed
|
||||
* roles are empty/null
|
||||
* @param roles The role configuration to be used when calculating the appropriate {@link AExperienceRole}
|
||||
* @param currentLevel
|
||||
* @return The best fitting {@link AExperienceRole} according to the level of the {@link AUserExperience}
|
||||
*/
|
||||
@Override
|
||||
public AExperienceRole calculateRole(AUserExperience userExperience, List<AExperienceRole> roles) {
|
||||
if(roles.isEmpty()) {
|
||||
public AExperienceRole calculateRole(List<AExperienceRole> roles, Integer currentLevel) {
|
||||
if(roles == null || roles.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
AExperienceRole lastRole = null;
|
||||
for (AExperienceRole experienceRole : roles) {
|
||||
if(userExperience.getCurrentLevel().getLevel() >= experienceRole.getLevel().getLevel()) {
|
||||
if(currentLevel >= experienceRole.getLevel().getLevel()) {
|
||||
lastRole = experienceRole;
|
||||
} else {
|
||||
return lastRole;
|
||||
|
||||
@@ -32,7 +32,7 @@ public class HasLevelCondition implements SystemCondition {
|
||||
|
||||
Long userId = (Long) parameters.get(USER_ID_VARIABLE);
|
||||
Integer level = (Integer) parameters.get(LEVEL_VARIABLE);
|
||||
Optional<AUserInAServer> userInServerOptional = userInServerManagementService.loadUser(userId);
|
||||
Optional<AUserInAServer> userInServerOptional = userInServerManagementService.loadUserConditional(userId);
|
||||
if(userInServerOptional.isPresent()) {
|
||||
AUserInAServer userInServer = userInServerOptional.get();
|
||||
AUserExperience user = userExperienceManagementService.findUserInServer(userInServer);
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package dev.sheldan.abstracto.experience.service.management;
|
||||
|
||||
import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException;
|
||||
import dev.sheldan.abstracto.core.models.database.ARole;
|
||||
import dev.sheldan.abstracto.core.models.database.AServer;
|
||||
import dev.sheldan.abstracto.core.service.management.RoleManagementService;
|
||||
import dev.sheldan.abstracto.experience.models.database.AExperienceLevel;
|
||||
import dev.sheldan.abstracto.experience.models.database.AExperienceRole;
|
||||
import dev.sheldan.abstracto.experience.repository.ExperienceRoleRepository;
|
||||
@@ -10,6 +12,7 @@ import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
@@ -18,6 +21,9 @@ public class ExperienceRoleManagementServiceBean implements ExperienceRoleManage
|
||||
@Autowired
|
||||
private ExperienceRoleRepository experienceRoleRepository;
|
||||
|
||||
@Autowired
|
||||
private RoleManagementService roleManagementService;
|
||||
|
||||
/**
|
||||
* Removes *all* assignments of roles for the given level
|
||||
* @param level The level to remove the roles for
|
||||
@@ -37,14 +43,35 @@ public class ExperienceRoleManagementServiceBean implements ExperienceRoleManage
|
||||
|
||||
@Override
|
||||
public AExperienceRole getRoleInServer(ARole role) {
|
||||
return this.getRoleInServerOptional(role).orElseThrow(AbstractoRunTimeException::new);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<AExperienceRole> getRoleInServerOptional(ARole role) {
|
||||
return experienceRoleRepository.findByRole(role);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AExperienceRole getRoleInServer(Long roleId) {
|
||||
ARole role = roleManagementService.findRole(roleId);
|
||||
return getRoleInServer(role);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<AExperienceRole> getExperienceRolesForServer(AServer server) {
|
||||
return experienceRoleRepository.findByRoleServer(server);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AExperienceRole getExperienceRoleById(Long experienceRoleId) {
|
||||
return getExperienceRoleByIdOptional(experienceRoleId).orElseThrow(() -> new AbstractoRunTimeException("Experience role not found"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<AExperienceRole> getExperienceRoleByIdOptional(Long experienceRoleId) {
|
||||
return experienceRoleRepository.findById(experienceRoleId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new role if nothing is found, and if its found the experience role will be set to the given level.
|
||||
* @param level The {@link AExperienceLevel} to set the role for
|
||||
@@ -53,18 +80,20 @@ public class ExperienceRoleManagementServiceBean implements ExperienceRoleManage
|
||||
*/
|
||||
@Override
|
||||
public AExperienceRole setLevelToRole(AExperienceLevel level, ARole role) {
|
||||
AExperienceRole byRoleServerAndRole = experienceRoleRepository.findByRole(role);
|
||||
if(byRoleServerAndRole != null) {
|
||||
byRoleServerAndRole.setLevel(level);
|
||||
Optional<AExperienceRole> byRoleServerAndRoleOptional = getRoleInServerOptional(role);
|
||||
AExperienceRole experienceRole;
|
||||
if(byRoleServerAndRoleOptional.isPresent()) {
|
||||
experienceRole = byRoleServerAndRoleOptional.get();
|
||||
experienceRole.setLevel(level);
|
||||
} else {
|
||||
byRoleServerAndRole = AExperienceRole
|
||||
experienceRole = AExperienceRole
|
||||
.builder()
|
||||
.level(level)
|
||||
.roleServer(role.getServer())
|
||||
.role(role)
|
||||
.build();
|
||||
byRoleServerAndRole = experienceRoleRepository.save(byRoleServerAndRole);
|
||||
experienceRole = experienceRoleRepository.save(experienceRole);
|
||||
}
|
||||
return byRoleServerAndRole;
|
||||
return experienceRole;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ public abstract class ExperienceRelatedTest {
|
||||
for (int i = 0; i < levelsWithRoles.size(); i++) {
|
||||
AExperienceLevel level = levelsWithRoles.get(i);
|
||||
ARole role = ARole.builder().id((long)i).server(server).build();
|
||||
roles.add(AExperienceRole.builder().level(level).roleServer(server).role(role).build());
|
||||
roles.add(AExperienceRole.builder().level(level).id(role.getId()).roleServer(server).role(role).build());
|
||||
}
|
||||
return roles;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import dev.sheldan.abstracto.experience.service.management.DisabledExpRoleManage
|
||||
import dev.sheldan.abstracto.test.MockUtils;
|
||||
import dev.sheldan.abstracto.test.command.CommandConfigValidator;
|
||||
import dev.sheldan.abstracto.test.command.CommandTestUtilities;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InjectMocks;
|
||||
@@ -20,6 +21,7 @@ import java.util.Arrays;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
@Slf4j
|
||||
public class DisableExpForRoleTest {
|
||||
|
||||
@InjectMocks
|
||||
|
||||
@@ -22,6 +22,7 @@ import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@@ -45,7 +46,7 @@ public class LeaderBoardCommandTest {
|
||||
|
||||
@Test(expected = IncorrectParameterException.class)
|
||||
public void testIncorrectParameterType() {
|
||||
CommandTestUtilities.executeWrongParametersTest(testUnit);
|
||||
CommandTestUtilities.executeWrongParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -68,9 +69,9 @@ public class LeaderBoardCommandTest {
|
||||
when(converter.fromLeaderBoardEntry(executingUserRank)).thenReturn(leaderBoardEntryModel);
|
||||
MessageToSend messageToSend = MessageToSend.builder().build();
|
||||
when(templateService.renderEmbedTemplate(eq(LeaderBoardCommand.LEADER_BOARD_POST_EMBED_TEMPLATE), any(LeaderBoardModel.class))).thenReturn(messageToSend);
|
||||
CommandResult result = testUnit.execute(context);
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(context);
|
||||
verify(channelService, times(1)).sendMessageToSendToChannel(messageToSend, context.getChannel());
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -12,14 +12,17 @@ import dev.sheldan.abstracto.experience.service.management.DisabledExpRoleManage
|
||||
import dev.sheldan.abstracto.test.MockUtils;
|
||||
import dev.sheldan.abstracto.test.command.CommandConfigValidator;
|
||||
import dev.sheldan.abstracto.test.command.CommandTestUtilities;
|
||||
import net.dv8tion.jda.api.entities.Role;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@@ -43,11 +46,11 @@ public class ListDisabledExperienceRolesTest {
|
||||
CommandContext context = CommandTestUtilities.getNoParameters();
|
||||
AServer server = context.getUserInitiatedContext().getServer();
|
||||
when(disabledExpRoleManagementService.getDisabledRolesForServer(server)).thenReturn(new ArrayList<>());
|
||||
CommandResult result = testUnit.execute(context);
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
when(channelService.sendEmbedTemplateInChannel(eq("list_disabled_experience_roles"),
|
||||
any(DisabledExperienceRolesModel.class), eq(context.getChannel()))).thenReturn(CommandTestUtilities.messageFutureList());
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(context);
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
verify(roleService, times(0)).getRoleFromGuild(any(ARole.class));
|
||||
verify(channelService, times(1)).sendEmbedTemplateInChannel(eq("list_disabled_experience_roles"),
|
||||
any(DisabledExperienceRolesModel.class), eq(context.getChannel()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -57,11 +60,14 @@ public class ListDisabledExperienceRolesTest {
|
||||
ADisabledExpRole disabledExpRole1 = ADisabledExpRole.builder().role(MockUtils.getRole(4L, server)).build();
|
||||
ADisabledExpRole disabledExpRole2 = ADisabledExpRole.builder().role(MockUtils.getRole(6L, server)).build();
|
||||
when(disabledExpRoleManagementService.getDisabledRolesForServer(server)).thenReturn(Arrays.asList(disabledExpRole1, disabledExpRole2));
|
||||
CommandResult result = testUnit.execute(context);
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
verify(roleService, times(2)).getRoleFromGuild(any(ARole.class));
|
||||
verify(channelService, times(1)).sendEmbedTemplateInChannel(eq("list_disabled_experience_roles"),
|
||||
any(DisabledExperienceRolesModel.class), eq(context.getChannel()));
|
||||
Role role1 = Mockito.mock(Role.class);
|
||||
Role role2 = Mockito.mock(Role.class);
|
||||
when(roleService.getRoleFromGuild(disabledExpRole1.getRole())).thenReturn(role1);
|
||||
when(roleService.getRoleFromGuild(disabledExpRole2.getRole())).thenReturn(role2);
|
||||
when(channelService.sendEmbedTemplateInChannel(eq("list_disabled_experience_roles"),
|
||||
any(DisabledExperienceRolesModel.class), eq(context.getChannel()))).thenReturn(CommandTestUtilities.messageFutureList());
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(context);
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -22,6 +22,8 @@ import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
@@ -59,9 +61,9 @@ public class RankTest {
|
||||
when(experienceLevelService.calculateExperienceToNextLevel(currentLevelValue, currentExperience)).thenReturn(140L);
|
||||
MessageToSend messageToSend = MessageToSend.builder().build();
|
||||
when(templateService.renderEmbedTemplate(eq(Rank.RANK_POST_EMBED_TEMPLATE), any(RankModel.class))).thenReturn(messageToSend);
|
||||
CommandResult result = testUnit.execute(context);
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(context);
|
||||
verify(channelService, Mockito.times(1)).sendMessageToSendToChannel(messageToSend, context.getChannel());
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -18,6 +18,7 @@ import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@@ -35,24 +36,24 @@ public class SetExpRoleTest {
|
||||
|
||||
@Test(expected = InsufficientParametersException.class)
|
||||
public void testTooLittleParameters() {
|
||||
CommandTestUtilities.executeNoParametersTest(testUnit);
|
||||
CommandTestUtilities.executeNoParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
@Test(expected = InsufficientParametersException.class)
|
||||
public void testRoleMissing() {
|
||||
CommandContext context = CommandTestUtilities.getWithParameters(Arrays.asList(4));
|
||||
testUnit.execute(context);
|
||||
testUnit.executeAsync(context);
|
||||
}
|
||||
|
||||
@Test(expected = IncorrectParameterException.class)
|
||||
public void testIncorrectParameterType() {
|
||||
CommandTestUtilities.executeWrongParametersTest(testUnit);
|
||||
CommandTestUtilities.executeWrongParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
@Test(expected = IncorrectParameterException.class)
|
||||
public void testLevelProvidedButNotRole() {
|
||||
CommandContext context = CommandTestUtilities.getWithParameters(Arrays.asList(4, ""));
|
||||
testUnit.execute(context);
|
||||
testUnit.executeAsync(context);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -62,9 +63,9 @@ public class SetExpRoleTest {
|
||||
Integer levelToSetTo = 4;
|
||||
CommandContext context = CommandTestUtilities.enhanceWithParameters(noParameters, Arrays.asList(levelToSetTo, changedRole));
|
||||
when(roleService.isRoleInServer(changedRole)).thenReturn(true);
|
||||
CommandResult result = testUnit.execute(context);
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
verify(experienceRoleService, times(1)).setRoleToLevel(changedRole, levelToSetTo, context.getUserInitiatedContext().getChannel());
|
||||
when(experienceRoleService.setRoleToLevel(changedRole, levelToSetTo, context.getUserInitiatedContext().getChannel())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(context);
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
|
||||
@Test(expected = RoleNotFoundInGuildException.class)
|
||||
@@ -74,7 +75,7 @@ public class SetExpRoleTest {
|
||||
Integer levelToSetTo = 4;
|
||||
CommandContext context = CommandTestUtilities.enhanceWithParameters(noParameters, Arrays.asList(levelToSetTo, changedRole));
|
||||
when(roleService.isRoleInServer(changedRole)).thenReturn(false);
|
||||
testUnit.execute(context);
|
||||
testUnit.executeAsync(context);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -13,6 +13,8 @@ import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
@@ -27,11 +29,11 @@ public class SyncRolesTest {
|
||||
@Test
|
||||
public void executeCommand() {
|
||||
CommandContext context = CommandTestUtilities.getNoParameters();
|
||||
CommandResult result = testUnit.execute(context);
|
||||
AServer server = context.getUserInitiatedContext().getServer();
|
||||
AChannel channel = context.getUserInitiatedContext().getChannel();
|
||||
verify(userExperienceService, times(1)).syncUserRolesWithFeedback(server, channel);
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
when(userExperienceService.syncUserRolesWithFeedback(server, channel)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(context);
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -16,9 +16,9 @@ import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class UnSetExpRoleTest {
|
||||
@@ -31,12 +31,12 @@ public class UnSetExpRoleTest {
|
||||
|
||||
@Test(expected = InsufficientParametersException.class)
|
||||
public void testTooLittleParameters() {
|
||||
CommandTestUtilities.executeNoParametersTest(testUnit);
|
||||
CommandTestUtilities.executeNoParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
@Test(expected = IncorrectParameterException.class)
|
||||
public void testIncorrectParameterType() {
|
||||
CommandTestUtilities.executeWrongParametersTest(testUnit);
|
||||
CommandTestUtilities.executeWrongParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -44,9 +44,9 @@ public class UnSetExpRoleTest {
|
||||
CommandContext noParameters = CommandTestUtilities.getNoParameters();
|
||||
ARole changedRole = MockUtils.getRole(4L, noParameters.getUserInitiatedContext().getServer());
|
||||
CommandContext context = CommandTestUtilities.enhanceWithParameters(noParameters, Arrays.asList(changedRole));
|
||||
CommandResult result = testUnit.execute(context);
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
verify(experienceRoleService, times(1)).unsetRole(changedRole, context.getUserInitiatedContext().getChannel());
|
||||
when(experienceRoleService.unsetRole(changedRole, context.getUserInitiatedContext().getChannel())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(context);
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -16,6 +16,8 @@ import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
@@ -41,8 +43,8 @@ public class JoiningUserRoleListenerTest extends ExperienceRelatedTest {
|
||||
Guild guild = Mockito.mock(Guild.class);
|
||||
AUserExperience experience = AUserExperience.builder().experience(3L).user(aUserInAServer).build();
|
||||
when(userExperienceManagementService.findUserInServer(aUserInAServer)).thenReturn(experience);
|
||||
when(userExperienceService.syncForSingleUser(experience)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
testUnit.execute(member, guild, aUserInAServer);
|
||||
verify(userExperienceService, times(1)).syncForSingleUser(experience);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -10,6 +10,7 @@ import dev.sheldan.abstracto.experience.ExperienceRelatedTest;
|
||||
import dev.sheldan.abstracto.experience.config.features.ExperienceFeatureConfig;
|
||||
import dev.sheldan.abstracto.experience.models.LeaderBoard;
|
||||
import dev.sheldan.abstracto.experience.models.LeaderBoardEntry;
|
||||
import dev.sheldan.abstracto.experience.models.RoleCalculationResult;
|
||||
import dev.sheldan.abstracto.experience.models.database.AExperienceLevel;
|
||||
import dev.sheldan.abstracto.experience.models.database.AExperienceRole;
|
||||
import dev.sheldan.abstracto.experience.models.database.AUserExperience;
|
||||
@@ -77,11 +78,14 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
@Captor
|
||||
private ArgumentCaptor<AUserExperience> aUserExperienceArgumentCaptor;
|
||||
|
||||
@Mock
|
||||
private AUserExperienceServiceBean self;
|
||||
|
||||
@Test
|
||||
public void testCalculateLevelTooLow() {
|
||||
AUserExperience experienceToCalculate = AUserExperience.builder().experience(50L).build();
|
||||
List<AExperienceLevel> levels = getLevelConfiguration();
|
||||
AExperienceLevel calculatedLevel = testUnit.calculateLevel(experienceToCalculate, levels);
|
||||
AExperienceLevel calculatedLevel = testUnit.calculateLevel(levels, experienceToCalculate.getExperience());
|
||||
Assert.assertEquals(0, calculatedLevel.getLevel().intValue());
|
||||
}
|
||||
|
||||
@@ -89,7 +93,7 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
public void testCalculateLevelBetweenLevels() {
|
||||
AUserExperience experienceToCalculate = AUserExperience.builder().experience(250L).build();
|
||||
List<AExperienceLevel> levels = getLevelConfiguration();
|
||||
AExperienceLevel calculatedLevel = testUnit.calculateLevel(experienceToCalculate, levels);
|
||||
AExperienceLevel calculatedLevel = testUnit.calculateLevel(levels, experienceToCalculate.getExperience());
|
||||
Assert.assertEquals(2, calculatedLevel.getLevel().intValue());
|
||||
}
|
||||
|
||||
@@ -97,7 +101,7 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
public void testCalculateLevelTooHigh() {
|
||||
AUserExperience experienceToCalculate = AUserExperience.builder().experience(500L).build();
|
||||
List<AExperienceLevel> levels = getLevelConfiguration();
|
||||
AExperienceLevel calculatedLevel = testUnit.calculateLevel(experienceToCalculate, levels);
|
||||
AExperienceLevel calculatedLevel = testUnit.calculateLevel(levels, experienceToCalculate.getExperience());
|
||||
Assert.assertEquals(3, calculatedLevel.getLevel().intValue());
|
||||
}
|
||||
|
||||
@@ -106,7 +110,7 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
List<AExperienceLevel> levels = getLevelConfiguration();
|
||||
AUserInAServer userObject = MockUtils.getUserObject(2L, MockUtils.getServer());
|
||||
AUserExperience experienceToCalculate = AUserExperience.builder().user(userObject).currentLevel(levels.get(1)).experience(250L).build();
|
||||
Assert.assertTrue(testUnit.updateUserLevel(experienceToCalculate, levels));
|
||||
Assert.assertTrue(testUnit.updateUserLevel(experienceToCalculate, levels, experienceToCalculate.getExperience()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -114,7 +118,7 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
List<AExperienceLevel> levels = getLevelConfiguration();
|
||||
AUserInAServer userObject = MockUtils.getUserObject(2L, MockUtils.getServer());
|
||||
AUserExperience experienceToCalculate = AUserExperience.builder().user(userObject).currentLevel(levels.get(2)).experience(250L).build();
|
||||
Assert.assertFalse(testUnit.updateUserLevel(experienceToCalculate, levels));
|
||||
Assert.assertFalse(testUnit.updateUserLevel(experienceToCalculate, levels, experienceToCalculate.getExperience()));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -126,9 +130,8 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
AUserInAServer userToUse = serverToUse.getUsers().get(0);
|
||||
AExperienceRole previousExperienceRole = experienceRoles.get(1);
|
||||
when(botService.isUserInGuild(userToUse)).thenReturn(true);
|
||||
AExperienceRole newAwardedRole = testRoleRelatedScenario(false, levels, servers, serverToUse, experienceRoles, userToUse, previousExperienceRole);
|
||||
verify(roleService, times(1)).addRoleToUser(userToUse, newAwardedRole.getRole());
|
||||
verify(roleService, times(1)).removeRoleFromUser(userToUse, previousExperienceRole.getRole());
|
||||
testRoleRelatedScenario(levels, servers, serverToUse, experienceRoles, userToUse, previousExperienceRole);
|
||||
verify(roleService, times(1)).removeRoleFromUserFuture(userToUse, previousExperienceRole.getRole());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -139,7 +142,7 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
List<AExperienceRole> experienceRoles = getExperienceRoles(levels, serverToUse);
|
||||
AUserInAServer userToUse = serverToUse.getUsers().get(0);
|
||||
AExperienceRole previousExperienceRole = experienceRoles.get(1);
|
||||
AExperienceRole newAwardedRole = testRoleRelatedScenario(true, levels, servers, serverToUse, experienceRoles, userToUse, previousExperienceRole);
|
||||
AExperienceRole newAwardedRole = testRoleRelatedScenario(levels, servers, serverToUse, experienceRoles, userToUse, previousExperienceRole);
|
||||
verify(roleService, times(0)).addRoleToUser(userToUse, newAwardedRole.getRole());
|
||||
verify(roleService, times(0)).removeRoleFromUser(userToUse, previousExperienceRole.getRole());
|
||||
}
|
||||
@@ -153,20 +156,14 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
levels.add(AExperienceLevel.builder().level(4).experienceNeeded(400L).build());
|
||||
mockSimpleServer(levels, experienceRoles, serverToUse);
|
||||
AUserInAServer userToUse = serverToUse.getUsers().get(0);
|
||||
Member jdaMember = Mockito.mock(Member.class);
|
||||
when(botService.getMemberInServer(serverToUse, userToUse.getUserReference())).thenReturn(jdaMember);
|
||||
AExperienceRole previousExperienceRole = experienceRoles.get(3);
|
||||
AUserExperience newUserExperience = mockServerWithSingleUser(levels, serverToUse, 401L, 3, previousExperienceRole, false);
|
||||
|
||||
AExperienceRole newAwardedRole = experienceRoles.get(3);
|
||||
when(experienceRoleService.calculateRole(newUserExperience, experienceRoles)).thenReturn(newAwardedRole);
|
||||
when(roleService.memberHasRole(jdaMember, newAwardedRole.getRole())).thenReturn(true);
|
||||
when(userExperienceManagementService.findUserInServer(userToUse)).thenReturn(newUserExperience);
|
||||
testUnit.handleExperienceGain(servers);
|
||||
verify(userExperienceManagementService, times(1)).saveUser(eq(newUserExperience));
|
||||
verify(roleService, times(0)).removeRoleFromUser(userToUse, previousExperienceRole.getRole());
|
||||
verify(roleService, times(0)).addRoleToUser(userToUse, newAwardedRole.getRole());
|
||||
Assert.assertEquals(4, newUserExperience.getCurrentLevel().getLevel().intValue());
|
||||
Assert.assertEquals(3L, newUserExperience.getCurrentExperienceRole().getRole().getId().longValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -177,15 +174,9 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
List<AExperienceRole> experienceRoles = getExperienceRoles(levels, serverToUse);
|
||||
mockSimpleServer(levels, experienceRoles, serverToUse);
|
||||
AUserInAServer userToUse = serverToUse.getUsers().get(0);
|
||||
Member jdaMember = Mockito.mock(Member.class);
|
||||
when(botService.getMemberInServer(serverToUse, userToUse.getUserReference())).thenReturn(jdaMember);
|
||||
AUserExperience newUserExperience = mockServerWithSingleUser(levels, serverToUse, 101L, 1, null, false);
|
||||
|
||||
when(experienceRoleService.calculateRole(newUserExperience, experienceRoles)).thenReturn(experienceRoles.get(1));
|
||||
when(userExperienceManagementService.findUserInServer(userToUse)).thenReturn(newUserExperience);
|
||||
testUnit.handleExperienceGain(servers);
|
||||
verify(userExperienceManagementService, times(1)).saveUser(eq(newUserExperience));
|
||||
Assert.assertEquals(1, newUserExperience.getCurrentLevel().getLevel().intValue());
|
||||
Assert.assertEquals(1L, newUserExperience.getCurrentExperienceRole().getRole().getId().longValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -196,13 +187,10 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
List<AExperienceRole> experienceRoles = getExperienceRoles(levels, serverToUse);
|
||||
mockSimpleServer(levels, experienceRoles, serverToUse);
|
||||
AUserInAServer userToUse = serverToUse.getUsers().get(0);
|
||||
Member jdaMember = Mockito.mock(Member.class);
|
||||
when(botService.getMemberInServer(serverToUse, userToUse.getUserReference())).thenReturn(jdaMember);
|
||||
AUserExperience newUserExperience = mockServerWithSingleUser(levels, serverToUse, 50L, 0, null, false);
|
||||
|
||||
when(experienceRoleService.calculateRole(newUserExperience, experienceRoles)).thenReturn(null);
|
||||
when(userExperienceManagementService.findUserInServer(userToUse)).thenReturn(newUserExperience);
|
||||
testUnit.handleExperienceGain(servers);
|
||||
verify(userExperienceManagementService, times(1)).saveUser(eq(newUserExperience));
|
||||
Assert.assertEquals(0, newUserExperience.getCurrentLevel().getLevel().intValue());
|
||||
Assert.assertNull(newUserExperience.getCurrentExperienceRole());
|
||||
}
|
||||
@@ -219,14 +207,12 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
when(botService.getMemberInServer(serverToUse, userToUse.getUserReference())).thenReturn(jdaMember);
|
||||
AUserExperience newUserExperience = mockServerWithSingleUser(levels, serverToUse, 50L, 0, experienceRoles.get(0), false);
|
||||
|
||||
when(experienceRoleService.calculateRole(newUserExperience, experienceRoles)).thenReturn(null);
|
||||
when(botService.isUserInGuild(userToUse)).thenReturn(true);
|
||||
when(userExperienceManagementService.findUserInServer(userToUse)).thenReturn(newUserExperience);
|
||||
when(roleService.removeRoleFromUserFuture(newUserExperience.getUser(), newUserExperience.getCurrentExperienceRole().getRole())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
testUnit.handleExperienceGain(servers);
|
||||
verify(userExperienceManagementService, times(1)).saveUser(eq(newUserExperience));
|
||||
verify(roleService, times(1)).removeRoleFromUser(userToUse, experienceRoles.get(0).getRole());
|
||||
verify(roleService, times(0)).addRoleToUser(eq(userToUse), any(ARole.class));
|
||||
Assert.assertEquals(0, newUserExperience.getCurrentLevel().getLevel().intValue());
|
||||
Assert.assertNull(newUserExperience.getCurrentExperienceRole());
|
||||
verify(roleService, times(1)).removeRoleFromUserFuture(userToUse, experienceRoles.get(0).getRole());
|
||||
verify(roleService, times(0)).addRoleToUserFuture(eq(userToUse), any(ARole.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -238,7 +224,7 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
mockSimpleServer(levels, experienceRoles, serverToUse);
|
||||
AUserInAServer userToUse = serverToUse.getUsers().get(0);
|
||||
AUserExperience newUserExperience = mockServerWithSingleUser(levels, serverToUse, 50L, 0, experienceRoles.get(0), true);
|
||||
|
||||
when(userExperienceManagementService.findUserInServer(userToUse)).thenReturn(newUserExperience);
|
||||
testUnit.handleExperienceGain(servers);
|
||||
verify(userExperienceManagementService, times(0)).saveUser(eq(newUserExperience));
|
||||
verify(roleService, times(0)).removeRoleFromUser(userToUse, experienceRoles.get(0).getRole());
|
||||
@@ -275,16 +261,12 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
List<AExperienceRole> experienceRoles = getExperienceRoles(levels, serverToUse);
|
||||
mockSimpleServer(levels, experienceRoles, serverToUse);
|
||||
AUserInAServer userToUse = serverToUse.getUsers().get(0);
|
||||
Member jdaMember = Mockito.mock(Member.class);
|
||||
when(botService.getMemberInServer(serverToUse, userToUse.getUserReference())).thenReturn(jdaMember);
|
||||
AUserExperience newUserExperience = mockServerWithSingleUser(levels, serverToUse, 101L, 1, experienceRoles.get(1), false);
|
||||
when(experienceRoleService.calculateRole(newUserExperience, experienceRoles)).thenReturn(experienceRoles.get(1));
|
||||
testUnit.handleExperienceGain(servers);
|
||||
verify(userExperienceManagementService, times(1)).saveUser(eq(newUserExperience));
|
||||
when(userExperienceManagementService.findUserInServer(userToUse)).thenReturn(newUserExperience);
|
||||
CompletableFuture<Void> future = testUnit.handleExperienceGain(servers);
|
||||
future.join();
|
||||
verify(roleService, times(0)).removeRoleFromUser(userToUse, experienceRoles.get(0).getRole());
|
||||
verify(roleService, times(0)).addRoleToUser(eq(userToUse), any(ARole.class));
|
||||
Assert.assertEquals(1, newUserExperience.getCurrentLevel().getLevel().intValue());
|
||||
Assert.assertEquals(experienceRoles.get(1).getRole().getId(), newUserExperience.getCurrentExperienceRole().getRole().getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -304,27 +286,19 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
List<AExperienceRole> experienceRoles = getExperienceRoles(levels, aServer);
|
||||
mockSimpleServer(levels, experienceRoles, aServer);
|
||||
AUserInAServer userToUse = aServer.getUsers().get(0);
|
||||
Member jdaMember = Mockito.mock(Member.class);
|
||||
when(botService.getMemberInServer(aServer, userToUse.getUserReference())).thenReturn(jdaMember);
|
||||
AExperienceRole role = experienceRoles.get(experienceRoleIndices.get(i));
|
||||
AUserExperience newUserExperience = mockServerWithSingleUser(levels, aServer, experienceValues, level, role, false);
|
||||
when(experienceRoleService.calculateRole(newUserExperience, experienceRoles)).thenReturn(role);
|
||||
when(userExperienceManagementService.findUserInServer(userToUse)).thenReturn(newUserExperience);
|
||||
userExperiences.add(newUserExperience);
|
||||
allExperienceRoles.add(experienceRoles);
|
||||
}
|
||||
testUnit.handleExperienceGain(servers);
|
||||
List<Integer> newLevels = Arrays.asList(1,3);
|
||||
List<Integer> newExperienceRoleIndices = Arrays.asList(1, 2);
|
||||
for (int i = 0; i < servers.size(); i++) {
|
||||
AServer server = servers.get(i);
|
||||
AUserExperience newUserExperience = userExperiences.get(i);
|
||||
AUserInAServer userToUse = server.getUsers().get(0);
|
||||
List<AExperienceRole> experienceRoles = allExperienceRoles.get(i);
|
||||
verify(userExperienceManagementService, times(2)).saveUser(aUserExperienceArgumentCaptor.capture());
|
||||
verify(roleService, times(0)).removeRoleFromUser(userToUse, experienceRoles.get(0).getRole());
|
||||
verify(roleService, times(0)).addRoleToUser(eq(userToUse), any(ARole.class));
|
||||
Assert.assertEquals(newLevels.get(i).intValue(), newUserExperience.getCurrentLevel().getLevel().intValue());
|
||||
Assert.assertEquals(experienceRoles.get(newExperienceRoleIndices.get(i)).getRole().getId(), newUserExperience.getCurrentExperienceRole().getRole().getId());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -336,7 +310,7 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
AExperienceRole afterRole = usedExperienceRoles.get(0);
|
||||
Integer removals = 0;
|
||||
Integer adds = 1;
|
||||
executeSyncSingleUserTest(server, usedExperienceRoles, previousRole, afterRole, removals, adds);
|
||||
executeSyncSingleUserTest(server, usedExperienceRoles, previousRole, afterRole);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -347,7 +321,7 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
AExperienceRole afterRole = null;
|
||||
Integer removals = 1;
|
||||
Integer adds = 0;
|
||||
executeSyncSingleUserTest(server, usedExperienceRoles, previousRole, afterRole, removals, adds);
|
||||
executeSyncSingleUserTest(server, usedExperienceRoles, previousRole, afterRole);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -358,7 +332,7 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
AExperienceRole afterRole = usedExperienceRoles.get(0);
|
||||
Integer removals = 0;
|
||||
Integer adds = 0;
|
||||
executeSyncSingleUserTest(server, usedExperienceRoles, previousRole, afterRole, removals, adds);
|
||||
executeSyncSingleUserTest(server, usedExperienceRoles, previousRole, afterRole);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -369,7 +343,7 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
AExperienceRole afterRole = usedExperienceRoles.get(1);
|
||||
Integer removals = 1;
|
||||
Integer adds = 1;
|
||||
executeSyncSingleUserTest(server, usedExperienceRoles, previousRole, afterRole, removals, adds);
|
||||
executeSyncSingleUserTest(server, usedExperienceRoles, previousRole, afterRole);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -438,7 +412,8 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
AExperienceRole secondPreviousRole = null;
|
||||
AExperienceRole secondAfterRole = null;
|
||||
AExperienceLevel level0 = AExperienceLevel.builder().level(0).build();
|
||||
AUserExperience experience = AUserExperience.builder().experience(40L).user(MockUtils.getUserObject(3L, server)).currentLevel(level0).build();
|
||||
AExperienceLevel level1 = AExperienceLevel.builder().level(1).build();
|
||||
AUserExperience experience = AUserExperience.builder().experience(40L).user(MockUtils.getUserObject(3L, server)).currentLevel(level1).build();
|
||||
AUserExperience experience2 = AUserExperience.builder().experience(201L).user(MockUtils.getUserObject(4L, server)).currentLevel(level0).build();
|
||||
List<AUserExperience> experiences = Arrays.asList(experience, experience2);
|
||||
|
||||
@@ -451,15 +426,19 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
experience2.setCurrentExperienceRole(secondPreviousRole);
|
||||
when(userExperienceManagementService.loadAllUsers(server)).thenReturn(experiences);
|
||||
when(experienceRoleManagementService.getExperienceRolesForServer(server)).thenReturn(usedExperienceRoles);
|
||||
when(experienceRoleService.calculateRole(experience, usedExperienceRoles)).thenReturn(firstAfterRole);
|
||||
when(experienceRoleService.calculateRole(experience2, usedExperienceRoles)).thenReturn(secondAfterRole);
|
||||
when(experienceRoleService.calculateRole(usedExperienceRoles, experience.getLevelOrDefault())).thenReturn(firstAfterRole);
|
||||
when(experienceRoleService.calculateRole(usedExperienceRoles, experience2.getLevelOrDefault())).thenReturn(secondAfterRole);
|
||||
when(botService.getMemberInServer(server, experience.getUser().getUserReference())).thenReturn(firstMember);
|
||||
when(botService.getMemberInServer(server, experience2.getUser().getUserReference())).thenReturn(secondMember);
|
||||
when(botService.isUserInGuild(experience.getUser())).thenReturn(true);
|
||||
when(botService.isUserInGuild(experience2.getUser())).thenReturn(true);
|
||||
when(roleService.addRoleToUserFuture(experience.getUser(), firstAfterRole.getRole())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(roleService.memberHasRole(firstMember, firstAfterRole.getRole())).thenReturn(false);
|
||||
testUnit.syncUserRoles(server);
|
||||
Assert.assertNull(experience2.getCurrentExperienceRole());
|
||||
Assert.assertEquals(usedExperienceRoles.get(0).getRole().getId(), experience.getCurrentExperienceRole().getRole().getId());
|
||||
verify(roleService, times(1)).addRoleToUser(users.get(0), usedExperienceRoles.get(0).getRole());
|
||||
List<CompletableFuture<RoleCalculationResult>> futures = testUnit.syncUserRoles(server);
|
||||
RoleCalculationResult result = futures.get(0).join();
|
||||
RoleCalculationResult result2 = futures.get(1).join();
|
||||
Assert.assertEquals(firstAfterRole.getRole().getId(), result.getExperienceRoleId());
|
||||
Assert.assertNull(result2.getExperienceRoleId());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -547,7 +526,7 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
verify(messageService, times(messageCount)).updateStatusMessage(channel, messageId, statusMessage);
|
||||
}
|
||||
|
||||
private void executeSyncSingleUserTest(AServer server, List<AExperienceRole> usedExperienceRoles, AExperienceRole previousRole, AExperienceRole afterRole, Integer removals, Integer adds) {
|
||||
private void executeSyncSingleUserTest(AServer server, List<AExperienceRole> usedExperienceRoles, AExperienceRole previousRole, AExperienceRole afterRole) {
|
||||
AExperienceLevel level0 = AExperienceLevel.builder().level(0).build();
|
||||
AUserExperience experience = AUserExperience.builder().experience(40L).user(MockUtils.getUserObject(3L, server)).currentLevel(level0).build();
|
||||
List<AUserExperience> experiences = Arrays.asList(experience);
|
||||
@@ -557,26 +536,25 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
when(botService.getMemberInServer(server, users.get(0).getUserReference())).thenReturn(firstMember);
|
||||
experience.setCurrentExperienceRole(previousRole);
|
||||
when(experienceRoleManagementService.getExperienceRolesForServer(server)).thenReturn(usedExperienceRoles);
|
||||
when(experienceRoleService.calculateRole(experience, usedExperienceRoles)).thenReturn(afterRole);
|
||||
when(experienceRoleService.calculateRole(usedExperienceRoles, experience.getLevelOrDefault())).thenReturn(afterRole);
|
||||
when(botService.getMemberInServer(server, experience.getUser().getUserReference())).thenReturn(firstMember);
|
||||
if(removals > 0) {
|
||||
users.forEach(aUserInAServer -> when(botService.isUserInGuild(aUserInAServer)).thenReturn(true));
|
||||
users.forEach(aUserInAServer -> when(botService.isUserInGuild(aUserInAServer)).thenReturn(true));
|
||||
if(afterRole != null) {
|
||||
when(roleService.addRoleToUserFuture(experience.getUser(), afterRole.getRole())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
}
|
||||
if(previousRole != null) {
|
||||
when(roleService.removeRoleFromUserFuture(experience.getUser(), previousRole.getRole())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
}
|
||||
if(afterRole != null && previousRole != null) {
|
||||
boolean sameRole = previousRole.getRole().getId().equals(afterRole.getRole().getId());
|
||||
when(roleService.memberHasRole(firstMember, afterRole.getRole())).thenReturn(sameRole);
|
||||
}
|
||||
testUnit.syncForSingleUser(experience);
|
||||
CompletableFuture<RoleCalculationResult> calculationFuture = testUnit.syncForSingleUser(experience);
|
||||
RoleCalculationResult result = calculationFuture.join();
|
||||
if(afterRole != null) {
|
||||
Assert.assertEquals(afterRole.getRole().getId(), experience.getCurrentExperienceRole().getRole().getId());
|
||||
Assert.assertEquals(afterRole.getRole().getId(), result.getExperienceRoleId());
|
||||
} else {
|
||||
Assert.assertNull(experience.getCurrentExperienceRole());
|
||||
}
|
||||
if(previousRole != null) {
|
||||
verify(roleService, times(removals)).removeRoleFromUser(experience.getUser(), previousRole.getRole());
|
||||
}
|
||||
if(afterRole != null) {
|
||||
verify(roleService, times(adds)).addRoleToUser(experience.getUser(), afterRole.getRole());
|
||||
Assert.assertNull(result.getExperienceRoleId());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -597,19 +575,16 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
Assert.assertEquals(pageSize, entries.size());
|
||||
}
|
||||
|
||||
private AExperienceRole testRoleRelatedScenario(boolean shouldHaveRole, List<AExperienceLevel> levels, List<AServer> servers, AServer serverToUse, List<AExperienceRole> experienceRoles, AUserInAServer userToUse, AExperienceRole previousExperienceRole) {
|
||||
private AExperienceRole testRoleRelatedScenario(List<AExperienceLevel> levels, List<AServer> servers, AServer serverToUse, List<AExperienceRole> experienceRoles, AUserInAServer userToUse, AExperienceRole previousExperienceRole) {
|
||||
mockSimpleServer(levels, experienceRoles, serverToUse);
|
||||
Member jdaMember = Mockito.mock(Member.class);
|
||||
when(botService.getMemberInServer(serverToUse, userToUse.getUserReference())).thenReturn(jdaMember);
|
||||
AUserExperience newUserExperience = mockServerWithSingleUser(levels, serverToUse, 301L, 1, previousExperienceRole, false);
|
||||
|
||||
AExperienceRole newAwardedRole = experienceRoles.get(3);
|
||||
when(experienceRoleService.calculateRole(newUserExperience, experienceRoles)).thenReturn(newAwardedRole);
|
||||
when(roleService.memberHasRole(jdaMember, newAwardedRole.getRole())).thenReturn(shouldHaveRole);
|
||||
testUnit.handleExperienceGain(servers);
|
||||
verify(userExperienceManagementService, times(1)).saveUser(eq(newUserExperience));
|
||||
Assert.assertEquals(3, newUserExperience.getCurrentLevel().getLevel().intValue());
|
||||
Assert.assertEquals(3L, newUserExperience.getCurrentExperienceRole().getRole().getId().longValue());
|
||||
when(roleService.removeRoleFromUserFuture(newUserExperience.getUser(), newUserExperience.getCurrentExperienceRole().getRole())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(userExperienceManagementService.findUserInServer(userToUse)).thenReturn(newUserExperience);
|
||||
testUnit.handleExperienceGain(servers).join();
|
||||
return newAwardedRole;
|
||||
}
|
||||
|
||||
@@ -624,9 +599,7 @@ public class AUserExperienceServiceBeanTest extends ExperienceRelatedTest {
|
||||
}
|
||||
|
||||
private AUserExperience mockUser(Long experience, AExperienceLevel currentLevel, AUserInAServer firstUser, boolean hasExpDisabled, AExperienceRole currentRole) {
|
||||
AUserExperience newUserExperience = AUserExperience.builder().currentLevel(currentLevel).experience(experience).user(firstUser).experienceGainDisabled(hasExpDisabled).currentExperienceRole(currentRole).build();
|
||||
when(userExperienceManagementService.incrementExpForUser(eq(firstUser), anyLong(), anyLong())).thenReturn(newUserExperience);
|
||||
return newUserExperience;
|
||||
return AUserExperience.builder().currentLevel(currentLevel).experience(experience).user(firstUser).experienceGainDisabled(hasExpDisabled).currentExperienceRole(currentRole).messageCount(0L).build();
|
||||
}
|
||||
|
||||
private void mockSimpleServer(List<AExperienceLevel> levels, List<AExperienceRole> experienceRoles, AServer server) {
|
||||
|
||||
@@ -4,7 +4,10 @@ import dev.sheldan.abstracto.core.models.database.AChannel;
|
||||
import dev.sheldan.abstracto.core.models.database.AChannelType;
|
||||
import dev.sheldan.abstracto.core.models.database.ARole;
|
||||
import dev.sheldan.abstracto.core.models.database.AServer;
|
||||
import dev.sheldan.abstracto.core.service.management.RoleManagementService;
|
||||
import dev.sheldan.abstracto.core.utils.CompletableFutureList;
|
||||
import dev.sheldan.abstracto.experience.ExperienceRelatedTest;
|
||||
import dev.sheldan.abstracto.experience.models.RoleCalculationResult;
|
||||
import dev.sheldan.abstracto.experience.models.database.AExperienceLevel;
|
||||
import dev.sheldan.abstracto.experience.models.database.AExperienceRole;
|
||||
import dev.sheldan.abstracto.experience.models.database.AUserExperience;
|
||||
@@ -22,6 +25,7 @@ import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@@ -40,6 +44,12 @@ public class ExperienceRoleServiceBeanTest extends ExperienceRelatedTest {
|
||||
@Mock
|
||||
private AUserExperienceService userExperienceService;
|
||||
|
||||
@Mock
|
||||
private RoleManagementService roleManagementService;
|
||||
|
||||
@Mock
|
||||
private ExperienceRoleServiceBean self;
|
||||
|
||||
|
||||
@Test
|
||||
public void testSettingRoleToLevelWithoutOldUsers() {
|
||||
@@ -48,10 +58,23 @@ public class ExperienceRoleServiceBeanTest extends ExperienceRelatedTest {
|
||||
AExperienceLevel level = AExperienceLevel.builder().experienceNeeded(10L).level(levelCount).build();
|
||||
ARole roleToChange = getRole(1L, server);
|
||||
AExperienceRole previousExperienceRole = AExperienceRole.builder().role(roleToChange).roleServer(server).level(level).build();
|
||||
when(experienceRoleManagementService.getRoleInServer(roleToChange)).thenReturn(previousExperienceRole);
|
||||
when(experienceLevelService.getLevel(levelCount)).thenReturn(Optional.of(level));
|
||||
testingUnit.setRoleToLevel(roleToChange, levelCount, getFeedbackChannel(server));
|
||||
when(experienceRoleManagementService.getRoleInServerOptional(roleToChange)).thenReturn(Optional.of(previousExperienceRole));
|
||||
CompletableFuture<Void> future = testingUnit.setRoleToLevel(roleToChange, levelCount, getFeedbackChannel(server));
|
||||
|
||||
future.join();
|
||||
verify(experienceRoleManagementService, times(1)).unsetRole(previousExperienceRole);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUnsetRoleInDb() {
|
||||
AServer server = MockUtils.getServer();
|
||||
Integer levelCount = 10;
|
||||
AExperienceLevel level = AExperienceLevel.builder().experienceNeeded(10L).level(levelCount).build();
|
||||
ARole roleToChange = getRole(1L, server);
|
||||
when(experienceLevelService.getLevel(levelCount)).thenReturn(Optional.of(level));
|
||||
when(roleManagementService.findRole(roleToChange.getId())).thenReturn(roleToChange);
|
||||
testingUnit.unsetRoleInDb(levelCount, roleToChange.getId());
|
||||
|
||||
verify(experienceRoleManagementService, times(1)).removeAllRoleAssignmentsForLevelInServer(level, server);
|
||||
verify(experienceRoleManagementService, times(1)).setLevelToRole(level, roleToChange);
|
||||
verify(experienceRoleManagementService, times(0)).getExperienceRolesForServer(server);
|
||||
@@ -70,23 +93,23 @@ public class ExperienceRoleServiceBeanTest extends ExperienceRelatedTest {
|
||||
List<AUserExperience> users = Arrays.asList(firstUser, secondUser);
|
||||
AExperienceRole previousExperienceRole = AExperienceRole.builder().role(roleToChange).id(roleToChange.getId()).roleServer(server).level(level).users(users).build();
|
||||
AExperienceRole newExperienceRole = AExperienceRole.builder().role(newRoleToAward).id(newRoleToAward.getId()).roleServer(server).level(level).build();
|
||||
when(experienceRoleManagementService.getRoleInServer(roleToChange)).thenReturn(previousExperienceRole);
|
||||
when(experienceLevelService.getLevel(levelCount)).thenReturn(Optional.of(level));
|
||||
when(experienceRoleManagementService.getRoleInServerOptional(roleToChange)).thenReturn(Optional.of(previousExperienceRole));
|
||||
when(experienceRoleManagementService.getExperienceRolesForServer(server)).thenReturn(new ArrayList<>(Arrays.asList(newExperienceRole, previousExperienceRole)));
|
||||
AChannel feedBackChannel = getFeedbackChannel(server);
|
||||
testingUnit.setRoleToLevel(roleToChange, levelCount, feedBackChannel);
|
||||
verify(experienceRoleManagementService, times(1)).unsetRole(previousExperienceRole);
|
||||
verify(experienceRoleManagementService, times(1)).removeAllRoleAssignmentsForLevelInServer(level, server);
|
||||
verify(experienceRoleManagementService, times(1)).setLevelToRole(level, roleToChange);
|
||||
verify(experienceRoleManagementService, times(1)).getExperienceRolesForServer(server);
|
||||
verify(userExperienceService, times(1)).executeActionOnUserExperiencesWithFeedBack(eq(users), eq(feedBackChannel), any());
|
||||
List<CompletableFuture<RoleCalculationResult>> futures = new ArrayList<>();
|
||||
futures.add(CompletableFuture.completedFuture(null));
|
||||
CompletableFutureList<RoleCalculationResult> futuresList = new CompletableFutureList<>(futures);
|
||||
when(userExperienceService.executeActionOnUserExperiencesWithFeedBack(eq(users), eq(feedBackChannel), any())).thenReturn(futuresList);
|
||||
CompletableFuture<Void> future = testingUnit.setRoleToLevel(roleToChange, levelCount, feedBackChannel);
|
||||
future.join();
|
||||
verify(experienceRoleManagementService, times(0)).unsetRole(previousExperienceRole);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCalculateRoleForLevelInBetween() {
|
||||
List<AExperienceRole> roles = getExperienceRoles();
|
||||
AUserExperience userExperience = AUserExperience.builder().currentLevel(AExperienceLevel.builder().level(6).build()).build();
|
||||
AExperienceRole aExperienceRole = testingUnit.calculateRole(userExperience, roles);
|
||||
AExperienceRole aExperienceRole = testingUnit.calculateRole(roles, userExperience.getLevelOrDefault());
|
||||
Assert.assertEquals(aExperienceRole.getLevel().getLevel().intValue(), 5);
|
||||
}
|
||||
|
||||
@@ -94,7 +117,7 @@ public class ExperienceRoleServiceBeanTest extends ExperienceRelatedTest {
|
||||
public void testCalculateRoleForLevelBelow() {
|
||||
List<AExperienceRole> roles = getExperienceRoles();
|
||||
AUserExperience userExperience = AUserExperience.builder().currentLevel(AExperienceLevel.builder().level(4).build()).build();
|
||||
AExperienceRole aExperienceRole = testingUnit.calculateRole(userExperience, roles);
|
||||
AExperienceRole aExperienceRole = testingUnit.calculateRole(roles, userExperience.getLevelOrDefault());
|
||||
Assert.assertNull(aExperienceRole);
|
||||
}
|
||||
|
||||
@@ -102,7 +125,7 @@ public class ExperienceRoleServiceBeanTest extends ExperienceRelatedTest {
|
||||
public void testCalculateRoleForLevelOver() {
|
||||
List<AExperienceRole> roles = getExperienceRoles();
|
||||
AUserExperience userExperience = AUserExperience.builder().currentLevel(AExperienceLevel.builder().level(11).build()).build();
|
||||
AExperienceRole aExperienceRole = testingUnit.calculateRole(userExperience, roles);
|
||||
AExperienceRole aExperienceRole = testingUnit.calculateRole(roles, userExperience.getLevelOrDefault());
|
||||
Assert.assertEquals(aExperienceRole.getLevel().getLevel().intValue(), 10);
|
||||
}
|
||||
|
||||
@@ -110,7 +133,7 @@ public class ExperienceRoleServiceBeanTest extends ExperienceRelatedTest {
|
||||
public void testCalculateRoleForLevelExact() {
|
||||
List<AExperienceRole> roles = getExperienceRoles();
|
||||
AUserExperience userExperience = AUserExperience.builder().currentLevel(AExperienceLevel.builder().level(10).build()).build();
|
||||
AExperienceRole aExperienceRole = testingUnit.calculateRole(userExperience, roles);
|
||||
AExperienceRole aExperienceRole = testingUnit.calculateRole(roles, userExperience.getLevelOrDefault());
|
||||
Assert.assertEquals(aExperienceRole.getLevel().getLevel().intValue(), 10);
|
||||
}
|
||||
|
||||
@@ -118,7 +141,7 @@ public class ExperienceRoleServiceBeanTest extends ExperienceRelatedTest {
|
||||
public void testCalculateRoleForNoRoleConfigFound() {
|
||||
List<AExperienceRole> roles = new ArrayList<>();
|
||||
AUserExperience userExperience = AUserExperience.builder().currentLevel(AExperienceLevel.builder().level(6).build()).build();
|
||||
AExperienceRole aExperienceRole = testingUnit.calculateRole(userExperience, roles);
|
||||
AExperienceRole aExperienceRole = testingUnit.calculateRole(roles, userExperience.getLevelOrDefault());
|
||||
Assert.assertNull(aExperienceRole);
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ import org.mockito.junit.MockitoJUnitRunner;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
@@ -77,7 +78,7 @@ public class ExperienceRoleManagementServiceBeanTest extends ExperienceRelatedTe
|
||||
@Test
|
||||
public void testFindExperienceRoleForRoleInServer() {
|
||||
AExperienceRole expRole = getExperienceRoleForLevel(37);
|
||||
when((experienceRoleRepository.findByRole(expRole.getRole()))).thenReturn(expRole);
|
||||
when((experienceRoleRepository.findByRole(expRole.getRole()))).thenReturn(Optional.of(expRole));
|
||||
AExperienceRole roleInServer = testUnit.getRoleInServer(expRole.getRole());
|
||||
Assert.assertEquals(expRole.getRole().getId(), roleInServer.getRole().getId());
|
||||
verify(experienceRoleRepository, times(1)).findByRole(expRole.getRole());
|
||||
@@ -104,7 +105,7 @@ public class ExperienceRoleManagementServiceBeanTest extends ExperienceRelatedTe
|
||||
public void setLevelToRoleWhichHasAnExistingMapping() {
|
||||
int level = 5;
|
||||
AExperienceRole experienceRole = getExperienceRoleForLevel(level);
|
||||
when(experienceRoleRepository.findByRole(experienceRole.getRole())).thenReturn(experienceRole);
|
||||
when(experienceRoleRepository.findByRole(experienceRole.getRole())).thenReturn(Optional.of(experienceRole));
|
||||
AExperienceLevel newLevel = AExperienceLevel.builder().level(8).build();
|
||||
AExperienceRole updatedExperienceRole = testUnit.setLevelToRole(newLevel, experienceRole.getRole());
|
||||
verify(experienceRoleRepository, times(1)).findByRole(experienceRole.getRole());
|
||||
@@ -115,7 +116,7 @@ public class ExperienceRoleManagementServiceBeanTest extends ExperienceRelatedTe
|
||||
public void setLevelToRoleWithoutAMappingExistingPreviously() {
|
||||
int level = 5;
|
||||
AExperienceRole experienceRole = getExperienceRoleForLevel(level);
|
||||
when(experienceRoleRepository.findByRole(experienceRole.getRole())).thenReturn(null);
|
||||
when(experienceRoleRepository.findByRole(experienceRole.getRole())).thenReturn(Optional.empty());
|
||||
when(experienceRoleRepository.save(any(AExperienceRole.class))).thenReturn(experienceRole);
|
||||
AExperienceLevel newLevel = AExperienceLevel.builder().level(8).build();
|
||||
AExperienceRole updatedExperienceRole = testUnit.setLevelToRole(newLevel, experienceRole.getRole());
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package dev.sheldan.abstracto.experience.models;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
public class ExperienceGainResult {
|
||||
private CompletableFuture<RoleCalculationResult> calculationResult;
|
||||
private Long userInServerId;
|
||||
private Long newExperience;
|
||||
private Integer newLevel;
|
||||
private Long newMessageCount;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package dev.sheldan.abstracto.experience.models;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@Builder
|
||||
public class RoleCalculationResult {
|
||||
private Long experienceRoleId;
|
||||
private Long userInServerId;
|
||||
}
|
||||
@@ -80,6 +80,10 @@ public class AUserExperience implements Serializable {
|
||||
this.updated = Instant.now();
|
||||
}
|
||||
|
||||
public Integer getLevelOrDefault() {
|
||||
return currentLevel != null ? currentLevel.getLevel() : 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
|
||||
@@ -3,15 +3,19 @@ package dev.sheldan.abstracto.experience.service;
|
||||
import dev.sheldan.abstracto.core.models.database.AChannel;
|
||||
import dev.sheldan.abstracto.core.models.database.AServer;
|
||||
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
|
||||
import dev.sheldan.abstracto.core.utils.CompletableFutureList;
|
||||
import dev.sheldan.abstracto.experience.models.LeaderBoard;
|
||||
import dev.sheldan.abstracto.experience.models.LeaderBoardEntry;
|
||||
import dev.sheldan.abstracto.experience.models.RoleCalculationResult;
|
||||
import dev.sheldan.abstracto.experience.models.database.AExperienceLevel;
|
||||
import dev.sheldan.abstracto.experience.models.database.AExperienceRole;
|
||||
import dev.sheldan.abstracto.experience.models.database.AUserExperience;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* Service providing the required mechanisms to provide experience tracking.
|
||||
@@ -36,21 +40,22 @@ public interface AUserExperienceService {
|
||||
/**
|
||||
* Calculates the appropriate level of the given {@link AUserExperience} according to the given {@link AExperienceLevel}
|
||||
* configuration.
|
||||
* @param experience The {@link AUserExperience} to calculate the level for
|
||||
* @param levels The list of {@link AExperienceLevel} representing the level configuration, this must include the initial level 0
|
||||
* This level will be taken as the initial value, and if no other level qualifies, this will be taken. The levels must be ordered.
|
||||
* @param experienceCount
|
||||
* @return The appropriate level of {@link AUserExperience} according to the provided {@link AExperienceLevel} configuration
|
||||
*/
|
||||
AExperienceLevel calculateLevel(AUserExperience experience, List<AExperienceLevel> levels);
|
||||
AExperienceLevel calculateLevel(List<AExperienceLevel> levels, Long experienceCount);
|
||||
|
||||
/**
|
||||
* Calculates the new level of the provided {@link AUserExperience} according
|
||||
* to the provided list of {@link AExperienceLevel} used as level configuration
|
||||
* @param userExperience The {@link AUserExperience} to increase the experience for
|
||||
* @param levels The list of {@link AExperienceLevel} to be used as level configuration
|
||||
* @param experienceCount
|
||||
* @return Whether or not the user changed level
|
||||
*/
|
||||
boolean updateUserLevel(AUserExperience userExperience, List<AExperienceLevel> levels);
|
||||
boolean updateUserLevel(AUserExperience userExperience, List<AExperienceLevel> levels, Long experienceCount);
|
||||
|
||||
/**
|
||||
* Iterates through the given list of {@link AServer} and increases the experience of the users contained in the
|
||||
@@ -59,7 +64,7 @@ public interface AUserExperienceService {
|
||||
* of each user by 1.
|
||||
* @param serverExp The list of {@link AServer} containing the users which get experience
|
||||
*/
|
||||
void handleExperienceGain(List<AServer> serverExp);
|
||||
CompletableFuture<Void> handleExperienceGain(List<AServer> serverExp);
|
||||
|
||||
/**
|
||||
* Calculates the currently appropriate {@link AExperienceRole} for the given user and updates the role on the
|
||||
@@ -68,7 +73,7 @@ public interface AUserExperienceService {
|
||||
* @param userExperience The {@link AUserExperience} object to recalculate the {@link AExperienceRole} for
|
||||
* @param roles The list of {@link AExperienceRole} used as a role configuration
|
||||
*/
|
||||
void updateUserRole(AUserExperience userExperience, List<AExperienceRole> roles);
|
||||
CompletableFuture<RoleCalculationResult> updateUserRole(AUserExperience userExperience, List<AExperienceRole> roles, Integer currentLevel);
|
||||
|
||||
|
||||
/**
|
||||
@@ -78,7 +83,7 @@ public interface AUserExperienceService {
|
||||
* to how much experience the user has. Runs completely in the background.
|
||||
* @param server The {@link AServer} to update the users for
|
||||
*/
|
||||
void syncUserRoles(AServer server);
|
||||
List<CompletableFuture<RoleCalculationResult>> syncUserRoles(AServer server);
|
||||
|
||||
/**
|
||||
* Synchronizes the state ({@link AExperienceRole}, {@link net.dv8tion.jda.api.entities.Role})
|
||||
@@ -90,14 +95,14 @@ public interface AUserExperienceService {
|
||||
* @param channel The {@link AChannel} in which the {@link dev.sheldan.abstracto.experience.models.templates.UserSyncStatusModel}
|
||||
* should be posted to
|
||||
*/
|
||||
void syncUserRolesWithFeedback(AServer server, AChannel channel);
|
||||
CompletableFuture<Void> syncUserRolesWithFeedback(AServer server, AChannel channel);
|
||||
|
||||
/**
|
||||
* Recalculates the role of a single user in a server and synchronize the {@link net.dv8tion.jda.api.entities.Role}
|
||||
* in the {@link net.dv8tion.jda.api.entities.Guild}
|
||||
* @param userExperience The {@link AUserExperience} to synchronize the role for
|
||||
*/
|
||||
void syncForSingleUser(AUserExperience userExperience);
|
||||
CompletableFuture<RoleCalculationResult> syncForSingleUser(AUserExperience userExperience);
|
||||
|
||||
/**
|
||||
* Loads the desired page of the ordered complete leaderboard from the {@link AServer} and returns the information as a {@link LeaderBoard}
|
||||
@@ -125,7 +130,7 @@ public interface AUserExperienceService {
|
||||
* @param channel The {@link AChannel} used to provide feedback to the user
|
||||
* @param toExecute The {@link Consumer} which should be executed on each element of the passed list
|
||||
*/
|
||||
void executeActionOnUserExperiencesWithFeedBack(List<AUserExperience> experiences, AChannel channel, Consumer<AUserExperience> toExecute);
|
||||
CompletableFutureList<RoleCalculationResult> executeActionOnUserExperiencesWithFeedBack(List<AUserExperience> experiences, AChannel channel, Function<AUserExperience, CompletableFuture<RoleCalculationResult>> toExecute);
|
||||
|
||||
/**
|
||||
* Disables the experience gain for a user directly. This sets the `experienceGainDisabled` on the respective {@link AUserExperience} object to true
|
||||
@@ -138,4 +143,6 @@ public interface AUserExperienceService {
|
||||
* @param userInAServer The {@link AUserInAServer} to enable experience for
|
||||
*/
|
||||
void enableExperienceForUser(AUserInAServer userInAServer);
|
||||
|
||||
void syncRolesInStorage(List<RoleCalculationResult> results);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import dev.sheldan.abstracto.experience.models.database.AExperienceRole;
|
||||
import dev.sheldan.abstracto.experience.models.database.AUserExperience;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
/**
|
||||
* Service providing several methods surrounding {@link dev.sheldan.abstracto.experience.models.database.AExperienceRole}.
|
||||
@@ -19,22 +20,22 @@ public interface ExperienceRoleService {
|
||||
* @param role The {@link ARole} to set the level to
|
||||
* @param level The level the {@link ARole} should be awarded at
|
||||
*/
|
||||
void setRoleToLevel(ARole role, Integer level, AChannel channel);
|
||||
CompletableFuture<Void> setRoleToLevel(ARole role, Integer level, AChannel channel);
|
||||
|
||||
/**
|
||||
* Removes the role from the {@link dev.sheldan.abstracto.experience.models.database.AExperienceRole} configuration
|
||||
* @param role The {@link ARole} to remove from the {@link dev.sheldan.abstracto.experience.models.database.AExperienceRole}
|
||||
* configuration
|
||||
*/
|
||||
void unsetRole(ARole role, AChannel feedbackChannel);
|
||||
CompletableFuture<Void> unsetRole(ARole role, AChannel feedbackChannel);
|
||||
|
||||
/**
|
||||
* Calculates the appropriate {@link AExperienceRole} based on the provided list of {@link AExperienceRole}
|
||||
* @param userExperience The {@link AUserExperience} containing the level to calculate the {@link AExperienceRole}
|
||||
* @param roles The role configuration to be used when calculating the appropriate {@link AExperienceRole}
|
||||
* @param currentLevel
|
||||
* @return The best matching {@link AExperienceRole} according to the experience in the provided {@link AUserExperience}
|
||||
*/
|
||||
AExperienceRole calculateRole(AUserExperience userExperience, List<AExperienceRole> roles);
|
||||
AExperienceRole calculateRole(List<AExperienceRole> roles, Integer currentLevel);
|
||||
|
||||
/**
|
||||
* Calculates the level at which the next role for a given level is available.
|
||||
|
||||
@@ -6,6 +6,7 @@ import dev.sheldan.abstracto.experience.models.database.AExperienceLevel;
|
||||
import dev.sheldan.abstracto.experience.models.database.AExperienceRole;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Service responsible to manage the {@link AExperienceRole} configuration of a server. This contains functionality to
|
||||
@@ -42,6 +43,8 @@ public interface ExperienceRoleManagementService {
|
||||
* @return the {@link AExperienceRole} which uses the given {@link ARole}
|
||||
*/
|
||||
AExperienceRole getRoleInServer(ARole role);
|
||||
Optional<AExperienceRole> getRoleInServerOptional(ARole role);
|
||||
AExperienceRole getRoleInServer(Long roleId);
|
||||
|
||||
/**
|
||||
* Retrieves all {@link AExperienceRole} configured in the given {@link AServer}
|
||||
@@ -49,4 +52,7 @@ public interface ExperienceRoleManagementService {
|
||||
* @return A list of {@link AExperienceRole} which are currently configured for the {@link AServer}
|
||||
*/
|
||||
List<AExperienceRole> getExperienceRolesForServer(AServer server);
|
||||
|
||||
AExperienceRole getExperienceRoleById(Long experienceRoleId);
|
||||
Optional<AExperienceRole> getExperienceRoleByIdOptional(Long experienceRoleId);
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
@@ -32,7 +33,7 @@ public class Ban extends AbstractConditionableCommand {
|
||||
private TemplateService templateService;
|
||||
|
||||
@Override
|
||||
public CommandResult execute(CommandContext commandContext) {
|
||||
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
|
||||
checkParameters(commandContext);
|
||||
List<Object> parameters = commandContext.getParameters().getParameters();
|
||||
Member member = (Member) parameters.get(0);
|
||||
@@ -43,8 +44,8 @@ public class Ban extends AbstractConditionableCommand {
|
||||
banLogModel.setBannedUser(member);
|
||||
banLogModel.setBanningUser(commandContext.getAuthor());
|
||||
banLogModel.setReason(reason);
|
||||
banService.banMember(member, reason, banLogModel);
|
||||
return CommandResult.fromSuccess();
|
||||
return banService.banMember(member, reason, banLogModel)
|
||||
.thenApply(aVoid -> CommandResult.fromSuccess());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -57,6 +58,7 @@ public class Ban extends AbstractConditionableCommand {
|
||||
.name("ban")
|
||||
.module(ModerationModule.MODERATION)
|
||||
.templated(true)
|
||||
.async(true)
|
||||
.supportsEmbedException(true)
|
||||
.causesReaction(true)
|
||||
.parameters(parameters)
|
||||
|
||||
@@ -16,6 +16,7 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@Component
|
||||
public class BanId extends AbstractConditionableCommand {
|
||||
@@ -27,7 +28,7 @@ public class BanId extends AbstractConditionableCommand {
|
||||
private BanService banService;
|
||||
|
||||
@Override
|
||||
public CommandResult execute(CommandContext commandContext) {
|
||||
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
|
||||
checkParameters(commandContext);
|
||||
List<Object> parameters = commandContext.getParameters().getParameters();
|
||||
Long userId = (Long) parameters.get(0);
|
||||
@@ -37,9 +38,8 @@ public class BanId extends AbstractConditionableCommand {
|
||||
banLogModel.setBannedUserId(userId);
|
||||
banLogModel.setBanningUser(commandContext.getAuthor());
|
||||
banLogModel.setReason(reason);
|
||||
banService.banMember(commandContext.getGuild().getIdLong(), userId, reason, banLogModel);
|
||||
|
||||
return CommandResult.fromSuccess();
|
||||
return banService.banMember(commandContext.getGuild().getIdLong(), userId, reason, banLogModel)
|
||||
.thenApply(aVoid -> CommandResult.fromSuccess());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -52,6 +52,7 @@ public class BanId extends AbstractConditionableCommand {
|
||||
.name("banId")
|
||||
.module(ModerationModule.MODERATION)
|
||||
.templated(true)
|
||||
.async(true)
|
||||
.supportsEmbedException(true)
|
||||
.causesReaction(true)
|
||||
.parameters(parameters)
|
||||
|
||||
@@ -15,6 +15,7 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@Component
|
||||
public class DecayAllWarnings extends AbstractConditionableCommand {
|
||||
@@ -23,12 +24,12 @@ public class DecayAllWarnings extends AbstractConditionableCommand {
|
||||
private WarnService warnService;
|
||||
|
||||
@Override
|
||||
public CommandResult execute(CommandContext commandContext) {
|
||||
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
|
||||
checkParameters(commandContext);
|
||||
List<Object> parameters = commandContext.getParameters().getParameters();
|
||||
boolean logWarnings = !parameters.isEmpty() ? (Boolean) parameters.get(0) : Boolean.FALSE;
|
||||
warnService.decayAllWarningsForServer(commandContext.getUserInitiatedContext().getServer(), logWarnings);
|
||||
return CommandResult.fromSuccess();
|
||||
return warnService.decayAllWarningsForServer(commandContext.getUserInitiatedContext().getServer(), logWarnings)
|
||||
.thenApply(aVoid -> CommandResult.fromSuccess());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -41,6 +42,7 @@ public class DecayAllWarnings extends AbstractConditionableCommand {
|
||||
.name("decayAllWarnings")
|
||||
.module(ModerationModule.MODERATION)
|
||||
.templated(true)
|
||||
.async(true)
|
||||
.supportsEmbedException(true)
|
||||
.causesReaction(true)
|
||||
.parameters(parameters)
|
||||
|
||||
@@ -15,6 +15,7 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@Component
|
||||
public class DecayWarnings extends AbstractConditionableCommand {
|
||||
@@ -23,9 +24,9 @@ public class DecayWarnings extends AbstractConditionableCommand {
|
||||
private WarnService warnService;
|
||||
|
||||
@Override
|
||||
public CommandResult execute(CommandContext commandContext) {
|
||||
warnService.decayWarningsForServer(commandContext.getUserInitiatedContext().getServer());
|
||||
return CommandResult.fromSuccess();
|
||||
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
|
||||
return warnService.decayWarningsForServer(commandContext.getUserInitiatedContext().getServer())
|
||||
.thenApply(aVoid -> CommandResult.fromSuccess());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -36,6 +37,7 @@ public class DecayWarnings extends AbstractConditionableCommand {
|
||||
.name("decayWarnings")
|
||||
.module(ModerationModule.MODERATION)
|
||||
.templated(true)
|
||||
.async(true)
|
||||
.supportsEmbedException(true)
|
||||
.causesReaction(true)
|
||||
.parameters(parameters)
|
||||
|
||||
@@ -29,12 +29,8 @@ public class DeleteWarning extends AbstractConditionableCommand {
|
||||
public CommandResult execute(CommandContext commandContext) {
|
||||
checkParameters(commandContext);
|
||||
Long warnId = (Long) commandContext.getParameters().getParameters().get(0);
|
||||
Optional<Warning> optional = warnManagementService.findById(warnId);
|
||||
optional.ifPresent(warning -> {
|
||||
if(warning.getWarnedUser().getServerReference().getId().equals(commandContext.getUserInitiatedContext().getServer().getId())) {
|
||||
warnManagementService.deleteWarning(warning);
|
||||
}
|
||||
});
|
||||
Optional<Warning> optional = warnManagementService.findById(warnId, commandContext.getGuild().getIdLong());
|
||||
optional.ifPresent(warning -> warnManagementService.deleteWarning(warning));
|
||||
return CommandResult.fromSuccess();
|
||||
}
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@Component
|
||||
public class Kick extends AbstractConditionableCommand {
|
||||
@@ -30,19 +31,18 @@ public class Kick extends AbstractConditionableCommand {
|
||||
private KickServiceBean kickService;
|
||||
|
||||
@Override
|
||||
public CommandResult execute(CommandContext commandContext) {
|
||||
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
|
||||
checkParameters(commandContext);
|
||||
List<Object> parameters = commandContext.getParameters().getParameters();
|
||||
Member member = (Member) parameters.get(0);
|
||||
String defaultReason = templateService.renderSimpleTemplate(KICK_DEFAULT_REASON_TEMPLATE);
|
||||
String reason = parameters.size() == 2 ? (String) parameters.get(1) : defaultReason;
|
||||
|
||||
KickLogModel kickLogModel = (KickLogModel) ContextConverter.fromCommandContext(commandContext, KickLogModel.class);
|
||||
KickLogModel kickLogModel = (KickLogModel) ContextConverter.slimFromCommandContext(commandContext, KickLogModel.class);
|
||||
kickLogModel.setKickedUser(member);
|
||||
kickLogModel.setKickingUser(commandContext.getAuthor());
|
||||
kickLogModel.setReason(reason);
|
||||
kickService.kickMember(member, reason, kickLogModel);
|
||||
return CommandResult.fromSuccess();
|
||||
return kickService.kickMember(member, reason, kickLogModel)
|
||||
.thenApply(aVoid -> CommandResult.fromSuccess());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -33,16 +33,15 @@ public class Purge extends AbstractConditionableCommand {
|
||||
private ExceptionUtils exceptionUtils;
|
||||
|
||||
@Override
|
||||
public CommandResult execute(CommandContext commandContext) {
|
||||
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
|
||||
checkParameters(commandContext);
|
||||
Integer amountOfMessages = (Integer) commandContext.getParameters().getParameters().get(0);
|
||||
Member memberToPurgeMessagesOf = null;
|
||||
if(commandContext.getParameters().getParameters().size() == 2) {
|
||||
memberToPurgeMessagesOf = (Member) commandContext.getParameters().getParameters().get(1);
|
||||
}
|
||||
CompletableFuture<Void> future = purgeService.purgeMessagesInChannel(amountOfMessages, commandContext.getChannel(), commandContext.getMessage(), memberToPurgeMessagesOf);
|
||||
future.whenComplete((aVoid, throwable) -> exceptionUtils.handleExceptionIfTemplatable(throwable, commandContext.getChannel()));
|
||||
return CommandResult.fromSelfDestruct();
|
||||
return purgeService.purgeMessagesInChannel(amountOfMessages, commandContext.getChannel(), commandContext.getMessage(), memberToPurgeMessagesOf)
|
||||
.thenApply(aVoid -> CommandResult.fromSelfDestruct());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -55,6 +54,7 @@ public class Purge extends AbstractConditionableCommand {
|
||||
.name("purge")
|
||||
.module(ModerationModule.MODERATION)
|
||||
.templated(true)
|
||||
.async(true)
|
||||
.supportsEmbedException(true)
|
||||
.causesReaction(true)
|
||||
.parameters(parameters)
|
||||
|
||||
@@ -18,6 +18,7 @@ import org.springframework.stereotype.Component;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@Component
|
||||
public class SlowMode extends AbstractConditionableCommand {
|
||||
@@ -26,7 +27,7 @@ public class SlowMode extends AbstractConditionableCommand {
|
||||
private SlowModeService slowModeService;
|
||||
|
||||
@Override
|
||||
public CommandResult execute(CommandContext commandContext) {
|
||||
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
|
||||
checkParameters(commandContext);
|
||||
TextChannel channel;
|
||||
String durationString = (String) commandContext.getParameters().getParameters().get(0);
|
||||
@@ -41,8 +42,8 @@ public class SlowMode extends AbstractConditionableCommand {
|
||||
} else {
|
||||
channel = commandContext.getChannel();
|
||||
}
|
||||
slowModeService.setSlowMode(channel, duration);
|
||||
return CommandResult.fromSuccess();
|
||||
return slowModeService.setSlowMode(channel, duration)
|
||||
.thenApply(aVoid -> CommandResult.fromSuccess());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -55,6 +56,7 @@ public class SlowMode extends AbstractConditionableCommand {
|
||||
.name("slowmode")
|
||||
.module(ModerationModule.MODERATION)
|
||||
.templated(true)
|
||||
.async(true)
|
||||
.supportsEmbedException(true)
|
||||
.causesReaction(true)
|
||||
.parameters(parameters)
|
||||
|
||||
@@ -12,6 +12,7 @@ import dev.sheldan.abstracto.core.models.FullUserInServer;
|
||||
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
|
||||
import dev.sheldan.abstracto.core.service.ChannelService;
|
||||
import dev.sheldan.abstracto.core.service.management.UserInServerManagementService;
|
||||
import dev.sheldan.abstracto.core.utils.FutureUtils;
|
||||
import dev.sheldan.abstracto.moderation.config.ModerationModule;
|
||||
import dev.sheldan.abstracto.moderation.config.features.ModerationFeatures;
|
||||
import dev.sheldan.abstracto.moderation.converter.UserNotesConverter;
|
||||
@@ -25,6 +26,7 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@Component
|
||||
public class UserNotes extends AbstractConditionableCommand {
|
||||
@@ -45,7 +47,7 @@ public class UserNotes extends AbstractConditionableCommand {
|
||||
private UserNotesConverter userNotesConverter;
|
||||
|
||||
@Override
|
||||
public CommandResult execute(CommandContext commandContext) {
|
||||
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
|
||||
checkParameters(commandContext);
|
||||
List<Object> parameters = commandContext.getParameters().getParameters();
|
||||
List<UserNote> userNotes;
|
||||
@@ -65,8 +67,8 @@ public class UserNotes extends AbstractConditionableCommand {
|
||||
userNotes = userNoteManagementService.loadNotesForServer(commandContext.getUserInitiatedContext().getServer());
|
||||
}
|
||||
model.setUserNotes(userNotesConverter.fromNotes(userNotes));
|
||||
channelService.sendEmbedTemplateInChannel(USER_NOTES_RESPONSE_TEMPLATE, model, commandContext.getChannel());
|
||||
return CommandResult.fromSuccess();
|
||||
return FutureUtils.toSingleFutureGeneric(channelService.sendEmbedTemplateInChannel(USER_NOTES_RESPONSE_TEMPLATE, model, commandContext.getChannel()))
|
||||
.thenApply(aVoid -> CommandResult.fromSuccess());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -79,6 +81,7 @@ public class UserNotes extends AbstractConditionableCommand {
|
||||
.name("userNotes")
|
||||
.module(ModerationModule.MODERATION)
|
||||
.templated(true)
|
||||
.async(true)
|
||||
.supportsEmbedException(true)
|
||||
.causesReaction(true)
|
||||
.parameters(parameters)
|
||||
|
||||
@@ -9,7 +9,7 @@ import dev.sheldan.abstracto.core.command.execution.*;
|
||||
import dev.sheldan.abstracto.core.config.FeatureEnum;
|
||||
import dev.sheldan.abstracto.moderation.config.ModerationModule;
|
||||
import dev.sheldan.abstracto.moderation.config.features.ModerationFeatures;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.WarnLog;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.WarnContext;
|
||||
import dev.sheldan.abstracto.moderation.service.WarnService;
|
||||
import dev.sheldan.abstracto.templating.service.TemplateService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -19,6 +19,7 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
@@ -32,19 +33,17 @@ public class Warn extends AbstractConditionableCommand {
|
||||
private TemplateService templateService;
|
||||
|
||||
@Override
|
||||
public CommandResult execute(CommandContext commandContext) {
|
||||
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
|
||||
checkParameters(commandContext);
|
||||
List<Object> parameters = commandContext.getParameters().getParameters();
|
||||
Member member = (Member) parameters.get(0);
|
||||
String defaultReason = templateService.renderSimpleTemplate(WARN_DEFAULT_REASON_TEMPLATE);
|
||||
String reason = parameters.size() == 2 ? (String) parameters.get(1) : defaultReason;
|
||||
WarnLog warnLogModel = (WarnLog) ContextConverter.fromCommandContext(commandContext, WarnLog.class);
|
||||
warnLogModel.setWarnedUser(member);
|
||||
warnLogModel.setMessage(commandContext.getMessage());
|
||||
WarnContext warnLogModel = (WarnContext) ContextConverter.slimFromCommandContext(commandContext, WarnContext.class);
|
||||
warnLogModel.setReason(reason);
|
||||
warnLogModel.setWarningUser(commandContext.getAuthor());
|
||||
warnService.warnUserWithLog(member, commandContext.getAuthor(), reason, warnLogModel, commandContext.getChannel());
|
||||
return CommandResult.fromSuccess();
|
||||
warnLogModel.setWarnedMember(member);
|
||||
return warnService.warnUserWithLog(warnLogModel)
|
||||
.thenApply(warning -> CommandResult.fromSuccess());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -57,6 +56,7 @@ public class Warn extends AbstractConditionableCommand {
|
||||
.name("warn")
|
||||
.module(ModerationModule.MODERATION)
|
||||
.templated(true)
|
||||
.async(true)
|
||||
.supportsEmbedException(true)
|
||||
.causesReaction(true)
|
||||
.parameters(parameters)
|
||||
|
||||
@@ -7,11 +7,11 @@ import dev.sheldan.abstracto.core.command.config.HelpInfo;
|
||||
import dev.sheldan.abstracto.core.command.config.Parameter;
|
||||
import dev.sheldan.abstracto.core.command.execution.CommandContext;
|
||||
import dev.sheldan.abstracto.core.command.execution.CommandResult;
|
||||
import dev.sheldan.abstracto.core.command.execution.ContextConverter;
|
||||
import dev.sheldan.abstracto.core.config.FeatureEnum;
|
||||
import dev.sheldan.abstracto.core.models.ServerChannelMessage;
|
||||
import dev.sheldan.abstracto.moderation.config.ModerationModule;
|
||||
import dev.sheldan.abstracto.moderation.config.features.ModerationFeatures;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.MuteLog;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.MuteContext;
|
||||
import dev.sheldan.abstracto.moderation.service.MuteService;
|
||||
import net.dv8tion.jda.api.entities.Member;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -21,6 +21,7 @@ import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@Component
|
||||
public class Mute extends AbstractConditionableCommand {
|
||||
@@ -29,18 +30,31 @@ public class Mute extends AbstractConditionableCommand {
|
||||
private MuteService muteService;
|
||||
|
||||
@Override
|
||||
public CommandResult execute(CommandContext commandContext) {
|
||||
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
|
||||
checkParameters(commandContext);
|
||||
List<Object> parameters = commandContext.getParameters().getParameters();
|
||||
Member member = (Member) parameters.get(0);
|
||||
Duration duration = (Duration) parameters.get(1);
|
||||
String reason = (String) parameters.get(2);
|
||||
MuteLog muteLogModel = (MuteLog) ContextConverter.fromCommandContext(commandContext, MuteLog.class);
|
||||
muteLogModel.setMessage(commandContext.getMessage());
|
||||
muteLogModel.setMutedUser(member);
|
||||
muteLogModel.setMutingUser(commandContext.getAuthor());
|
||||
muteService.muteMemberWithLog(member, commandContext.getAuthor(), reason, Instant.now().plus(duration), muteLogModel, commandContext.getMessage());
|
||||
return CommandResult.fromSuccess();
|
||||
ServerChannelMessage context = ServerChannelMessage
|
||||
.builder()
|
||||
.serverId(commandContext.getGuild().getIdLong())
|
||||
.channelId(commandContext.getChannel().getIdLong())
|
||||
.messageId(commandContext.getMessage().getIdLong())
|
||||
.build();
|
||||
MuteContext muteLogModel = MuteContext
|
||||
.builder()
|
||||
.muteDate(Instant.now())
|
||||
.muteTargetDate(Instant.now().plus(duration))
|
||||
.mutedUser(member)
|
||||
.reason(reason)
|
||||
.contextChannel(commandContext.getChannel())
|
||||
.message(commandContext.getMessage())
|
||||
.mutingUser(commandContext.getAuthor())
|
||||
.context(context)
|
||||
.build();
|
||||
return muteService.muteMemberWithLog(muteLogModel)
|
||||
.thenApply(aVoid -> CommandResult.fromSuccess());
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -54,6 +68,7 @@ public class Mute extends AbstractConditionableCommand {
|
||||
.name("mute")
|
||||
.module(ModerationModule.MODERATION)
|
||||
.templated(true)
|
||||
.async(true)
|
||||
.causesReaction(true)
|
||||
.supportsEmbedException(true)
|
||||
.parameters(parameters)
|
||||
|
||||
@@ -7,9 +7,10 @@ import dev.sheldan.abstracto.core.command.config.Parameter;
|
||||
import dev.sheldan.abstracto.core.command.execution.CommandContext;
|
||||
import dev.sheldan.abstracto.core.command.execution.CommandResult;
|
||||
import dev.sheldan.abstracto.core.config.FeatureEnum;
|
||||
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
|
||||
import dev.sheldan.abstracto.core.service.management.UserInServerManagementService;
|
||||
import dev.sheldan.abstracto.moderation.config.ModerationModule;
|
||||
import dev.sheldan.abstracto.moderation.config.features.ModerationFeatures;
|
||||
import dev.sheldan.abstracto.moderation.models.database.Mute;
|
||||
import dev.sheldan.abstracto.moderation.service.MuteService;
|
||||
import dev.sheldan.abstracto.moderation.service.management.MuteManagementService;
|
||||
import dev.sheldan.abstracto.templating.service.TemplateService;
|
||||
@@ -19,6 +20,7 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@Component
|
||||
public class UnMute extends AbstractConditionableCommand {
|
||||
@@ -33,19 +35,18 @@ public class UnMute extends AbstractConditionableCommand {
|
||||
@Autowired
|
||||
private TemplateService templateService;
|
||||
|
||||
@Autowired
|
||||
private UserInServerManagementService userInServerManagementService;
|
||||
|
||||
@Override
|
||||
public CommandResult execute(CommandContext commandContext) {
|
||||
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
|
||||
checkParameters(commandContext);
|
||||
List<Object> parameters = commandContext.getParameters().getParameters();
|
||||
Member member = (Member) parameters.get(0);
|
||||
if(!muteManagementService.hasActiveMute(member)) {
|
||||
return CommandResult.fromError(templateService.renderSimpleTemplate(NO_ACTIVE_MUTE));
|
||||
}
|
||||
Mute mute = muteManagementService.getAMuteOf(member);
|
||||
muteService.unMuteUser(mute);
|
||||
muteService.cancelUnMuteJob(mute);
|
||||
muteService.completelyUnMuteMember(member);
|
||||
return CommandResult.fromSuccess();
|
||||
AUserInAServer userToUnMute = userInServerManagementService.loadUser(member);
|
||||
return muteService.unMuteUser(userToUnMute).thenApply(aVoid ->
|
||||
CommandResult.fromSuccess()
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -57,6 +58,7 @@ public class UnMute extends AbstractConditionableCommand {
|
||||
.name("unMute")
|
||||
.module(ModerationModule.MODERATION)
|
||||
.templated(true)
|
||||
.async(true)
|
||||
.supportsEmbedException(true)
|
||||
.causesReaction(true)
|
||||
.parameters(parameters)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package dev.sheldan.abstracto.moderation.job;
|
||||
|
||||
import dev.sheldan.abstracto.moderation.service.MuteService;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.quartz.DisallowConcurrentExecution;
|
||||
import org.quartz.JobExecutionContext;
|
||||
@@ -14,9 +16,12 @@ import org.springframework.stereotype.Component;
|
||||
@DisallowConcurrentExecution
|
||||
@Component
|
||||
@PersistJobDataAfterExecution
|
||||
@Getter
|
||||
@Setter
|
||||
public class UnMuteJob extends QuartzJobBean {
|
||||
|
||||
private Long muteId;
|
||||
private Long serverId;
|
||||
|
||||
@Autowired
|
||||
private MuteService muteService;
|
||||
@@ -24,14 +29,7 @@ public class UnMuteJob extends QuartzJobBean {
|
||||
@Override
|
||||
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
|
||||
log.info("Executing unMute job for mute {}", muteId);
|
||||
muteService.endMute(muteId);
|
||||
muteService.endMute(muteId, serverId);
|
||||
}
|
||||
|
||||
public Long getMuteId() {
|
||||
return muteId;
|
||||
}
|
||||
|
||||
public void setMuteId(Long muteId) {
|
||||
this.muteId = muteId;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,12 +2,14 @@ package dev.sheldan.abstracto.moderation.repository;
|
||||
|
||||
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
|
||||
import dev.sheldan.abstracto.moderation.models.database.Mute;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.QueryHints;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import javax.persistence.QueryHint;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface MuteRepository extends JpaRepository<Mute, Long> {
|
||||
@@ -18,5 +20,9 @@ public interface MuteRepository extends JpaRepository<Mute, Long> {
|
||||
Mute findTopByMutedUserAndMuteEndedFalse(AUserInAServer userInAServer);
|
||||
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
List<Mute> findAllByMutedUserAndMuteEndedFalseOrderByIdDesc(AUserInAServer aUserInAServer);
|
||||
List<Mute> findAllByMutedUserAndMuteEndedFalseOrderByMuteId_IdDesc(AUserInAServer aUserInAServer);
|
||||
|
||||
@NotNull
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
Optional<Mute> findByMuteId_IdAndMuteId_ServerId(Long muteId, Long serverId);
|
||||
}
|
||||
|
||||
@@ -18,5 +18,6 @@ public interface MuteRoleRepository extends JpaRepository<MuteRole, Long> {
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
List<MuteRole> findAllByRoleServer(AServer server);
|
||||
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
boolean existsByRoleServer(AServer server);
|
||||
}
|
||||
|
||||
@@ -4,13 +4,23 @@ import dev.sheldan.abstracto.core.models.database.AServer;
|
||||
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
|
||||
import dev.sheldan.abstracto.moderation.models.database.UserNote;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.QueryHints;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import javax.persistence.QueryHint;
|
||||
import java.util.List;
|
||||
|
||||
@Repository
|
||||
public interface UserNoteRepository extends JpaRepository<UserNote, Long> {
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
List<UserNote> findByUser(AUserInAServer aUserInAServer);
|
||||
|
||||
@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);
|
||||
|
||||
}
|
||||
|
||||
@@ -3,13 +3,16 @@ package dev.sheldan.abstracto.moderation.repository;
|
||||
import dev.sheldan.abstracto.core.models.database.AServer;
|
||||
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
|
||||
import dev.sheldan.abstracto.moderation.models.database.Warning;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.QueryHints;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import javax.persistence.QueryHint;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface WarnRepository extends JpaRepository<Warning, Long> {
|
||||
@@ -25,7 +28,15 @@ public interface WarnRepository extends JpaRepository<Warning, Long> {
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
Long countByWarnedUserAndDecayedFalse(AUserInAServer aUserInAServer);
|
||||
|
||||
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
List<Warning> findByWarnedUser(AUserInAServer aUserInAServer);
|
||||
|
||||
@NotNull
|
||||
@Override
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
Optional<Warning> findById(@NonNull Long aLong);
|
||||
|
||||
@NotNull
|
||||
@QueryHints(@QueryHint(name = org.hibernate.annotations.QueryHints.CACHEABLE, value = "true"))
|
||||
Optional<Warning> findByWarnId_IdAndWarnId_ServerId(Long warnId, Long serverId);
|
||||
}
|
||||
|
||||
@@ -4,16 +4,20 @@ import dev.sheldan.abstracto.core.exception.GuildNotFoundException;
|
||||
import dev.sheldan.abstracto.core.models.context.ServerContext;
|
||||
import dev.sheldan.abstracto.core.service.BotService;
|
||||
import dev.sheldan.abstracto.core.service.PostTargetService;
|
||||
import dev.sheldan.abstracto.core.utils.FutureUtils;
|
||||
import dev.sheldan.abstracto.moderation.config.posttargets.ModerationPostTarget;
|
||||
import dev.sheldan.abstracto.templating.model.MessageToSend;
|
||||
import dev.sheldan.abstracto.templating.service.TemplateService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.dv8tion.jda.api.entities.Guild;
|
||||
import net.dv8tion.jda.api.entities.Member;
|
||||
import net.dv8tion.jda.api.entities.Message;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
@@ -32,31 +36,33 @@ public class BanServiceBean implements BanService {
|
||||
private PostTargetService postTargetService;
|
||||
|
||||
@Override
|
||||
public void banMember(Member member, String reason, ServerContext banLog) {
|
||||
this.banUser(member.getGuild(), member.getIdLong(), reason);
|
||||
public CompletableFuture<Void> banMember(Member member, String reason, ServerContext banLog) {
|
||||
CompletableFuture<Void> banFuture = banUser(member.getGuild(), member.getIdLong(), reason);
|
||||
MessageToSend banLogMessage = templateService.renderEmbedTemplate(BAN_LOG_TEMPLATE, banLog);
|
||||
postTargetService.sendEmbedInPostTarget(banLogMessage, ModerationPostTarget.BAN_LOG, member.getGuild().getIdLong());
|
||||
List<CompletableFuture<Message>> notificationFutures = postTargetService.sendEmbedInPostTarget(banLogMessage, ModerationPostTarget.BAN_LOG, member.getGuild().getIdLong());
|
||||
return CompletableFuture.allOf(banFuture, FutureUtils.toSingleFutureGeneric(notificationFutures));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void banMember(Long guildId, Long userId, String reason, ServerContext banIdLog) {
|
||||
banUser(guildId, userId, reason);
|
||||
public CompletableFuture<Void> banMember(Long guildId, Long userId, String reason, ServerContext banIdLog) {
|
||||
CompletableFuture<Void> banFuture = banUser(guildId, userId, reason);
|
||||
MessageToSend banLogMessage = templateService.renderEmbedTemplate(BAN_ID_LOG_TEMPLATE, banIdLog);
|
||||
postTargetService.sendEmbedInPostTarget(banLogMessage, ModerationPostTarget.BAN_LOG, guildId);
|
||||
List<CompletableFuture<Message>> notificationFutures = postTargetService.sendEmbedInPostTarget(banLogMessage, ModerationPostTarget.BAN_LOG, guildId);
|
||||
return CompletableFuture.allOf(banFuture, FutureUtils.toSingleFutureGeneric(notificationFutures));
|
||||
}
|
||||
|
||||
private void banUser(Long guildId, Long userId, String reason) {
|
||||
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);
|
||||
banUser(guildByIdOptional.get(), userId, reason);
|
||||
return banUser(guildByIdOptional.get(), userId, reason);
|
||||
} else {
|
||||
log.warn("Guild {} not found. Not able to ban user {}", guildId, userId);
|
||||
throw new GuildNotFoundException(guildId);
|
||||
}
|
||||
}
|
||||
|
||||
private void banUser(Guild guild, Long userId, String reason) {
|
||||
guild.ban(userId.toString(), 0, reason).queue();
|
||||
private CompletableFuture<Void> banUser(Guild guild, Long userId, String reason) {
|
||||
return guild.ban(userId.toString(), 0, reason).submit();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package dev.sheldan.abstracto.moderation.service;
|
||||
|
||||
import dev.sheldan.abstracto.core.service.PostTargetService;
|
||||
import dev.sheldan.abstracto.core.utils.FutureUtils;
|
||||
import dev.sheldan.abstracto.moderation.config.posttargets.ModerationPostTarget;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.KickLogModel;
|
||||
import dev.sheldan.abstracto.templating.model.MessageToSend;
|
||||
@@ -11,6 +12,8 @@ import net.dv8tion.jda.api.entities.Member;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
public class KickServiceBean implements KickService {
|
||||
@@ -24,15 +27,16 @@ public class KickServiceBean implements KickService {
|
||||
private PostTargetService postTargetService;
|
||||
|
||||
@Override
|
||||
public void kickMember(Member member, String reason, KickLogModel kickLogModel) {
|
||||
public CompletableFuture<Void> kickMember(Member member, String reason, KickLogModel kickLogModel) {
|
||||
Guild guild = member.getGuild();
|
||||
log.info("Kicking user {} from guild {}", member.getUser().getIdLong(), guild.getIdLong());
|
||||
guild.kick(member, reason).queue();
|
||||
this.sendKickLog(kickLogModel);
|
||||
CompletableFuture<Void> kickFuture = guild.kick(member, reason).submit();
|
||||
CompletableFuture<Void> logFuture = this.sendKickLog(kickLogModel);
|
||||
return CompletableFuture.allOf(kickFuture, logFuture);
|
||||
}
|
||||
|
||||
private void sendKickLog(KickLogModel kickLogModel) {
|
||||
private CompletableFuture<Void> sendKickLog(KickLogModel kickLogModel) {
|
||||
MessageToSend warnLogMessage = templateService.renderEmbedTemplate(KICK_LOG_TEMPLATE, kickLogModel);
|
||||
postTargetService.sendEmbedInPostTarget(warnLogMessage, ModerationPostTarget.KICK_LOG, kickLogModel.getServer().getId());
|
||||
return FutureUtils.toSingleFutureGeneric(postTargetService.sendEmbedInPostTarget(warnLogMessage, ModerationPostTarget.KICK_LOG, kickLogModel.getGuild().getIdLong()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,17 +2,21 @@ package dev.sheldan.abstracto.moderation.service;
|
||||
|
||||
import dev.sheldan.abstracto.core.models.AServerAChannelMessage;
|
||||
import dev.sheldan.abstracto.core.models.FullUserInServer;
|
||||
import dev.sheldan.abstracto.core.models.ServerChannelMessage;
|
||||
import dev.sheldan.abstracto.core.models.database.AChannel;
|
||||
import dev.sheldan.abstracto.core.models.database.AServer;
|
||||
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
|
||||
import dev.sheldan.abstracto.core.service.*;
|
||||
import dev.sheldan.abstracto.core.service.management.ChannelManagementService;
|
||||
import dev.sheldan.abstracto.core.service.management.ServerManagementService;
|
||||
import dev.sheldan.abstracto.core.service.management.UserInServerManagementService;
|
||||
import dev.sheldan.abstracto.core.utils.FutureUtils;
|
||||
import dev.sheldan.abstracto.moderation.config.posttargets.MutingPostTarget;
|
||||
import dev.sheldan.abstracto.moderation.exception.MuteRoleNotSetupException;
|
||||
import dev.sheldan.abstracto.moderation.exception.NoMuteFoundException;
|
||||
import dev.sheldan.abstracto.moderation.models.database.Mute;
|
||||
import dev.sheldan.abstracto.moderation.models.database.MuteRole;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.MuteLog;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.MuteContext;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.MuteNotification;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.UnMuteLog;
|
||||
import dev.sheldan.abstracto.moderation.service.management.MuteManagementService;
|
||||
@@ -30,9 +34,11 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@@ -68,7 +74,7 @@ public class MuteServiceBean implements MuteService {
|
||||
private PostTargetService postTargetService;
|
||||
|
||||
@Autowired
|
||||
private MuteService self;
|
||||
private MuteServiceBean self;
|
||||
|
||||
@Autowired
|
||||
@Qualifier("unmuteScheduler")
|
||||
@@ -77,12 +83,19 @@ public class MuteServiceBean implements MuteService {
|
||||
@Autowired
|
||||
private ChannelManagementService channelManagementService;
|
||||
|
||||
@Autowired
|
||||
private CounterService counterService;
|
||||
|
||||
@Autowired
|
||||
private ServerManagementService serverManagementService;
|
||||
|
||||
public static final String MUTE_LOG_TEMPLATE = "mute_log";
|
||||
public static final String UN_MUTE_LOG_TEMPLATE = "unmute_log";
|
||||
public static final String MUTE_NOTIFICATION_TEMPLATE = "mute_notification";
|
||||
public static final String MUTE_COUNTER_KEY = "MUTES";
|
||||
|
||||
@Override
|
||||
public Mute muteMember(Member memberToMute, Member mutingMember, String reason, Instant unMuteDate, Message message) {
|
||||
public CompletableFuture<Void> muteMember(Member memberToMute, Member mutingMember, String reason, Instant unMuteDate, ServerChannelMessage message) {
|
||||
FullUserInServer mutedUser = FullUserInServer
|
||||
.builder()
|
||||
.aUserInAServer(userInServerManagementService.loadUser(memberToMute))
|
||||
@@ -94,11 +107,11 @@ public class MuteServiceBean implements MuteService {
|
||||
.aUserInAServer(userInServerManagementService.loadUser(mutingMember))
|
||||
.member(mutingMember)
|
||||
.build();
|
||||
return muteUser(mutedUser, mutingUser, reason, unMuteDate, message);
|
||||
return muteUserInServer(mutedUser, mutingUser, reason, unMuteDate, message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mute muteAUserInAServer(AUserInAServer userBeingMuted, AUserInAServer userMuting, String reason, Instant unMuteDate, Message message) {
|
||||
public CompletableFuture<Void> muteAUserInAServer(AUserInAServer userBeingMuted, AUserInAServer userMuting, String reason, Instant unMuteDate, ServerChannelMessage message) {
|
||||
FullUserInServer mutedUser = FullUserInServer
|
||||
.builder()
|
||||
.aUserInAServer(userBeingMuted)
|
||||
@@ -110,11 +123,11 @@ public class MuteServiceBean implements MuteService {
|
||||
.aUserInAServer(userMuting)
|
||||
.member(botService.getMemberInServer(userMuting))
|
||||
.build();
|
||||
return muteUser(mutedUser, mutingUser, reason, unMuteDate, message);
|
||||
return muteUserInServer(mutedUser, mutingUser, reason, unMuteDate, message);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mute muteUser(FullUserInServer userBeingMuted, FullUserInServer userMuting, String reason, Instant unMuteDate, Message message) {
|
||||
public CompletableFuture<Void> muteUserInServer(FullUserInServer userBeingMuted, FullUserInServer userMuting, String reason, Instant unMuteDate, ServerChannelMessage message) {
|
||||
AServer serverBeingMutedIn = userBeingMuted.getAUserInAServer().getServerReference();
|
||||
if(!muteRoleManagementService.muteRoleForServerExists(serverBeingMutedIn)) {
|
||||
log.error("Mute role for server {} has not been setup.", serverBeingMutedIn.getId());
|
||||
@@ -123,64 +136,73 @@ public class MuteServiceBean implements MuteService {
|
||||
Member memberBeingMuted = userBeingMuted.getMember();
|
||||
log.info("User {} mutes user {} until {}",
|
||||
memberBeingMuted.getIdLong(), userMuting.getMember().getIdLong(), unMuteDate);
|
||||
if(message != null) {
|
||||
log.trace("because of message {} in channel {} in server {}", message.getId(), message.getChannel().getId(), message.getGuild().getId());
|
||||
if(message.getMessageId() != null) {
|
||||
log.trace("because of message {} in channel {} in server {}", message.getMessageId(), message.getChannelId(), message.getServerId());
|
||||
} else {
|
||||
log.trace("This mute was not triggered by a message.");
|
||||
}
|
||||
|
||||
List<CompletableFuture<Void>> futures = new ArrayList<>();
|
||||
AUserInAServer userInServerBeingMuted = userBeingMuted.getAUserInAServer();
|
||||
applyMuteRole(userInServerBeingMuted);
|
||||
Mute mute = createMuteObject(userMuting, reason, unMuteDate, message, userInServerBeingMuted);
|
||||
futures.add(applyMuteRole(userInServerBeingMuted));
|
||||
Guild guild = memberBeingMuted.getGuild();
|
||||
if(memberBeingMuted.getVoiceState() != null && memberBeingMuted.getVoiceState().getChannel() != null) {
|
||||
guild.kickVoiceMember(memberBeingMuted).queue();
|
||||
futures.add(guild.kickVoiceMember(memberBeingMuted).submit());
|
||||
}
|
||||
sendMuteNotification(message, memberBeingMuted, mute, guild);
|
||||
|
||||
String triggerKey = startUnMuteJobFor(unMuteDate, mute);
|
||||
mute.setTriggerKey(triggerKey);
|
||||
muteManagementService.saveMute(mute);
|
||||
return mute;
|
||||
MuteNotification muteNotification = MuteNotification
|
||||
.builder()
|
||||
.muteTargetDate(unMuteDate)
|
||||
.reason(reason)
|
||||
.serverName(guild.getName())
|
||||
.build();
|
||||
futures.add(sendMuteNotification(message, memberBeingMuted, muteNotification));
|
||||
return FutureUtils.toSingleFutureGeneric(futures);
|
||||
}
|
||||
|
||||
private void sendMuteNotification(Message message, Member memberBeingMuted, Mute mute, Guild guild) {
|
||||
private CompletableFuture<Void> sendMuteNotification(ServerChannelMessage message, Member memberBeingMuted, MuteNotification muteNotification) {
|
||||
log.trace("Notifying the user about the mute.");
|
||||
MuteNotification muteNotification = MuteNotification.builder().mute(mute).serverName(guild.getName()).build();
|
||||
CompletableFuture<Void> notificationFuture = new CompletableFuture<>();
|
||||
String muteNotificationMessage = templateService.renderTemplate(MUTE_NOTIFICATION_TEMPLATE, muteNotification);
|
||||
MessageChannel textChannel = message != null ? message.getChannel() : null;
|
||||
messageService.sendMessageToUser(memberBeingMuted.getUser(), muteNotificationMessage, textChannel);
|
||||
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)
|
||||
);
|
||||
return null;
|
||||
});
|
||||
messageCompletableFuture.thenAccept(message1 ->
|
||||
notificationFuture.complete(null)
|
||||
);
|
||||
return notificationFuture;
|
||||
}
|
||||
|
||||
private Mute createMuteObject(FullUserInServer userMuting, String reason, Instant unMuteDate, Message message, AUserInAServer userInServerBeingMuted) {
|
||||
AServerAChannelMessage origin = null;
|
||||
if(message != null) {
|
||||
long channelId = message.getChannel().getIdLong();
|
||||
AChannel channel = channelManagementService.loadChannel(channelId);
|
||||
origin = AServerAChannelMessage
|
||||
.builder()
|
||||
.channel(channel)
|
||||
.server(channel.getServer())
|
||||
.messageId(message.getIdLong())
|
||||
.build();
|
||||
}
|
||||
return muteManagementService.createMute(userInServerBeingMuted, userMuting.getAUserInAServer(), reason, unMuteDate, origin);
|
||||
private void createMuteObject(MuteContext muteContext, String triggerKey) {
|
||||
AChannel channel = channelManagementService.loadChannel(muteContext.getContext().getChannelId());
|
||||
AServerAChannelMessage origin = AServerAChannelMessage
|
||||
.builder()
|
||||
.channel(channel)
|
||||
.server(channel.getServer())
|
||||
.messageId(muteContext.getContext().getMessageId())
|
||||
.build();
|
||||
AUserInAServer userInServerBeingMuted = userInServerManagementService.loadUser(muteContext.getMutedUser());
|
||||
AUserInAServer userInServerMuting = userInServerManagementService.loadUser(muteContext.getMutedUser());
|
||||
muteManagementService.createMute(userInServerBeingMuted, userInServerMuting, muteContext.getReason(), muteContext.getMuteTargetDate(), origin, triggerKey, muteContext.getMuteId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void applyMuteRole(AUserInAServer aUserInAServer) {
|
||||
public CompletableFuture<Void> applyMuteRole(AUserInAServer aUserInAServer) {
|
||||
MuteRole muteRole = muteRoleManagementService.retrieveMuteRoleForServer(aUserInAServer.getServerReference());
|
||||
roleService.addRoleToUser(aUserInAServer, muteRole.getRole());
|
||||
return roleService.addRoleToUserFuture(aUserInAServer, muteRole.getRole());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String startUnMuteJobFor(Instant unMuteDate, Mute mute) {
|
||||
public String startUnMuteJobFor(Instant unMuteDate, Long muteId, Long serverId) {
|
||||
Duration muteDuration = Duration.between(Instant.now(), unMuteDate);
|
||||
if(muteDuration.getSeconds() < 60) {
|
||||
log.trace("Directly scheduling the unMute, because it was below the threshold.");
|
||||
unMuteScheduler.schedule(() -> {
|
||||
try {
|
||||
self.endMute(mute.getId());
|
||||
self.endMute(muteId, serverId);
|
||||
} catch (Exception exception) {
|
||||
log.error("Failed to remind immediately.", exception);
|
||||
}
|
||||
@@ -189,7 +211,8 @@ public class MuteServiceBean implements MuteService {
|
||||
} else {
|
||||
log.trace("Starting scheduled job to execute unMute.");
|
||||
JobDataMap parameters = new JobDataMap();
|
||||
parameters.putAsString("muteId", mute.getId());
|
||||
parameters.putAsString("muteId", muteId);
|
||||
parameters.putAsString("serverId", serverId);
|
||||
return schedulerService.executeJobWithParametersOnce("unMuteJob", "moderation", parameters, Date.from(unMuteDate));
|
||||
}
|
||||
}
|
||||
@@ -202,61 +225,101 @@ public class MuteServiceBean implements MuteService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void muteMemberWithLog(Member memberToMute, Member memberMuting, String reason, Instant unMuteDate, MuteLog muteLog, Message message) {
|
||||
public CompletableFuture<Void> muteMemberWithLog(MuteContext context) {
|
||||
log.trace("Muting member with sending a mute log");
|
||||
Mute mute = muteMember(memberToMute, memberMuting, reason, unMuteDate, message);
|
||||
muteLog.setMute(mute);
|
||||
sendMuteLog(muteLog);
|
||||
AServer server = serverManagementService.loadOrCreate(context.getContext().getServerId());
|
||||
Long nextCounterValue = counterService.getNextCounterValue(server, MUTE_COUNTER_KEY);
|
||||
context.setMuteId(nextCounterValue);
|
||||
CompletableFuture<Void> mutingFuture = muteMember(context.getMutedUser(), context.getMutingUser(), context.getReason(), context.getMuteTargetDate(), context.getContext());
|
||||
CompletableFuture<Void> muteLogFuture = sendMuteLog(context);
|
||||
return CompletableFuture.allOf(mutingFuture, muteLogFuture).thenAccept(aVoid ->
|
||||
self.persistMute(context)
|
||||
);
|
||||
}
|
||||
|
||||
private void sendMuteLog(MuteLog muteLogModel) {
|
||||
@Transactional
|
||||
public void persistMute(MuteContext context) {
|
||||
String triggerKey = startUnMuteJobFor(context.getMuteTargetDate(), context.getMuteId(), context.getContext().getServerId());
|
||||
createMuteObject(context, triggerKey);
|
||||
}
|
||||
|
||||
public CompletableFuture<Void> sendMuteLog(MuteContext muteLogModel) {
|
||||
log.trace("Sending mute log to the mute posttarget");
|
||||
MessageToSend message = templateService.renderEmbedTemplate(MUTE_LOG_TEMPLATE, muteLogModel);
|
||||
postTargetService.sendEmbedInPostTarget(message, MutingPostTarget.MUTE_LOG, muteLogModel.getServer().getId());
|
||||
List<CompletableFuture<Message>> completableFutures = postTargetService.sendEmbedInPostTarget(message, MutingPostTarget.MUTE_LOG, muteLogModel.getContext().getServerId());
|
||||
return FutureUtils.toSingleFutureGeneric(completableFutures);
|
||||
}
|
||||
|
||||
private void sendUnMuteLog(UnMuteLog muteLogModel) {
|
||||
private CompletableFuture<Void> sendUnMuteLog(UnMuteLog muteLogModel) {
|
||||
log.trace("Sending unMute log to the mute posttarget");
|
||||
MessageToSend message = templateService.renderEmbedTemplate(UN_MUTE_LOG_TEMPLATE, muteLogModel);
|
||||
postTargetService.sendEmbedInPostTarget(message, MutingPostTarget.MUTE_LOG, muteLogModel.getServer().getId());
|
||||
List<CompletableFuture<Message>> completableFutures = postTargetService.sendEmbedInPostTarget(message, MutingPostTarget.MUTE_LOG, muteLogModel.getServer().getId());
|
||||
return FutureUtils.toSingleFutureGeneric(completableFutures);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void unMuteUser(Mute mute) {
|
||||
if(Boolean.TRUE.equals(mute.getMuteEnded())) {
|
||||
log.info("Mute {} has ended already, user {} does not need to be unMuted anymore.", mute.getId(), mute.getMutedUser().getUserReference().getId());
|
||||
return;
|
||||
public CompletableFuture<Void> unMuteUser(AUserInAServer aUserInAServer) {
|
||||
if(muteManagementService.hasActiveMute(aUserInAServer)) {
|
||||
throw new NoMuteFoundException();
|
||||
}
|
||||
AServer mutingServer = mute.getMutingServer();
|
||||
Mute mute = muteManagementService.getAMuteOf(aUserInAServer);
|
||||
if(Boolean.TRUE.equals(mute.getMuteEnded())) {
|
||||
log.info("Mute {} has ended already, user {} does not need to be unMuted anymore.", mute.getMuteId().getId(), mute.getMutedUser().getUserReference().getId());
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
return endMute(mute);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompletableFuture<Void> endMute(Mute mute) {
|
||||
Long muteId = mute.getMuteId().getId();
|
||||
AServer mutingServer = mute.getServer();
|
||||
log.info("UnMuting {} in server {}", mute.getMutedUser().getUserReference().getId(), mutingServer.getId());
|
||||
MuteRole muteRole = muteRoleManagementService.retrieveMuteRoleForServer(mutingServer);
|
||||
log.trace("Using the mute role {} mapping to role {}", muteRole.getId(), muteRole.getRole().getId());
|
||||
Guild guild = botService.getGuildByIdNullable(mute.getMutingServer().getId());
|
||||
Guild guild = botService.getGuildByIdNullable(mutingServer.getId());
|
||||
CompletableFuture<Void> roleRemovalFuture;
|
||||
if(botService.isUserInGuild(guild, mute.getMutedUser())) {
|
||||
roleService.removeRoleFromUser(mute.getMutedUser(), muteRole.getRole());
|
||||
roleRemovalFuture = roleService.removeRoleFromUserFuture(mute.getMutedUser(), muteRole.getRole());
|
||||
} else {
|
||||
roleRemovalFuture = CompletableFuture.completedFuture(null);
|
||||
log.info("User to unMute left the guild.");
|
||||
}
|
||||
Long serverId = mutingServer.getId();
|
||||
UnMuteLog unMuteLog = UnMuteLog
|
||||
.builder()
|
||||
.mute(mute)
|
||||
.mutingUser(botService.getMemberInServer(mute.getMutingUser()))
|
||||
.unMutedUser(botService.getMemberInServer(mute.getMutedUser()))
|
||||
.guild(guild)
|
||||
.server(mute.getMutingServer())
|
||||
.server(mutingServer)
|
||||
.build();
|
||||
sendUnMuteLog(unMuteLog);
|
||||
mute.setMuteEnded(true);
|
||||
muteManagementService.saveMute(mute);
|
||||
CompletableFuture<Void> notificationFuture = sendUnMuteLog(unMuteLog);
|
||||
return CompletableFuture.allOf(roleRemovalFuture, notificationFuture).thenAccept(aVoid ->
|
||||
self.endMuteInDatabase(muteId, serverId)
|
||||
);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void endMuteInDatabase(Long muteId, Long serverId) {
|
||||
Optional<Mute> muteOptional = muteManagementService.findMute(muteId, serverId);
|
||||
muteOptional.ifPresent(mute ->
|
||||
completelyUnMuteUser(mute.getMutedUser())
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void endMute(Long muteId) {
|
||||
public CompletableFuture<Void> endMute(Long muteId, Long serverId) {
|
||||
log.info("UnMuting the mute {}", muteId);
|
||||
Optional<Mute> mute = muteManagementService.findMute(muteId);
|
||||
mute.ifPresent(this::unMuteUser);
|
||||
Optional<Mute> muteOptional = muteManagementService.findMute(muteId, serverId);
|
||||
if(muteOptional.isPresent()) {
|
||||
return endMute(muteOptional.get());
|
||||
} else {
|
||||
throw new NoMuteFoundException();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -10,6 +10,7 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
@@ -19,26 +20,26 @@ public class SlowModeServiceBean implements SlowModeService {
|
||||
private BotService botService;
|
||||
|
||||
@Override
|
||||
public void setSlowMode(TextChannel channel, Duration duration) {
|
||||
public CompletableFuture<Void> setSlowMode(TextChannel channel, Duration duration) {
|
||||
log.info("Setting slow mode to {} in channel {} in server {}", duration.toString(), channel.getIdLong(), channel.getGuild().getId());
|
||||
long seconds = duration.getSeconds();
|
||||
if(seconds > TextChannel.MAX_SLOWMODE) {
|
||||
throw new IllegalArgumentException("Slow mode duration must be < " + TextChannel.MAX_SLOWMODE + " seconds.");
|
||||
}
|
||||
channel.getManager().setSlowmode((int) seconds).queue();
|
||||
return channel.getManager().setSlowmode((int) seconds).submit();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disableSlowMode(TextChannel channel) {
|
||||
setSlowMode(channel, Duration.ZERO);
|
||||
public CompletableFuture<Void> disableSlowMode(TextChannel channel) {
|
||||
return setSlowMode(channel, Duration.ZERO);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setSlowMode(AChannel channel, Duration duration) {
|
||||
public CompletableFuture<Void> setSlowMode(AChannel channel, Duration duration) {
|
||||
Optional<TextChannel> textChannelOptional = botService.getTextChannelFromServerOptional(channel.getServer().getId(), channel.getId());
|
||||
if(textChannelOptional.isPresent()) {
|
||||
TextChannel textChannel = textChannelOptional.get();
|
||||
this.setSlowMode(textChannel, duration);
|
||||
return this.setSlowMode(textChannel, duration);
|
||||
} else {
|
||||
throw new ChannelNotFoundException(channel.getId());
|
||||
}
|
||||
|
||||
@@ -1,26 +1,25 @@
|
||||
package dev.sheldan.abstracto.moderation.service;
|
||||
|
||||
import dev.sheldan.abstracto.core.models.FullUserInServer;
|
||||
import dev.sheldan.abstracto.core.models.database.AServer;
|
||||
import dev.sheldan.abstracto.core.service.ConfigService;
|
||||
import dev.sheldan.abstracto.core.service.MessageService;
|
||||
import dev.sheldan.abstracto.core.service.*;
|
||||
import dev.sheldan.abstracto.core.service.management.ServerManagementService;
|
||||
import dev.sheldan.abstracto.core.utils.FutureUtils;
|
||||
import dev.sheldan.abstracto.moderation.config.features.WarningDecayFeature;
|
||||
import dev.sheldan.abstracto.moderation.config.posttargets.WarnDecayPostTarget;
|
||||
import dev.sheldan.abstracto.moderation.config.posttargets.WarningPostTarget;
|
||||
import dev.sheldan.abstracto.moderation.models.template.job.WarnDecayLogModel;
|
||||
import dev.sheldan.abstracto.moderation.models.template.job.WarnDecayWarning;
|
||||
import dev.sheldan.abstracto.templating.model.MessageToSend;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.WarnLog;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.WarnContext;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.WarnNotification;
|
||||
import dev.sheldan.abstracto.moderation.models.database.Warning;
|
||||
import dev.sheldan.abstracto.moderation.service.management.WarnManagementService;
|
||||
import dev.sheldan.abstracto.core.service.management.UserInServerManagementService;
|
||||
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
|
||||
import dev.sheldan.abstracto.core.service.BotService;
|
||||
import dev.sheldan.abstracto.core.service.PostTargetService;
|
||||
import dev.sheldan.abstracto.templating.service.TemplateService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import net.dv8tion.jda.api.entities.*;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -29,6 +28,8 @@ import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@@ -55,73 +56,88 @@ public class WarnServiceBean implements WarnService {
|
||||
@Autowired
|
||||
private ConfigService configService;
|
||||
|
||||
@Autowired
|
||||
private CounterService counterService;
|
||||
|
||||
@Autowired
|
||||
private ServerManagementService serverManagementService;
|
||||
|
||||
@Autowired
|
||||
private WarnServiceBean self;
|
||||
|
||||
public static final String WARN_LOG_TEMPLATE = "warn_log";
|
||||
public static final String WARN_NOTIFICATION_TEMPLATE = "warn_notification";
|
||||
public static final String WARNINGS_COUNTER_KEY = "WARNINGS";
|
||||
public static final String WARN_DECAY_LOG_TEMPLATE_KEY = "warn_decay_log";
|
||||
|
||||
@Override
|
||||
public Warning warnUser(AUserInAServer warnedAUserInAServer, AUserInAServer warningAUserInAServer, String reason, MessageChannel feedbackChannel) {
|
||||
FullUserInServer warnedUser = FullUserInServer
|
||||
.builder()
|
||||
.aUserInAServer(warnedAUserInAServer)
|
||||
.member(botService.getMemberInServer(warnedAUserInAServer))
|
||||
.build();
|
||||
|
||||
FullUserInServer warningUser = FullUserInServer
|
||||
.builder()
|
||||
.aUserInAServer(warningAUserInAServer)
|
||||
.member(botService.getMemberInServer(warningAUserInAServer))
|
||||
.build();
|
||||
return warnFullUser(warnedUser, warningUser, reason, feedbackChannel);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Warning warnMember(Member warnedMember, Member warningMember, String reason, MessageChannel feedbackChannel) {
|
||||
FullUserInServer warnedUser = FullUserInServer
|
||||
.builder()
|
||||
.aUserInAServer(userInServerManagementService.loadUser(warnedMember))
|
||||
.member(warnedMember)
|
||||
.build();
|
||||
|
||||
FullUserInServer warningUser = FullUserInServer
|
||||
.builder()
|
||||
.aUserInAServer(userInServerManagementService.loadUser(warningMember))
|
||||
.member(warningMember)
|
||||
.build();
|
||||
return warnFullUser(warnedUser, warningUser, reason, feedbackChannel);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Warning warnFullUser(FullUserInServer warnedMember, FullUserInServer warningMember, String reason, MessageChannel feedbackChannel) {
|
||||
Guild guild = warnedMember.getMember().getGuild();
|
||||
log.info("User {} is warning {} in server {}", warnedMember.getMember().getId(), warningMember.getMember().getId(), guild.getIdLong());
|
||||
Warning warning = warnManagementService.createWarning(warnedMember.getAUserInAServer(), warningMember.getAUserInAServer(), reason);
|
||||
WarnNotification warnNotification = WarnNotification.builder().warning(warning).serverName(guild.getName()).build();
|
||||
public CompletableFuture<Void> notifyAndLogFullUserWarning(WarnContext context) {
|
||||
AServer server = serverManagementService.loadOrCreate(context.getGuild().getIdLong());
|
||||
Long warningId = counterService.getNextCounterValue(server, WARNINGS_COUNTER_KEY);
|
||||
context.setWarnId(warningId);
|
||||
Member warnedMember = context.getWarnedMember();
|
||||
Member warningMember = context.getMember();
|
||||
Guild guild = warnedMember.getGuild();
|
||||
log.info("User {} is warning {} in server {}", warnedMember.getId(), warningMember.getId(), guild.getIdLong());
|
||||
WarnNotification warnNotification = WarnNotification.builder().reason(context.getReason()).warnId(warningId).serverName(guild.getName()).build();
|
||||
String warnNotificationMessage = templateService.renderTemplate(WARN_NOTIFICATION_TEMPLATE, warnNotification);
|
||||
messageService.sendMessageToUser(warnedMember.getMember().getUser(), warnNotificationMessage, feedbackChannel);
|
||||
return warning;
|
||||
List<CompletableFuture<Message>> futures = new ArrayList<>();
|
||||
futures.add(messageService.sendMessageToUser(warnedMember.getUser(), warnNotificationMessage));
|
||||
MessageToSend message = templateService.renderEmbedTemplate(WARN_LOG_TEMPLATE, context);
|
||||
futures.addAll(postTargetService.sendEmbedInPostTarget(message, WarningPostTarget.WARN_LOG, context.getGuild().getIdLong()));
|
||||
|
||||
return FutureUtils.toSingleFutureGeneric(futures);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Warning warnUserWithLog(Member warnedMember, Member warningMember, String reason, WarnLog warnLog, MessageChannel feedbackChannel) {
|
||||
Warning warning = warnMember(warnedMember, warningMember, reason, feedbackChannel);
|
||||
warnLog.setWarning(warning);
|
||||
this.sendWarnLog(warnLog);
|
||||
return warning;
|
||||
public CompletableFuture<Void> warnUserWithLog(WarnContext context) {
|
||||
return notifyAndLogFullUserWarning(context).thenAccept(aVoid ->
|
||||
self.persistWarning(context)
|
||||
);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void persistWarning(WarnContext context) {
|
||||
AUserInAServer warnedUser = userInServerManagementService.loadUser(context.getWarnedMember());
|
||||
AUserInAServer warningUser = userInServerManagementService.loadUser(context.getMember());
|
||||
warnManagementService.createWarning(warnedUser, warningUser, context.getReason(), context.getWarnId());
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void decayWarningsForServer(AServer server) {
|
||||
public CompletableFuture<Void> decayWarningsForServer(AServer server) {
|
||||
Long days = configService.getLongValue(WarningDecayFeature.DECAY_DAYS_KEY, server.getId());
|
||||
Instant cutOffDay = Instant.now().minus(days, ChronoUnit.DAYS);
|
||||
List<Warning> warningsToDecay = warnManagementService.getActiveWarningsInServerOlderThan(server, cutOffDay);
|
||||
decayWarnings(warningsToDecay);
|
||||
logDecayedWarnings(server, warningsToDecay);
|
||||
List<Long> warningIds = flattenWarnings(warningsToDecay);
|
||||
Long serverId = server.getId();
|
||||
return logDecayedWarnings(server, warningsToDecay).thenAccept(aVoid ->
|
||||
self.decayWarnings(warningIds, serverId)
|
||||
);
|
||||
}
|
||||
|
||||
private void decayWarnings(List<Warning> warningsToDecay) {
|
||||
@NotNull
|
||||
private List<Long> flattenWarnings(List<Warning> warningsToDecay) {
|
||||
List<Long> warningIds = new ArrayList<>();
|
||||
warningsToDecay.forEach(warning ->
|
||||
warningIds.add(warning.getWarnId().getId())
|
||||
);
|
||||
return warningIds;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void decayWarnings(List<Long> warningIds, Long serverId) {
|
||||
Instant now = Instant.now();
|
||||
warningsToDecay.forEach(warning -> decayWarning(warning, now));
|
||||
warningIds.forEach(warningId -> {
|
||||
Optional<Warning> warningOptional = warnManagementService.findById(warningId, serverId);
|
||||
warningOptional.ifPresent(warning ->
|
||||
decayWarning(warning, now)
|
||||
);
|
||||
if(!warningOptional.isPresent()) {
|
||||
log.warn("Warning with id {} in server {} not found. Was not decayed.", warningId, serverId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -130,7 +146,7 @@ public class WarnServiceBean implements WarnService {
|
||||
warning.setDecayed(true);
|
||||
}
|
||||
|
||||
private void logDecayedWarnings(AServer server, List<Warning> warningsToDecay) {
|
||||
private CompletableFuture<Void> logDecayedWarnings(AServer server, List<Warning> warningsToDecay) {
|
||||
List<WarnDecayWarning> warnDecayWarnings = new ArrayList<>();
|
||||
warningsToDecay.forEach(warning -> {
|
||||
WarnDecayWarning warnDecayWarning = WarnDecayWarning
|
||||
@@ -147,21 +163,23 @@ public class WarnServiceBean implements WarnService {
|
||||
.server(server)
|
||||
.warnings(warnDecayWarnings)
|
||||
.build();
|
||||
MessageToSend messageToSend = templateService.renderEmbedTemplate("warn_decay_log", warnDecayLogModel);
|
||||
postTargetService.sendEmbedInPostTarget(messageToSend, WarnDecayPostTarget.DECAY_LOG, server.getId());
|
||||
MessageToSend messageToSend = templateService.renderEmbedTemplate(WARN_DECAY_LOG_TEMPLATE_KEY, warnDecayLogModel);
|
||||
List<CompletableFuture<Message>> messageFutures = postTargetService.sendEmbedInPostTarget(messageToSend, WarnDecayPostTarget.DECAY_LOG, server.getId());
|
||||
return FutureUtils.toSingleFutureGeneric(messageFutures);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void decayAllWarningsForServer(AServer server, boolean logWarnings) {
|
||||
public CompletableFuture<Void> decayAllWarningsForServer(AServer server, boolean logWarnings) {
|
||||
List<Warning> warningsToDecay = warnManagementService.getActiveWarningsInServerOlderThan(server, Instant.now());
|
||||
decayWarnings(warningsToDecay);
|
||||
List<Long> warnIds = flattenWarnings(warningsToDecay);
|
||||
Long serverId = server.getId();
|
||||
if(logWarnings) {
|
||||
logDecayedWarnings(server, warningsToDecay);
|
||||
return logDecayedWarnings(server, warningsToDecay).thenAccept(aVoid ->
|
||||
self.decayWarnings(warnIds, serverId)
|
||||
);
|
||||
} else {
|
||||
decayWarnings(warnIds, serverId);
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
}
|
||||
|
||||
private void sendWarnLog(WarnLog warnLogModel) {
|
||||
MessageToSend message = templateService.renderEmbedTemplate(WARN_LOG_TEMPLATE, warnLogModel);
|
||||
postTargetService.sendEmbedInPostTarget(message, WarningPostTarget.WARN_LOG, warnLogModel.getServer().getId());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package dev.sheldan.abstracto.moderation.service.management;
|
||||
|
||||
import dev.sheldan.abstracto.core.models.AServerAChannelMessage;
|
||||
import dev.sheldan.abstracto.core.models.ServerSpecificId;
|
||||
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
|
||||
import dev.sheldan.abstracto.core.service.management.UserInServerManagementService;
|
||||
import dev.sheldan.abstracto.moderation.models.database.Mute;
|
||||
@@ -25,18 +26,21 @@ public class MuteManagementServiceBean implements MuteManagementService {
|
||||
private UserInServerManagementService userInServerManagementService;
|
||||
|
||||
@Override
|
||||
public Mute createMute(AUserInAServer mutedUser, AUserInAServer mutingUser, String reason, Instant unMuteDate, AServerAChannelMessage muteMessage) {
|
||||
public Mute createMute(AUserInAServer mutedUser, AUserInAServer mutingUser, String reason, Instant unMuteDate, AServerAChannelMessage muteMessage, String triggerKey, Long muteId) {
|
||||
log.trace("Creating mute for user {} executed by user {} in server {}, user will be un-muted at {}",
|
||||
mutedUser.getUserReference().getId(), mutingUser.getUserReference().getId(), mutedUser.getServerReference().getId(), unMuteDate);
|
||||
ServerSpecificId id = new ServerSpecificId(muteMessage.getServer().getId(), muteId);
|
||||
Mute mute = Mute
|
||||
.builder()
|
||||
.mutedUser(mutedUser)
|
||||
.mutingUser(mutingUser)
|
||||
.muteTargetDate(unMuteDate)
|
||||
.mutingServer(mutedUser.getServerReference())
|
||||
.server(mutedUser.getServerReference())
|
||||
.mutingChannel(muteMessage.getChannel())
|
||||
.messageId(muteMessage.getMessageId())
|
||||
.reason(reason)
|
||||
.triggerKey(triggerKey)
|
||||
.muteId(id)
|
||||
.muteEnded(false)
|
||||
.build();
|
||||
muteRepository.save(mute);
|
||||
@@ -44,8 +48,8 @@ public class MuteManagementServiceBean implements MuteManagementService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Mute> findMute(Long muteId) {
|
||||
return muteRepository.findById(muteId);
|
||||
public Optional<Mute> findMute(Long muteId, Long serverId) {
|
||||
return muteRepository.findByMuteId_IdAndMuteId_ServerId(muteId, serverId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -76,7 +80,7 @@ public class MuteManagementServiceBean implements MuteManagementService {
|
||||
|
||||
@Override
|
||||
public List<Mute> getAllMutesOf(AUserInAServer aUserInAServer) {
|
||||
return muteRepository.findAllByMutedUserAndMuteEndedFalseOrderByIdDesc(aUserInAServer);
|
||||
return muteRepository.findAllByMutedUserAndMuteEndedFalseOrderByMuteId_IdDesc(aUserInAServer);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
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.core.service.CounterService;
|
||||
import dev.sheldan.abstracto.moderation.models.database.UserNote;
|
||||
import dev.sheldan.abstracto.moderation.repository.UserNoteRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -15,11 +17,20 @@ public class UserNoteManagementServiceBean implements UserNoteManagementService
|
||||
@Autowired
|
||||
private UserNoteRepository userNoteRepository;
|
||||
|
||||
@Autowired
|
||||
private CounterService counterService;
|
||||
|
||||
public static final String USER_NOTE_COUNTER_KEY = "USER_NOTES";
|
||||
|
||||
@Override
|
||||
public UserNote createUserNote(AUserInAServer aUserInAServer, String note) {
|
||||
Long id = counterService.getNextCounterValue(aUserInAServer.getServerReference(), USER_NOTE_COUNTER_KEY);
|
||||
ServerSpecificId userNoteId = new ServerSpecificId(aUserInAServer.getServerReference().getId(), id);
|
||||
UserNote newNote = UserNote
|
||||
.builder()
|
||||
.note(note)
|
||||
.userNoteId(userNoteId)
|
||||
.server(aUserInAServer.getServerReference())
|
||||
.user(aUserInAServer)
|
||||
.build();
|
||||
userNoteRepository.save(newNote);
|
||||
|
||||
@@ -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.moderation.models.database.Warning;
|
||||
import dev.sheldan.abstracto.moderation.repository.WarnRepository;
|
||||
@@ -18,12 +19,15 @@ public class WarnManagementServiceBean implements WarnManagementService {
|
||||
private WarnRepository warnRepository;
|
||||
|
||||
@Override
|
||||
public Warning createWarning(AUserInAServer warnedAUser, AUserInAServer warningAUser, String reason) {
|
||||
public Warning createWarning(AUserInAServer warnedAUser, AUserInAServer warningAUser, String reason, Long warnId) {
|
||||
ServerSpecificId warningId = new ServerSpecificId(warnId, warningAUser.getServerReference().getId());
|
||||
Warning warning = Warning.builder()
|
||||
.reason(reason)
|
||||
.warnedUser(warnedAUser)
|
||||
.warningUser(warningAUser)
|
||||
.warnDate(Instant.now())
|
||||
.server(warningAUser.getServerReference())
|
||||
.warnId(warningId)
|
||||
.decayed(false)
|
||||
.build();
|
||||
warnRepository.save(warning);
|
||||
@@ -56,8 +60,8 @@ public class WarnManagementServiceBean implements WarnManagementService {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Warning> findById(Long id) {
|
||||
return warnRepository.findById(id);
|
||||
public Optional<Warning> findById(Long id, Long serverId) {
|
||||
return warnRepository.findByWarnId_IdAndWarnId_ServerId(id, serverId);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
<column name="muting_channel" type="BIGINT">
|
||||
<constraints nullable="false"/>
|
||||
</column>
|
||||
<column name="muting_server" type="BIGINT">
|
||||
<column name="server_id" type="BIGINT">
|
||||
<constraints nullable="false"/>
|
||||
</column>
|
||||
<column name="mute_ended" type="BOOLEAN"/>
|
||||
@@ -44,8 +44,8 @@
|
||||
<changeSet author="Sheldan" id="mute-fk_mute_muted_user">
|
||||
<addForeignKeyConstraint baseColumnNames="muted_user" baseTableName="mute" constraintName="fk_mute_muted_user" deferrable="false" initiallyDeferred="false" onDelete="NO ACTION" onUpdate="NO ACTION" referencedColumnNames="user_in_server_id" referencedTableName="user_in_server" validate="true"/>
|
||||
</changeSet>
|
||||
<changeSet author="Sheldan" id="mute-fk_mute_muting_server">
|
||||
<addForeignKeyConstraint baseColumnNames="muting_server" baseTableName="mute" constraintName="fk_mute_muting_server" deferrable="false" initiallyDeferred="false" onDelete="NO ACTION" onUpdate="NO ACTION" referencedColumnNames="id" referencedTableName="server" validate="true"/>
|
||||
<changeSet author="Sheldan" id="mute-fk_mute_server_id">
|
||||
<addForeignKeyConstraint baseColumnNames="server_id" baseTableName="mute" constraintName="fk_mute_server_id" deferrable="false" initiallyDeferred="false" onDelete="NO ACTION" onUpdate="NO ACTION" referencedColumnNames="id" referencedTableName="server" validate="true"/>
|
||||
</changeSet>
|
||||
|
||||
</databaseChangeLog>
|
||||
@@ -16,11 +16,17 @@
|
||||
<column name="note_user" type="BIGINT">
|
||||
<constraints nullable="false"/>
|
||||
</column>
|
||||
<column name="server_id" type="BIGINT">
|
||||
<constraints nullable="false"/>
|
||||
</column>
|
||||
</createTable>
|
||||
</changeSet>
|
||||
|
||||
<changeSet author="Sheldan" id="user_note-fk_user_note_user">
|
||||
<addForeignKeyConstraint baseColumnNames="note_user" baseTableName="user_note" constraintName="fk_user_note_user" deferrable="false" initiallyDeferred="false" onDelete="NO ACTION" onUpdate="NO ACTION" referencedColumnNames="user_in_server_id" referencedTableName="user_in_server" validate="true"/>
|
||||
</changeSet>
|
||||
<changeSet author="Sheldan" id="user_note-fk_user_note_server_id">
|
||||
<addForeignKeyConstraint baseColumnNames="server_id" baseTableName="user_note" constraintName="fk_user_note_server_id" deferrable="false" initiallyDeferred="false" onDelete="NO ACTION" onUpdate="NO ACTION" referencedColumnNames="id" referencedTableName="server" validate="true"/>
|
||||
</changeSet>
|
||||
|
||||
</databaseChangeLog>
|
||||
@@ -23,6 +23,9 @@
|
||||
<column name="warning_user_id" type="BIGINT">
|
||||
<constraints nullable="false"/>
|
||||
</column>
|
||||
<column name="server_id" type="BIGINT">
|
||||
<constraints nullable="false"/>
|
||||
</column>
|
||||
</createTable>
|
||||
</changeSet>
|
||||
|
||||
@@ -33,4 +36,8 @@
|
||||
<changeSet author="Sheldan" id="warning-fk_warning_warning_user">
|
||||
<addForeignKeyConstraint baseColumnNames="warning_user_id" baseTableName="warning" constraintName="fk_warning_warning_user" deferrable="false" initiallyDeferred="false" onDelete="NO ACTION" onUpdate="NO ACTION" referencedColumnNames="user_in_server_id" referencedTableName="user_in_server" validate="true"/>
|
||||
</changeSet>
|
||||
<changeSet author="Sheldan" id="warning-fk_warning_server_id">
|
||||
<addForeignKeyConstraint baseColumnNames="server_id" baseTableName="warning" constraintName="fk_warning_server_id" deferrable="false" initiallyDeferred="false" onDelete="NO ACTION" onUpdate="NO ACTION" referencedColumnNames="id" referencedTableName="server" validate="true"/>
|
||||
</changeSet>
|
||||
|
||||
</databaseChangeLog>
|
||||
@@ -16,6 +16,7 @@ import org.mockito.*;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@@ -43,13 +44,13 @@ public class BanIdTest {
|
||||
Long guildId = parameters.getUserInitiatedContext().getServer().getId();
|
||||
when(templateService.renderSimpleTemplate(Ban.BAN_DEFAULT_REASON_TEMPLATE)).thenReturn(REASON);
|
||||
when(parameters.getGuild().getIdLong()).thenReturn(guildId);
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
verify(banService, times(1)).banMember(eq(guildId), eq(BANNED_USER_ID), eq(REASON), banLogModelCaptor.capture());
|
||||
when(banService.banMember(eq(guildId), eq(BANNED_USER_ID), eq(REASON), banLogModelCaptor.capture())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(parameters);
|
||||
BanIdLog usedModel = banLogModelCaptor.getValue();
|
||||
Assert.assertEquals(REASON, usedModel.getReason());
|
||||
Assert.assertEquals(BANNED_USER_ID, usedModel.getBannedUserId());
|
||||
Assert.assertEquals(parameters.getAuthor(), usedModel.getBanningUser());
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -59,25 +60,25 @@ public class BanIdTest {
|
||||
Long guildId = parameters.getUserInitiatedContext().getServer().getId();
|
||||
when(parameters.getGuild().getIdLong()).thenReturn(guildId);
|
||||
when(templateService.renderSimpleTemplate(Ban.BAN_DEFAULT_REASON_TEMPLATE)).thenReturn(REASON);
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
verify(banService, times(1)).banMember(eq(guildId), eq(BANNED_USER_ID), eq(customReason), banLogModelCaptor.capture());
|
||||
when(banService.banMember(eq(guildId), eq(BANNED_USER_ID), eq(customReason), banLogModelCaptor.capture())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(parameters);
|
||||
BanIdLog usedModel = banLogModelCaptor.getValue();
|
||||
Assert.assertEquals(customReason, usedModel.getReason());
|
||||
Assert.assertEquals(BANNED_USER_ID, usedModel.getBannedUserId());
|
||||
Assert.assertEquals(parameters.getAuthor(), usedModel.getBanningUser());
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Test(expected = InsufficientParametersException.class)
|
||||
public void testTooLittleParameters() {
|
||||
CommandTestUtilities.executeNoParametersTest(testUnit);
|
||||
CommandTestUtilities.executeNoParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
@Test(expected = IncorrectParameterException.class)
|
||||
public void testIncorrectParameterType() {
|
||||
CommandTestUtilities.executeWrongParametersTest(testUnit);
|
||||
CommandTestUtilities.executeWrongParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -17,6 +17,7 @@ import org.mockito.*;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@@ -44,13 +45,13 @@ public class BanTest {
|
||||
public void testBanWithDefaultReason() {
|
||||
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(bannedMember));
|
||||
when(templateService.renderSimpleTemplate(Ban.BAN_DEFAULT_REASON_TEMPLATE)).thenReturn(REASON);
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
verify(banService, times(1)).banMember(eq(bannedMember), eq(REASON), banLogModelCaptor.capture());
|
||||
when(banService.banMember(eq(bannedMember), eq(REASON), banLogModelCaptor.capture())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(parameters);
|
||||
BanLog usedModel = banLogModelCaptor.getValue();
|
||||
Assert.assertEquals(REASON, usedModel.getReason());
|
||||
Assert.assertEquals(bannedMember, usedModel.getBannedUser());
|
||||
Assert.assertEquals(parameters.getAuthor(), usedModel.getBanningUser());
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -58,23 +59,23 @@ public class BanTest {
|
||||
String customReason = "reason2";
|
||||
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(bannedMember, customReason));
|
||||
when(templateService.renderSimpleTemplate(Ban.BAN_DEFAULT_REASON_TEMPLATE)).thenReturn(REASON);
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
verify(banService, times(1)).banMember(eq(bannedMember), eq(customReason), banLogModelCaptor.capture());
|
||||
when(banService.banMember(eq(bannedMember), eq(customReason), banLogModelCaptor.capture())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(parameters);
|
||||
BanLog usedModel = banLogModelCaptor.getValue();
|
||||
Assert.assertEquals(customReason, usedModel.getReason());
|
||||
Assert.assertEquals(bannedMember, usedModel.getBannedUser());
|
||||
Assert.assertEquals(parameters.getAuthor(), usedModel.getBanningUser());
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
|
||||
@Test(expected = InsufficientParametersException.class)
|
||||
public void testTooLittleParameters() {
|
||||
CommandTestUtilities.executeNoParametersTest(testUnit);
|
||||
CommandTestUtilities.executeNoParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
@Test(expected = IncorrectParameterException.class)
|
||||
public void testIncorrectParameterType() {
|
||||
CommandTestUtilities.executeWrongParametersTest(testUnit);
|
||||
CommandTestUtilities.executeWrongParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -13,6 +13,7 @@ import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@@ -42,13 +43,13 @@ public class DecayAllWarningsTest {
|
||||
|
||||
@Test(expected = IncorrectParameterException.class)
|
||||
public void testIncorrectParameterType() {
|
||||
CommandTestUtilities.executeWrongParametersTest(testUnit);
|
||||
CommandTestUtilities.executeWrongParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
private void executeTest(Boolean logWarnings) {
|
||||
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(logWarnings));
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
verify(warnService, times(1)).decayAllWarningsForServer(parameters.getUserInitiatedContext().getServer(), logWarnings);
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
CommandContext commandContext = CommandTestUtilities.getWithParameters(Arrays.asList(logWarnings));
|
||||
when(warnService.decayAllWarningsForServer(commandContext.getUserInitiatedContext().getServer(), logWarnings)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(commandContext);
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
@@ -25,9 +27,9 @@ public class DecayWarningsTest {
|
||||
@Test
|
||||
public void testExecuteCommand() {
|
||||
CommandContext noParameters = CommandTestUtilities.getNoParameters();
|
||||
CommandResult result = testUnit.execute(noParameters);
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
verify(warnService, times(1)).decayWarningsForServer(noParameters.getUserInitiatedContext().getServer());
|
||||
when(warnService.decayWarningsForServer(noParameters.getUserInitiatedContext().getServer())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(noParameters);
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -38,15 +38,15 @@ public class DeleteWarningTest {
|
||||
AUserInAServer warnedUser = MockUtils.getUserObject(5L, server);
|
||||
AUserInAServer warningUser = MockUtils.getUserObject(6L, server);
|
||||
Warning existingWarning = Warning.builder().warnedUser(warnedUser).warningUser(warningUser).build();
|
||||
when(warnManagementService.findById(WARN_ID)).thenReturn(Optional.of(existingWarning));
|
||||
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(WARN_ID));
|
||||
when(warnManagementService.findById(WARN_ID, parameters.getGuild().getIdLong())).thenReturn(Optional.of(existingWarning));
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
verify(warnManagementService, times(1)).deleteWarning(existingWarning);
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteNotExistingWarning() {
|
||||
when(warnManagementService.findById(WARN_ID)).thenReturn(Optional.empty());
|
||||
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(WARN_ID));
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
|
||||
@@ -20,6 +20,7 @@ import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@@ -47,37 +48,37 @@ public class KickTest {
|
||||
public void testKickMemberWithoutReason() {
|
||||
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(memberToKick));
|
||||
when(templateService.renderSimpleTemplate(Kick.KICK_DEFAULT_REASON_TEMPLATE)).thenReturn(REASON);
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
verify(kickService, times(1)).kickMember(eq(memberToKick), eq(REASON), logModelArgumentCaptor.capture());
|
||||
when(kickService.kickMember(eq(memberToKick), eq(REASON), logModelArgumentCaptor.capture())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(parameters);
|
||||
KickLogModel usedLogModel = logModelArgumentCaptor.getValue();
|
||||
Assert.assertEquals(REASON, usedLogModel.getReason());
|
||||
Assert.assertEquals(memberToKick, usedLogModel.getKickedUser());
|
||||
Assert.assertEquals(parameters.getAuthor(), usedLogModel.getKickingUser());
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
Assert.assertEquals(parameters.getAuthor(), usedLogModel.getMember());
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testKickMemberWithReason() {
|
||||
String customReason = "reason2";
|
||||
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(memberToKick, customReason));
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
verify(kickService, times(1)).kickMember(eq(memberToKick), eq(customReason), logModelArgumentCaptor.capture());
|
||||
when(kickService.kickMember(eq(memberToKick), eq(customReason), logModelArgumentCaptor.capture())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(parameters);
|
||||
KickLogModel usedLogModel = logModelArgumentCaptor.getValue();
|
||||
Assert.assertEquals(customReason, usedLogModel.getReason());
|
||||
Assert.assertEquals(memberToKick, usedLogModel.getKickedUser());
|
||||
Assert.assertEquals(parameters.getAuthor(), usedLogModel.getKickingUser());
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
Assert.assertEquals(parameters.getAuthor(), usedLogModel.getMember());
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
|
||||
|
||||
@Test(expected = InsufficientParametersException.class)
|
||||
public void testTooLittleParameters() {
|
||||
CommandTestUtilities.executeNoParametersTest(testUnit);
|
||||
CommandTestUtilities.executeNoParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
@Test(expected = IncorrectParameterException.class)
|
||||
public void testIncorrectParameterType() {
|
||||
CommandTestUtilities.executeWrongParametersTest(testUnit);
|
||||
CommandTestUtilities.executeWrongParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -5,7 +5,6 @@ import dev.sheldan.abstracto.core.command.exception.InsufficientParametersExcept
|
||||
import dev.sheldan.abstracto.core.command.execution.CommandContext;
|
||||
import dev.sheldan.abstracto.core.command.execution.CommandResult;
|
||||
import dev.sheldan.abstracto.core.command.execution.ResultState;
|
||||
import dev.sheldan.abstracto.core.utils.ExceptionUtils;
|
||||
import dev.sheldan.abstracto.moderation.service.PurgeService;
|
||||
import dev.sheldan.abstracto.templating.service.TemplateService;
|
||||
import dev.sheldan.abstracto.test.command.CommandConfigValidator;
|
||||
@@ -36,17 +35,13 @@ public class PurgeTest {
|
||||
@Mock
|
||||
private TemplateService templateService;
|
||||
|
||||
@Mock
|
||||
private ExceptionUtils exceptionUtils;
|
||||
|
||||
@Test
|
||||
public void testExecutePurgeOfNoMemberCommand() {
|
||||
Integer count = 10;
|
||||
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(count));
|
||||
when(purgeService.purgeMessagesInChannel(count, parameters.getChannel(), parameters.getMessage(), null)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
verify(exceptionUtils, times(1)).handleExceptionIfTemplatable(null, parameters.getChannel());
|
||||
Assert.assertEquals(ResultState.SELF_DESTRUCT, result.getResult());
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(parameters);
|
||||
Assert.assertEquals(ResultState.SELF_DESTRUCT, result.join().getResult());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -55,33 +50,18 @@ public class PurgeTest {
|
||||
Integer count = 10;
|
||||
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(count, messageAuthor));
|
||||
when(purgeService.purgeMessagesInChannel(count, parameters.getChannel(), parameters.getMessage(), messageAuthor)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
verify(exceptionUtils, times(1)).handleExceptionIfTemplatable(null, parameters.getChannel());
|
||||
Assert.assertEquals(ResultState.SELF_DESTRUCT, result.getResult());
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(parameters);
|
||||
Assert.assertEquals(ResultState.SELF_DESTRUCT, result.join().getResult());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testExecutePurgeErroneousCommand() {
|
||||
Integer count = 10;
|
||||
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(count));
|
||||
CompletableFuture<Void> failingFuture = new CompletableFuture<>();
|
||||
RuntimeException exception = new RuntimeException();
|
||||
failingFuture.completeExceptionally(exception);
|
||||
when(purgeService.purgeMessagesInChannel(count, parameters.getChannel(), parameters.getMessage(), null)).thenReturn(failingFuture);
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
verify(exceptionUtils, times(1)).handleExceptionIfTemplatable(eq(exception), eq(parameters.getChannel()));
|
||||
Assert.assertEquals(ResultState.SELF_DESTRUCT, result.getResult());
|
||||
}
|
||||
|
||||
|
||||
@Test(expected = InsufficientParametersException.class)
|
||||
public void testTooLittleParameters() {
|
||||
CommandTestUtilities.executeNoParametersTest(testUnit);
|
||||
CommandTestUtilities.executeNoParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
@Test(expected = IncorrectParameterException.class)
|
||||
public void testIncorrectParameterType() {
|
||||
CommandTestUtilities.executeWrongParametersTest(testUnit);
|
||||
CommandTestUtilities.executeWrongParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -17,6 +17,7 @@ import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@@ -33,18 +34,18 @@ public class SlowModeTest {
|
||||
public void testExecuteSlowModeWithDurationCurrentChannel() {
|
||||
String duration = "1m";
|
||||
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(duration));
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
verify(slowModeService, times(1)).setSlowMode(parameters.getChannel(), Duration.ofMinutes(1));
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
when(slowModeService.setSlowMode(parameters.getChannel(), Duration.ofMinutes(1))).thenReturn(CompletableFuture.completedFuture(null));
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(parameters);
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDisableSlowModeCurrentChannel() {
|
||||
String duration = "off";
|
||||
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(duration));
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
verify(slowModeService, times(1)).setSlowMode(parameters.getChannel(), Duration.ZERO);
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
when(slowModeService.setSlowMode(parameters.getChannel(), Duration.ZERO)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(parameters);
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -52,9 +53,9 @@ public class SlowModeTest {
|
||||
String duration = "off";
|
||||
TextChannel channel = Mockito.mock(TextChannel.class);
|
||||
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(duration, channel));
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
verify(slowModeService, times(1)).setSlowMode(channel, Duration.ZERO);
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
when(slowModeService.setSlowMode(channel, Duration.ZERO)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(parameters);
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -62,19 +63,19 @@ public class SlowModeTest {
|
||||
String duration = "1m";
|
||||
TextChannel channel = Mockito.mock(TextChannel.class);
|
||||
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(duration, channel));
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
verify(slowModeService, times(1)).setSlowMode(channel, Duration.ofMinutes(1));
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
when(slowModeService.setSlowMode(channel, Duration.ofMinutes(1))).thenReturn(CompletableFuture.completedFuture(null));
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(parameters);
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
|
||||
@Test(expected = InsufficientParametersException.class)
|
||||
public void testTooLittleParameters() {
|
||||
CommandTestUtilities.executeNoParametersTest(testUnit);
|
||||
CommandTestUtilities.executeNoParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
@Test(expected = IncorrectParameterException.class)
|
||||
public void testIncorrectParameterType() {
|
||||
CommandTestUtilities.executeWrongParametersTest(testUnit);
|
||||
CommandTestUtilities.executeWrongParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -24,6 +24,7 @@ import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@@ -65,7 +66,7 @@ public class UserNotesTest {
|
||||
NoteEntryModel secondConvertedNote = NoteEntryModel.builder().build();
|
||||
List<NoteEntryModel> convertedNotes = Arrays.asList(firstConvertedNote, secondConvertedNote);
|
||||
when(userNotesConverter.fromNotes(userNotes)).thenReturn(convertedNotes);
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(parameters);
|
||||
verify(channelService, times(1)).sendEmbedTemplateInChannel(eq(UserNotes.USER_NOTES_RESPONSE_TEMPLATE), captor.capture(), eq(parameters.getChannel()));
|
||||
ListNotesModel usedModel = captor.getValue();
|
||||
Assert.assertEquals(convertedNotes.size(), usedModel.getUserNotes().size());
|
||||
@@ -76,7 +77,7 @@ public class UserNotesTest {
|
||||
}
|
||||
Assert.assertEquals(userNoteUser, usedModel.getSpecifiedUser().getAUserInAServer());
|
||||
Assert.assertEquals(member, usedModel.getSpecifiedUser().getMember());
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -90,7 +91,7 @@ public class UserNotesTest {
|
||||
NoteEntryModel secondConvertedNote = NoteEntryModel.builder().build();
|
||||
List<NoteEntryModel> convertedNotes = Arrays.asList(firstConvertedNote, secondConvertedNote);
|
||||
when(userNotesConverter.fromNotes(userNotes)).thenReturn(convertedNotes);
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(parameters);
|
||||
verify(channelService, times(1)).sendEmbedTemplateInChannel(eq(UserNotes.USER_NOTES_RESPONSE_TEMPLATE), captor.capture(), eq(parameters.getChannel()));
|
||||
ListNotesModel usedModel = captor.getValue();
|
||||
Assert.assertEquals(convertedNotes.size(), usedModel.getUserNotes().size());
|
||||
@@ -100,12 +101,12 @@ public class UserNotesTest {
|
||||
Assert.assertEquals(expectedEntry, usedEntry);
|
||||
}
|
||||
Assert.assertNull(usedModel.getSpecifiedUser());
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
|
||||
@Test(expected = IncorrectParameterException.class)
|
||||
public void testIncorrectParameterType() {
|
||||
CommandTestUtilities.executeWrongParametersTest(testUnit);
|
||||
CommandTestUtilities.executeWrongParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -4,7 +4,7 @@ import dev.sheldan.abstracto.core.command.exception.IncorrectParameterException;
|
||||
import dev.sheldan.abstracto.core.command.exception.InsufficientParametersException;
|
||||
import dev.sheldan.abstracto.core.command.execution.CommandContext;
|
||||
import dev.sheldan.abstracto.core.command.execution.CommandResult;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.WarnLog;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.WarnContext;
|
||||
import dev.sheldan.abstracto.moderation.service.WarnService;
|
||||
import dev.sheldan.abstracto.templating.service.TemplateService;
|
||||
import dev.sheldan.abstracto.test.command.CommandConfigValidator;
|
||||
@@ -17,6 +17,7 @@ import org.mockito.*;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@@ -34,7 +35,7 @@ public class WarnTest {
|
||||
private static final String DEFAULT_REASON = "defaultReason";
|
||||
|
||||
@Captor
|
||||
private ArgumentCaptor<WarnLog> parameterCaptor;
|
||||
private ArgumentCaptor<WarnContext> parameterCaptor;
|
||||
|
||||
@Test
|
||||
public void testExecuteWarnCommandWithReason() {
|
||||
@@ -42,13 +43,13 @@ public class WarnTest {
|
||||
String reason = "reason";
|
||||
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(warnedMember, reason));
|
||||
when(templateService.renderSimpleTemplate(Warn.WARN_DEFAULT_REASON_TEMPLATE)).thenReturn(DEFAULT_REASON);
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
verify(warnService, times(1)).warnUserWithLog(eq(warnedMember), eq(parameters.getAuthor()), eq(reason), parameterCaptor.capture(), eq(parameters.getChannel()));
|
||||
WarnLog value = parameterCaptor.getValue();
|
||||
when(warnService.warnUserWithLog(parameterCaptor.capture())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(parameters);
|
||||
WarnContext value = parameterCaptor.getValue();
|
||||
Assert.assertEquals(reason, value.getReason());
|
||||
Assert.assertEquals(warnedMember, value.getWarnedUser());
|
||||
Assert.assertEquals(parameters.getAuthor(), value.getWarningUser());
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
Assert.assertEquals(warnedMember, value.getWarnedMember());
|
||||
Assert.assertEquals(parameters.getAuthor(), value.getMember());
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -56,23 +57,23 @@ public class WarnTest {
|
||||
Member warnedMember = Mockito.mock(Member.class);
|
||||
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(warnedMember));
|
||||
when(templateService.renderSimpleTemplate(Warn.WARN_DEFAULT_REASON_TEMPLATE)).thenReturn(DEFAULT_REASON);
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
verify(warnService, times(1)).warnUserWithLog(eq(warnedMember), eq(parameters.getAuthor()), eq(DEFAULT_REASON), parameterCaptor.capture(), eq(parameters.getChannel()));
|
||||
WarnLog value = parameterCaptor.getValue();
|
||||
when(warnService.warnUserWithLog(parameterCaptor.capture())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(parameters);
|
||||
WarnContext value = parameterCaptor.getValue();
|
||||
Assert.assertEquals(DEFAULT_REASON, value.getReason());
|
||||
Assert.assertEquals(warnedMember, value.getWarnedUser());
|
||||
Assert.assertEquals(parameters.getAuthor(), value.getWarningUser());
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
Assert.assertEquals(warnedMember, value.getWarnedMember());
|
||||
Assert.assertEquals(parameters.getAuthor(), value.getMember());
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
|
||||
@Test(expected = InsufficientParametersException.class)
|
||||
public void testTooLittleParameters() {
|
||||
CommandTestUtilities.executeNoParametersTest(testUnit);
|
||||
CommandTestUtilities.executeNoParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
@Test(expected = IncorrectParameterException.class)
|
||||
public void testIncorrectParameterType() {
|
||||
CommandTestUtilities.executeWrongParametersTest(testUnit);
|
||||
CommandTestUtilities.executeWrongParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -4,7 +4,7 @@ import dev.sheldan.abstracto.core.command.exception.IncorrectParameterException;
|
||||
import dev.sheldan.abstracto.core.command.exception.InsufficientParametersException;
|
||||
import dev.sheldan.abstracto.core.command.execution.CommandContext;
|
||||
import dev.sheldan.abstracto.core.command.execution.CommandResult;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.MuteLog;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.MuteContext;
|
||||
import dev.sheldan.abstracto.moderation.service.MuteService;
|
||||
import dev.sheldan.abstracto.test.command.CommandConfigValidator;
|
||||
import dev.sheldan.abstracto.test.command.CommandTestUtilities;
|
||||
@@ -16,8 +16,8 @@ import org.mockito.*;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@@ -31,7 +31,7 @@ public class MuteTest {
|
||||
private MuteService muteService;
|
||||
|
||||
@Captor
|
||||
private ArgumentCaptor<MuteLog> muteLogArgumentCaptor;
|
||||
private ArgumentCaptor<MuteContext> muteLogArgumentCaptor;
|
||||
|
||||
@Test
|
||||
public void testMuteMember() {
|
||||
@@ -39,22 +39,22 @@ public class MuteTest {
|
||||
String reason = "reason";
|
||||
Duration duration = Duration.ofMinutes(1);
|
||||
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(mutedMember, duration, reason));
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
verify(muteService, times(1)).muteMemberWithLog(eq(mutedMember), eq(parameters.getAuthor()), eq(reason), any(Instant.class), muteLogArgumentCaptor.capture(), eq(parameters.getMessage()));
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
MuteLog muteLog = muteLogArgumentCaptor.getValue();
|
||||
when(muteService.muteMemberWithLog(muteLogArgumentCaptor.capture())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(parameters);
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
MuteContext muteLog = muteLogArgumentCaptor.getValue();
|
||||
Assert.assertEquals(mutedMember, muteLog.getMutedUser());
|
||||
Assert.assertEquals(parameters.getAuthor(), muteLog.getMutingUser());
|
||||
}
|
||||
|
||||
@Test(expected = InsufficientParametersException.class)
|
||||
public void testTooLittleParameters() {
|
||||
CommandTestUtilities.executeNoParametersTest(testUnit);
|
||||
CommandTestUtilities.executeNoParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
@Test(expected = IncorrectParameterException.class)
|
||||
public void testIncorrectParameterType() {
|
||||
CommandTestUtilities.executeWrongParametersTest(testUnit);
|
||||
CommandTestUtilities.executeWrongParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -4,15 +4,15 @@ import dev.sheldan.abstracto.core.command.exception.IncorrectParameterException;
|
||||
import dev.sheldan.abstracto.core.command.exception.InsufficientParametersException;
|
||||
import dev.sheldan.abstracto.core.command.execution.CommandContext;
|
||||
import dev.sheldan.abstracto.core.command.execution.CommandResult;
|
||||
import dev.sheldan.abstracto.core.command.execution.ResultState;
|
||||
import dev.sheldan.abstracto.moderation.models.database.Mute;
|
||||
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
|
||||
import dev.sheldan.abstracto.core.service.management.UserInServerManagementService;
|
||||
import dev.sheldan.abstracto.moderation.exception.NoMuteFoundException;
|
||||
import dev.sheldan.abstracto.moderation.service.MuteService;
|
||||
import dev.sheldan.abstracto.moderation.service.management.MuteManagementService;
|
||||
import dev.sheldan.abstracto.templating.service.TemplateService;
|
||||
import dev.sheldan.abstracto.test.command.CommandConfigValidator;
|
||||
import dev.sheldan.abstracto.test.command.CommandTestUtilities;
|
||||
import net.dv8tion.jda.api.entities.Member;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InjectMocks;
|
||||
@@ -21,6 +21,7 @@ import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@@ -42,38 +43,36 @@ public class UnMuteTest {
|
||||
@Mock
|
||||
private Member memberToUnMute;
|
||||
|
||||
@Mock
|
||||
private UserInServerManagementService userInServerManagementService;
|
||||
|
||||
@Test
|
||||
public void testUnMuteCommand() {
|
||||
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(memberToUnMute));
|
||||
when(muteManagementService.hasActiveMute(memberToUnMute)).thenReturn(true);
|
||||
Mute mute = Mute.builder().build();
|
||||
when(muteManagementService.getAMuteOf(memberToUnMute)).thenReturn(mute);
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
verify(muteService, times(1)).unMuteUser(mute);
|
||||
verify(muteService, times(1)).cancelUnMuteJob(mute);
|
||||
verify(muteService, times(1)).completelyUnMuteMember(memberToUnMute);
|
||||
CommandTestUtilities.checkSuccessfulCompletion(result);
|
||||
AUserInAServer user = AUserInAServer.builder().build();
|
||||
when(userInServerManagementService.loadUser(memberToUnMute)).thenReturn(user);
|
||||
when(muteService.unMuteUser(user)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
CompletableFuture<CommandResult> result = testUnit.executeAsync(parameters);
|
||||
CommandTestUtilities.checkSuccessfulCompletionAsync(result);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Test(expected = NoMuteFoundException.class)
|
||||
public void testUnMuteCommandWithoutExistingMute() {
|
||||
CommandContext parameters = CommandTestUtilities.getWithParameters(Arrays.asList(memberToUnMute));
|
||||
when(muteManagementService.hasActiveMute(memberToUnMute)).thenReturn(false);
|
||||
String message = "text";
|
||||
when(templateService.renderSimpleTemplate(UnMute.NO_ACTIVE_MUTE)).thenReturn(message);
|
||||
CommandResult result = testUnit.execute(parameters);
|
||||
Assert.assertEquals(ResultState.ERROR, result.getResult());
|
||||
Assert.assertEquals(message, result.getMessage());
|
||||
AUserInAServer user = AUserInAServer.builder().build();
|
||||
when(userInServerManagementService.loadUser(memberToUnMute)).thenReturn(user);
|
||||
when(muteService.unMuteUser(user)).thenThrow(new NoMuteFoundException());
|
||||
testUnit.executeAsync(parameters);
|
||||
}
|
||||
|
||||
@Test(expected = InsufficientParametersException.class)
|
||||
public void testTooLittleParameters() {
|
||||
CommandTestUtilities.executeNoParametersTest(testUnit);
|
||||
CommandTestUtilities.executeNoParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
@Test(expected = IncorrectParameterException.class)
|
||||
public void testIncorrectParameterType() {
|
||||
CommandTestUtilities.executeWrongParametersTest(testUnit);
|
||||
CommandTestUtilities.executeWrongParametersTestAsync(testUnit);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
@@ -18,6 +18,7 @@ import org.mockito.Mockito;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@@ -48,6 +49,7 @@ public class BanServiceBeanTest {
|
||||
when(memberToBan.getGuild()).thenReturn(mockedGuild);
|
||||
when(mockedGuild.getIdLong()).thenReturn(serverId);
|
||||
AuditableRestAction mockedAction = mock(AuditableRestAction.class);
|
||||
when(mockedAction.submit()).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(mockedGuild.ban(userId.toString(), 0, REASON)).thenReturn(mockedAction);
|
||||
MessageToSend mockedMessage = Mockito.mock(MessageToSend.class);
|
||||
when(templateService.renderEmbedTemplate(BanServiceBean.BAN_LOG_TEMPLATE, context)).thenReturn(mockedMessage);
|
||||
@@ -64,6 +66,7 @@ public class BanServiceBeanTest {
|
||||
ServerContext context = Mockito.mock(ServerContext.class);
|
||||
Guild mockedGuild = Mockito.mock(Guild.class);
|
||||
AuditableRestAction mockedAction = mock(AuditableRestAction.class);
|
||||
when(mockedAction.submit()).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(mockedGuild.ban(userId.toString(), 0, REASON)).thenReturn(mockedAction);
|
||||
MessageToSend mockedMessage = Mockito.mock(MessageToSend.class);
|
||||
when(templateService.renderEmbedTemplate(BanServiceBean.BAN_ID_LOG_TEMPLATE, context)).thenReturn(mockedMessage);
|
||||
|
||||
@@ -7,6 +7,7 @@ import dev.sheldan.abstracto.moderation.models.template.commands.KickLogModel;
|
||||
import dev.sheldan.abstracto.templating.model.MessageToSend;
|
||||
import dev.sheldan.abstracto.templating.service.TemplateService;
|
||||
import dev.sheldan.abstracto.test.MockUtils;
|
||||
import dev.sheldan.abstracto.test.command.CommandTestUtilities;
|
||||
import net.dv8tion.jda.api.entities.Guild;
|
||||
import net.dv8tion.jda.api.entities.Member;
|
||||
import net.dv8tion.jda.api.entities.User;
|
||||
@@ -18,6 +19,8 @@ import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
@@ -40,16 +43,17 @@ public class KickServiceBeanTest {
|
||||
when(member.getUser()).thenReturn(user);
|
||||
when(user.getIdLong()).thenReturn(6L);
|
||||
Guild mockedGuild = Mockito.mock(Guild.class);
|
||||
when(mockedGuild.getIdLong()).thenReturn(server.getId());
|
||||
when(member.getGuild()).thenReturn(mockedGuild);
|
||||
AuditableRestAction<Void> mockedAction = Mockito.mock(AuditableRestAction.class);
|
||||
String reason = "reason";
|
||||
AuditableRestAction<Void> mockedAction = Mockito.mock(AuditableRestAction.class);
|
||||
when(mockedGuild.kick(member, reason)).thenReturn(mockedAction);
|
||||
when(mockedAction.submit()).thenReturn(CompletableFuture.completedFuture(null));
|
||||
KickLogModel model = Mockito.mock(KickLogModel.class);
|
||||
when(model.getServer()).thenReturn(server);
|
||||
when(model.getGuild()).thenReturn(mockedGuild);
|
||||
MessageToSend messageToSend = Mockito.mock(MessageToSend.class);
|
||||
when(templateService.renderEmbedTemplate(KickServiceBean.KICK_LOG_TEMPLATE, model)).thenReturn(messageToSend);
|
||||
when(postTargetService.sendEmbedInPostTarget(messageToSend, ModerationPostTarget.KICK_LOG, server.getId())).thenReturn(CommandTestUtilities.messageFutureList());
|
||||
testUnit.kickMember(member, reason, model);
|
||||
verify(mockedGuild, times(1)).kick(member, reason);
|
||||
verify(postTargetService, times(1)).sendEmbedInPostTarget(messageToSend, ModerationPostTarget.KICK_LOG, server.getId());
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,22 @@
|
||||
package dev.sheldan.abstracto.moderation.service;
|
||||
|
||||
import dev.sheldan.abstracto.core.models.AServerAChannelMessage;
|
||||
import dev.sheldan.abstracto.core.models.FullUserInServer;
|
||||
import dev.sheldan.abstracto.core.models.ServerChannelMessage;
|
||||
import dev.sheldan.abstracto.core.models.ServerSpecificId;
|
||||
import dev.sheldan.abstracto.core.models.database.AChannel;
|
||||
import dev.sheldan.abstracto.core.models.database.ARole;
|
||||
import dev.sheldan.abstracto.core.models.database.AServer;
|
||||
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
|
||||
import dev.sheldan.abstracto.core.service.BotService;
|
||||
import dev.sheldan.abstracto.core.service.MessageService;
|
||||
import dev.sheldan.abstracto.core.service.PostTargetService;
|
||||
import dev.sheldan.abstracto.core.service.RoleService;
|
||||
import dev.sheldan.abstracto.core.service.*;
|
||||
import dev.sheldan.abstracto.core.service.management.ChannelManagementService;
|
||||
import dev.sheldan.abstracto.core.service.management.ServerManagementService;
|
||||
import dev.sheldan.abstracto.core.service.management.UserInServerManagementService;
|
||||
import dev.sheldan.abstracto.moderation.config.posttargets.MutingPostTarget;
|
||||
import dev.sheldan.abstracto.moderation.exception.MuteRoleNotSetupException;
|
||||
import dev.sheldan.abstracto.moderation.exception.NoMuteFoundException;
|
||||
import dev.sheldan.abstracto.moderation.models.database.Mute;
|
||||
import dev.sheldan.abstracto.moderation.models.database.MuteRole;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.MuteLog;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.MuteContext;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.MuteNotification;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.UnMuteLog;
|
||||
import dev.sheldan.abstracto.moderation.service.management.MuteManagementService;
|
||||
@@ -25,6 +25,7 @@ import dev.sheldan.abstracto.scheduling.service.SchedulerService;
|
||||
import dev.sheldan.abstracto.templating.model.MessageToSend;
|
||||
import dev.sheldan.abstracto.templating.service.TemplateService;
|
||||
import dev.sheldan.abstracto.test.MockUtils;
|
||||
import dev.sheldan.abstracto.test.command.CommandTestUtilities;
|
||||
import net.dv8tion.jda.api.entities.*;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
@@ -33,20 +34,19 @@ import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.quartz.JobDataMap;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
|
||||
import static dev.sheldan.abstracto.moderation.service.MuteServiceBean.MUTE_NOTIFICATION_TEMPLATE;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class MuteServiceBeanTest {
|
||||
|
||||
@InjectMocks
|
||||
private MuteServiceBean testUnit;
|
||||
|
||||
@@ -78,7 +78,7 @@ public class MuteServiceBeanTest {
|
||||
private PostTargetService postTargetService;
|
||||
|
||||
@Mock
|
||||
private MuteService self;
|
||||
private MuteServiceBean self;
|
||||
|
||||
@Mock
|
||||
private ScheduledExecutorService executorService;
|
||||
@@ -111,7 +111,7 @@ public class MuteServiceBeanTest {
|
||||
private MessageChannel channel;
|
||||
|
||||
@Mock
|
||||
private Message cause;
|
||||
private ServerChannelMessage cause;
|
||||
|
||||
@Mock
|
||||
private Guild guild;
|
||||
@@ -125,11 +125,21 @@ public class MuteServiceBeanTest {
|
||||
@Mock
|
||||
private MessageToSend messageToSend;
|
||||
|
||||
private static final Long CHANNEL_ID = 8L;
|
||||
@Mock
|
||||
private Mute mute;
|
||||
|
||||
@Mock
|
||||
private ServerManagementService serverManagementService;
|
||||
|
||||
@Mock
|
||||
private CounterService counterService;
|
||||
|
||||
private static final Long CHANNEL_ID = 8L;
|
||||
private static final String REASON = "reason";
|
||||
private static final String NOTIFICATION_TEXT = "text";
|
||||
private static final String TRIGGER = "trigger";
|
||||
public static final long MUTE_ID = 6L;
|
||||
public static final long SERVER_ID = 7L;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
@@ -142,7 +152,7 @@ public class MuteServiceBeanTest {
|
||||
memberMuting = Mockito.mock(Member.class);
|
||||
memberBeingMuted = Mockito.mock(Member.class);
|
||||
channel = Mockito.mock(MessageChannel.class);
|
||||
cause = Mockito.mock(Message.class);
|
||||
cause = Mockito.mock(ServerChannelMessage.class);
|
||||
aRole = ARole.builder().build();
|
||||
muteRole = MuteRole.builder().role(aRole).build();
|
||||
messageToSend = Mockito.mock(MessageToSend.class);
|
||||
@@ -155,12 +165,15 @@ public class MuteServiceBeanTest {
|
||||
when(memberBeingMuted.getUser()).thenReturn(jdaUserBeingMuted);
|
||||
FullUserInServer mutedUser = FullUserInServer.builder().member(memberBeingMuted).aUserInAServer(userBeingMuted).build();
|
||||
FullUserInServer mutingUser = FullUserInServer.builder().member(memberMuting).aUserInAServer(userMuting).build();
|
||||
setupShortMute(unMuteDate);
|
||||
when(schedulerService.executeJobWithParametersOnce(eq("unMuteJob"), eq("moderation"), any(JobDataMap.class), eq(Date.from(unMuteDate)))).thenReturn(TRIGGER);
|
||||
testUnit.muteUser(mutedUser, mutingUser, REASON, unMuteDate, cause);
|
||||
verify(messageService, times(1)).sendMessageToUser(jdaUserBeingMuted, NOTIFICATION_TEXT, channel);
|
||||
verify(muteManagementService, times(1)).saveMute(any(Mute.class));
|
||||
verify(roleService, times(1)).addRoleToUser(userBeingMuted, aRole);
|
||||
when(memberBeingMuted.getGuild()).thenReturn(guild);
|
||||
when(memberBeingMuted.getUser()).thenReturn(jdaUserBeingMuted);
|
||||
when(muteRoleManagementService.muteRoleForServerExists(server)).thenReturn(true);
|
||||
when(muteRoleManagementService.retrieveMuteRoleForServer(server)).thenReturn(muteRole);
|
||||
when(templateService.renderTemplate(eq(MUTE_NOTIFICATION_TEMPLATE), any(MuteNotification.class))).thenReturn(NOTIFICATION_TEXT);
|
||||
|
||||
when(messageService.sendMessageToUser(jdaUserBeingMuted, NOTIFICATION_TEXT)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(roleService.addRoleToUserFuture(userBeingMuted, aRole)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
testUnit.muteUserInServer(mutedUser, mutingUser, REASON, unMuteDate, cause);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -170,8 +183,16 @@ public class MuteServiceBeanTest {
|
||||
FullUserInServer mutedUser = FullUserInServer.builder().member(memberBeingMuted).aUserInAServer(userBeingMuted).build();
|
||||
FullUserInServer mutingUser = FullUserInServer.builder().member(memberMuting).aUserInAServer(userMuting).build();
|
||||
Instant unMuteDate = shorterMute();
|
||||
setupShortMute(unMuteDate);
|
||||
testUnit.muteUser(mutedUser, mutingUser, REASON, unMuteDate, cause);
|
||||
when(memberBeingMuted.getGuild()).thenReturn(guild);
|
||||
when(memberBeingMuted.getUser()).thenReturn(jdaUserBeingMuted);
|
||||
when(muteRoleManagementService.muteRoleForServerExists(server)).thenReturn(true);
|
||||
when(muteRoleManagementService.retrieveMuteRoleForServer(server)).thenReturn(muteRole);
|
||||
|
||||
String notificationText = "text";
|
||||
when(templateService.renderTemplate(eq(MUTE_NOTIFICATION_TEMPLATE), any(MuteNotification.class))).thenReturn(notificationText);
|
||||
when(messageService.sendMessageToUser(memberBeingMuted.getUser(), notificationText)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(roleService.addRoleToUserFuture(userBeingMuted, muteRole.getRole())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
testUnit.muteUserInServer(mutedUser, mutingUser, REASON, unMuteDate, cause);
|
||||
verifyDirectMute();
|
||||
}
|
||||
|
||||
@@ -179,19 +200,18 @@ public class MuteServiceBeanTest {
|
||||
public void testMuteUserWithoutMuteRole() {
|
||||
FullUserInServer mutedUser = FullUserInServer.builder().aUserInAServer(userBeingMuted).build();
|
||||
when(muteRoleManagementService.muteRoleForServerExists(server)).thenReturn(false);
|
||||
testUnit.muteUser(mutedUser, FullUserInServer.builder().build(), REASON, longerMute(), Mockito.mock(Message.class));
|
||||
testUnit.muteUserInServer(mutedUser, FullUserInServer.builder().build(), REASON, longerMute(), Mockito.mock(ServerChannelMessage.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCancelUnMuteJob() {
|
||||
Mute mute = Mute.builder().triggerKey(TRIGGER).build();
|
||||
when(mute.getTriggerKey()).thenReturn(TRIGGER);
|
||||
testUnit.cancelUnMuteJob(mute);
|
||||
verify(schedulerService, times(1)).stopTrigger(TRIGGER);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCancelNotExistingJob() {
|
||||
Mute mute = Mute.builder().build();
|
||||
testUnit.cancelUnMuteJob(mute);
|
||||
verify(schedulerService, times(0)).stopTrigger(anyString());
|
||||
}
|
||||
@@ -201,7 +221,15 @@ public class MuteServiceBeanTest {
|
||||
when(userInServerManagementService.loadUser(memberBeingMuted)).thenReturn(userBeingMuted);
|
||||
when(userInServerManagementService.loadUser(memberMuting)).thenReturn(userMuting);
|
||||
Instant unMuteDate = shorterMute();
|
||||
setupShortMute(unMuteDate);
|
||||
when(memberBeingMuted.getGuild()).thenReturn(guild);
|
||||
when(memberBeingMuted.getUser()).thenReturn(jdaUserBeingMuted);
|
||||
when(muteRoleManagementService.muteRoleForServerExists(server)).thenReturn(true);
|
||||
when(muteRoleManagementService.retrieveMuteRoleForServer(server)).thenReturn(muteRole);
|
||||
|
||||
String notificationText = "text";
|
||||
when(templateService.renderTemplate(eq(MUTE_NOTIFICATION_TEMPLATE), any(MuteNotification.class))).thenReturn(notificationText);
|
||||
when(messageService.sendMessageToUser(memberBeingMuted.getUser(), notificationText)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(roleService.addRoleToUserFuture(userBeingMuted, muteRole.getRole())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
testUnit.muteMember(memberBeingMuted, memberMuting, REASON, unMuteDate, cause);
|
||||
verifyDirectMute();
|
||||
}
|
||||
@@ -211,7 +239,15 @@ public class MuteServiceBeanTest {
|
||||
when(botService.getMemberInServer(userBeingMuted)).thenReturn(memberBeingMuted);
|
||||
when(botService.getMemberInServer(userMuting)).thenReturn(memberMuting);
|
||||
Instant unMuteDate = shorterMute();
|
||||
setupShortMute(unMuteDate);
|
||||
when(memberBeingMuted.getGuild()).thenReturn(guild);
|
||||
when(memberBeingMuted.getUser()).thenReturn(jdaUserBeingMuted);
|
||||
when(muteRoleManagementService.muteRoleForServerExists(server)).thenReturn(true);
|
||||
when(muteRoleManagementService.retrieveMuteRoleForServer(server)).thenReturn(muteRole);
|
||||
|
||||
String notificationText = "text";
|
||||
when(templateService.renderTemplate(eq(MUTE_NOTIFICATION_TEMPLATE), any(MuteNotification.class))).thenReturn(notificationText);
|
||||
when(messageService.sendMessageToUser(memberBeingMuted.getUser(), notificationText)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(roleService.addRoleToUserFuture(userBeingMuted, muteRole.getRole())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
testUnit.muteAUserInAServer(userBeingMuted, userMuting, REASON, unMuteDate, cause);
|
||||
verifyDirectMute();
|
||||
}
|
||||
@@ -221,53 +257,63 @@ public class MuteServiceBeanTest {
|
||||
when(userInServerManagementService.loadUser(memberBeingMuted)).thenReturn(userBeingMuted);
|
||||
when(userInServerManagementService.loadUser(memberMuting)).thenReturn(userMuting);
|
||||
Instant unMuteDate = shorterMute();
|
||||
setupShortMute(unMuteDate);
|
||||
MuteLog muteLog = MuteLog.builder().server(server).build();
|
||||
when(templateService.renderEmbedTemplate(eq(MuteServiceBean.MUTE_LOG_TEMPLATE), any(MuteLog.class))).thenReturn(messageToSend);
|
||||
testUnit.muteMemberWithLog(memberBeingMuted, memberMuting, REASON, unMuteDate, muteLog, cause);
|
||||
when(memberBeingMuted.getGuild()).thenReturn(guild);
|
||||
when(memberBeingMuted.getUser()).thenReturn(jdaUserBeingMuted);
|
||||
when(muteRoleManagementService.muteRoleForServerExists(server)).thenReturn(true);
|
||||
when(muteRoleManagementService.retrieveMuteRoleForServer(server)).thenReturn(muteRole);
|
||||
|
||||
ServerChannelMessage serverChannelMessage = Mockito.mock(ServerChannelMessage.class);
|
||||
when(serverChannelMessage.getServerId()).thenReturn(SERVER_ID);
|
||||
MuteContext muteLog = Mockito.mock(MuteContext.class);
|
||||
when(muteLog.getMutedUser()).thenReturn(memberBeingMuted);
|
||||
when(muteLog.getMutingUser()).thenReturn(memberMuting);
|
||||
when(muteLog.getContext()).thenReturn(serverChannelMessage);
|
||||
when(muteLog.getMuteTargetDate()).thenReturn(unMuteDate);
|
||||
String notificationText = "text";
|
||||
when(templateService.renderTemplate(eq(MUTE_NOTIFICATION_TEMPLATE), any(MuteNotification.class))).thenReturn(notificationText);
|
||||
when(messageService.sendMessageToUser(memberBeingMuted.getUser(), notificationText)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(templateService.renderEmbedTemplate(eq(MuteServiceBean.MUTE_LOG_TEMPLATE), any(MuteContext.class))).thenReturn(messageToSend);
|
||||
when(roleService.addRoleToUserFuture(userBeingMuted, muteRole.getRole())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
testUnit.muteMemberWithLog(muteLog);
|
||||
verifyDirectMute();
|
||||
verify(templateService, times(1)).renderEmbedTemplate(eq(MuteServiceBean.MUTE_LOG_TEMPLATE), any(MuteLog.class));
|
||||
verify(postTargetService, times(1)).sendEmbedInPostTarget(messageToSend, MutingPostTarget.MUTE_LOG, server.getId());
|
||||
verify(templateService, times(1)).renderEmbedTemplate(eq(MuteServiceBean.MUTE_LOG_TEMPLATE), any(MuteContext.class));
|
||||
verify(postTargetService, times(1)).sendEmbedInPostTarget(messageToSend, MutingPostTarget.MUTE_LOG, SERVER_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUnMuteMemberWhoseMuteEnded() {
|
||||
Mute mute = Mockito.mock(Mute.class);
|
||||
when(mute.getMuteEnded()).thenReturn(true);
|
||||
when(mute.getMutedUser()).thenReturn(userBeingMuted);
|
||||
testUnit.unMuteUser(mute);
|
||||
when(muteManagementService.getAMuteOf(userBeingMuted)).thenReturn(mute);
|
||||
when(mute.getMuteId()).thenReturn(new ServerSpecificId(SERVER_ID, MUTE_ID));
|
||||
testUnit.unMuteUser(userBeingMuted);
|
||||
verifyNoUnMuteHappened();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEndMute() {
|
||||
Long muteId = 6L;
|
||||
setupUnMuteMocks(true);
|
||||
Mute mute = Mockito.mock(Mute.class);
|
||||
when(mute.getMuteEnded()).thenReturn(false);
|
||||
when(mute.getMutedUser()).thenReturn(userBeingMuted);
|
||||
when(mute.getMutingServer()).thenReturn(server);
|
||||
when(muteManagementService.findMute(muteId)).thenReturn(Optional.of(mute));
|
||||
testUnit.endMute(muteId);
|
||||
verifyUnMute(1);
|
||||
when(mute.getServer()).thenReturn(server);
|
||||
when(muteManagementService.findMute(MUTE_ID, SERVER_ID)).thenReturn(Optional.of(mute));
|
||||
when(roleService.removeRoleFromUserFuture(userBeingMuted, aRole)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
testUnit.endMute(MUTE_ID, SERVER_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Test(expected = NoMuteFoundException.class)
|
||||
public void testEndNonExistingMute() {
|
||||
Long muteId = 6L;
|
||||
when(muteManagementService.findMute(muteId)).thenReturn(Optional.empty());
|
||||
testUnit.endMute(muteId);
|
||||
verifyNoUnMuteHappened();
|
||||
when(muteManagementService.findMute(MUTE_ID, SERVER_ID)).thenReturn(Optional.empty());
|
||||
testUnit.endMute(MUTE_ID, SERVER_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUnMuteMemberInGuild() {
|
||||
executeUnMuteWithLogTest(true, 1);
|
||||
executeUnMuteWithLogTest(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUnMuteMemberWhoLeftGuild() {
|
||||
executeUnMuteWithLogTest(false, 0);
|
||||
executeUnMuteWithLogTest(false);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -279,7 +325,6 @@ public class MuteServiceBeanTest {
|
||||
|
||||
@Test
|
||||
public void testCompletelyUnMuteNotScheduledMuteUser() {
|
||||
Mute mute = Mockito.mock(Mute.class);
|
||||
when(muteManagementService.getAllMutesOf(userBeingMuted)).thenReturn(Arrays.asList(mute));
|
||||
testUnit.completelyUnMuteUser(userBeingMuted);
|
||||
verify(muteManagementService, times(1)).saveMute(any(Mute.class));
|
||||
@@ -288,7 +333,6 @@ public class MuteServiceBeanTest {
|
||||
|
||||
@Test
|
||||
public void testCompletelyUnMuteScheduledMuteUser() {
|
||||
Mute mute = Mockito.mock(Mute.class);
|
||||
when(mute.getTriggerKey()).thenReturn(TRIGGER);
|
||||
when(muteManagementService.getAllMutesOf(userBeingMuted)).thenReturn(Arrays.asList(mute));
|
||||
testUnit.completelyUnMuteUser(userBeingMuted);
|
||||
@@ -298,7 +342,6 @@ public class MuteServiceBeanTest {
|
||||
|
||||
@Test
|
||||
public void testCompletelyUnMuteMember() {
|
||||
Mute mute = Mockito.mock(Mute.class);
|
||||
when(mute.getTriggerKey()).thenReturn(TRIGGER);
|
||||
when(muteManagementService.getAllMutesOf(userBeingMuted)).thenReturn(Arrays.asList(mute));
|
||||
when(userInServerManagementService.loadUser(memberBeingMuted)).thenReturn(userBeingMuted);
|
||||
@@ -307,24 +350,40 @@ public class MuteServiceBeanTest {
|
||||
verify(schedulerService, times(1)).stopTrigger(TRIGGER);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void verifyScheduling() {
|
||||
Instant unMuteDate = shorterMute();
|
||||
MuteContext muteLog = Mockito.mock(MuteContext.class);
|
||||
when(muteLog.getMuteTargetDate()).thenReturn(unMuteDate);
|
||||
when(muteLog.getMuteId()).thenReturn(MUTE_ID);
|
||||
ServerChannelMessage serverContext = Mockito.mock(ServerChannelMessage.class);
|
||||
when(serverContext.getServerId()).thenReturn(SERVER_ID);
|
||||
when(serverContext.getChannelId()).thenReturn(CHANNEL_ID);
|
||||
when(channelManagementService.loadChannel(CHANNEL_ID)).thenReturn(aChannel);
|
||||
when(muteLog.getContext()).thenReturn(serverContext);
|
||||
testUnit.persistMute(muteLog);
|
||||
verify(executorService, times(1)).schedule(any(Runnable.class), anyLong(), any());
|
||||
}
|
||||
|
||||
private void verifyNoUnMuteHappened() {
|
||||
verify(muteManagementService, times(0)).saveMute(any(Mute.class));
|
||||
verify(roleService, times(0)).removeRoleFromUser(eq(userBeingMuted), any(ARole.class));
|
||||
verify(postTargetService, times(0)).sendEmbedInPostTarget(any(MessageToSend.class), eq(MutingPostTarget.MUTE_LOG), eq(server.getId()));
|
||||
}
|
||||
|
||||
private void executeUnMuteWithLogTest(boolean stillInGuild, int roleRemovals) {
|
||||
Mute mute = Mockito.mock(Mute.class);
|
||||
private void executeUnMuteWithLogTest(boolean stillInGuild) {
|
||||
when(mute.getMutedUser()).thenReturn(userBeingMuted);
|
||||
when(mute.getMutingServer()).thenReturn(server);
|
||||
when(mute.getServer()).thenReturn(server);
|
||||
setupUnMuteMocks(stillInGuild);
|
||||
when(roleService.removeRoleFromUserFuture(userBeingMuted, aRole)).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(postTargetService.sendEmbedInPostTarget(messageToSend, MutingPostTarget.MUTE_LOG, server.getId())).thenReturn(CommandTestUtilities.messageFutureList());
|
||||
testUnit.unMuteUser(userBeingMuted);
|
||||
|
||||
testUnit.unMuteUser(mute);
|
||||
|
||||
verifyUnMute(roleRemovals);
|
||||
}
|
||||
|
||||
private void setupUnMuteMocks(boolean stillInGuild) {
|
||||
when(mute.getMuteId()).thenReturn(new ServerSpecificId(SERVER_ID, MUTE_ID));
|
||||
when(muteManagementService.getAMuteOf(userBeingMuted)).thenReturn(mute);
|
||||
when(muteRoleManagementService.retrieveMuteRoleForServer(server)).thenReturn(muteRole);
|
||||
when(botService.getGuildByIdNullable(server.getId())).thenReturn(guild);
|
||||
when(botService.isUserInGuild(guild, userBeingMuted)).thenReturn(stillInGuild);
|
||||
@@ -332,32 +391,8 @@ public class MuteServiceBeanTest {
|
||||
when(templateService.renderEmbedTemplate(eq(MuteServiceBean.UN_MUTE_LOG_TEMPLATE), any(UnMuteLog.class))).thenReturn(messageToSend);
|
||||
}
|
||||
|
||||
private void verifyUnMute(int roleRemovals) {
|
||||
verify(muteManagementService, times(1)).saveMute(any(Mute.class));
|
||||
verify(roleService, times(roleRemovals)).removeRoleFromUser(userBeingMuted, aRole);
|
||||
verify(postTargetService, times(1)).sendEmbedInPostTarget(messageToSend, MutingPostTarget.MUTE_LOG, server.getId());
|
||||
}
|
||||
|
||||
private void setupShortMute(Instant unMuteDate) {
|
||||
Long muteId = 12L;
|
||||
when(memberBeingMuted.getGuild()).thenReturn(guild);
|
||||
when(memberBeingMuted.getUser()).thenReturn(jdaUserBeingMuted);
|
||||
when(channel.getIdLong()).thenReturn(CHANNEL_ID);
|
||||
when(cause.getGuild()).thenReturn(guild);
|
||||
when(cause.getChannel()).thenReturn(channel);
|
||||
when(muteRoleManagementService.muteRoleForServerExists(server)).thenReturn(true);
|
||||
when(muteRoleManagementService.retrieveMuteRoleForServer(server)).thenReturn(muteRole);
|
||||
when(channelManagementService.loadChannel(CHANNEL_ID)).thenReturn(aChannel);
|
||||
Mute createdMute = Mute.builder().id(muteId).build();
|
||||
when(muteManagementService.createMute(eq(userBeingMuted), eq(userMuting), eq(REASON), eq(unMuteDate), any(AServerAChannelMessage.class))).thenReturn(createdMute);
|
||||
when(templateService.renderTemplate(eq(MuteServiceBean.MUTE_NOTIFICATION_TEMPLATE), any(MuteNotification.class))).thenReturn(NOTIFICATION_TEXT);
|
||||
}
|
||||
|
||||
private void verifyDirectMute() {
|
||||
verify(messageService, times(1)).sendMessageToUser(jdaUserBeingMuted, NOTIFICATION_TEXT, channel);
|
||||
verify(muteManagementService, times(1)).saveMute(any(Mute.class));
|
||||
verify(roleService, times(1)).addRoleToUser(userBeingMuted, aRole);
|
||||
verify(executorService, times(1)).schedule(any(Runnable.class), anyLong(), any());
|
||||
verify(messageService, times(1)).sendMessageToUser(jdaUserBeingMuted, NOTIFICATION_TEXT);
|
||||
}
|
||||
|
||||
private Instant longerMute() {
|
||||
|
||||
@@ -1,31 +1,26 @@
|
||||
package dev.sheldan.abstracto.moderation.service;
|
||||
|
||||
import dev.sheldan.abstracto.core.models.FullUserInServer;
|
||||
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.core.service.BotService;
|
||||
import dev.sheldan.abstracto.core.service.ConfigService;
|
||||
import dev.sheldan.abstracto.core.service.MessageService;
|
||||
import dev.sheldan.abstracto.core.service.PostTargetService;
|
||||
import dev.sheldan.abstracto.core.service.management.UserInServerManagementService;
|
||||
import dev.sheldan.abstracto.core.service.*;
|
||||
import dev.sheldan.abstracto.core.service.management.ServerManagementService;
|
||||
import dev.sheldan.abstracto.moderation.config.features.WarningDecayFeature;
|
||||
import dev.sheldan.abstracto.moderation.config.posttargets.WarnDecayPostTarget;
|
||||
import dev.sheldan.abstracto.moderation.config.posttargets.WarningPostTarget;
|
||||
import dev.sheldan.abstracto.moderation.models.database.Warning;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.WarnLog;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.WarnContext;
|
||||
import dev.sheldan.abstracto.moderation.models.template.commands.WarnNotification;
|
||||
import dev.sheldan.abstracto.moderation.models.template.job.WarnDecayLogModel;
|
||||
import dev.sheldan.abstracto.moderation.models.template.job.WarnDecayWarning;
|
||||
import dev.sheldan.abstracto.moderation.service.management.WarnManagementService;
|
||||
import dev.sheldan.abstracto.templating.model.MessageToSend;
|
||||
import dev.sheldan.abstracto.templating.service.TemplateService;
|
||||
import dev.sheldan.abstracto.test.MockUtils;
|
||||
import dev.sheldan.abstracto.test.command.CommandTestUtilities;
|
||||
import net.dv8tion.jda.api.entities.Guild;
|
||||
import net.dv8tion.jda.api.entities.Member;
|
||||
import net.dv8tion.jda.api.entities.MessageChannel;
|
||||
import net.dv8tion.jda.api.entities.User;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.*;
|
||||
@@ -35,18 +30,18 @@ import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
|
||||
import static dev.sheldan.abstracto.moderation.service.WarnServiceBean.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class WarnServiceBeanTest {
|
||||
|
||||
public static final long WARN_ID = 8L;
|
||||
@InjectMocks
|
||||
private WarnServiceBean testUnit;
|
||||
|
||||
@Mock
|
||||
private UserInServerManagementService userInServerManagementService;
|
||||
|
||||
@Mock
|
||||
private WarnManagementService warnManagementService;
|
||||
|
||||
@@ -59,9 +54,6 @@ public class WarnServiceBeanTest {
|
||||
@Mock
|
||||
private BotService botService;
|
||||
|
||||
@Mock
|
||||
private MessageService messageService;
|
||||
|
||||
@Mock
|
||||
private ConfigService configService;
|
||||
|
||||
@@ -81,10 +73,10 @@ public class WarnServiceBeanTest {
|
||||
private MessageToSend messageToSend;
|
||||
|
||||
@Mock
|
||||
private MessageChannel feedBackChannel;
|
||||
private User warnedSimpleUser;
|
||||
|
||||
@Mock
|
||||
private User warnedSimpleUser;
|
||||
private WarnContext context;
|
||||
|
||||
@Captor
|
||||
private ArgumentCaptor<WarnDecayLogModel> warnDecayLogModelArgumentCaptor;
|
||||
@@ -92,38 +84,43 @@ public class WarnServiceBeanTest {
|
||||
@Captor
|
||||
private ArgumentCaptor<WarnNotification> notificationCaptor;
|
||||
|
||||
@Mock
|
||||
private AServer server;
|
||||
|
||||
@Mock
|
||||
private AUserInAServer warningUser;
|
||||
|
||||
@Mock
|
||||
private AUserInAServer firstWarnedUser;
|
||||
|
||||
@Mock
|
||||
private AUserInAServer secondWarnedUser;
|
||||
|
||||
@Mock
|
||||
private Warning firstWarning;
|
||||
|
||||
@Mock
|
||||
private Warning secondWarning;
|
||||
private static final String REASON = "reason";
|
||||
|
||||
@Mock
|
||||
private ServerManagementService serverManagementService;
|
||||
|
||||
@Mock
|
||||
private CounterService counterService;
|
||||
|
||||
@Mock
|
||||
private MessageService messageService;
|
||||
|
||||
private static final String NOTIFICATION_TEXT = "text";
|
||||
private static final String GUILD_NAME = "guild";
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
server = MockUtils.getServer();
|
||||
warningUser = MockUtils.getUserObject(8L, server);
|
||||
firstWarnedUser = MockUtils.getUserObject(5L, server);
|
||||
firstWarning = getDefaultWarning();
|
||||
firstWarning.setWarningUser(warningUser);
|
||||
firstWarning.setWarnedUser(firstWarnedUser);
|
||||
|
||||
secondWarnedUser = MockUtils.getUserObject(7L, server);
|
||||
secondWarning = getDefaultWarning();
|
||||
secondWarning.setWarnedUser(secondWarnedUser);
|
||||
secondWarning.setWarningUser(warningUser);
|
||||
}
|
||||
private static final Long SERVER_ID = 4L;
|
||||
|
||||
@Test
|
||||
public void testDecayWarning() {
|
||||
Warning warning = getDefaultWarning();
|
||||
Instant date = Instant.now();
|
||||
testUnit.decayWarning(warning, date);
|
||||
Assert.assertTrue(warning.getDecayed());
|
||||
Assert.assertEquals(date, warning.getDecayDate());
|
||||
testUnit.decayWarning(firstWarning, date);
|
||||
verify(firstWarning, times(1)).setDecayed(true);
|
||||
verify(firstWarning, times(1)).setDecayDate(date);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -151,7 +148,7 @@ public class WarnServiceBeanTest {
|
||||
public void testDecayAllWarningsWithoutWarnings() {
|
||||
List<Warning> warnings = Collections.emptyList();
|
||||
when(botService.getGuildByIdNullable(server.getId())).thenReturn(guild);
|
||||
when(templateService.renderEmbedTemplate(eq("warn_decay_log"), warnDecayLogModelArgumentCaptor.capture())).thenReturn(messageToSend);
|
||||
when(templateService.renderEmbedTemplate(eq(WARN_DECAY_LOG_TEMPLATE_KEY), warnDecayLogModelArgumentCaptor.capture())).thenReturn(messageToSend);
|
||||
when(warnManagementService.getActiveWarningsInServerOlderThan(eq(server), any(Instant.class))).thenReturn(warnings);
|
||||
testUnit.decayAllWarningsForServer(server, true);
|
||||
verify(postTargetService, times(1)).sendEmbedInPostTarget(messageToSend, WarnDecayPostTarget.DECAY_LOG, server.getId());
|
||||
@@ -162,57 +159,42 @@ public class WarnServiceBeanTest {
|
||||
|
||||
@Test
|
||||
public void testWarnFullUser() {
|
||||
setupWarnContext();
|
||||
setupMocksForWarning();
|
||||
FullUserInServer warnedFullUser = FullUserInServer.builder().member(warnedMember).aUserInAServer(firstWarnedUser).build();
|
||||
FullUserInServer warningFullUser = FullUserInServer.builder().member(warningMember).aUserInAServer(warningUser).build();
|
||||
Warning warning = testUnit.warnFullUser(warnedFullUser, warningFullUser, REASON, feedBackChannel);
|
||||
verifyWarning(warning);
|
||||
testUnit.notifyAndLogFullUserWarning(context);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWarnUser() {
|
||||
setupMocksForWarning();
|
||||
when(botService.getMemberInServer(firstWarnedUser)).thenReturn(warnedMember);
|
||||
when(botService.getMemberInServer(warningUser)).thenReturn(warningMember);
|
||||
Warning warning = testUnit.warnUser(firstWarnedUser, warningUser, REASON, feedBackChannel);
|
||||
verifyWarning(warning);
|
||||
private void setupWarnContext() {
|
||||
when(guild.getIdLong()).thenReturn(SERVER_ID);
|
||||
when(context.getGuild()).thenReturn(guild);
|
||||
when(context.getWarnedMember()).thenReturn(warnedMember);
|
||||
when(context.getMember()).thenReturn(warningMember);
|
||||
when(counterService.getNextCounterValue(server, WARNINGS_COUNTER_KEY)).thenReturn(WARN_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWarnMember() {
|
||||
setupMocksForWarning();
|
||||
when(userInServerManagementService.loadUser(warnedMember)).thenReturn(firstWarnedUser);
|
||||
when(userInServerManagementService.loadUser(warningMember)).thenReturn(warningUser);
|
||||
Warning warning = testUnit.warnMember(warnedMember, warningMember, REASON, feedBackChannel);
|
||||
verifyWarning(warning);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWarnUserWithLog() {
|
||||
setupMocksForWarning();
|
||||
when(userInServerManagementService.loadUser(warnedMember)).thenReturn(firstWarnedUser);
|
||||
when(userInServerManagementService.loadUser(warningMember)).thenReturn(warningUser);
|
||||
WarnLog log = WarnLog.builder().server(server).build();
|
||||
when(templateService.renderEmbedTemplate(eq(WarnServiceBean.WARN_LOG_TEMPLATE), any(WarnLog.class))).thenReturn(messageToSend);
|
||||
Warning warning = testUnit.warnUserWithLog(warnedMember, warningMember, REASON, log, feedBackChannel);
|
||||
verifyWarning(warning);
|
||||
verify( postTargetService, times(1)).sendEmbedInPostTarget(messageToSend, WarningPostTarget.WARN_LOG, server.getId());
|
||||
}
|
||||
|
||||
private void verifyWarning(Warning warning) {
|
||||
verify(messageService, times(1)).sendMessageToUser(warnedSimpleUser, NOTIFICATION_TEXT, feedBackChannel);
|
||||
WarnNotification notificationValue = notificationCaptor.getValue();
|
||||
Assert.assertEquals(firstWarning, notificationValue.getWarning());
|
||||
Assert.assertEquals(GUILD_NAME, notificationValue.getServerName());
|
||||
Assert.assertEquals(firstWarning, warning);
|
||||
}
|
||||
|
||||
private void setupMocksForWarning() {
|
||||
setupWarnings();
|
||||
when(warnedMember.getGuild()).thenReturn(guild);
|
||||
when(guild.getName()).thenReturn(GUILD_NAME);
|
||||
when(guild.getIdLong()).thenReturn(SERVER_ID);
|
||||
when(warnedMember.getUser()).thenReturn(warnedSimpleUser);
|
||||
when(warnManagementService.createWarning(firstWarnedUser, warningUser, REASON)).thenReturn(firstWarning);
|
||||
when(templateService.renderEmbedTemplate(eq(WARN_LOG_TEMPLATE), warnDecayLogModelArgumentCaptor.capture())).thenReturn(messageToSend);
|
||||
when(messageService.sendMessageToUser(eq(warnedMember.getUser()), any())).thenReturn(CompletableFuture.completedFuture(null));
|
||||
when(postTargetService.sendEmbedInPostTarget(messageToSend, WarningPostTarget.WARN_LOG, context.getGuild().getIdLong())).thenReturn(CommandTestUtilities.messageFutureList());
|
||||
when(templateService.renderTemplate(eq(WarnServiceBean.WARN_NOTIFICATION_TEMPLATE), notificationCaptor.capture())).thenReturn(NOTIFICATION_TEXT);
|
||||
when(serverManagementService.loadOrCreate(SERVER_ID)).thenReturn(server);
|
||||
}
|
||||
|
||||
private void setupWarnings() {
|
||||
when(firstWarning.getWarningUser()).thenReturn(warningUser);
|
||||
when(secondWarning.getWarningUser()).thenReturn(warningUser);
|
||||
|
||||
when(firstWarning.getWarnedUser()).thenReturn(firstWarnedUser);
|
||||
when(secondWarning.getWarnedUser()).thenReturn(secondWarnedUser);
|
||||
when(firstWarning.getWarnId()).thenReturn(new ServerSpecificId(SERVER_ID, WARN_ID));
|
||||
when(secondWarning.getWarnId()).thenReturn(new ServerSpecificId(SERVER_ID, 9L));
|
||||
when(server.getId()).thenReturn(SERVER_ID);
|
||||
}
|
||||
|
||||
private void verifyWarnDecayWithLog(boolean withLog) {
|
||||
@@ -232,18 +214,15 @@ public class WarnServiceBeanTest {
|
||||
}
|
||||
|
||||
private void setupWarnDecay() {
|
||||
setupWarnings();
|
||||
when(configService.getLongValue(WarningDecayFeature.DECAY_DAYS_KEY, server.getId())).thenReturn(5L);
|
||||
List<Warning> warnings = Arrays.asList(firstWarning, secondWarning);
|
||||
when(botService.getMemberInServer(warningUser)).thenReturn(warningMember);
|
||||
when(botService.getMemberInServer(firstWarnedUser)).thenReturn(warnedMember);
|
||||
when(botService.getMemberInServer(secondWarnedUser)).thenReturn(secondWarnedMember);
|
||||
when(botService.getGuildByIdNullable(server.getId())).thenReturn(guild);
|
||||
when(templateService.renderEmbedTemplate(eq("warn_decay_log"), warnDecayLogModelArgumentCaptor.capture())).thenReturn(messageToSend);
|
||||
when(templateService.renderEmbedTemplate(eq(WARN_DECAY_LOG_TEMPLATE_KEY), warnDecayLogModelArgumentCaptor.capture())).thenReturn(messageToSend);
|
||||
when(warnManagementService.getActiveWarningsInServerOlderThan(eq(server), any(Instant.class))).thenReturn(warnings);
|
||||
}
|
||||
|
||||
public Warning getDefaultWarning() {
|
||||
return Warning.builder().build();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package dev.sheldan.abstracto.moderation.service.management;
|
||||
|
||||
import dev.sheldan.abstracto.core.models.AServerAChannelMessage;
|
||||
import dev.sheldan.abstracto.core.models.ServerSpecificId;
|
||||
import dev.sheldan.abstracto.core.models.database.AChannel;
|
||||
import dev.sheldan.abstracto.core.models.database.AServer;
|
||||
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
|
||||
@@ -45,16 +46,17 @@ public class MuteManagementServiceBeanTest {
|
||||
AUserInAServer mutingUser = MockUtils.getUserObject(5L, server);
|
||||
AUserInAServer mutedUser = MockUtils.getUserObject(7L, server);
|
||||
String reason = "reason";
|
||||
String triggerKey = "key";
|
||||
Instant unMuteDate = Instant.now();
|
||||
AServerAChannelMessage muteMessage = AServerAChannelMessage.builder().server(server).channel(channel).messageId(messageId).build();
|
||||
|
||||
testUnit.createMute(mutedUser, mutingUser, reason, unMuteDate, muteMessage);
|
||||
testUnit.createMute(mutedUser, mutingUser, reason, unMuteDate, muteMessage, triggerKey, 8L);
|
||||
verify(muteRepository, times(1)).save(muteArgumentCaptor.capture());
|
||||
Mute createdMute = muteArgumentCaptor.getValue();
|
||||
Assert.assertEquals(reason, createdMute.getReason());
|
||||
Assert.assertEquals(mutingUser, createdMute.getMutingUser());
|
||||
Assert.assertEquals(mutedUser, createdMute.getMutedUser());
|
||||
Assert.assertEquals(server, createdMute.getMutingServer());
|
||||
Assert.assertEquals(server, createdMute.getServer());
|
||||
Assert.assertFalse(createdMute.getMuteEnded());
|
||||
Assert.assertEquals(messageId, createdMute.getMessageId().longValue());
|
||||
Assert.assertEquals(channel, createdMute.getMutingChannel());
|
||||
@@ -64,18 +66,20 @@ public class MuteManagementServiceBeanTest {
|
||||
@Test
|
||||
public void testFindMute() {
|
||||
Long id = 5L;
|
||||
Mute mute = Mute.builder().id(id).build();
|
||||
when(muteRepository.findById(id)).thenReturn(Optional.of(mute));
|
||||
Optional<Mute> foundMuteOptional = testUnit.findMute(id);
|
||||
Long serverId = 7L;
|
||||
Mute mute = Mute.builder().muteId(new ServerSpecificId(serverId, id)).build();
|
||||
when(muteRepository.findByMuteId_IdAndMuteId_ServerId(id, serverId)).thenReturn(Optional.of(mute));
|
||||
Optional<Mute> foundMuteOptional = testUnit.findMute(id, serverId);
|
||||
Assert.assertTrue(foundMuteOptional.isPresent());
|
||||
foundMuteOptional.ifPresent(foundMute -> Assert.assertEquals(id, foundMute.getId()));
|
||||
foundMuteOptional.ifPresent(foundMute -> Assert.assertEquals(id, foundMute.getMuteId().getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFindNonExistingMute() {
|
||||
Long id = 5L;
|
||||
when(muteRepository.findById(id)).thenReturn(Optional.empty());
|
||||
Optional<Mute> foundMuteOptional = testUnit.findMute(id);
|
||||
Long serverId = 7L;
|
||||
when(muteRepository.findByMuteId_IdAndMuteId_ServerId(id, serverId)).thenReturn(Optional.empty());
|
||||
Optional<Mute> foundMuteOptional = testUnit.findMute(id, serverId);
|
||||
Assert.assertFalse(foundMuteOptional.isPresent());
|
||||
}
|
||||
|
||||
@@ -114,7 +118,7 @@ public class MuteManagementServiceBeanTest {
|
||||
AUserInAServer userInAServer = MockUtils.getUserObject(9L, server);
|
||||
Mute mute1 = Mute.builder().build();
|
||||
Mute mute2 = Mute.builder().build();
|
||||
when(muteRepository.findAllByMutedUserAndMuteEndedFalseOrderByIdDesc(userInAServer)).thenReturn(Arrays.asList(mute1, mute2));
|
||||
when(muteRepository.findAllByMutedUserAndMuteEndedFalseOrderByMuteId_IdDesc(userInAServer)).thenReturn(Arrays.asList(mute1, mute2));
|
||||
List<Mute> allMutesOf = testUnit.getAllMutesOf(userInAServer);
|
||||
Assert.assertEquals(2, allMutesOf.size());
|
||||
Assert.assertEquals(mute1, allMutesOf.get(0));
|
||||
|
||||
@@ -2,6 +2,7 @@ package dev.sheldan.abstracto.moderation.service.management;
|
||||
|
||||
import dev.sheldan.abstracto.core.models.database.AServer;
|
||||
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 dev.sheldan.abstracto.test.MockUtils;
|
||||
@@ -27,6 +28,9 @@ public class UserNoteManagementServiceBeanTest {
|
||||
@Mock
|
||||
private UserNoteRepository userNoteRepository;
|
||||
|
||||
@Mock
|
||||
private CounterService counterService;
|
||||
|
||||
private static final String NOTE_TEXT = "noteText";
|
||||
private static final Long NOTE_ID = 5L;
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ public class WarnManagementServiceBeanTest {
|
||||
public void testCreateWarning() {
|
||||
AUserInAServer warningUser = MockUtils.getUserObject(7L, server);
|
||||
String reason = "REASON";
|
||||
Warning warning = testUnit.createWarning(warnedUser, warningUser, reason);
|
||||
Warning warning = testUnit.createWarning(warnedUser, warningUser, reason, 8L);
|
||||
Assert.assertEquals(warningUser, warning.getWarningUser());
|
||||
Assert.assertEquals(warnedUser, warning.getWarnedUser());
|
||||
Assert.assertEquals(reason, warning.getReason());
|
||||
@@ -95,9 +95,10 @@ public class WarnManagementServiceBeanTest {
|
||||
@Test
|
||||
public void testFindByIdExisting() {
|
||||
Long warnId = 6L;
|
||||
Long serverId = 8L;
|
||||
Warning existingWarning = getWarning();
|
||||
when(warnRepository.findById(warnId)).thenReturn(Optional.ofNullable(existingWarning));
|
||||
Optional<Warning> warningOptional = testUnit.findById(warnId);
|
||||
when(warnRepository.findByWarnId_IdAndWarnId_ServerId(warnId, serverId)).thenReturn(Optional.ofNullable(existingWarning));
|
||||
Optional<Warning> warningOptional = testUnit.findById(warnId, serverId);
|
||||
Assert.assertTrue(warningOptional.isPresent());
|
||||
warningOptional.ifPresent(foundWarning -> Assert.assertEquals(existingWarning, foundWarning));
|
||||
}
|
||||
@@ -105,8 +106,9 @@ public class WarnManagementServiceBeanTest {
|
||||
@Test
|
||||
public void testFindByIdNotExisting() {
|
||||
Long warnId = 6L;
|
||||
when(warnRepository.findById(warnId)).thenReturn(Optional.ofNullable(null));
|
||||
Optional<Warning> warningOptional = testUnit.findById(warnId);
|
||||
Long serverId = 8L;
|
||||
when(warnRepository.findByWarnId_IdAndWarnId_ServerId(warnId, serverId)).thenReturn(Optional.ofNullable(null));
|
||||
Optional<Warning> warningOptional = testUnit.findById(warnId, serverId);
|
||||
Assert.assertFalse(warningOptional.isPresent());
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package dev.sheldan.abstracto.moderation.exception;
|
||||
|
||||
import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException;
|
||||
import dev.sheldan.abstracto.templating.Templatable;
|
||||
|
||||
public class NoMuteFoundException extends AbstractoRunTimeException implements Templatable {
|
||||
|
||||
public NoMuteFoundException() {
|
||||
super("No mute found for user.");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getTemplateName() {
|
||||
return "unMute_has_no_active_mute_exception";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getTemplateModel() {
|
||||
return new Object();
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package dev.sheldan.abstracto.moderation.models.database;
|
||||
import dev.sheldan.abstracto.core.models.database.AChannel;
|
||||
import dev.sheldan.abstracto.core.models.database.AServer;
|
||||
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
|
||||
import dev.sheldan.abstracto.core.models.ServerSpecificId;
|
||||
import lombok.*;
|
||||
|
||||
import javax.persistence.*;
|
||||
@@ -24,9 +25,13 @@ public class Mute {
|
||||
/**
|
||||
* The globally unique id of the mute.
|
||||
*/
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@EmbeddedId
|
||||
private ServerSpecificId muteId;
|
||||
|
||||
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
|
||||
@MapsId("serverId")
|
||||
@JoinColumn(name = "server_id", referencedColumnName = "id", nullable = false)
|
||||
private AServer server;
|
||||
|
||||
/**
|
||||
* The {@link AUserInAServer} which was muted
|
||||
@@ -68,13 +73,6 @@ public class Mute {
|
||||
@Column
|
||||
private Long messageId;
|
||||
|
||||
/**
|
||||
* The {@link AServer} in which this mute was cast
|
||||
*/
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "mutingServer", nullable = false)
|
||||
private AServer mutingServer;
|
||||
|
||||
/**
|
||||
* The channel in which this mute was cast
|
||||
*/
|
||||
@@ -109,7 +107,7 @@ public class Mute {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Mute mute = (Mute) o;
|
||||
return Objects.equals(id, mute.id) &&
|
||||
return Objects.equals(muteId, mute.muteId) &&
|
||||
Objects.equals(mutedUser, mute.mutedUser) &&
|
||||
Objects.equals(mutingUser, mute.mutingUser) &&
|
||||
Objects.equals(reason, mute.reason) &&
|
||||
@@ -117,13 +115,13 @@ public class Mute {
|
||||
Objects.equals(muteTargetDate, mute.muteTargetDate) &&
|
||||
Objects.equals(muteEnded, mute.muteEnded) &&
|
||||
Objects.equals(messageId, mute.messageId) &&
|
||||
Objects.equals(mutingServer, mute.mutingServer) &&
|
||||
Objects.equals(server, mute.server) &&
|
||||
Objects.equals(mutingChannel, mute.mutingChannel) &&
|
||||
Objects.equals(triggerKey, mute.triggerKey);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, mutedUser, mutingUser, reason, muteDate, muteTargetDate, muteEnded, messageId, mutingServer, mutingChannel, triggerKey);
|
||||
return Objects.hash(muteId, mutedUser, mutingUser, reason, muteDate, muteTargetDate, muteEnded, messageId, server, mutingChannel, triggerKey);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package dev.sheldan.abstracto.moderation.models.database;
|
||||
|
||||
import dev.sheldan.abstracto.core.models.ServerSpecificId;
|
||||
import dev.sheldan.abstracto.core.models.database.AServer;
|
||||
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
|
||||
import lombok.*;
|
||||
|
||||
@@ -15,9 +17,13 @@ import java.time.Instant;
|
||||
@Setter
|
||||
public class UserNote {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
@EmbeddedId
|
||||
private ServerSpecificId userNoteId;
|
||||
|
||||
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
|
||||
@MapsId("serverId")
|
||||
@JoinColumn(name = "server_id", referencedColumnName = "id", nullable = false)
|
||||
private AServer server;
|
||||
|
||||
@ManyToOne
|
||||
@JoinColumn(name = "noteUser", nullable = false)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package dev.sheldan.abstracto.moderation.models.database;
|
||||
|
||||
import dev.sheldan.abstracto.core.models.ServerSpecificId;
|
||||
import dev.sheldan.abstracto.core.models.database.AServer;
|
||||
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
|
||||
import lombok.*;
|
||||
|
||||
@@ -20,10 +22,15 @@ public class Warning {
|
||||
/**
|
||||
* The globally unique id of this warning
|
||||
*/
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
@EmbeddedId
|
||||
@Getter
|
||||
private Long id;
|
||||
@Setter
|
||||
private ServerSpecificId warnId;
|
||||
|
||||
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
|
||||
@MapsId("serverId")
|
||||
@JoinColumn(name = "server_id", referencedColumnName = "id", nullable = false)
|
||||
private AServer server;
|
||||
|
||||
/**
|
||||
* The {@link AUserInAServer} which was warned
|
||||
@@ -93,7 +100,7 @@ public class Warning {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
Warning warning = (Warning) o;
|
||||
return Objects.equals(id, warning.id) &&
|
||||
return Objects.equals(warnId, warning.warnId) &&
|
||||
Objects.equals(warnedUser, warning.warnedUser) &&
|
||||
Objects.equals(warningUser, warning.warningUser) &&
|
||||
Objects.equals(reason, warning.reason) &&
|
||||
@@ -104,6 +111,6 @@ public class Warning {
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, warnedUser, warningUser, reason, warnDate, decayed, decayDate);
|
||||
return Objects.hash(warnId, warnedUser, warningUser, reason, warnDate, decayed, decayDate);
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user