refactored channel exception to have a unified interface to form the exception message

replaced getOne with findById in order to get optionals and handle those
some places still have the general abstracto run time exception
This commit is contained in:
Sheldan
2020-05-13 12:49:08 +02:00
parent 5755d033eb
commit c429aa882b
52 changed files with 501 additions and 344 deletions

View File

@@ -20,6 +20,7 @@ import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Component
@Slf4j
@@ -39,14 +40,18 @@ public class SetExpRole extends AbstractConditionableCommand {
public CommandResult execute(CommandContext commandContext) {
Integer level = (Integer) commandContext.getParameters().getParameters().get(0);
Long roleId = (Long) commandContext.getParameters().getParameters().get(1);
ARole role = roleManagementService.findRole(roleId, commandContext.getUserInitiatedContext().getServer());
AServer server = commandContext.getUserInitiatedContext().getServer();
if(!roleService.isRoleInServer(role)) {
throw new RoleException("Role not found.");
Optional<ARole> roleOpt = roleManagementService.findRole(roleId, commandContext.getUserInitiatedContext().getServer());
if(roleOpt.isPresent()) {
ARole role = roleOpt.get();
AServer server = commandContext.getUserInitiatedContext().getServer();
if(!roleService.isRoleInServer(role)) {
throw new RoleException("Role not found.");
}
log.info("Setting role {} to be used for level {} on server {}", roleId, level, server.getId());
experienceRoleService.setRoleToLevel(role, level, server, commandContext.getUserInitiatedContext().getChannel());
return CommandResult.fromSuccess();
}
log.info("Setting role {} to be used for level {} on server {}", roleId, level, server.getId());
experienceRoleService.setRoleToLevel(role, level, server, commandContext.getUserInitiatedContext().getChannel());
return CommandResult.fromSuccess();
return CommandResult.fromError("Could not find role");
}
@Override

View File

@@ -1,5 +1,6 @@
package dev.sheldan.abstracto.experience.service;
import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException;
import dev.sheldan.abstracto.core.models.database.AChannel;
import dev.sheldan.abstracto.core.models.database.AServer;
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
@@ -121,7 +122,9 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
Integer currentLevel = userExperience.getCurrentLevel() != null ? userExperience.getCurrentLevel().getLevel() : 0;
if(!correctLevel.equals(currentLevel)) {
log.info("User {} leveled from {} to {}", user.getUserReference().getId(), currentLevel, correctLevel);
userExperience.setCurrentLevel(experienceLevelManagementService.getLevel(correctLevel));
AExperienceLevel currentLevel1 = experienceLevelManagementService.getLevel(correctLevel)
.orElseThrow(() -> new AbstractoRunTimeException(String.format("Could not find level %s", correctLevel)));
userExperience.setCurrentLevel(currentLevel1);
return true;
}
return false;
@@ -289,13 +292,15 @@ public class AUserExperienceServiceBean implements AUserExperienceService {
log.info("Retrieving rank for {}", userInAServer.getUserReference().getId());
AUserExperience experience = userExperienceManagementService.findUserInServer(userInAServer);
LeaderBoardEntryResult rankOfUserInServer = userExperienceManagementService.getRankOfUserInServer(experience);
AExperienceLevel currentLevel = experienceLevelManagementService.getLevel(rankOfUserInServer.getLevel())
.orElseThrow(() -> new AbstractoRunTimeException(String.format("Could not find level %s", rankOfUserInServer.getLevel())));
AUserExperience aUserExperience = AUserExperience
.builder()
.experience(rankOfUserInServer.getExperience())
.user(userInAServer)
.messageCount(rankOfUserInServer.getMessageCount())
.id(userInAServer.getUserInServerId())
.currentLevel(experienceLevelManagementService.getLevel(rankOfUserInServer.getLevel()))
.currentLevel(currentLevel)
.build();
return LeaderBoardEntry.builder().experience(aUserExperience).rank(rankOfUserInServer.getRank()).build();
}

View File

@@ -1,5 +1,6 @@
package dev.sheldan.abstracto.experience.service;
import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException;
import dev.sheldan.abstracto.experience.models.database.AExperienceLevel;
import dev.sheldan.abstracto.experience.service.management.ExperienceLevelManagementService;
import lombok.extern.slf4j.Slf4j;
@@ -46,7 +47,7 @@ public class ExperienceLevelServiceBean implements ExperienceLevelService {
@Override
public Long calculateExperienceToNextLevel(Integer level, Long currentExperience) {
AExperienceLevel nextLevel = experienceLevelManagementService.getLevel(level + 1);
AExperienceLevel nextLevel = experienceLevelManagementService.getLevel(level + 1).orElseThrow(() -> new AbstractoRunTimeException(String.format("Could not find level %s", level)));
return nextLevel.getExperienceNeeded() - currentExperience;
}

View File

@@ -1,5 +1,6 @@
package dev.sheldan.abstracto.experience.service;
import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException;
import dev.sheldan.abstracto.core.models.database.AChannel;
import dev.sheldan.abstracto.core.models.database.ARole;
import dev.sheldan.abstracto.core.models.database.AServer;
@@ -38,7 +39,7 @@ public class ExperienceRoleServiceBean implements ExperienceRoleService {
*/
@Override
public void setRoleToLevel(ARole role, Integer level, AServer server, AChannel feedbackChannel) {
AExperienceLevel experienceLevel = experienceLevelService.getLevel(level);
AExperienceLevel experienceLevel = experienceLevelService.getLevel(level).orElseThrow(() -> new AbstractoRunTimeException(String.format("Could not find level %s", level)));
unsetRole(role, server, feedbackChannel);
experienceRoleManagementService.removeAllRoleAssignmentsForLevelInServer(experienceLevel, server);
experienceRoleManagementService.setLevelToRole(experienceLevel, role, server);

View File

@@ -6,6 +6,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;
@Component
public class ExperienceLevelManagementServiceBean implements ExperienceLevelManagementService {
@@ -30,8 +31,8 @@ public class ExperienceLevelManagementServiceBean implements ExperienceLevelMana
}
@Override
public AExperienceLevel getLevel(Integer level) {
return experienceLevelRepository.getOne(level);
public Optional<AExperienceLevel> getLevel(Integer level) {
return experienceLevelRepository.findById(level);
}
@Override

View File

@@ -1,5 +1,6 @@
package dev.sheldan.abstracto.experience.service.management;
import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException;
import dev.sheldan.abstracto.core.models.database.AServer;
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
import dev.sheldan.abstracto.experience.models.database.LeaderBoardEntryResult;
@@ -31,7 +32,7 @@ public class UserExperienceManagementServiceBean implements UserExperienceManage
@Override
public AUserExperience createUserInServer(AUserInAServer aUserInAServer) {
AExperienceLevel startingLevel = experienceLevelManagementService.getLevel(0);
AExperienceLevel startingLevel = experienceLevelManagementService.getLevel(0).orElseThrow(() -> new AbstractoRunTimeException(String.format("Could not find level %s", 0)));
return AUserExperience
.builder()
.experience(0L)
@@ -63,7 +64,7 @@ public class UserExperienceManagementServiceBean implements UserExperienceManage
userExperience.setExperience(userExperience.getExperience() + experience);
return userExperience;
} else {
AExperienceLevel startingLevel = experienceLevelManagementService.getLevel(0);
AExperienceLevel startingLevel = experienceLevelManagementService.getLevel(0).orElseThrow(() -> new AbstractoRunTimeException(String.format("Could not find level %s", 0)));
return AUserExperience
.builder()
.experience(experience)

View File

@@ -3,6 +3,7 @@ package dev.sheldan.abstracto.experience.service.management;
import dev.sheldan.abstracto.experience.models.database.AExperienceLevel;
import java.util.List;
import java.util.Optional;
/**
* Service responsible to create and retrieve {@link AExperienceLevel} objects in the database.
@@ -26,9 +27,9 @@ public interface ExperienceLevelManagementService {
/**
* Retrieves a {@link AExperienceLevel} according to the given level.
* @param level The level of the wanted {@link AExperienceLevel} to look for
* @return If the level exists, returns the {@link AExperienceLevel}, if it does not exists, returns null.
* @return Returns an optional containing the {@link AExperienceLevel} if it exists, and null otherwise
*/
AExperienceLevel getLevel(Integer level);
Optional<AExperienceLevel> getLevel(Integer level);
/**
* Loads the complete level configuration and returns all found {@link AExperienceLevel} objects from the database.

View File

@@ -1,5 +1,7 @@
package dev.sheldan.abstracto.moderation.service;
import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException;
import dev.sheldan.abstracto.core.exception.ChannelNotFoundException;
import dev.sheldan.abstracto.core.models.AServerAChannelMessage;
import dev.sheldan.abstracto.core.models.FullUser;
import dev.sheldan.abstracto.core.models.database.AChannel;
@@ -33,6 +35,7 @@ import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@@ -129,7 +132,9 @@ public class MuteServiceBean implements MuteService {
applyMuteRole(userInServerBeingMuted);
AServerAChannelMessage origin = null;
if(message != null) {
AChannel channel = channelManagementService.loadChannel(message.getChannel().getIdLong());
long channelId = message.getChannel().getIdLong();
Optional<AChannel> channelOpt = channelManagementService.loadChannel(channelId);
AChannel channel = channelOpt.orElseThrow(() -> new ChannelNotFoundException(channelId, userInServerBeingMuted.getServerReference().getId()));
origin = AServerAChannelMessage
.builder()
.channel(channel)
@@ -213,7 +218,8 @@ public class MuteServiceBean implements MuteService {
@Transactional
public void unmuteUser(Mute mute) {
AServer mutingServer = mute.getMutingServer();
Mute updatedMute = muteManagementService.findMute(mute.getId());
Optional<Mute> updatedMuteOpt = muteManagementService.findMute(mute.getId());
Mute updatedMute = updatedMuteOpt.orElseThrow(() -> new AbstractoRunTimeException(String.format("Cannot find mute with id %s", mute.getId())));
// we do not store any reference to the instant unmutes (<=60sec), so we cannot cancel it
// but if the person gets unmuted immediately, via command, this might still execute of the instant unmute
// so we need to load the mute, and check if the mute was unmuted already, because the mute object we have at
@@ -248,8 +254,8 @@ public class MuteServiceBean implements MuteService {
@Transactional
public void endMute(Long muteId) {
log.info("Unmuting the mute {}", muteId);
Mute mute = muteManagementService.findMute(muteId);
unmuteUser(mute);
Optional<Mute> mute = muteManagementService.findMute(muteId);
mute.ifPresent(this::unmuteUser);
}
@Override

View File

@@ -1,6 +1,6 @@
package dev.sheldan.abstracto.moderation.service;
import dev.sheldan.abstracto.core.exception.ChannelException;
import dev.sheldan.abstracto.core.exception.ChannelNotFoundException;
import dev.sheldan.abstracto.core.models.database.AChannel;
import dev.sheldan.abstracto.core.service.BotService;
import lombok.extern.slf4j.Slf4j;
@@ -40,7 +40,7 @@ public class SlowModeServiceBean implements SlowModeService {
TextChannel textChannel = textChannelOptional.get();
this.setSlowMode(textChannel, duration);
} else {
throw new ChannelException(String.format("Channel %s not found in guild %s", channel.getId(), channel.getServer().getId()));
throw new ChannelNotFoundException(channel.getId(), channel.getServer().getId());
}
}
}

View File

@@ -12,6 +12,7 @@ import org.springframework.stereotype.Component;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
@Component
@Slf4j
@@ -44,8 +45,8 @@ public class MuteManagementServiceBean implements MuteManagementService {
}
@Override
public Mute findMute(Long muteId) {
return muteRepository.getOne(muteId);
public Optional<Mute> findMute(Long muteId) {
return muteRepository.findById(muteId);
}
@Override

View File

@@ -7,6 +7,7 @@ import net.dv8tion.jda.api.entities.Member;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
/**
* Responsible for creating/updating/retrieving mutes in the database.
@@ -26,9 +27,9 @@ public interface MuteManagementService {
/**
* Finds the mute from the database by the given ID.
* @param muteId The id of the mute to search for
* @return The found {@link Mute}, the first access fails, if the entity was not found
* @return An optional containing a {@link Mute} if the ID exists, and null otherwise
*/
Mute findMute(Long muteId);
Optional<Mute> findMute(Long muteId);
/**
* Saves the given mute to the database.

View File

@@ -2,6 +2,7 @@ package dev.sheldan.abstracto.modmail.service;
import com.jagrosh.jdautilities.commons.waiter.EventWaiter;
import com.jagrosh.jdautilities.menu.ButtonMenu;
import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException;
import dev.sheldan.abstracto.core.exception.PostTargetException;
import dev.sheldan.abstracto.core.models.FullGuild;
import dev.sheldan.abstracto.core.models.FullUser;
@@ -292,19 +293,24 @@ public class ModMailThreadServiceBean implements ModMailThreadService {
@Transactional
public void postProcessSendMessages(Long modMailThreadId, Message message, List<CompletableFuture<Message>> completableFutures) {
ModMailThread modMailThread = modMailThreadManagementService.getById(modMailThreadId);
List<Message> messages = new ArrayList<>();
completableFutures.forEach(messageCompletableFuture -> {
try {
Message messageToAdd = messageCompletableFuture.get();
messages.add(messageToAdd);
} catch (InterruptedException | ExecutionException e) {
log.error("Error while executing future to retrieve reaction.", e);
}
self.saveMessageIds(messages, modMailThread, modMailThread.getUser(), false, false);
modMailThreadManagementService.setModMailThreadState(modMailThread, ModMailThreadState.USER_REPLIED);
messageService.addReactionToMessage("readReaction", modMailThread.getServer().getId(), message);
});
Optional<ModMailThread> modMailThreadOpt = modMailThreadManagementService.getById(modMailThreadId);
if(modMailThreadOpt.isPresent()) {
ModMailThread modMailThread = modMailThreadOpt.get();
List<Message> messages = new ArrayList<>();
completableFutures.forEach(messageCompletableFuture -> {
try {
Message messageToAdd = messageCompletableFuture.get();
messages.add(messageToAdd);
} catch (InterruptedException | ExecutionException e) {
log.error("Error while executing future to retrieve reaction.", e);
}
self.saveMessageIds(messages, modMailThread, modMailThread.getUser(), false, false);
modMailThreadManagementService.setModMailThreadState(modMailThread, ModMailThreadState.USER_REPLIED);
messageService.addReactionToMessage("readReaction", modMailThread.getServer().getId(), message);
});
} else {
throw new AbstractoRunTimeException(String.format("Could not find mod mail thread with id %s", modMailThreadId));
}
}
@Override
@@ -322,22 +328,27 @@ public class ModMailThreadServiceBean implements ModMailThreadService {
@Transactional
public void sendModMailFailure(String template, AUserInAServer aUserInAServer, Long modMailTreadId, MessageChannel channel, Throwable throwable) {
ModMailThread modMailThread = modMailThreadManagementService.getById(modMailTreadId);
try {
FullUser fullUser = FullUser
.builder()
.aUserInAServer(aUserInAServer)
.member(botService.getMemberInServer(aUserInAServer))
.build();
ModMailExceptionModel modMailExceptionModel = ModMailExceptionModel
.builder()
.modMailThread(modMailThread)
.user(fullUser)
.throwable(throwable)
.build();
channelService.sendTemplateInChannel(template, modMailExceptionModel, channel);
} catch (Exception e) {
log.error("Failed to notify about mod mail exception.", e);
Optional<ModMailThread> modMailThreadOpt = modMailThreadManagementService.getById(modMailTreadId);
if(modMailThreadOpt.isPresent()) {
ModMailThread modMailThread = modMailThreadOpt.get();
try {
FullUser fullUser = FullUser
.builder()
.aUserInAServer(aUserInAServer)
.member(botService.getMemberInServer(aUserInAServer))
.build();
ModMailExceptionModel modMailExceptionModel = ModMailExceptionModel
.builder()
.modMailThread(modMailThread)
.user(fullUser)
.throwable(throwable)
.build();
channelService.sendTemplateInChannel(template, modMailExceptionModel, channel);
} catch (Exception e) {
log.error("Failed to notify about mod mail exception.", e);
}
} else {
throw new AbstractoRunTimeException(String.format("Could not find mod mail thread with id %s", modMailTreadId));
}
}
@@ -360,157 +371,181 @@ public class ModMailThreadServiceBean implements ModMailThreadService {
});
}
CompletableFuture.allOf(messages.toArray(new CompletableFuture[0])).whenComplete((avoid, throwable) -> {
ModMailThread innerModMailThread = modMailThreadManagementService.getById(modMailThreadId);
log.trace("Loaded {} mod mail thread messages", messages.size());
if(throwable != null) {
log.warn("Failed to load some mod mail messages for mod mail thread {}. Still trying to post the ones we got.", modMailThreadId, throwable);
}
try {
CompletableFutureList<Message> list = self.logModMailThread(modMailThreadId, messages, note);
list.getMainFuture().thenRun(() -> {
list.getFutures().forEach(messageCompletableFuture -> {
try {
Message message = messageCompletableFuture.get();
undoActions.add(UndoActionInstance.getMessageDeleteAction(message.getChannel().getIdLong(), message.getIdLong()));
} catch (InterruptedException | ExecutionException e) {
log.error("Failed to post logging messages.", e);
} catch (Exception e) {
log.error("Failed to handle the mod mail log messages.", e);
}
Optional<ModMailThread> modMailThreadOpt = modMailThreadManagementService.getById(modMailThreadId);
if(modMailThreadOpt.isPresent()) {
ModMailThread innerModMailThread = modMailThreadOpt.get();
log.trace("Loaded {} mod mail thread messages", messages.size());
if(throwable != null) {
log.warn("Failed to load some mod mail messages for mod mail thread {}. Still trying to post the ones we got.", modMailThreadId, throwable);
}
try {
CompletableFutureList<Message> list = self.logModMailThread(modMailThreadId, messages, note);
list.getMainFuture().thenRun(() -> {
list.getFutures().forEach(messageCompletableFuture -> {
try {
Message message = messageCompletableFuture.get();
undoActions.add(UndoActionInstance.getMessageDeleteAction(message.getChannel().getIdLong(), message.getIdLong()));
} catch (InterruptedException | ExecutionException e) {
log.error("Failed to post logging messages.", e);
} catch (Exception e) {
log.error("Failed to handle the mod mail log messages.", e);
}
});
self.afterSuccessfulLog(modMailThreadId, feedBack, notifyUser, undoActions);
});
self.afterSuccessfulLog(modMailThreadId, feedBack, notifyUser, undoActions);
});
list.getMainFuture().exceptionally(innerThrowable -> {
sendModMailFailure("modmail_exception_generic", innerModMailThread.getUser(), modMailThreadId, feedBack, innerThrowable);
log.error("Failed to log messages for mod mail thread {}.", modMailThreadId, innerThrowable);
return null;
});
} catch (PostTargetException po) {
log.error("Failed to log mod mail messages", po);
sendModMailFailure("modmail_exception_post_target_not_defined", innerModMailThread.getUser(), modMailThreadId, feedBack, po);
} catch (Exception e) {
log.error("Failed to log mod mail messages", e);
sendModMailFailure("modmail_exception_generic", innerModMailThread.getUser(), modMailThreadId, feedBack, e);
sendModMailFailure("modmail_exception_generic", innerModMailThread.getUser(), modMailThreadId, feedBack, innerThrowable);
log.error("Failed to log messages for mod mail thread {}.", modMailThreadId, innerThrowable);
return null;
});
} catch (PostTargetException po) {
log.error("Failed to log mod mail messages", po);
sendModMailFailure("modmail_exception_post_target_not_defined", innerModMailThread.getUser(), modMailThreadId, feedBack, po);
} catch (Exception e) {
log.error("Failed to log mod mail messages", e);
sendModMailFailure("modmail_exception_generic", innerModMailThread.getUser(), modMailThreadId, feedBack, e);
}
} else {
throw new AbstractoRunTimeException(String.format("Could not find mod mail thread with id %s", modMailThreadId));
}
});
} else {
self.afterSuccessfulLog(modMailThreadId, feedBack, notifyUser, undoActions);
}
}
@Transactional
public void afterSuccessfulLog(Long modMailThreadId, MessageChannel feedBack, Boolean notifyUser, List<UndoActionInstance> undoActions) {
log.trace("Mod mail logging for thread {} has completed. Starting post logging activities.", modMailThreadId);
ModMailThread modMailThread = modMailThreadManagementService.getById(modMailThreadId);
User user = botService.getMemberInServer(modMailThread.getUser()).getUser();
user.openPrivateChannel().queue(privateChannel -> {
try {
List<CompletableFuture<Message>> messageFutures = new ArrayList<>();
if(notifyUser){
log.trace("Notifying user {}", user.getIdLong());
messageFutures.addAll(channelService.sendTemplateInChannel("modmail_closing_user_message", new Object(), privateChannel));
} else {
log.trace("*Not* notifying user {}", user.getIdLong());
messageFutures.add(CompletableFuture.completedFuture(null));
}
CompletableFuture.allOf(messageFutures.toArray(new CompletableFuture[0])).whenComplete((result, throwable) -> {
if(throwable != null) {
log.warn("Failed to send closing message to user {} after closing mod mail thread {}", user.getIdLong(), modMailThread.getId(), throwable);
Optional<ModMailThread> modMailThreadOpt = modMailThreadManagementService.getById(modMailThreadId);
if(modMailThreadOpt.isPresent()) {
ModMailThread modMailThread = modMailThreadOpt.get();
User user = botService.getMemberInServer(modMailThread.getUser()).getUser();
user.openPrivateChannel().queue(privateChannel -> {
try {
List<CompletableFuture<Message>> messageFutures = new ArrayList<>();
if(notifyUser){
log.trace("Notifying user {}", user.getIdLong());
messageFutures.addAll(channelService.sendTemplateInChannel("modmail_closing_user_message", new Object(), privateChannel));
} else {
log.trace("*Not* notifying user {}", user.getIdLong());
messageFutures.add(CompletableFuture.completedFuture(null));
}
self.deleteChannelAndClose(modMailThreadId, feedBack, undoActions);
});
} catch (Exception e) {
log.error("Failed to render closing user message", e);
sendModMailFailure("modmail_exception_generic", modMailThread.getUser(), modMailThreadId, feedBack, e);
}
}, throwable -> {
log.error("Failed to load private channel with user {}", user.getIdLong(), throwable);
undoActionService.performActions(undoActions);
});
CompletableFuture.allOf(messageFutures.toArray(new CompletableFuture[0])).whenComplete((result, throwable) -> {
if(throwable != null) {
log.warn("Failed to send closing message to user {} after closing mod mail thread {}", user.getIdLong(), modMailThread.getId(), throwable);
}
self.deleteChannelAndClose(modMailThreadId, feedBack, undoActions);
});
} catch (Exception e) {
log.error("Failed to render closing user message", e);
sendModMailFailure("modmail_exception_generic", modMailThread.getUser(), modMailThreadId, feedBack, e);
}
}, throwable -> {
log.error("Failed to load private channel with user {}", user.getIdLong(), throwable);
undoActionService.performActions(undoActions);
});
} else {
throw new AbstractoRunTimeException(String.format("Could not find mod mail thread with id %s", modMailThreadId));
}
}
@Transactional
public void deleteChannelAndClose(Long modMailThreadId, MessageChannel feedBack, List<UndoActionInstance> undoActions) {
ModMailThread modMailThread = modMailThreadManagementService.getById(modMailThreadId);
try {
channelService.deleteTextChannel(modMailThread.getChannel()).thenRun(() -> {
try {
self.closeModMailThreadInDb(modMailThreadId);
} catch (Exception e) {
Optional<ModMailThread> modMailThreadOpt = modMailThreadManagementService.getById(modMailThreadId);
if(modMailThreadOpt.isPresent()) {
ModMailThread modMailThread = modMailThreadOpt.get();
try {
channelService.deleteTextChannel(modMailThread.getChannel()).thenRun(() -> {
try {
self.closeModMailThreadInDb(modMailThreadId);
} catch (Exception e) {
undoActionService.performActions(undoActions);
}
}).exceptionally(throwable2 -> {
undoActionService.performActions(undoActions);
}
}).exceptionally(throwable2 -> {
log.error("Failed to delete text channel containing mod mail thread {}", modMailThread.getId(), throwable2);
return null;
});
} catch (InsufficientPermissionException ex) {
log.error("Failed to delete text channel containing mod mail thread {}", modMailThreadId, ex);
undoActionService.performActions(undoActions);
log.error("Failed to delete text channel containing mod mail thread {}", modMailThread.getId(), throwable2);
return null;
});
} catch (InsufficientPermissionException ex) {
log.error("Failed to delete text channel containing mod mail thread {}", modMailThreadId, ex);
undoActionService.performActions(undoActions);
sendModMailFailure("modmail_exception_cannot_delete_channel", modMailThread.getUser(), modMailThreadId, feedBack, ex);
} catch (Exception ex) {
log.error("Failed to delete text channel containing mod mail thread {}", modMailThreadId, ex);
undoActionService.performActions(undoActions);
sendModMailFailure("modmail_exception_cannot_delete_channel", modMailThread.getUser(), modMailThreadId, feedBack, ex);
} catch (Exception ex) {
log.error("Failed to delete text channel containing mod mail thread {}", modMailThreadId, ex);
undoActionService.performActions(undoActions);
}
} else {
throw new AbstractoRunTimeException(String.format("Could not find mod mail thread with id %s", modMailThreadId));
}
}
@Transactional
public CompletableFutureList<Message> logModMailThread(Long modMailThreadId, List<CompletableFuture<Message>> messages, String note) {
log.info("Logging mod mail thread {}.", modMailThreadId);
ModMailThread modMailThread = modMailThreadManagementService.getById(modMailThreadId);
List<ModMailLoggedMessage> loggedMessages = new ArrayList<>();
messages.forEach(future -> {
try {
if(!future.isCompletedExceptionally()) {
Message loadedMessage = future.get();
if(loadedMessage != null) {
ModMailMessage modmailMessage = modMailThread.getMessages()
.stream()
.filter(modMailMessage -> modMailMessage.getMessageId().equals(loadedMessage.getIdLong()))
.findFirst().get();
ModMailLoggedMessage modMailLoggedMessage =
ModMailLoggedMessage
.builder()
.message(loadedMessage)
.modMailMessage(modmailMessage)
.author(userInServerService.getFullUser(modmailMessage.getAuthor()))
.build();
loggedMessages.add(modMailLoggedMessage);
Optional<ModMailThread> modMailThreadOpt = modMailThreadManagementService.getById(modMailThreadId);
if(modMailThreadOpt.isPresent()) {
ModMailThread modMailThread = modMailThreadOpt.get();
List<ModMailLoggedMessage> loggedMessages = new ArrayList<>();
messages.forEach(future -> {
try {
if(!future.isCompletedExceptionally()) {
Message loadedMessage = future.get();
if(loadedMessage != null) {
ModMailMessage modmailMessage = modMailThread.getMessages()
.stream()
.filter(modMailMessage -> modMailMessage.getMessageId().equals(loadedMessage.getIdLong()))
.findFirst().get();
ModMailLoggedMessage modMailLoggedMessage =
ModMailLoggedMessage
.builder()
.message(loadedMessage)
.modMailMessage(modmailMessage)
.author(userInServerService.getFullUser(modmailMessage.getAuthor()))
.build();
loggedMessages.add(modMailLoggedMessage);
}
}
} catch (InterruptedException | ExecutionException e) {
log.error("Error while executing future to retrieve reaction.", e);
} catch (Exception e) {
log.error("Failed handle the loaded messages.", e);
}
} catch (InterruptedException | ExecutionException e) {
log.error("Error while executing future to retrieve reaction.", e);
} catch (Exception e) {
log.error("Failed handle the loaded messages.", e);
}
});
List<CompletableFuture<Message>> completableFutures = new ArrayList<>();
modMailThread.setClosed(Instant.now());
ModMailClosingHeaderModel headerModel = ModMailClosingHeaderModel
.builder()
.closedThread(modMailThread)
.note(note)
.build();
log.trace("Sending close header and individual mod mail messages to mod mail log target.");
MessageToSend messageToSend = templateService.renderEmbedTemplate("modmail_close_header", headerModel);
List<CompletableFuture<Message>> closeHeaderFutures = postTargetService.sendEmbedInPostTarget(messageToSend, MODMAIL_LOG_POSTTARGET, modMailThread.getServer().getId());
completableFutures.addAll(closeHeaderFutures);
completableFutures.addAll(self.sendMessagesToPostTarget(modMailThread, loggedMessages));
CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0]));
return CompletableFutureList
.<Message>builder()
.mainFuture(voidCompletableFuture)
.futures(completableFutures)
.build();
});
List<CompletableFuture<Message>> completableFutures = new ArrayList<>();
modMailThread.setClosed(Instant.now());
ModMailClosingHeaderModel headerModel = ModMailClosingHeaderModel
.builder()
.closedThread(modMailThread)
.note(note)
.build();
log.trace("Sending close header and individual mod mail messages to mod mail log target.");
MessageToSend messageToSend = templateService.renderEmbedTemplate("modmail_close_header", headerModel);
List<CompletableFuture<Message>> closeHeaderFutures = postTargetService.sendEmbedInPostTarget(messageToSend, MODMAIL_LOG_POSTTARGET, modMailThread.getServer().getId());
completableFutures.addAll(closeHeaderFutures);
completableFutures.addAll(self.sendMessagesToPostTarget(modMailThread, loggedMessages));
CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0]));
return CompletableFutureList
.<Message>builder()
.mainFuture(voidCompletableFuture)
.futures(completableFutures)
.build();
} else {
throw new AbstractoRunTimeException(String.format("Could not find mod mail thread with id %s", modMailThreadId));
}
}
@Transactional
public void closeModMailThreadInDb(Long modMailThreadId) {
ModMailThread modMailThread = modMailThreadManagementService.getById(modMailThreadId);
log.info("Setting thread {} to closed in db.", modMailThread.getId());
modMailThreadManagementService.setModMailThreadState(modMailThread, ModMailThreadState.CLOSED);
Optional<ModMailThread> modMailThreadOpt = modMailThreadManagementService.getById(modMailThreadId);
if(modMailThreadOpt.isPresent()) {
ModMailThread modMailThread = modMailThreadOpt.get();
log.info("Setting thread {} to closed in db.", modMailThread.getId());
modMailThreadManagementService.setModMailThreadState(modMailThread, ModMailThreadState.CLOSED);
} else {
throw new AbstractoRunTimeException(String.format("Could not find mod mail thread with id %s", modMailThreadId));
}
}
public List<CompletableFuture<Message>> sendMessagesToPostTarget(ModMailThread modMailThread, List<ModMailLoggedMessage> loadedMessages) {
@@ -525,55 +560,66 @@ public class ModMailThreadServiceBean implements ModMailThreadService {
@Transactional
public void sendReply(Long modMailThreadId, String text, Message message, PrivateChannel privateChannel, Boolean anonymous, MessageChannel feedBack) {
ModMailThread modMailThread = modMailThreadManagementService.getById(modMailThreadId);
AUserInAServer moderator = userInServerManagementService.loadUser(message.getMember());
Member userInGuild = botService.getMemberInServer(modMailThread.getUser());
Member moderatorMember = botService.getMemberInServer(moderator);
FullUser fullThreadUser = FullUser
.builder()
.aUserInAServer(modMailThread.getUser())
.member(userInGuild)
.build();
ModMailModeratorReplyModel.ModMailModeratorReplyModelBuilder modMailModeratorReplyModelBuilder = ModMailModeratorReplyModel
.builder()
.text(text)
.modMailThread(modMailThread)
.postedMessage(message)
.anonymous(anonymous)
.threadUser(fullThreadUser);
if(anonymous) {
modMailModeratorReplyModelBuilder.moderator(botService.getBotInGuild(modMailThread.getServer()));
Optional<ModMailThread> modMailThreadOpt = modMailThreadManagementService.getById(modMailThreadId);
if(modMailThreadOpt.isPresent()) {
ModMailThread modMailThread = modMailThreadOpt.get();
AUserInAServer moderator = userInServerManagementService.loadUser(message.getMember());
Member userInGuild = botService.getMemberInServer(modMailThread.getUser());
Member moderatorMember = botService.getMemberInServer(moderator);
FullUser fullThreadUser = FullUser
.builder()
.aUserInAServer(modMailThread.getUser())
.member(userInGuild)
.build();
ModMailModeratorReplyModel.ModMailModeratorReplyModelBuilder modMailModeratorReplyModelBuilder = ModMailModeratorReplyModel
.builder()
.text(text)
.modMailThread(modMailThread)
.postedMessage(message)
.anonymous(anonymous)
.threadUser(fullThreadUser);
if(anonymous) {
modMailModeratorReplyModelBuilder.moderator(botService.getBotInGuild(modMailThread.getServer()));
} else {
modMailModeratorReplyModelBuilder.moderator(moderatorMember);
}
ModMailModeratorReplyModel modMailUserReplyModel = modMailModeratorReplyModelBuilder.build();
MessageToSend messageToSend = templateService.renderEmbedTemplate("modmail_staff_message", modMailUserReplyModel);
List<CompletableFuture<Message>> completableFutures = channelService.sendMessageToSendToChannel(messageToSend, privateChannel);
CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0])).thenAccept(aVoid -> {
self.saveSendMessagesAndUpdateState(modMailThreadId, anonymous, moderator, completableFutures);
}).exceptionally(throwable -> {
log.error("Failed to send message to user {}", modMailThread.getUser().getUserReference().getId());
sendModMailFailure("modmail_exception_cannot_message_user", modMailThread.getUser(), modMailThread.getId(), feedBack, throwable);
return null;
});
} else {
modMailModeratorReplyModelBuilder.moderator(moderatorMember);
throw new AbstractoRunTimeException(String.format("Could not find mod mail thread with id %s", modMailThreadId));
}
ModMailModeratorReplyModel modMailUserReplyModel = modMailModeratorReplyModelBuilder.build();
MessageToSend messageToSend = templateService.renderEmbedTemplate("modmail_staff_message", modMailUserReplyModel);
List<CompletableFuture<Message>> completableFutures = channelService.sendMessageToSendToChannel(messageToSend, privateChannel);
CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0])).thenAccept(aVoid -> {
self.saveSendMessagesAndUpdateState(modMailThreadId, anonymous, moderator, completableFutures);
}).exceptionally(throwable -> {
log.error("Failed to send message to user {}", modMailThread.getUser().getUserReference().getId());
sendModMailFailure("modmail_exception_cannot_message_user", modMailThread.getUser(), modMailThread.getId(), feedBack, throwable);
return null;
});
}
@Transactional
public void saveSendMessagesAndUpdateState(Long modMailThreadId, Boolean anonymous, AUserInAServer moderator, List<CompletableFuture<Message>> completableFutures) {
ModMailThread modMailThread = modMailThreadManagementService.getById(modMailThreadId);
List<Message> messages = new ArrayList<>();
completableFutures.forEach(messageCompletableFuture -> {
try {
Message messageToAdd = messageCompletableFuture.get();
messages.add(messageToAdd);
} catch (InterruptedException | ExecutionException e) {
log.error("A future when sending the message to the user was interrupted.", e);
} catch (Exception e) {
log.error("Failed to handle the send staff message.", e);
}
});
self.saveMessageIds(messages, modMailThread, moderator, anonymous, true);
modMailThreadManagementService.setModMailThreadState(modMailThread, ModMailThreadState.MOD_REPLIED);
Optional<ModMailThread> modMailThreadOpt = modMailThreadManagementService.getById(modMailThreadId);
if(modMailThreadOpt.isPresent()) {
ModMailThread modMailThread = modMailThreadOpt.get();
List<Message> messages = new ArrayList<>();
completableFutures.forEach(messageCompletableFuture -> {
try {
Message messageToAdd = messageCompletableFuture.get();
messages.add(messageToAdd);
} catch (InterruptedException | ExecutionException e) {
log.error("A future when sending the message to the user was interrupted.", e);
} catch (Exception e) {
log.error("Failed to handle the send staff message.", e);
}
});
self.saveMessageIds(messages, modMailThread, moderator, anonymous, true);
modMailThreadManagementService.setModMailThreadState(modMailThread, ModMailThreadState.MOD_REPLIED);
} else {
throw new AbstractoRunTimeException(String.format("Could not find mod mail thread with id %s", modMailThreadId));
}
}
public void saveMessageIds(List<Message> messages, ModMailThread modMailThread, AUserInAServer author, Boolean anonymous, Boolean inDmChannel) {

View File

@@ -1,5 +1,6 @@
package dev.sheldan.abstracto.modmail.service.management;
import dev.sheldan.abstracto.core.exception.ChannelNotFoundException;
import dev.sheldan.abstracto.core.models.database.AChannel;
import dev.sheldan.abstracto.core.models.database.AUser;
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
@@ -12,6 +13,7 @@ import org.springframework.stereotype.Component;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
@Component
public class ModMailThreadManagementServiceBean implements ModMailThreadManagementService {
@@ -24,13 +26,14 @@ public class ModMailThreadManagementServiceBean implements ModMailThreadManageme
@Override
public ModMailThread getByChannelId(Long channelId) {
AChannel channel = channelManagementService.loadChannel(channelId);
Optional<AChannel> channelOpt = channelManagementService.loadChannel(channelId);
AChannel channel = channelOpt.orElseThrow(() -> new ChannelNotFoundException(channelId, 0L));
return getByChannel(channel);
}
@Override
public ModMailThread getById(Long modMailThreadId) {
return modMailThreadRepository.getOne(modMailThreadId);
public Optional<ModMailThread> getById(Long modMailThreadId) {
return modMailThreadRepository.findById(modMailThreadId);
}
@Override

View File

@@ -7,10 +7,11 @@ import dev.sheldan.abstracto.modmail.models.database.ModMailThread;
import dev.sheldan.abstracto.modmail.models.database.ModMailThreadState;
import java.util.List;
import java.util.Optional;
public interface ModMailThreadManagementService {
ModMailThread getByChannelId(Long channelId);
ModMailThread getById(Long modMailThreadId);
Optional<ModMailThread> getById(Long modMailThreadId);
ModMailThread getByChannel(AChannel channel);
List<ModMailThread> getThreadByUserAndState(AUserInAServer userInAServer, ModMailThreadState state);
ModMailThread getOpenModmailThreadForUser(AUserInAServer userInAServer);

View File

@@ -138,7 +138,10 @@ public class StarboardListener implements ReactedAddedListener, ReactedRemovedLi
}
private List<AUserInAServer> getUsersExcept(List<Long> users, AUserInAServer author) {
return users.stream().filter(user -> !user.equals(author.getUserInServerId())).map(aLong -> userInServerManagementService.loadUser(aLong)).collect(Collectors.toList());
return users.stream().filter(user -> !user.equals(author.getUserInServerId())).map(aLong -> {
Optional<AUserInAServer> aUserInAServer = userInServerManagementService.loadUser(aLong);
return aUserInAServer.get();
}).collect(Collectors.toList());
}
@Override

View File

@@ -1,5 +1,6 @@
package dev.sheldan.abstracto.utility.service;
import dev.sheldan.abstracto.core.exception.ChannelNotFoundException;
import dev.sheldan.abstracto.core.models.template.listener.MessageEmbeddedModel;
import dev.sheldan.abstracto.templating.model.MessageToSend;
import dev.sheldan.abstracto.core.models.cache.CachedMessage;
@@ -112,31 +113,38 @@ public class MessageEmbedServiceBean implements MessageEmbedService {
@Override
@Transactional
public void embedLink(CachedMessage cachedMessage, TextChannel target, Long userEmbeddingUserInServerId, Message embeddingMessage) {
AUserInAServer cause = userInServerManagementService.loadUser(userEmbeddingUserInServerId);
MessageEmbeddedModel messageEmbeddedModel = buildTemplateParameter(embeddingMessage, cachedMessage);
MessageToSend embed = templateService.renderEmbedTemplate(MESSAGE_EMBED_TEMPLATE, messageEmbeddedModel);
List<CompletableFuture<Message>> completableFutures = channelService.sendMessageToSendToChannel(embed, target);
log.trace("Embedding message {} from channel {} from server {}, because of user {}", cachedMessage.getMessageId(),
cachedMessage.getChannelId(), cachedMessage.getServerId(), cause.getUserReference().getId());
Long userInServerId = cause.getUserInServerId();
CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0])).thenAccept(aVoid -> {
try {
Message createdMessage = completableFutures.get(0).get();
messageEmbedPostManagementService.createMessageEmbed(cachedMessage, createdMessage, userInServerManagementService.loadUser(userInServerId));
messageService.addReactionToMessage(REMOVAL_EMOTE, cachedMessage.getServerId(), createdMessage);
} catch (InterruptedException | ExecutionException e) {
log.error("Failed to post message embed.", e);
}
}).exceptionally(throwable -> {
log.error("Failed to send message for embedding the link for message {} in channel {} in server {}",
cachedMessage.getMessageId(), cachedMessage.getChannelId(), cachedMessage.getServerId(), throwable);
return null;
});
Optional<AUserInAServer> causeOpt = userInServerManagementService.loadUser(userEmbeddingUserInServerId);
if(causeOpt.isPresent()) {
AUserInAServer cause = causeOpt.get();
MessageEmbeddedModel messageEmbeddedModel = buildTemplateParameter(embeddingMessage, cachedMessage);
MessageToSend embed = templateService.renderEmbedTemplate(MESSAGE_EMBED_TEMPLATE, messageEmbeddedModel);
List<CompletableFuture<Message>> completableFutures = channelService.sendMessageToSendToChannel(embed, target);
log.trace("Embedding message {} from channel {} from server {}, because of user {}", cachedMessage.getMessageId(),
cachedMessage.getChannelId(), cachedMessage.getServerId(), cause.getUserReference().getId());
Long userInServerId = cause.getUserInServerId();
CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0])).thenAccept(aVoid -> {
try {
Message createdMessage = completableFutures.get(0).get();
Optional<AUserInAServer> innerCauseOpt = userInServerManagementService.loadUser(userInServerId);
innerCauseOpt.ifPresent(aUserInAServer -> {
messageEmbedPostManagementService.createMessageEmbed(cachedMessage, createdMessage, aUserInAServer);
messageService.addReactionToMessage(REMOVAL_EMOTE, cachedMessage.getServerId(), createdMessage);
});
} catch (InterruptedException | ExecutionException e) {
log.error("Failed to post message embed.", e);
}
}).exceptionally(throwable -> {
log.error("Failed to send message for embedding the link for message {} in channel {} in server {}",
cachedMessage.getMessageId(), cachedMessage.getChannelId(), cachedMessage.getServerId(), throwable);
return null;
});
}
}
private MessageEmbeddedModel buildTemplateParameter(Message message, CachedMessage embeddedMessage) {
AChannel channel = channelManagementService.loadChannel(message.getChannel().getIdLong());
Optional<AChannel> channelOpt = channelManagementService.loadChannel(message.getChannel().getIdLong());
AServer server = serverManagementService.loadOrCreate(message.getGuild().getIdLong());
AUserInAServer user = userInServerManagementService.loadUser(message.getMember());
Member author = botService.getMemberInServer(embeddedMessage.getServerId(), embeddedMessage.getAuthorId());
@@ -145,6 +153,7 @@ public class MessageEmbedServiceBean implements MessageEmbedService {
if(textChannelFromServer.isPresent()) {
sourceChannel = textChannelFromServer.get();
}
AChannel channel = channelOpt.orElseThrow(() -> new ChannelNotFoundException(message.getChannel().getIdLong(), server.getId()));
return MessageEmbeddedModel
.builder()
.channel(channel)

View File

@@ -59,7 +59,7 @@ public class RemindServiceBean implements ReminderService {
@Override
public void createReminderInForUser(AUserInAServer user, String remindText, Duration remindIn, ReminderModel reminderModel) {
AChannel channel = channelManagementService.loadChannel(reminderModel.getChannel().getId());
AChannel channel = reminderModel.getChannel();
AServerAChannelAUser aServerAChannelAUser = AServerAChannelAUser
.builder()
.user(user.getUserReference())
@@ -98,7 +98,7 @@ public class RemindServiceBean implements ReminderService {
@Override
@Transactional
public void executeReminder(Long reminderId) {
Reminder reminderToRemindFor = reminderManagementService.loadReminder(reminderId);
Reminder reminderToRemindFor = reminderManagementService.loadReminder(reminderId).orElseThrow(() -> new AbstractoRunTimeException(String.format("Could not find reminder with id %s", reminderId)));
if(reminderToRemindFor.isReminded()) {
return;
}

View File

@@ -1,5 +1,7 @@
package dev.sheldan.abstracto.utility.service;
import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException;
import dev.sheldan.abstracto.core.exception.ChannelNotFoundException;
import dev.sheldan.abstracto.core.service.management.ChannelManagementService;
import dev.sheldan.abstracto.core.service.management.PostTargetManagement;
import dev.sheldan.abstracto.core.models.AServerAChannelMessage;
@@ -101,10 +103,10 @@ public class StarboardServiceBean implements StarboardService {
@Transactional
public void persistPost(CachedMessage message, List<Long> userExceptAuthorIds, List<CompletableFuture<Message>> completableFutures, Long starboardChannelId, Long starredUserId, Long userReactingId) {
AUserInAServer innerStarredUser = userInServerManagementService.loadUser(starredUserId);
AUserInAServer innerUserReacting = userInServerManagementService.loadUser(userReactingId);
AUserInAServer innerStarredUser = userInServerManagementService.loadUser(starredUserId).orElseThrow(() -> new AbstractoRunTimeException(String.format("Cannnot find user with id %s", starredUserId)));
AUserInAServer innerUserReacting = userInServerManagementService.loadUser(userReactingId).orElseThrow(() -> new AbstractoRunTimeException(String.format("Cannnot find user with id %s", userReactingId)));
try {
AChannel starboardChannel = channelManagementService.loadChannel(starboardChannelId);
AChannel starboardChannel = channelManagementService.loadChannel(starboardChannelId).orElseThrow(() -> new ChannelNotFoundException(starboardChannelId, message.getServerId()));
Message message1 = completableFutures.get(0).get();
AServerAChannelMessage aServerAChannelMessage = AServerAChannelMessage
.builder()
@@ -114,7 +116,7 @@ public class StarboardServiceBean implements StarboardService {
.build();
StarboardPost starboardPost = starboardPostManagementService.createStarboardPost(message, innerStarredUser, innerUserReacting, aServerAChannelMessage);
userExceptAuthorIds.forEach(aLong -> {
AUserInAServer user = userInServerManagementService.loadUser(aLong);
AUserInAServer user = userInServerManagementService.loadUser(aLong).orElseThrow(() -> new AbstractoRunTimeException(String.format("Could not find user with id %s", aLong)));
starboardPostReactorManagementService.addReactor(starboardPost, user);
});
} catch (InterruptedException | ExecutionException e) {

View File

@@ -1,5 +1,6 @@
package dev.sheldan.abstracto.utility.service;
import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException;
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
import dev.sheldan.abstracto.templating.model.MessageToSend;
import dev.sheldan.abstracto.core.service.BotService;
@@ -64,7 +65,7 @@ public class SuggestionServiceBean implements SuggestionService {
if(guildById != null) {
List<CompletableFuture<Message>> completableFutures = postTargetService.sendEmbedInPostTarget(messageToSend, SUGGESTIONS_TARGET, guildId);
CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0])).thenAccept(aVoid -> {
Suggestion innerSuggestion = suggestionManagementService.getSuggestion(suggestionId);
Suggestion innerSuggestion = suggestionManagementService.getSuggestion(suggestionId).orElseThrow(() -> new AbstractoRunTimeException(String.format("Could not find suggestion with id %s", suggestionId)));
try {
Message message = completableFutures.get(0).get();
suggestionManagementService.setPostedMessage(innerSuggestion, message);
@@ -84,7 +85,7 @@ public class SuggestionServiceBean implements SuggestionService {
@Override
public void acceptSuggestion(Long suggestionId, String text, SuggestionLog suggestionLog) {
Suggestion suggestion = suggestionManagementService.getSuggestion(suggestionId);
Suggestion suggestion = suggestionManagementService.getSuggestion(suggestionId).orElseThrow(() -> new AbstractoRunTimeException(String.format("Could not find suggestion with id %s", suggestionId)));
suggestionManagementService.setSuggestionState(suggestion, SuggestionState.ACCEPTED);
updateSuggestion(text, suggestionLog, suggestion);
}
@@ -129,7 +130,7 @@ public class SuggestionServiceBean implements SuggestionService {
@Override
public void rejectSuggestion(Long suggestionId, String text, SuggestionLog log) {
Suggestion suggestion = suggestionManagementService.getSuggestion(suggestionId);
Suggestion suggestion = suggestionManagementService.getSuggestion(suggestionId).orElseThrow(() -> new AbstractoRunTimeException(String.format("Could not find suggestion with id %s", suggestionId)));
suggestionManagementService.setSuggestionState(suggestion, SuggestionState.REJECTED);
updateSuggestion(text, log, suggestion);
}

View File

@@ -9,6 +9,7 @@ import org.springframework.stereotype.Component;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
@Component
public class ReminderManagementServiceBean implements ReminderManagementService {
@@ -34,8 +35,8 @@ public class ReminderManagementServiceBean implements ReminderManagementService
}
@Override
public Reminder loadReminder(Long reminderId) {
return reminderRepository.getOne(reminderId);
public Optional<Reminder> loadReminder(Long reminderId) {
return reminderRepository.findById(reminderId);
}
@Override

View File

@@ -1,5 +1,6 @@
package dev.sheldan.abstracto.utility.service.management;
import dev.sheldan.abstracto.core.exception.ChannelNotFoundException;
import dev.sheldan.abstracto.core.service.management.ChannelManagementService;
import dev.sheldan.abstracto.core.service.management.ServerManagementService;
import dev.sheldan.abstracto.core.service.management.UserInServerManagementService;
@@ -15,6 +16,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.Instant;
import java.util.Optional;
@Component
public class SuggestionManagementServiceBean implements SuggestionManagementService {
@@ -50,16 +52,21 @@ public class SuggestionManagementServiceBean implements SuggestionManagementServ
}
@Override
public Suggestion getSuggestion(Long suggestionId) {
return suggestionRepository.getOne(suggestionId);
public Optional<Suggestion> getSuggestion(Long suggestionId) {
return suggestionRepository.findById(suggestionId);
}
@Override
public void setPostedMessage(Suggestion suggestion, Message message) {
suggestion.setMessageId(message.getIdLong());
AChannel channel = channelManagementService.loadChannel(message.getTextChannel().getIdLong());
suggestion.setChannel(channel);
long channelId = message.getTextChannel().getIdLong();
Optional<AChannel> channelOptional = channelManagementService.loadChannel(channelId);
if(channelOptional.isPresent()) {
suggestion.setChannel(channelOptional.get());
} else {
throw new ChannelNotFoundException(channelId, suggestion.getServer().getId());
}
AServer server = serverManagementService.loadOrCreate(message.getGuild().getIdLong());
suggestion.setServer(server);
suggestionRepository.save(suggestion);

View File

@@ -6,10 +6,11 @@ import dev.sheldan.abstracto.utility.models.database.Reminder;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
public interface ReminderManagementService {
Reminder createReminder(AServerAChannelAUser userToBeReminded, String text, Instant timeToBeRemindedAt, Long messageId);
Reminder loadReminder(Long reminderId);
Optional<Reminder> loadReminder(Long reminderId);
void setReminded(Reminder reminder);
Reminder saveReminder(Reminder reminder);
List<Reminder> getActiveRemindersForUser(AUserInAServer aUserInAServer);

View File

@@ -6,10 +6,12 @@ import dev.sheldan.abstracto.utility.models.SuggestionState;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Message;
import java.util.Optional;
public interface SuggestionManagementService {
Suggestion createSuggestion(Member suggester, String text);
Suggestion createSuggestion(AUserInAServer suggester, String text);
Suggestion getSuggestion(Long suggestionId);
Optional<Suggestion> getSuggestion(Long suggestionId);
void setPostedMessage(Suggestion suggestion, Message message);
void setSuggestionState(Suggestion suggestion, SuggestionState newState);
}

View File

@@ -11,6 +11,7 @@ import dev.sheldan.abstracto.core.command.service.PostCommandExecution;
import dev.sheldan.abstracto.core.command.execution.*;
import dev.sheldan.abstracto.core.command.execution.UnParsedCommandParameter;
import dev.sheldan.abstracto.core.Constants;
import dev.sheldan.abstracto.core.exception.ChannelNotFoundException;
import dev.sheldan.abstracto.core.models.database.ARole;
import dev.sheldan.abstracto.core.service.management.ChannelManagementService;
import dev.sheldan.abstracto.core.service.management.RoleManagementService;
@@ -116,12 +117,13 @@ public class CommandReceivedHandler extends ListenerAdapter {
}
private UserInitiatedServerContext buildTemplateParameter(MessageReceivedEvent event) {
AChannel channel = channelManagementService.loadChannel(event.getChannel().getIdLong());
Optional<AChannel> channel = channelManagementService.loadChannel(event.getChannel().getIdLong());
AServer server = serverManagementService.loadOrCreate(event.getGuild().getIdLong());
AUserInAServer user = userInServerManagementService.loadUser(event.getMember());
AChannel channel1 = channel.orElseThrow(() -> new ChannelNotFoundException(event.getChannel().getIdLong(), event.getGuild().getIdLong()));
return UserInitiatedServerContext
.builder()
.channel(channel)
.channel(channel1)
.server(server)
.member(event.getMember())
.aUserInAServer(user)

View File

@@ -2,9 +2,8 @@ package dev.sheldan.abstracto.core.listener;
import dev.sheldan.abstracto.core.service.management.ChannelManagementService;
import dev.sheldan.abstracto.core.models.database.AChannelType;
import dev.sheldan.abstracto.core.models.database.AChannel;
import dev.sheldan.abstracto.core.models.database.AServer;
import dev.sheldan.abstracto.core.repository.ServerRepository;
import dev.sheldan.abstracto.core.service.management.ServerManagementService;
import lombok.extern.slf4j.Slf4j;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.events.channel.text.TextChannelCreateEvent;
@@ -21,7 +20,7 @@ import javax.annotation.Nonnull;
public class ChannelListener extends ListenerAdapter {
@Autowired
private ServerRepository serverRepository;
private ServerManagementService serverManagementService;
@Autowired
private ChannelManagementService channelManagementService;
@@ -37,7 +36,7 @@ public class ChannelListener extends ListenerAdapter {
@Transactional
public void onTextChannelCreate(@Nonnull TextChannelCreateEvent event) {
log.info("Handling channel created event. Channel {}, Server {}", event.getChannel().getIdLong(), event.getGuild().getIdLong());
AServer serverObject = serverRepository.getOne(event.getGuild().getIdLong());
AServer serverObject = serverManagementService.loadOrCreate(event.getGuild().getIdLong());
TextChannel createdChannel = event.getChannel();
AChannelType type = AChannelType.getAChannelType(createdChannel.getType());
channelManagementService.createChannel(createdChannel.getIdLong(), type, serverObject);

View File

@@ -1,6 +1,6 @@
package dev.sheldan.abstracto.core.service;
import dev.sheldan.abstracto.core.exception.ChannelException;
import dev.sheldan.abstracto.core.exception.ChannelNotFoundException;
import dev.sheldan.abstracto.core.exception.GuildException;
import dev.sheldan.abstracto.core.models.GuildChannelMember;
import dev.sheldan.abstracto.core.models.database.AEmote;
@@ -55,7 +55,7 @@ public class BotServiceBean implements BotService {
Member member = guild.getMemberById(userId);
return GuildChannelMember.builder().guild(guild).textChannel(textChannel).member(member).build();
} else {
throw new ChannelException(String.format("Text channel %s not found in guild %s", channelId, serverId));
throw new ChannelNotFoundException(channelId, serverId);
}
}
else {

View File

@@ -5,6 +5,7 @@ import dev.sheldan.abstracto.core.command.exception.CommandException;
import dev.sheldan.abstracto.core.command.models.database.ACommand;
import dev.sheldan.abstracto.core.command.service.management.ChannelGroupCommandManagementService;
import dev.sheldan.abstracto.core.command.service.management.CommandManagementService;
import dev.sheldan.abstracto.core.exception.ChannelNotFoundException;
import dev.sheldan.abstracto.core.models.database.AChannel;
import dev.sheldan.abstracto.core.models.database.AChannelGroup;
import dev.sheldan.abstracto.core.models.database.AServer;
@@ -15,6 +16,8 @@ import net.dv8tion.jda.api.entities.TextChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Optional;
@Component
public class ChannelGroupServiceBean implements ChannelGroupService {
@@ -50,13 +53,14 @@ public class ChannelGroupServiceBean implements ChannelGroupService {
@Override
public void addChannelToChannelGroup(String channelGroupName, TextChannel textChannel) {
addChannelToChannelGroup(channelGroupName, textChannel.getIdLong());
addChannelToChannelGroup(channelGroupName, textChannel.getIdLong(), textChannel.getGuild().getIdLong());
}
@Override
public void addChannelToChannelGroup(String channelGroupName, Long channelId) {
AChannel aChannel = channelManagementService.loadChannel(channelId);
addChannelToChannelGroup(channelGroupName, aChannel);
public void addChannelToChannelGroup(String channelGroupName, Long channelId, Long serverId) {
Optional<AChannel> aChannel = channelManagementService.loadChannel(channelId);
AChannel channel = aChannel.orElseThrow(() -> new ChannelNotFoundException(channelId, serverId));
addChannelToChannelGroup(channelGroupName, channel);
}
@Override
@@ -71,13 +75,14 @@ public class ChannelGroupServiceBean implements ChannelGroupService {
@Override
public void removeChannelFromChannelGroup(String channelGroupName, TextChannel textChannel) {
removeChannelFromChannelGroup(channelGroupName, textChannel.getIdLong());
removeChannelFromChannelGroup(channelGroupName, textChannel.getIdLong(), textChannel.getGuild().getIdLong());
}
@Override
public void removeChannelFromChannelGroup(String channelGroupName, Long channelId) {
AChannel aChannel = channelManagementService.loadChannel(channelId);
removeChannelFromChannelGroup(channelGroupName, aChannel);
public void removeChannelFromChannelGroup(String channelGroupName, Long channelId, Long serverId) {
Optional<AChannel> aChannel = channelManagementService.loadChannel(channelId);
AChannel channel = aChannel.orElseThrow(() -> new ChannelNotFoundException(channelId, serverId));
removeChannelFromChannelGroup(channelGroupName, channel);
}
@Override

View File

@@ -1,7 +1,7 @@
package dev.sheldan.abstracto.core.service;
import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException;
import dev.sheldan.abstracto.core.exception.ChannelException;
import dev.sheldan.abstracto.core.exception.ChannelNotFoundException;
import dev.sheldan.abstracto.core.exception.GuildException;
import dev.sheldan.abstracto.core.models.database.AServer;
import dev.sheldan.abstracto.templating.model.MessageToSend;
@@ -15,7 +15,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.nio.channels.Channel;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@@ -50,7 +49,7 @@ public class ChannelServiceBean implements ChannelService {
return sendTextToChannel(text, textChannel);
} else {
log.error("Channel {} to post towards was not found in server {}", channel.getId(), channel.getServer().getId());
throw new ChannelException(String.format("Channel %s to post to not found.", channel.getId()));
throw new ChannelNotFoundException(channel.getId(), channel.getServer().getId());
}
} else {
log.error("Guild {} was not found when trying to post a message", channel.getServer().getId());
@@ -65,7 +64,7 @@ public class ChannelServiceBean implements ChannelService {
TextChannel textChannel = textChannelOpt.get();
return sendMessageToChannel(message, textChannel);
}
throw new ChannelException(String.format("Channel %s in guild %s not found.", channel.getId(), channel.getServer().getId()));
throw new ChannelNotFoundException(channel.getId(), channel.getServer().getId());
}
@Override
@@ -87,7 +86,7 @@ public class ChannelServiceBean implements ChannelService {
return sendEmbedToChannel(embed, textChannel);
} else {
log.error("Channel {} to post towards was not found in server {}", channel.getId(), channel.getServer().getId());
throw new ChannelException(String.format("Channel %s to post to not found.", channel.getId()));
throw new ChannelNotFoundException(channel.getId(), guild.getIdLong());
}
} else {
log.error("Guild {} was not found when trying to post a message", channel.getServer().getId());
@@ -106,7 +105,7 @@ public class ChannelServiceBean implements ChannelService {
if(textChannelFromServer.isPresent()) {
return sendMessageToSendToChannel(messageToSend, textChannelFromServer.get());
}
throw new ChannelException(String.format("Channel %s was not found.", channel.getId()));
throw new ChannelNotFoundException(channel.getId(), channel.getServer().getId());
}
@Override
@@ -144,7 +143,7 @@ public class ChannelServiceBean implements ChannelService {
TextChannel textChannel = textChannelFromServer.get();
editMessageInAChannel(messageToSend, textChannel, messageId);
} else {
throw new ChannelException(String.format("Channel %s was not found.", channel.getId()));
throw new ChannelNotFoundException(channel.getId(), channel.getServer().getId());
}
}
@@ -177,7 +176,7 @@ public class ChannelServiceBean implements ChannelService {
if(textChannelById != null) {
return textChannelById.delete().submit();
}
throw new ChannelException(String.format("Failed to delete channel %s in server %s", channelId, serverId));
throw new ChannelNotFoundException(channelId, serverId);
}
@Override

View File

@@ -1,6 +1,6 @@
package dev.sheldan.abstracto.core.service;
import dev.sheldan.abstracto.core.exception.ChannelException;
import dev.sheldan.abstracto.core.exception.ChannelNotFoundException;
import dev.sheldan.abstracto.core.exception.GuildException;
import dev.sheldan.abstracto.core.models.cache.CachedMessage;
import dev.sheldan.abstracto.core.models.cache.CachedReaction;
@@ -100,7 +100,7 @@ public class MessageCacheBean implements MessageCache {
);
} else {
log.error("Not able to load message {} in channel {} in guild {}. Text channel not found.", messageId, textChannelId, guildId);
future.completeExceptionally(new ChannelException(String.format("Not able to load message %s. Text channel %s not found in guild %s", messageId, textChannelId, guildId)));
future.completeExceptionally(new ChannelNotFoundException(textChannelId, guildId));
}
} else {
log.error("Not able to load message {} in channel {} in guild {}. Guild not found.", messageId, textChannelId, guildId);

View File

@@ -1,7 +1,7 @@
package dev.sheldan.abstracto.core.service;
import dev.sheldan.abstracto.core.config.DynamicKeyLoader;
import dev.sheldan.abstracto.core.exception.ChannelException;
import dev.sheldan.abstracto.core.exception.ChannelNotFoundException;
import dev.sheldan.abstracto.core.exception.GuildException;
import dev.sheldan.abstracto.core.exception.PostTargetException;
import dev.sheldan.abstracto.core.service.management.PostTargetManagement;
@@ -57,8 +57,7 @@ public class PostTargetServiceBean implements PostTargetService {
} else {
log.error("Incorrect post target configuration: {} points to {} on server {}", target.getName(),
target.getChannelReference().getId(), target.getServerReference().getId());
throw new ChannelException(String.format("Incorrect post target configuration. The channel %s of target %s cannot be found",
target.getChannelReference().getId(), target.getChannelReference().getId()));
throw new ChannelNotFoundException(target.getChannelReference().getId(), target.getServerReference().getId());
}
} else {
throw new GuildException(String.format("Incorrect post target configuration. Guild %s cannot be found.", target.getServerReference().getId()));
@@ -172,7 +171,7 @@ public class PostTargetServiceBean implements PostTargetService {
public void throwIfPostTargetIsNotDefined(String name, Long serverId) {
PostTarget postTarget = postTargetManagement.getPostTarget(name, serverId);
if(postTarget == null) {
throw new ChannelException(String.format("Post target %s is not defined.", name));
throw new PostTargetException(String.format("Post target %s is not defined.", name));
}
}

View File

@@ -10,6 +10,7 @@ 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.Role;
import org.aspectj.lang.annotation.Around;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@@ -66,12 +67,9 @@ public class RoleServiceBean implements RoleService {
@Override
public void markDeleted(Long id, AServer server) {
ARole role = roleManagementService.findRole(id, server);
if(role != null) {
roleManagementService.markDeleted(role);
} else {
throw new RoleException(String.format("Cannot find role %s to mark as deleted.", id));
}
Optional<ARole> role = roleManagementService.findRole(id, server);
ARole role1 = role.orElseThrow(() -> new RoleException(String.format("Cannot find role %s to mark as deleted.", id)));
roleManagementService.markDeleted(role1);
}
@Override

View File

@@ -1,7 +1,7 @@
package dev.sheldan.abstracto.core.service.management;
import dev.sheldan.abstracto.core.command.exception.ChannelGroupException;
import dev.sheldan.abstracto.core.exception.ChannelException;
import dev.sheldan.abstracto.core.exception.ChannelNotFoundException;
import dev.sheldan.abstracto.core.models.database.AChannel;
import dev.sheldan.abstracto.core.models.database.AChannelGroup;
import dev.sheldan.abstracto.core.models.database.AServer;
@@ -25,7 +25,7 @@ public class ChannelGroupManagementServiceBean implements ChannelGroupManagement
public AChannelGroup createChannelGroup(String name, AServer server) {
name = name.toLowerCase();
if(doesChannelGroupExist(name, server)) {
throw new ChannelException("Channel group already exists.");
throw new ChannelGroupException("Channel group already exists.");
}
AChannelGroup channelGroup = AChannelGroup
.builder()
@@ -58,7 +58,7 @@ public class ChannelGroupManagementServiceBean implements ChannelGroupManagement
throw new ChannelGroupException("Channel group was not found.");
}
if(channelGroup.getChannels().stream().anyMatch(channelInGroupPredicate)) {
throw new ChannelException(String.format("Channel %s is already part of group %s.", channel.getId(), channelGroup.getGroupName()));
throw new ChannelGroupException(String.format("Channel %s is already part of group %s.", channel.getId(), channelGroup.getGroupName()));
}
channelGroup.getChannels().add(channel);
channel.getGroups().add(channelGroup);
@@ -69,7 +69,7 @@ public class ChannelGroupManagementServiceBean implements ChannelGroupManagement
public void removeChannelFromChannelGroup(AChannelGroup channelGroup, AChannel channel) {
Predicate<AChannel> channelInGroupPredicate = channel1 -> channel1.getId().equals(channel.getId());
if(channelGroup.getChannels().stream().noneMatch(channelInGroupPredicate)) {
throw new ChannelException(String.format("Channel %s is not part of group %s.", channel.getId(), channelGroup.getGroupName()));
throw new ChannelGroupException(String.format("Channel %s is not part of group %s.", channel.getId(), channelGroup.getGroupName()));
}
channelGroup.getChannels().removeIf(channelInGroupPredicate);
channel.getGroups().removeIf(channelGroup1 -> channelGroup1.getId().equals(channelGroup.getId()));

View File

@@ -1,6 +1,7 @@
package dev.sheldan.abstracto.core.service.management;
import dev.sheldan.abstracto.core.command.models.TableLocks;
import dev.sheldan.abstracto.core.exception.ChannelNotFoundException;
import dev.sheldan.abstracto.core.models.database.AChannel;
import dev.sheldan.abstracto.core.models.database.AChannelType;
import dev.sheldan.abstracto.core.models.database.AServer;
@@ -10,6 +11,8 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
@Slf4j
public class ChannelManagementServiceBean implements ChannelManagementService {
@@ -21,8 +24,8 @@ public class ChannelManagementServiceBean implements ChannelManagementService {
private LockService lockService;
@Override
public AChannel loadChannel(Long id) {
return repository.getOne(id);
public Optional<AChannel> loadChannel(Long id) {
return repository.findById(id);
}
@Override
@@ -39,13 +42,14 @@ public class ChannelManagementServiceBean implements ChannelManagementService {
.build();
return repository.save(build);
} else {
return loadChannel(id);
return loadChannel(id).get();
}
}
@Override
public AChannel markAsDeleted(Long id) {
AChannel channel = loadChannel(id);
Optional<AChannel> channelOptional = loadChannel(id);
AChannel channel = channelOptional.orElseThrow(() -> new ChannelNotFoundException(id, 0L));
channel.setDeleted(true);
return channel;
}

View File

@@ -25,8 +25,8 @@ public class EmoteManagementServiceBean implements EmoteManagementService {
private DynamicKeyLoader dynamicKeyLoader;
@Override
public AEmote loadEmote(Long id) {
return repository.getOne(id);
public Optional<AEmote> loadEmote(Long id) {
return repository.findById(id);
}
@Override

View File

@@ -1,6 +1,7 @@
package dev.sheldan.abstracto.core.service.management;
import dev.sheldan.abstracto.core.config.DynamicKeyLoader;
import dev.sheldan.abstracto.core.exception.ChannelNotFoundException;
import dev.sheldan.abstracto.core.exception.PostTargetException;
import dev.sheldan.abstracto.core.models.database.AChannel;
import dev.sheldan.abstracto.core.models.database.AServer;
@@ -11,6 +12,8 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
@Slf4j
public class PostTargetManagementBean implements PostTargetManagement {
@@ -53,13 +56,15 @@ public class PostTargetManagementBean implements PostTargetManagement {
@Override
public PostTarget createOrUpdate(String name, AServer server, Long channelId) {
AChannel dbChannel = channelManagementService.loadChannel(channelId);
Optional<AChannel> dbChannelOpt = channelManagementService.loadChannel(channelId);
AChannel dbChannel = dbChannelOpt.orElseThrow(() -> new ChannelNotFoundException(channelId, server.getId()));
return createOrUpdate(name, server, dbChannel);
}
@Override
public PostTarget createOrUpdate(String name, Long serverId, Long channelId) {
AChannel dbChannel = channelManagementService.loadChannel(channelId);
Optional<AChannel> dbChannelOpt = channelManagementService.loadChannel(channelId);
AChannel dbChannel = dbChannelOpt.orElseThrow(() -> new ChannelNotFoundException(channelId, serverId));
AServer dbServer = serverManagementService.loadOrCreate(serverId);
return createOrUpdate(name, dbServer, dbChannel);
}

View File

@@ -6,6 +6,8 @@ import dev.sheldan.abstracto.core.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class RoleManagementServiceBean implements RoleManagementService {
@@ -24,8 +26,8 @@ public class RoleManagementServiceBean implements RoleManagementService {
}
@Override
public ARole findRole(Long id, AServer server) {
return repository.getOne(id);
public Optional<ARole> findRole(Long id, AServer server) {
return repository.findById(id);
}
@Override

View File

@@ -1,5 +1,6 @@
package dev.sheldan.abstracto.core.service.management;
import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException;
import dev.sheldan.abstracto.core.models.database.*;
import dev.sheldan.abstracto.core.repository.ServerRepository;
import lombok.extern.slf4j.Slf4j;
@@ -7,6 +8,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
@Slf4j
@@ -29,7 +31,7 @@ public class ServerManagementServiceBean implements ServerManagementService {
@Override
public AServer loadOrCreate(Long id) {
if(repository.existsById(id)) {
return repository.getOne(id);
return repository.findById(id).get();
} else {
return createServer(id);
}
@@ -49,10 +51,11 @@ public class ServerManagementServiceBean implements ServerManagementService {
@Override
public AUserInAServer addUserToServer(Long serverId, Long userId) {
log.info("Adding user {} to server {}", userId, serverId);
AServer server = repository.getOne(serverId);
Optional<AServer> server = repository.findById(serverId);
AUser user = userManagementService.loadUser(userId);
AUserInAServer aUserInAServer = AUserInAServer.builder().serverReference(server).userReference(user).build();
server.getUsers().add(aUserInAServer);
AServer serverReference = server.orElseThrow(() -> new AbstractoRunTimeException(String.format("Cannnot find server %s", serverId)));
AUserInAServer aUserInAServer = AUserInAServer.builder().serverReference(serverReference).userReference(user).build();
serverReference.getUsers().add(aUserInAServer);
return aUserInAServer;
}

View File

@@ -10,6 +10,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Optional;
@Component
@Slf4j
@@ -47,8 +48,8 @@ public class UserInServerManagementServiceBean implements UserInServerManagement
}
@Override
public AUserInAServer loadUser(Long userInServerId) {
return userInServerRepository.getOne(userInServerId);
public Optional<AUserInAServer> loadUser(Long userInServerId) {
return userInServerRepository.findById(userInServerId);
}
@Override

View File

@@ -30,7 +30,7 @@ public class UserManagementServiceBean implements UserManagementService {
@Override
public AUser loadUser(Long userId) {
if(userRepository.existsById(userId)) {
return userRepository.getOne(userId);
return userRepository.findById(userId).get();
} else {
return this.createUser(userId);
}

View File

@@ -1,7 +0,0 @@
package dev.sheldan.abstracto.core.exception;
public class ChannelException extends AbstractoRunTimeException {
public ChannelException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,34 @@
package dev.sheldan.abstracto.core.exception;
import dev.sheldan.abstracto.templating.Templatable;
import java.util.HashMap;
public class ChannelNotFoundException extends AbstractoRunTimeException implements Templatable {
private Long channelId;
private Long guildId;
public ChannelNotFoundException(String message) {
super(message);
}
public ChannelNotFoundException(Long channelId, Long guildId) {
super("");
this.channelId = channelId;
this.guildId = guildId;
}
@Override
public String getTemplateName() {
return "channel_not_found_exception";
}
@Override
public Object getTemplateModel() {
HashMap<String, Long> param = new HashMap<>();
param.put("channelId", this.channelId);
param.put("guildID", this.guildId);
return param;
}
}

View File

@@ -8,10 +8,10 @@ public interface ChannelGroupService {
AChannelGroup createChannelGroup(String name, Long serverId);
void deleteChannelGroup(String name, Long serverId);
void addChannelToChannelGroup(String channelGroupName, TextChannel textChannel);
void addChannelToChannelGroup(String channelGroupName, Long channelId);
void addChannelToChannelGroup(String channelGroupName, Long channelId, Long serverId);
void addChannelToChannelGroup(String channelGroupName, AChannel channel);
void removeChannelFromChannelGroup(String channelGroupName, TextChannel textChannel);
void removeChannelFromChannelGroup(String channelGroupName, Long channelId);
void removeChannelFromChannelGroup(String channelGroupName, Long channelId, Long serverId);
void removeChannelFromChannelGroup(String channelGroupName, AChannel channel);
void disableCommandInChannelGroup(String commandName, String channelGroupName, Long serverId);
void enableCommandInChannelGroup(String commandName, String channelGroupName, Long serverId);

View File

@@ -4,8 +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.AServer;
import java.util.Optional;
public interface ChannelManagementService {
AChannel loadChannel(Long id);
Optional<AChannel> loadChannel(Long id);
AChannel createChannel(Long id, AChannelType type, AServer server);
AChannel markAsDeleted(Long id);
boolean channelExists(Long id);

View File

@@ -7,7 +7,7 @@ import net.dv8tion.jda.api.entities.Emote;
import java.util.Optional;
public interface EmoteManagementService {
AEmote loadEmote(Long id);
Optional<AEmote> loadEmote(Long id);
AEmote createCustomEmote(String name, String emoteKey, Long emoteId, Boolean animated, Long serverId) ;
AEmote createCustomEmote(String name, String emoteKey, Long emoteId, Boolean animated, AServer server) ;
AEmote createDefaultEmote(String name, String emoteKey, Long serverId) ;

View File

@@ -3,8 +3,10 @@ package dev.sheldan.abstracto.core.service.management;
import dev.sheldan.abstracto.core.models.database.ARole;
import dev.sheldan.abstracto.core.models.database.AServer;
import java.util.Optional;
public interface RoleManagementService {
ARole createRole(Long id, AServer server);
ARole findRole(Long id, AServer server);
Optional<ARole> findRole(Long id, AServer server);
void markDeleted(ARole role);
}

View File

@@ -6,12 +6,13 @@ import dev.sheldan.abstracto.core.models.database.AUserInAServer;
import net.dv8tion.jda.api.entities.Member;
import java.util.List;
import java.util.Optional;
public interface UserInServerManagementService {
AUserInAServer loadUser(Long serverId, Long userId);
AUserInAServer loadUser(AServer server, AUser user);
AUserInAServer loadUser(Member member);
AUserInAServer loadUser(Long userInServerId);
Optional<AUserInAServer> loadUser(Long userInServerId);
AUserInAServer createUserInServer(Member member);
AUserInAServer createUserInServer(Long guildId, Long userId);
List<AUserInAServer> getUserInAllServers(Long userId);

View File

@@ -1,6 +1,8 @@
package dev.sheldan.abstracto.core.utils;
import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException;
import dev.sheldan.abstracto.core.exception.ChannelNotFoundException;
import dev.sheldan.abstracto.core.models.database.AChannel;
import dev.sheldan.abstracto.core.service.management.ChannelManagementService;
import dev.sheldan.abstracto.core.service.management.UserInServerManagementService;
import dev.sheldan.abstracto.core.models.cache.CachedMessage;
@@ -14,6 +16,7 @@ import org.springframework.stereotype.Component;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Optional;
@Component
@Slf4j
@@ -35,11 +38,13 @@ public class ContextUtils {
m = clazz.getMethod("builder");
UserInitiatedServerContext.UserInitiatedServerContextBuilder<?, ?> builder = (UserInitiatedServerContext.UserInitiatedServerContextBuilder) m.invoke(null, null);
AUserInAServer aUserInAServer = userInServerManagementService.loadUser(message.getServerId(), message.getAuthorId());
Optional<AChannel> channelOptional = channelManagementService.loadChannel(message.getChannelId());
AChannel channel = channelOptional.orElseThrow(() -> new ChannelNotFoundException(message.getChannelId(), message.getServerId()));
return builder
.member(guildChannelMember.getMember())
.guild(guildChannelMember.getGuild())
.messageChannel(guildChannelMember.getTextChannel())
.channel(channelManagementService.loadChannel(message.getChannelId()))
.channel(channel)
.server(aUserInAServer.getServerReference())
.aUserInAServer(aUserInAServer)
.user(aUserInAServer.getUserReference())

View File

@@ -17,6 +17,8 @@ import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Optional;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
@@ -47,7 +49,8 @@ public class ContextUtilsTest {
AUserInAServer aUserInAServer = AUserInAServer.builder().userReference(AUser.builder().id(AUTHOR_ID).build()).serverReference(server).build();
when(userInServerManagementService.loadUser(eq(SERVER_ID), eq(AUTHOR_ID))).thenReturn(aUserInAServer);
AChannel channel = AChannel.builder().id(CHANNEL_ID).build();
when(channelManagementService.loadChannel(eq(CHANNEL_ID))).thenReturn(channel);
Optional<AChannel> op = Optional.of(channel);
when(channelManagementService.loadChannel(eq(CHANNEL_ID))).thenReturn(op);
}
@Test

View File

@@ -0,0 +1 @@
The channel ${channelId} was not found in guild ${guildId}.

View File

@@ -10,6 +10,7 @@ import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Optional;
/**
* Loads the the template from the database to be used by Freemarker. This bean is also used when the templates within
@@ -37,12 +38,8 @@ public class DatabaseTemplateLoader implements TemplateLoader {
@Override
public long getLastModified(Object o) {
Template casted = (Template) o;
Template templateByKey = templateManagementService.getTemplateByKey(casted.getKey());
if(templateByKey != null){
return templateByKey.getLastModified().getEpochSecond();
} else {
return Long.MAX_VALUE;
}
Optional<Template> templateByKey = templateManagementService.getTemplateByKey(casted.getKey());
return templateByKey.map(template -> template.getLastModified().getEpochSecond()).orElse(Long.MAX_VALUE);
}
/**

View File

@@ -7,6 +7,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.Instant;
import java.util.Optional;
/**
* ManagementService bean used to retrieve the templates by key from the database.
@@ -20,8 +21,8 @@ public class TemplateManagementServiceBean implements TemplateManagementService
private TemplateRepository repository;
@Override
public Template getTemplateByKey(String key) {
return repository.getOne(key);
public Optional<Template> getTemplateByKey(String key) {
return repository.findById(key);
}
@Override

View File

@@ -2,6 +2,8 @@ package dev.sheldan.abstracto.templating.service.management;
import dev.sheldan.abstracto.templating.model.database.Template;
import java.util.Optional;
/**
* Provides methods to access the stored templates.
*/
@@ -9,9 +11,9 @@ public interface TemplateManagementService {
/**
* Retrieves the template identified by the key.
* @param key They template key to search for
* @return The {@link Template} identified by the key, if it exists.
* @return An {@link Optional} containing the {@link Template} if it exists, and null otherwise
*/
Template getTemplateByKey(String key);
Optional<Template> getTemplateByKey(String key);
/**
* Checks whether or not the template exists in the database.