[AB-139] changing the places at which there might be an uncached member object

fixing integer validator
fixing syncing roles not working if the role did not change in the database
fixing warn id being flipped
fixing star stats model
This commit is contained in:
Sheldan
2020-10-11 22:04:18 +02:00
parent 1d3c414d6b
commit 36d11371cb
105 changed files with 1762 additions and 1086 deletions

View File

@@ -19,6 +19,7 @@ import dev.sheldan.abstracto.core.service.EmoteService;
import dev.sheldan.abstracto.core.service.RoleService;
import dev.sheldan.abstracto.core.service.management.*;
import dev.sheldan.abstracto.core.models.context.UserInitiatedServerContext;
import dev.sheldan.abstracto.core.utils.FutureUtils;
import lombok.extern.slf4j.Slf4j;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
@@ -30,6 +31,7 @@ import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Nonnull;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import static java.util.Comparator.comparing;
@@ -106,27 +108,24 @@ public class CommandReceivedHandler extends ListenerAdapter {
tryToExecuteFoundCommand(event, commandContextBuilder, foundCommand, unParsedParameter);
} catch (Exception e) {
log.error("Exception when executing command.", e);
CommandResult commandResult = CommandResult.fromError(e.getMessage(), e);
CommandContext commandContext = commandContextBuilder.build();
self.executePostCommandListener(null, commandContext, commandResult);
reportException(commandContextBuilder, null, e, "Exception when executing command.");
}
}
private void tryToExecuteFoundCommand(@Nonnull MessageReceivedEvent event, CommandContext.CommandContextBuilder commandContextBuilder, Command foundCommand, UnParsedCommandParameter unParsedParameter) {
try {
Parameters parsedParameters = getParsedParameters(unParsedParameter, foundCommand, event.getMessage());
CompletableFuture<Parameters> parsingFuture = getParsedParameters(unParsedParameter, foundCommand, event.getMessage());
parsingFuture.thenAccept(parsedParameters -> {
validateCommandParameters(parsedParameters, foundCommand);
CommandContext commandContext = commandContextBuilder.parameters(parsedParameters).build();
ConditionResult conditionResult = commandService.isCommandExecutable(foundCommand, commandContext);
CommandResult commandResult = null;
if(conditionResult.isResult()) {
if(foundCommand.getConfiguration().isAsync()) {
log.info("Executing async command {} for server {} in channel {} based on message {} by user {}.",
foundCommand.getConfiguration().getName(), commandContext.getGuild().getId(), commandContext.getChannel().getId(), commandContext.getMessage().getId(), commandContext.getAuthor().getId());
if(foundCommand.getConfiguration().isAsync()) {
log.info("Executing async command {} for server {} in channel {} based on message {} by user {}.",
foundCommand.getConfiguration().getName(), commandContext.getGuild().getId(), commandContext.getChannel().getId(), commandContext.getMessage().getId(), commandContext.getAuthor().getId());
foundCommand.executeAsync(commandContext).thenAccept(result ->
executePostCommandListener(foundCommand, commandContext, result)
foundCommand.executeAsync(commandContext).thenAccept(result ->
executePostCommandListener(foundCommand, commandContext, result)
).exceptionally(throwable -> {
log.error("Asynchronous command {} failed.", foundCommand.getConfiguration().getName(), throwable);
UserInitiatedServerContext rebuildUserContext = buildTemplateParameter(event);
@@ -155,12 +154,21 @@ public class CommandReceivedHandler extends ListenerAdapter {
if(commandResult != null) {
self.executePostCommandListener(foundCommand, commandContext, commandResult);
}
} catch (Exception e) {
log.error("Exception when executing command.", e);
CommandResult commandResult = CommandResult.fromError(e.getMessage(), e);
CommandContext commandContext = commandContextBuilder.build();
self.executePostCommandListener(foundCommand, commandContext, commandResult);
}
}).exceptionally(throwable -> {
reportException(commandContextBuilder, foundCommand, throwable, "Exception when executing command.");
return null;
});
parsingFuture.exceptionally(throwable -> {
reportException(commandContextBuilder, foundCommand, throwable, "Exception when parsing command.");
return null;
});
}
private void reportException(CommandContext.CommandContextBuilder commandContextBuilder, Command foundCommand, Throwable throwable, String s) {
log.error(s, throwable);
CommandResult commandResult = CommandResult.fromError(throwable.getMessage(), throwable);
CommandContext commandContext = commandContextBuilder.build();
self.executePostCommandListener(foundCommand, commandContext, commandResult);
}
private void validateCommandParameters(Parameters parameters, Command foundCommand) {
@@ -210,10 +218,10 @@ public class CommandReceivedHandler extends ListenerAdapter {
.build();
}
public Parameters getParsedParameters(UnParsedCommandParameter unParsedCommandParameter, Command command, Message message){
public CompletableFuture<Parameters> getParsedParameters(UnParsedCommandParameter unParsedCommandParameter, Command command, Message message){
List<Object> parsedParameters = new ArrayList<>();
if(command.getConfiguration().getParameters() == null || command.getConfiguration().getParameters().isEmpty()) {
return Parameters.builder().parameters(parsedParameters).build();
return CompletableFuture.completedFuture(Parameters.builder().parameters(parsedParameters).build());
}
log.trace("Parsing parameters for command {} based on message {}.", command.getConfiguration().getName(), message.getId());
Iterator<TextChannel> channelIterator = message.getMentionedChannels().iterator();
@@ -224,6 +232,7 @@ public class CommandReceivedHandler extends ListenerAdapter {
CommandParameterIterators iterators = new CommandParameterIterators(channelIterator, emoteIterator, memberIterator, roleIterator);
boolean reminderActive = false;
List<CommandParameterHandler> orderedHandlers = parameterHandlers.stream().sorted(comparing(CommandParameterHandler::getPriority)).collect(Collectors.toList());
List<CompletableFuture> futures = new ArrayList<>();
for (int i = 0; i < unParsedCommandParameter.getParameters().size(); i++) {
if(i < command.getConfiguration().getParameters().size() && !param.isRemainder()) {
param = command.getConfiguration().getParameters().get(i);
@@ -236,7 +245,13 @@ public class CommandReceivedHandler extends ListenerAdapter {
try {
if(handler.handles(param.getType())) {
handlerMatched = true;
parsedParameters.add(handler.handle(value, iterators, param.getType(), message));
if(handler.async()) {
CompletableFuture future = handler.handleAsync(value, iterators, param.getType(), message);
futures.add(future);
parsedParameters.add(future);
} else {
parsedParameters.add(handler.handle(value, iterators, param.getType(), message));
}
break;
}
} catch (Exception e) {
@@ -256,9 +271,22 @@ public class CommandReceivedHandler extends ListenerAdapter {
}
}
}
}
return Parameters.builder().parameters(parsedParameters).build();
if(!futures.isEmpty()) {
return FutureUtils.toSingleFuture(futures).thenApply(aVoid -> {
List<Object> usableParameters = parsedParameters.stream().map(o -> {
if(o instanceof CompletableFuture) {
return ((CompletableFuture) o).join();
} else {
return o;
}
}).collect(Collectors.toList());
return Parameters.builder().parameters(usableParameters).build();
});
} else {
Parameters parameters = Parameters.builder().parameters(parsedParameters).build();
return CompletableFuture.completedFuture(parameters);
}
}
}

View File

@@ -5,6 +5,7 @@ import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.Message;
import org.springframework.stereotype.Component;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Matcher;
@Component
@@ -15,14 +16,19 @@ public class MemberParameterHandler implements CommandParameterHandler {
}
@Override
public Object handle(String input, CommandParameterIterators iterators, Class clazz, Message context) {
public boolean async() {
return true;
}
@Override
public CompletableFuture<Object> handleAsync(String input, CommandParameterIterators iterators, Class clazz, Message context) {
Matcher matcher = Message.MentionType.USER.getPattern().matcher(input);
if(matcher.matches()) {
return iterators.getMemberIterator().next();
return CompletableFuture.completedFuture(iterators.getMemberIterator().next());
} else {
// TODO add handling for names
long emoteId = Long.parseLong(input);
return context.getGuild().getMemberById(emoteId);
long userId = Long.parseLong(input);
return context.getGuild().retrieveMemberById(userId).submit().thenApply(member -> member);
}
}

View File

@@ -76,24 +76,29 @@ public class MessageDeletedListenerBean extends ListenerAdapter {
.channel(channelManagementService.loadChannel(cachedMessage.getChannelId()))
.aUserInAServer(userInServerManagementService.loadUser(cachedMessage.getServerId(), cachedMessage.getAuthorId()))
.build();
GuildChannelMember authorMember = GuildChannelMember
.builder()
.guild(botService.getGuildByIdNullable(cachedMessage.getServerId()))
.textChannel(botService.getTextChannelFromServerOptional(cachedMessage.getServerId(), cachedMessage.getChannelId()).orElseThrow(() -> new ChannelNotFoundException(cachedMessage.getChannelId())))
.member(botService.getMemberInServer(cachedMessage.getServerId(), cachedMessage.getAuthorId()))
.build();
listener.forEach(messageDeletedListener -> {
FeatureConfig feature = featureConfigService.getFeatureDisplayForFeature(messageDeletedListener.getFeature());
if(!featureFlagService.isFeatureEnabled(feature, cachedMessage.getServerId())) {
return;
}
try {
self.executeIndividualMessageDeletedListener(cachedMessage, authorUser, authorMember, messageDeletedListener);
} catch (AbstractoRunTimeException e) {
log.error("Listener {} failed with exception:", messageDeletedListener.getClass().getName(), e);
}
botService.getMemberInServerAsync(cachedMessage.getServerId(), cachedMessage.getAuthorId()).thenAccept(member -> {
GuildChannelMember authorMember = GuildChannelMember
.builder()
.guild(botService.getGuildById(cachedMessage.getServerId()))
.textChannel(botService.getTextChannelFromServerOptional(cachedMessage.getServerId(), cachedMessage.getChannelId()).orElseThrow(() -> new ChannelNotFoundException(cachedMessage.getChannelId())))
.member(botService.getMemberInServer(cachedMessage.getServerId(), cachedMessage.getAuthorId()))
.build();
listener.forEach(messageDeletedListener -> {
FeatureConfig feature = featureConfigService.getFeatureDisplayForFeature(messageDeletedListener.getFeature());
if(!featureFlagService.isFeatureEnabled(feature, cachedMessage.getServerId())) {
return;
}
try {
self.executeIndividualMessageDeletedListener(cachedMessage, authorUser, authorMember, messageDeletedListener);
} catch (AbstractoRunTimeException e) {
log.error("Listener {} failed with exception:", messageDeletedListener.getClass().getName(), e);
}
});
}).exceptionally(throwable -> {
log.error("Message deleted listener failed.", throwable);
return null;
});
}
@Transactional(propagation = Propagation.REQUIRES_NEW)

View File

@@ -50,9 +50,7 @@ public class BotServiceBean implements BotService {
@Override
public GuildChannelMember getServerChannelUser(Long serverId, Long channelId, Long userId) {
log.trace("Trying to retrieve member {}, channel {} in server {} from cache.", userId, channelId, serverId);
Optional<Guild> guildOptional = getGuildById(serverId);
if(guildOptional.isPresent()) {
Guild guild = guildOptional.get();
Guild guild = getGuildById(serverId);
Optional<TextChannel> textChannelOptional = this.getTextChannelFromServerOptional(guild, channelId);
if(textChannelOptional.isPresent()) {
TextChannel textChannel = textChannelOptional.get();
@@ -61,10 +59,18 @@ public class BotServiceBean implements BotService {
} else {
throw new ChannelNotFoundException(channelId);
}
}
else {
throw new GuildNotFoundException(serverId);
}
}
@Override
public CompletableFuture<GuildChannelMember> getServerChannelUserAsync(Long serverId, Long channelId, Long userId) {
log.trace("Trying to retrieve member {}, channel {} in server {} async.", userId, channelId, serverId);
CompletableFuture<Member> memberFuture = getMemberInServerAsync(serverId, userId);
Guild guild = getGuildById(serverId);
TextChannel textChannel = this.getTextChannelFromServer(guild, channelId);
return memberFuture.thenApply(member ->
GuildChannelMember.builder().guild(guild).textChannel(textChannel).member(member).build()
);
}
@Override
@@ -78,6 +84,17 @@ public class BotServiceBean implements BotService {
}
}
@Override
public CompletableFuture<Member> getMemberInServerAsync(Long serverId, Long memberId) {
log.trace("Retrieving member {} in server {} from cache.", memberId, serverId);
Guild guildById = instance.getGuildById(serverId);
if(guildById != null) {
return guildById.retrieveMemberById(memberId).submit();
} else {
throw new GuildNotFoundException(serverId);
}
}
@Override
public boolean isUserInGuild(AUserInAServer aUserInAServer) {
Guild guildById = instance.getGuildById(aUserInAServer.getServerReference().getId());
@@ -98,6 +115,11 @@ public class BotServiceBean implements BotService {
return getMemberInServer(aUserInAServer.getServerReference().getId(), aUserInAServer.getUserReference().getId());
}
@Override
public CompletableFuture<Member> getMemberInServerAsync(AUserInAServer aUserInAServer) {
return getMemberInServerAsync(aUserInAServer.getServerReference().getId(), aUserInAServer.getUserReference().getId());
}
@Override
public Member getMemberInServer(AServer server, AUser member) {
return getMemberInServer(server.getId(), member.getId());
@@ -139,7 +161,7 @@ public class BotServiceBean implements BotService {
if(Boolean.FALSE.equals(emote.getCustom())) {
return Optional.empty();
}
Optional<Guild> guildById = getGuildById(serverId);
Optional<Guild> guildById = getGuildByIdOptional(serverId);
if(guildById.isPresent()) {
Guild guild = guildById.get();
Emote emoteById = guild.getEmoteById(emote.getEmoteId());
@@ -168,7 +190,7 @@ public class BotServiceBean implements BotService {
@Override
public Optional<TextChannel> getTextChannelFromServerOptional(Long serverId, Long textChannelId) {
Optional<Guild> guildOptional = getGuildById(serverId);
Optional<Guild> guildOptional = getGuildByIdOptional(serverId);
if(guildOptional.isPresent()) {
Guild guild = guildOptional.get();
return Optional.ofNullable(guild.getTextChannelById(textChannelId));
@@ -182,22 +204,22 @@ public class BotServiceBean implements BotService {
}
@Override
public Optional<Guild> getGuildById(Long serverId) {
public Optional<Guild> getGuildByIdOptional(Long serverId) {
return Optional.ofNullable(instance.getGuildById(serverId));
}
@Override
public Guild getGuildByIdNullable(Long serverId) {
return instance.getGuildById(serverId);
public Guild getGuildById(Long serverId) {
Guild guildById = instance.getGuildById(serverId);
if(guildById == null) {
throw new GuildNotFoundException(serverId);
}
return guildById;
}
@Override
public Member getBotInGuild(AServer server) {
Optional<Guild> guildOptional = getGuildById(server.getId());
if(guildOptional.isPresent()) {
Guild guild = guildOptional.get();
return guild.getMemberById(instance.getSelfUser().getId());
}
return null;
Guild guild = getGuildById(server.getId());
return guild.getMemberById(instance.getSelfUser().getId());
}
}

View File

@@ -252,7 +252,7 @@ public class ChannelServiceBean implements ChannelService {
@Override
public CompletableFuture<TextChannel> createTextChannel(String name, AServer server, Long categoryId) {
Optional<Guild> guildById = botService.getGuildById(server.getId());
Optional<Guild> guildById = botService.getGuildByIdOptional(server.getId());
if(guildById.isPresent()) {
Guild guild = guildById.get();
Category categoryById = guild.getCategoryById(categoryId);

View File

@@ -76,7 +76,7 @@ public class MessageCacheBean implements MessageCache {
@Override
public CompletableFuture<CachedMessage> loadMessage(Long guildId, Long textChannelId, Long messageId) {
CompletableFuture<CachedMessage> future = new CompletableFuture<>();
Optional<Guild> guildOptional = botService.getGuildById(guildId);
Optional<Guild> guildOptional = botService.getGuildByIdOptional(guildId);
if(guildOptional.isPresent()) {
Optional<TextChannel> textChannelByIdOptional = botService.getTextChannelFromServerOptional(guildOptional.get(), textChannelId);
if(textChannelByIdOptional.isPresent()) {

View File

@@ -13,6 +13,7 @@ import lombok.extern.slf4j.Slf4j;
import net.dv8tion.jda.api.entities.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
@@ -47,7 +48,7 @@ public class MessageServiceBean implements MessageService {
@Override
public CompletableFuture<Void> addReactionToMessageWithFuture(String emoteKey, Long serverId, Message message) {
Guild guild = botService.getGuildByIdNullable(serverId);
Guild guild = botService.getGuildById(serverId);
return addReactionToMessageWithFuture(emoteKey, guild, message);
}
@@ -93,7 +94,7 @@ public class MessageServiceBean implements MessageService {
}
@Override
public CompletableFuture<Void> removeReactionFromMessageWithFuture(AEmote emote, Long serverId, Message message) {
public CompletableFuture<Void> removeReactionFromMessageWithFuture(AEmote emote, Message message) {
if(Boolean.TRUE.equals(emote.getCustom())) {
Emote emoteById = botService.getInstance().getEmoteById(emote.getEmoteId());
if(emoteById == null) {
@@ -123,13 +124,13 @@ public class MessageServiceBean implements MessageService {
}
@Override
public CompletableFuture<Void> removeReactionFromMessageWithFuture(Integer emoteId, Long serverId, Message message) {
public CompletableFuture<Void> removeReactionFromMessageWithFuture(Integer emoteId, Message message) {
AEmote emote = emoteManagementService.loadEmote(emoteId);
return removeReactionFromMessageWithFuture(emote, serverId, message);
return removeReactionFromMessageWithFuture(emote, message);
}
@Override
public CompletableFuture<Void> clearReactionFromMessageWithFuture(Integer emoteId, Long serverId, Message message) {
public CompletableFuture<Void> clearReactionFromMessageWithFuture(Integer emoteId, Message message) {
AEmote emote = emoteManagementService.loadEmote(emoteId);
return clearReactionFromMessageWithFuture(emote, message);
}
@@ -139,14 +140,22 @@ public class MessageServiceBean implements MessageService {
TextChannel channel = botService.getTextChannelFromServer(serverId, channelId);
Integer emoteId = emote.getId();
return channel.retrieveMessageById(messageId).submit()
.thenCompose(message1 -> removeReactionFromMessageWithFuture(emoteId, serverId, message1));
.thenCompose(message -> self.removeReactionFromMessageWithFuture(emoteId, message));
}
@Override
public CompletableFuture<Void> removeReactionOfUserFromMessageWithFuture(AEmote emote, Long serverId, Long channelId, Long messageId, Long userId) {
Guild guild = botService.getGuildByIdNullable(serverId);
Member memberById = guild.getMemberById(userId);
return removeReactionOfUserFromMessageWithFuture(emote, serverId, channelId, messageId, memberById);
Guild guild = botService.getGuildById(serverId);
Integer emoteId = emote.getId();
TextChannel textChannel = botService.getTextChannelFromServer(serverId, channelId);
CompletableFuture<Member> memberFuture = guild.retrieveMemberById(userId).submit();
CompletableFuture<Message> messageFuture = textChannel.retrieveMessageById(messageId).submit();
return CompletableFuture.allOf(memberFuture, messageFuture).thenCompose(aVoid ->
memberFuture.thenCompose(member ->
self.removeReactionOfUserFromMessageWithFuture(emoteId, messageFuture.join(), memberFuture.join())
)
);
}
@Override
@@ -154,7 +163,7 @@ public class MessageServiceBean implements MessageService {
TextChannel channel = botService.getTextChannelFromServer(serverId, channelId);
Integer emoteId = emote.getId();
return channel.retrieveMessageById(messageId).submit()
.thenCompose(message1 -> removeReactionOfUserFromMessageWithFuture(emoteId, message1, member));
.thenCompose(message -> self.removeReactionOfUserFromMessageWithFuture(emoteId, message, member));
}
@Override
@@ -173,6 +182,7 @@ public class MessageServiceBean implements MessageService {
}
@Override
@Transactional
public CompletableFuture<Void> removeReactionOfUserFromMessageWithFuture(Integer emoteId, Message message, Member member) {
AEmote emote = emoteManagementService.loadEmote(emoteId);
return removeReactionOfUserFromMessageWithFuture(emote, message, member);
@@ -180,15 +190,17 @@ public class MessageServiceBean implements MessageService {
@Override
public CompletableFuture<Void> removeReactionOfUserFromMessageWithFuture(AEmote emote, Message message, Long userId) {
Member memberById = message.getGuild().getMemberById(userId);
return removeReactionOfUserFromMessageWithFuture(emote, message, memberById);
Integer emoteId = emote.getId();
return message.getGuild().retrieveMemberById(userId).submit().thenCompose(member ->
self.removeReactionOfUserFromMessageWithFuture(emoteId, message, member)
);
}
@Override
public CompletableFuture<Void> removeReactionOfUserFromMessageWithFuture(Integer emoteId, Message message, Long userId) {
Member memberById = message.getGuild().getMemberById(userId);
AEmote emote = emoteManagementService.loadEmote(emoteId);
return removeReactionOfUserFromMessageWithFuture(emote, message, memberById);
return message.getGuild().retrieveMemberById(userId).submit().thenCompose(member ->
self.removeReactionOfUserFromMessageWithFuture(emoteId, message, member)
);
}
@Override
@@ -196,7 +208,7 @@ public class MessageServiceBean implements MessageService {
TextChannel channel = botService.getTextChannelFromServer(serverId, channelId);
Integer emoteId = emote.getId();
return channel.retrieveMessageById(messageId).submit()
.thenCompose(message1 -> clearReactionFromMessageWithFuture(emoteId, serverId, message1));
.thenCompose(message1 -> clearReactionFromMessageWithFuture(emoteId, message1));
}
@Override
@@ -239,8 +251,9 @@ public class MessageServiceBean implements MessageService {
@Override
public CompletableFuture<Message> sendMessageToUser(AUserInAServer userInAServer, String text) {
Member memberInServer = botService.getMemberInServer(userInAServer);
return sendMessageToUser(memberInServer.getUser(), text);
return botService.getMemberInServerAsync(userInAServer).thenCompose(member ->
sendMessageToUser(member.getUser(), text)
);
}
@Override

View File

@@ -32,7 +32,7 @@ public class RoleServiceBean implements RoleService {
@Override
public void addRoleToUser(AUserInAServer aUserInAServer, ARole role) {
Optional<Guild> guildById = botService.getGuildById(aUserInAServer.getServerReference().getId());
Optional<Guild> guildById = botService.getGuildByIdOptional(aUserInAServer.getServerReference().getId());
if(guildById.isPresent()) {
addRoleToUser(guildById.get(), role, aUserInAServer.getUserReference().getId());
} else {
@@ -42,7 +42,7 @@ public class RoleServiceBean implements RoleService {
@Override
public CompletableFuture<Void> addRoleToUserFuture(AUserInAServer aUserInAServer, ARole role) {
Optional<Guild> guildById = botService.getGuildById(aUserInAServer.getServerReference().getId());
Optional<Guild> guildById = botService.getGuildByIdOptional(aUserInAServer.getServerReference().getId());
if(guildById.isPresent()) {
return addRoleToUserFuture(guildById.get(), role, aUserInAServer.getUserReference().getId());
} else {
@@ -50,30 +50,46 @@ public class RoleServiceBean implements RoleService {
}
}
@Override
public CompletableFuture<Void> addRoleToMemberFuture(Member member, Long roleId) {
Role role = member.getGuild().getRoleById(roleId);
if(role == null) {
throw new RoleNotFoundInGuildException(roleId, member.getGuild().getIdLong());
}
return member.getGuild().addRoleToMember(member, role).submit();
}
@Override
public void addRoleToMember(Member member, ARole role) {
Guild guild = member.getGuild();
addRoleToUser(guild, role, member.getIdLong());
addRoleToMemberFuture(member, role.getId());
}
@Override
public CompletableFuture<Void> addRoleToMemberFuture(Member member, ARole role) {
Guild guild = member.getGuild();
return addRoleToUserFuture(guild, role, member.getIdLong());
return addRoleToMemberFuture(member, role.getId());
}
@Override
public void removeRoleFromMember(Member member, ARole role) {
Guild guild = member.getGuild();
removeRoleFromUser(guild, role, member.getIdLong());
removeRoleFromMemberAsync(member, role.getId());
}
@Override
public CompletableFuture<Void> removeRoleFromMemberFuture(Member member, ARole role) {
public CompletableFuture<Void> removeRoleFromMemberAsync(Member member, ARole role) {
Guild guild = member.getGuild();
return removeRoleFromUserFuture(guild, role, member.getIdLong());
}
@Override
public CompletableFuture<Void> removeRoleFromMemberAsync(Member member, Long roleId) {
Role role = member.getGuild().getRoleById(roleId);
if(role == null) {
throw new RoleNotFoundInGuildException(roleId, member.getGuild().getIdLong());
}
return member.getGuild().removeRoleFromMember(member, role).submit();
}
private CompletableFuture<Void> addRoleToUserFuture(Guild guild, ARole role, Long userId) {
if(role.getDeleted()) {
log.warn("Not possible to add role to user. Role {} was marked as deleted.", role.getId());
@@ -114,7 +130,7 @@ public class RoleServiceBean implements RoleService {
@Override
public void removeRoleFromUser(AUserInAServer aUserInAServer, ARole role) {
Optional<Guild> guildById = botService.getGuildById(aUserInAServer.getServerReference().getId());
Optional<Guild> guildById = botService.getGuildByIdOptional(aUserInAServer.getServerReference().getId());
if(guildById.isPresent()) {
removeRoleFromUser(guildById.get(), role, aUserInAServer.getUserReference().getId());
} else {
@@ -124,7 +140,7 @@ public class RoleServiceBean implements RoleService {
@Override
public CompletableFuture<Void> removeRoleFromUserFuture(AUserInAServer aUserInAServer, ARole role) {
Optional<Guild> guildById = botService.getGuildById(aUserInAServer.getServerReference().getId());
Optional<Guild> guildById = botService.getGuildByIdOptional(aUserInAServer.getServerReference().getId());
if(guildById.isPresent()) {
return removeRoleFromUserFuture(guildById.get(), role, aUserInAServer.getUserReference().getId());
} else {
@@ -150,7 +166,7 @@ public class RoleServiceBean implements RoleService {
log.warn("Trying to load role {} which is marked as deleted.", role.getId());
throw new RoleDeletedException(role);
}
Optional<Guild> guildById = botService.getGuildById(role.getServer().getId());
Optional<Guild> guildById = botService.getGuildByIdOptional(role.getServer().getId());
if(guildById.isPresent()) {
log.trace("Loading role {} from server {}.", role.getId(), role.getServer().getId());
return guildById.get().getRoleById(role.getId());
@@ -171,12 +187,17 @@ public class RoleServiceBean implements RoleService {
@Override
public boolean memberHasRole(Member member, Role role) {
return member.getRoles().stream().anyMatch(role1 -> role1.getIdLong() == role.getIdLong());
return memberHasRole(member, role.getIdLong());
}
@Override
public boolean memberHasRole(Member member, ARole role) {
return member.getRoles().stream().anyMatch(role1 -> role1.getIdLong() == role.getId());
return memberHasRole(member, role.getId());
}
@Override
public boolean memberHasRole(Member member, Long roleId) {
return member.getRoles().stream().anyMatch(role1 -> role1.getIdLong() == roleId);
}
@Override

View File

@@ -10,7 +10,6 @@ import dev.sheldan.abstracto.core.models.template.commands.SetupCompletedNotific
import dev.sheldan.abstracto.core.models.template.commands.SetupInitialMessageModel;
import dev.sheldan.abstracto.templating.service.TemplateService;
import lombok.extern.slf4j.Slf4j;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.TextChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@@ -141,8 +140,12 @@ public class SetupServiceBean implements SetupService {
@Transactional
public void showExceptionMessage(Throwable throwable, AServerChannelUserId aServerChannelUserId) {
Optional<TextChannel> channelOptional = botService.getTextChannelFromServerOptional(aServerChannelUserId.getGuildId(), aServerChannelUserId.getChannelId());
Member member = botService.getMemberInServer(aServerChannelUserId.getGuildId(), aServerChannelUserId.getUserId());
channelOptional.ifPresent(textChannel -> exceptionService.reportExceptionToChannel(throwable, textChannel, member));
botService.getMemberInServerAsync(aServerChannelUserId.getGuildId(), aServerChannelUserId.getUserId()).thenAccept(member ->
channelOptional.ifPresent(textChannel -> exceptionService.reportExceptionToChannel(throwable, textChannel, member))
).exceptionally(innserThrowable -> {
log.error("Failed to report exception message for exception {} for user {} in channel {} in server {}.", throwable, aServerChannelUserId.getUserId(), aServerChannelUserId.getChannelId(), aServerChannelUserId.getGuildId(), innserThrowable);
return null;
});
}
@Transactional

View File

@@ -1,23 +0,0 @@
package dev.sheldan.abstracto.core.service;
import dev.sheldan.abstracto.core.models.FullUserInServer;
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
import dev.sheldan.abstracto.core.service.management.UserInServerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class UserInServerServiceBean implements UserInServerService {
@Autowired
private BotService botService;
@Override
public FullUserInServer getFullUser(AUserInAServer aUserInAServer) {
return FullUserInServer
.builder()
.member(botService.getMemberInServer(aUserInAServer))
.aUserInAServer(aUserInAServer)
.build();
}
}

View File

@@ -1,15 +1,18 @@
package dev.sheldan.abstracto.core.command.handler;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.requests.RestAction;
import org.junit.Assert;
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.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import static org.mockito.Mockito.when;
@@ -44,25 +47,27 @@ public class MemberParameterHandlerTest {
}
@Test
@SuppressWarnings("unchecked")
public void testProperMemberMention() {
oneMemberInIterator();
String input = getUserMention();
Member parsed = (Member) testUnit.handle(input, iterators, Member.class, null);
Assert.assertEquals(parsed, member);
CompletableFuture<Member> parsed = (CompletableFuture) testUnit.handleAsync(input, iterators, Member.class, null);
Assert.assertEquals(parsed.join(), member);
}
@Test
@SuppressWarnings("unchecked")
public void testMemberById() {
setupMessage();
String input = USER_ID.toString();
Member parsed = (Member) testUnit.handle(input, null, Member.class, message);
Assert.assertEquals(parsed, member);
CompletableFuture<Member> parsed = (CompletableFuture) testUnit.handleAsync(input, null, Member.class, message);
Assert.assertEquals(parsed.join(), member);
}
@Test(expected = NumberFormatException.class)
public void testInvalidMemberMention() {
String input = "test";
testUnit.handle(input, null, Member.class, null);
testUnit.handleAsync(input, null, Member.class, null);
}
private String getUserMention() {
@@ -76,7 +81,9 @@ public class MemberParameterHandlerTest {
private void setupMessage() {
when(message.getGuild()).thenReturn(guild);
when(guild.getMemberById(USER_ID)).thenReturn(member);
RestAction<Member> restAction = Mockito.mock(RestAction.class);
when(restAction.submit()).thenReturn(CompletableFuture.completedFuture(member));
when(guild.retrieveMemberById(USER_ID)).thenReturn(restAction);
}
}

View File

@@ -21,12 +21,19 @@ public class MinIntegerValueValidator implements ParameterValidator {
if(value == null) {
throw new IllegalArgumentException("Object to validate must not be null");
}
if(!(value instanceof Long)) {
boolean isLong = value instanceof Long;
boolean isInteger = value instanceof Integer;
if(!isLong && !isInteger) {
throw new ValidatorConfigException("Incorrect value passed to max value validator.");
}
SingleNumberValidatorParam param = (SingleNumberValidatorParam) getParameters().get(0);
Long longValue = (Long) value;
return longValue >= param.getNumber();
if(isLong) {
Long longValue = (Long) value;
return longValue >= param.getNumber();
} else {
Integer integerValue = (Integer) value;
return integerValue >= param.getNumber();
}
}
@Override

View File

@@ -3,8 +3,12 @@ package dev.sheldan.abstracto.core.command.handler;
import net.dv8tion.jda.api.entities.Message;
import java.util.concurrent.CompletableFuture;
public interface CommandParameterHandler {
boolean handles(Class clazz);
Object handle(String input, CommandParameterIterators iterators, Class clazz, Message context);
default boolean async() { return false; }
default Object handle(String input, CommandParameterIterators iterators, Class clazz, Message context) { return new Object();}
default CompletableFuture handleAsync(String input, CommandParameterIterators iterators, Class clazz, Message context) { return CompletableFuture.completedFuture(null); }
Integer getPriority();
}

View File

@@ -0,0 +1,17 @@
package dev.sheldan.abstracto.core.models;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import net.dv8tion.jda.api.entities.Member;
import java.util.concurrent.CompletableFuture;
@Getter
@Setter
@Builder
public class FutureMemberPair {
private CompletableFuture<Member> firstMember;
private CompletableFuture<Member> secondMember;
}

View File

@@ -0,0 +1,15 @@
package dev.sheldan.abstracto.core.models;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import net.dv8tion.jda.api.entities.Member;
@Getter
@Setter
@Builder
public class MemberPair {
private Member firstMember;
private Member secondMember;
}

View File

@@ -0,0 +1,15 @@
package dev.sheldan.abstracto.core.models;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Builder
public class ServerChannelMessageUser {
private Long serverId;
private Long channelId;
private Long messageId;
private Long userId;
}

View File

@@ -18,10 +18,13 @@ public interface BotService {
void login() throws LoginException;
JDA getInstance();
GuildChannelMember getServerChannelUser(Long serverId, Long channelId, Long userId);
CompletableFuture<GuildChannelMember> getServerChannelUserAsync(Long serverId, Long channelId, Long userId);
Member getMemberInServer(Long serverId, Long memberId);
CompletableFuture<Member> getMemberInServerAsync(Long serverId, Long memberId);
boolean isUserInGuild(AUserInAServer aUserInAServer);
boolean isUserInGuild(Guild guild, AUserInAServer aUserInAServer);
Member getMemberInServer(AUserInAServer aUserInAServer);
CompletableFuture<Member> getMemberInServerAsync(AUserInAServer aUserInAServer);
Member getMemberInServer(AServer server, AUser member);
CompletableFuture<Void> deleteMessage(Long serverId, Long channelId, Long messageId);
CompletableFuture<Void> deleteMessage(Long channelId, Long messageId);
@@ -32,7 +35,7 @@ public interface BotService {
TextChannel getTextChannelFromServer(Guild serverId, Long textChannelId);
Optional<TextChannel> getTextChannelFromServerOptional(Long serverId, Long textChannelId);
TextChannel getTextChannelFromServer(Long serverId, Long textChannelId);
Optional<Guild> getGuildById(Long serverId);
Guild getGuildByIdNullable(Long serverId);
Optional<Guild> getGuildByIdOptional(Long serverId);
Guild getGuildById(Long serverId);
Member getBotInGuild(AServer server);
}

View File

@@ -16,10 +16,10 @@ public interface MessageService {
CompletableFuture<Void> addReactionToMessageWithFuture(AEmote emote, Long serverId, Message message);
CompletableFuture<Void> addReactionToMessageWithFuture(AEmote emote, Guild guild, Message message);
CompletableFuture<Void> addReactionToMessageWithFuture(Long emoteId, Long serverId, Message message);
CompletableFuture<Void> removeReactionFromMessageWithFuture(AEmote emote, Long serverId, Message message);
CompletableFuture<Void> removeReactionFromMessageWithFuture(AEmote emote, Message message);
CompletableFuture<Void> clearReactionFromMessageWithFuture(AEmote emote, Message message);
CompletableFuture<Void> removeReactionFromMessageWithFuture(Integer emoteId, Long serverId, Message message);
CompletableFuture<Void> clearReactionFromMessageWithFuture(Integer emoteId, Long serverId, Message message);
CompletableFuture<Void> removeReactionFromMessageWithFuture(Integer emoteId, Message message);
CompletableFuture<Void> clearReactionFromMessageWithFuture(Integer emoteId, Message message);
CompletableFuture<Void> removeReactionFromMessageWithFuture(AEmote emote, Long serverId, Long channelId, Long messageId);
CompletableFuture<Void> removeReactionOfUserFromMessageWithFuture(AEmote emote, Long serverId, Long channelId, Long messageId, Long userId);
CompletableFuture<Void> removeReactionOfUserFromMessageWithFuture(AEmote emote, Long serverId, Long channelId, Long messageId, Member member);

View File

@@ -12,10 +12,12 @@ import java.util.concurrent.CompletableFuture;
public interface RoleService {
void addRoleToUser(AUserInAServer aUserInAServer, ARole role);
CompletableFuture<Void> addRoleToUserFuture(AUserInAServer aUserInAServer, ARole role);
CompletableFuture<Void> addRoleToMemberFuture(Member member, Long roleId);
void addRoleToMember(Member member, ARole role);
CompletableFuture<Void> addRoleToMemberFuture(Member member, ARole role);
void removeRoleFromMember(Member member, ARole role);
CompletableFuture<Void> removeRoleFromMemberFuture(Member member, ARole role);
CompletableFuture<Void> removeRoleFromMemberAsync(Member member, ARole role);
CompletableFuture<Void> removeRoleFromMemberAsync(Member member, Long roleId);
void removeRoleFromUser(AUserInAServer aUserInAServer, ARole role);
CompletableFuture<Void> removeRoleFromUserFuture(AUserInAServer aUserInAServer, ARole role);
void markDeleted(Role role, AServer server);
@@ -25,6 +27,7 @@ public interface RoleService {
boolean hasAnyOfTheRoles(Member member, List<ARole> roles);
boolean memberHasRole(Member member, Role role);
boolean memberHasRole(Member member, ARole role);
boolean memberHasRole(Member member, Long roleId);
boolean isRoleInServer(ARole role);
boolean canBotInteractWithRole(ARole role);
ARole getFakeRoleFromRole(Role role);

View File

@@ -1,8 +0,0 @@
package dev.sheldan.abstracto.core.service.management;
import dev.sheldan.abstracto.core.models.FullUserInServer;
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
public interface UserInServerService {
FullUserInServer getFullUser(AUserInAServer aUserInAServer);
}

View File

@@ -11,4 +11,8 @@ public class FutureUtils {
public static <T> CompletableFuture<Void> toSingleFutureGeneric(List<CompletableFuture<T>> futures) {
return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
}
public static CompletableFuture<Void> toSingleFuture(List<CompletableFuture> futures) {
return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
}
}