added configurable warning and success reactions

changed that channels dont actually get deleted, but rather with a deleted flag, so the foreign keys are valid
added more optionals to server/channel/message/member retrieval
added throwing exceptions instead of just returning null
fixed filtering of deleted channels while the bot was offline
fixed channel listener
added message deleted listener structure
moved quartz properties to general application properties, because they were not found in the separate one
added try catch to reminderJob, so that the job is not in an invalid state
we now completely remove the starboard post, in case it falls under the threshold
added code to 'ignore' a staroard post form further stars, in case the post in the starboard gets deleted
now actually setting the reminded flag on a reminder
added handnling in case the channel to remind in does not exist anymore
This commit is contained in:
Sheldan
2020-04-01 23:46:28 +02:00
parent 089862bf15
commit c9557fccc2
45 changed files with 409 additions and 181 deletions

View File

@@ -1,5 +1,6 @@
package dev.sheldan.abstracto.moderation.listener; package dev.sheldan.abstracto.moderation.listener;
import dev.sheldan.abstracto.core.listener.MessageDeletedListener;
import dev.sheldan.abstracto.core.models.CachedMessage; import dev.sheldan.abstracto.core.models.CachedMessage;
import dev.sheldan.abstracto.core.utils.ContextUtils; import dev.sheldan.abstracto.core.utils.ContextUtils;
import dev.sheldan.abstracto.core.service.MessageCache; import dev.sheldan.abstracto.core.service.MessageCache;
@@ -9,19 +10,12 @@ import dev.sheldan.abstracto.moderation.models.template.listener.MessageDeletedL
import dev.sheldan.abstracto.core.models.embed.MessageToSend; import dev.sheldan.abstracto.core.models.embed.MessageToSend;
import dev.sheldan.abstracto.templating.TemplateService; import dev.sheldan.abstracto.templating.TemplateService;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.events.message.guild.GuildMessageDeleteEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Nonnull;
import java.util.concurrent.ExecutionException;
@Component @Component
@Slf4j @Slf4j
public class MessageDeletedListener extends ListenerAdapter { public class MessageDeleteLogListener implements MessageDeletedListener {
private static final String DELETE_LOG_TARGET = "deleteLog"; private static final String DELETE_LOG_TARGET = "deleteLog";
private static String MESSAGE_DELETED_TEMPLATE = "message_deleted"; private static String MESSAGE_DELETED_TEMPLATE = "message_deleted";
@@ -39,37 +33,20 @@ public class MessageDeletedListener extends ListenerAdapter {
@Autowired @Autowired
private PostTargetService postTargetService; private PostTargetService postTargetService;
@Autowired
private MessageDeletedListener self;
@Override @Override
@Transactional public void execute(CachedMessage messageFromCache) {
public void onGuildMessageDelete(@Nonnull GuildMessageDeleteEvent event) {
messageCache.getMessageFromCache(event.getGuild().getIdLong(), event.getChannel().getIdLong(), event.getMessageIdLong())
.thenAccept(messageFromCache -> {
try {
self.logMessage(event, messageFromCache);
} catch (Exception e) {
log.error("Error when logging message deletion.", e);
}
});
}
@Transactional
public void logMessage(@Nonnull GuildMessageDeleteEvent event, CachedMessage messageFromCache) {
MessageDeletedLog logModel = (MessageDeletedLog) contextUtils.fromMessage(messageFromCache, MessageDeletedLog.class); MessageDeletedLog logModel = (MessageDeletedLog) contextUtils.fromMessage(messageFromCache, MessageDeletedLog.class);
logModel.setMessage(messageFromCache); logModel.setMessage(messageFromCache);
String simpleMessageUpdatedMessage = templateService.renderTemplate(MESSAGE_DELETED_TEMPLATE, logModel); String simpleMessageUpdatedMessage = templateService.renderTemplate(MESSAGE_DELETED_TEMPLATE, logModel);
postTargetService.sendTextInPostTarget(simpleMessageUpdatedMessage, DELETE_LOG_TARGET, event.getGuild().getIdLong()); postTargetService.sendTextInPostTarget(simpleMessageUpdatedMessage, DELETE_LOG_TARGET, messageFromCache.getServerId());
MessageToSend message = templateService.renderEmbedTemplate(MESSAGE_DELETED_TEMPLATE, logModel); MessageToSend message = templateService.renderEmbedTemplate(MESSAGE_DELETED_TEMPLATE, logModel);
postTargetService.sendEmbedInPostTarget(message, DELETE_LOG_TARGET, event.getGuild().getIdLong()); postTargetService.sendEmbedInPostTarget(message, DELETE_LOG_TARGET, messageFromCache.getServerId());
for (int i = 0; i < messageFromCache.getAttachmentUrls().size(); i++) { for (int i = 0; i < messageFromCache.getAttachmentUrls().size(); i++) {
MessageDeletedAttachmentLog log = (MessageDeletedAttachmentLog) contextUtils.fromMessage(messageFromCache, MessageDeletedAttachmentLog.class); MessageDeletedAttachmentLog log = (MessageDeletedAttachmentLog) contextUtils.fromMessage(messageFromCache, MessageDeletedAttachmentLog.class);
log.setImageUrl(messageFromCache.getAttachmentUrls().get(i)); log.setImageUrl(messageFromCache.getAttachmentUrls().get(i));
log.setCounter(i + 1); log.setCounter(i + 1);
MessageToSend attachmentEmbed = templateService.renderEmbedTemplate(MESSAGE_DELETED_ATTACHMENT_TEMPLATE, log); MessageToSend attachmentEmbed = templateService.renderEmbedTemplate(MESSAGE_DELETED_ATTACHMENT_TEMPLATE, log);
postTargetService.sendEmbedInPostTarget(attachmentEmbed, DELETE_LOG_TARGET, event.getGuild().getIdLong()); postTargetService.sendEmbedInPostTarget(attachmentEmbed, DELETE_LOG_TARGET, messageFromCache.getServerId());
} }
} }
} }

View File

@@ -1,5 +1,6 @@
package dev.sheldan.abstracto.moderation.service; package dev.sheldan.abstracto.moderation.service;
import dev.sheldan.abstracto.core.exception.NotFoundException;
import dev.sheldan.abstracto.core.models.ServerContext; import dev.sheldan.abstracto.core.models.ServerContext;
import dev.sheldan.abstracto.core.service.Bot; import dev.sheldan.abstracto.core.service.Bot;
import dev.sheldan.abstracto.core.service.PostTargetService; import dev.sheldan.abstracto.core.service.PostTargetService;
@@ -10,6 +11,8 @@ import net.dv8tion.jda.api.entities.Member;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.Optional;
@Component @Component
@Slf4j @Slf4j
public class BanServiceBean implements BanService { public class BanServiceBean implements BanService {
@@ -41,8 +44,13 @@ public class BanServiceBean implements BanService {
} }
private void banUser(Long guildId, Long userId, String reason) { private void banUser(Long guildId, Long userId, String reason) {
Guild guildById = bot.getGuildById(guildId); Optional<Guild> guildByIdOptional = bot.getGuildById(guildId);
log.info("Banning user {} in guild {}.", userId, guildId); if(guildByIdOptional.isPresent()) {
guildById.ban(userId.toString(), 0, reason).queue(); log.info("Banning user {} in guild {}.", userId, guildId);
guildByIdOptional.get().ban(userId.toString(), 0, reason).queue();
} else {
log.warn("Guild {} not found. Not able to ban user {}", guildId, userId);
throw new NotFoundException(String.format("Guild %s not found. Not able to ban user %s", guildId, userId));
}
} }
} }

View File

@@ -1,5 +1,6 @@
package dev.sheldan.abstracto.moderation.service; package dev.sheldan.abstracto.moderation.service;
import dev.sheldan.abstracto.core.exception.NotFoundException;
import dev.sheldan.abstracto.core.service.Bot; import dev.sheldan.abstracto.core.service.Bot;
import dev.sheldan.abstracto.core.service.PostTargetService; import dev.sheldan.abstracto.core.service.PostTargetService;
import dev.sheldan.abstracto.moderation.models.template.KickLogModel; import dev.sheldan.abstracto.moderation.models.template.KickLogModel;
@@ -10,6 +11,8 @@ import net.dv8tion.jda.api.entities.Member;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.Optional;
@Component @Component
@Slf4j @Slf4j
public class KickServiceBean implements KickService { public class KickServiceBean implements KickService {
@@ -27,9 +30,14 @@ public class KickServiceBean implements KickService {
@Override @Override
public void kickMember(Member member, String reason, KickLogModel kickLogModel) { public void kickMember(Member member, String reason, KickLogModel kickLogModel) {
Guild guildById = bot.getGuildById(kickLogModel.getGuild().getIdLong()); Optional<Guild> guildById = bot.getGuildById(kickLogModel.getGuild().getIdLong());
guildById.kick(member, reason).queue(); if(guildById.isPresent()) {
this.sendKickLog(kickLogModel); guildById.get().kick(member, reason).queue();
this.sendKickLog(kickLogModel);
} else {
log.warn("Not able to kick. Guild {} not found.", kickLogModel.getGuild().getIdLong());
throw new NotFoundException(String.format("Not able to kick %s. Guild %s not found", kickLogModel.getMember().getIdLong(), kickLogModel.getGuild().getIdLong()));
}
} }
private void sendKickLog(KickLogModel kickLogModel) { private void sendKickLog(KickLogModel kickLogModel) {

View File

@@ -1,15 +1,15 @@
package dev.sheldan.abstracto.moderation.service; package dev.sheldan.abstracto.moderation.service;
import dev.sheldan.abstracto.core.exception.NotFoundException;
import dev.sheldan.abstracto.core.models.database.AChannel; import dev.sheldan.abstracto.core.models.database.AChannel;
import dev.sheldan.abstracto.core.service.Bot; import dev.sheldan.abstracto.core.service.Bot;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.entities.TextChannel;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.time.Duration; import java.time.Duration;
import java.util.Optional;
@Component @Component
@Slf4j @Slf4j
@@ -29,7 +29,12 @@ public class SlowModeServiceBean implements SlowModeService {
@Override @Override
public void setSlowMode(AChannel channel, Duration duration) { public void setSlowMode(AChannel channel, Duration duration) {
TextChannel textChannel = bot.getTextChannelFromServer(channel.getServer().getId(), channel.getId()); Optional<TextChannel> textChannelOptional = bot.getTextChannelFromServer(channel.getServer().getId(), channel.getId());
this.setSlowMode(textChannel, duration); if(textChannelOptional.isPresent()) {
TextChannel textChannel = textChannelOptional.get();
this.setSlowMode(textChannel, duration);
} else {
throw new NotFoundException(String.format("Channel %s not found in guild %s", channel.getId(), channel.getServer().getId()));
}
} }
} }

View File

@@ -22,6 +22,8 @@ import net.dv8tion.jda.api.entities.User;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.Optional;
@Slf4j @Slf4j
@Component @Component
public class WarnServiceBean implements WarnService { public class WarnServiceBean implements WarnService {
@@ -57,10 +59,10 @@ public class WarnServiceBean implements WarnService {
Warning warning = warnManagementService.createWarning(warnedAUserInAServer, warningAUserInAServer, reason); Warning warning = warnManagementService.createWarning(warnedAUserInAServer, warningAUserInAServer, reason);
JDA instance = bot.getInstance(); JDA instance = bot.getInstance();
User userBeingWarned = instance.getUserById(warnedAUser.getId()); User userBeingWarned = instance.getUserById(warnedAUser.getId());
Guild guildById = bot.getGuildById(serverOfWarning.getId()); Optional<Guild> guildById = bot.getGuildById(serverOfWarning.getId());
String guildName = "<defaultName>"; String guildName = "<defaultName>";
if(guildById != null) { if(guildById.isPresent()) {
guildName = guildById.getName(); guildName = guildById.get().getName();
} }
WarnNotification warnNotification = WarnNotification.builder().warning(warning).serverName(guildName).build(); WarnNotification warnNotification = WarnNotification.builder().warning(warning).serverName(guildName).build();
if(userBeingWarned != null) { if(userBeingWarned != null) {

View File

@@ -23,8 +23,12 @@ public class ReminderJob extends QuartzJobBean {
@Override @Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException { protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
reminderService.executeReminder(reminderId); try {
log.info("executing reminder job for reminder {}", reminderId); reminderService.executeReminder(reminderId);
log.info("executing reminder job for reminder {}", reminderId);
} catch (Exception e) {
log.error("Reminder job failed to execute.", e);
}
} }
public Long getReminderId() { public Long getReminderId() {

View File

@@ -32,7 +32,7 @@ import java.util.stream.Collectors;
@Slf4j @Slf4j
public class StarboardListener implements ReactedAddedListener, ReactedRemovedListener { public class StarboardListener implements ReactedAddedListener, ReactedRemovedListener {
public static final String STAR_EMOTE = "STAR"; public static final String STAR_EMOTE = "star";
@Autowired @Autowired
private EmoteManagementService emoteManagementService; private EmoteManagementService emoteManagementService;
@@ -69,8 +69,8 @@ public class StarboardListener implements ReactedAddedListener, ReactedRemovedLi
if(aEmote.isPresent()) { if(aEmote.isPresent()) {
AEmote emote = aEmote.get(); AEmote emote = aEmote.get();
MessageReaction.ReactionEmote reactionEmote = addedReaction.getReactionEmote(); MessageReaction.ReactionEmote reactionEmote = addedReaction.getReactionEmote();
Emote emoteInGuild = bot.getEmote(guildId, emote); Optional<Emote> emoteInGuild = bot.getEmote(guildId, emote);
if(EmoteUtils.isReactionEmoteAEmote(reactionEmote, emote, Optional.ofNullable(emoteInGuild))) { if(EmoteUtils.isReactionEmoteAEmote(reactionEmote, emote, emoteInGuild.orElse(null))) {
Optional<CachedReaction> reactionOptional = EmoteUtils.getReactionFromMessageByEmote(message, emote); Optional<CachedReaction> reactionOptional = EmoteUtils.getReactionFromMessageByEmote(message, emote);
updateStarboardPost(message, reactionOptional.orElse(null), userAdding, true); updateStarboardPost(message, reactionOptional.orElse(null), userAdding, true);
} }
@@ -88,6 +88,7 @@ public class StarboardListener implements ReactedAddedListener, ReactedRemovedLi
AUserInAServer author = userManagementService.loadUser(message.getServerId(), message.getAuthorId()); AUserInAServer author = userManagementService.loadUser(message.getServerId(), message.getAuthorId());
if(starboardPostOptional.isPresent()) { if(starboardPostOptional.isPresent()) {
StarboardPost starboardPost = starboardPostOptional.get(); StarboardPost starboardPost = starboardPostOptional.get();
starboardPost.setIgnored(false);
starboardService.updateStarboardPost(starboardPost, message, userExceptAuthor); starboardService.updateStarboardPost(starboardPost, message, userExceptAuthor);
if(adding) { if(adding) {
starboardPostReactorManagementService.addReactor(starboardPost, userReacting.getUserReference()); starboardPostReactorManagementService.addReactor(starboardPost, userReacting.getUserReference());
@@ -98,19 +99,19 @@ public class StarboardListener implements ReactedAddedListener, ReactedRemovedLi
starboardService.createStarboardPost(message, userExceptAuthor, userReacting, author); starboardService.createStarboardPost(message, userExceptAuthor, userReacting, author);
} }
} else { } else {
starboardPostOptional.ifPresent(starboardPost -> { starboardPostOptional.ifPresent(this::completelyRemoveStarboardPost);
starboardService.removeStarboardPost(starboardPost);
starboardPostReactorManagementService.removeReactors(starboardPost);
});
} }
} else { } else {
starboardPostOptional.ifPresent(starboardPost -> { starboardPostOptional.ifPresent(this::completelyRemoveStarboardPost);
starboardService.removeStarboardPost(starboardPost);
starboardPostReactorManagementService.removeReactors(starboardPost);
});
} }
} }
private void completelyRemoveStarboardPost(StarboardPost starboardPost) {
starboardPostReactorManagementService.removeReactors(starboardPost);
starboardService.removeStarboardPost(starboardPost);
starboardPostManagementService.removePost(starboardPost);
}
@Override @Override
@Transactional @Transactional
public void executeReactionRemoved(CachedMessage message, MessageReaction removedReaction, AUserInAServer userRemoving) { public void executeReactionRemoved(CachedMessage message, MessageReaction removedReaction, AUserInAServer userRemoving) {
@@ -122,8 +123,8 @@ public class StarboardListener implements ReactedAddedListener, ReactedRemovedLi
if(aEmote.isPresent()) { if(aEmote.isPresent()) {
AEmote emote = aEmote.get(); AEmote emote = aEmote.get();
MessageReaction.ReactionEmote reactionEmote = removedReaction.getReactionEmote(); MessageReaction.ReactionEmote reactionEmote = removedReaction.getReactionEmote();
Emote emoteInGuild = bot.getEmote(guildId, emote); Optional<Emote> emoteInGuild = bot.getEmote(guildId, emote);
if(EmoteUtils.isReactionEmoteAEmote(reactionEmote, emote, Optional.ofNullable(emoteInGuild))) { if(EmoteUtils.isReactionEmoteAEmote(reactionEmote, emote, emoteInGuild.orElse(null))) {
Optional<CachedReaction> reactionOptional = EmoteUtils.getReactionFromMessageByEmote(message, emote); Optional<CachedReaction> reactionOptional = EmoteUtils.getReactionFromMessageByEmote(message, emote);
updateStarboardPost(message, reactionOptional.orElse(null), userRemoving, false); updateStarboardPost(message, reactionOptional.orElse(null), userRemoving, false);
} }

View File

@@ -0,0 +1,25 @@
package dev.sheldan.abstracto.utility.listener;
import dev.sheldan.abstracto.core.listener.MessageDeletedListener;
import dev.sheldan.abstracto.core.models.CachedMessage;
import dev.sheldan.abstracto.utility.models.StarboardPost;
import dev.sheldan.abstracto.utility.service.management.StarboardPostManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Optional;
@Component
public class StarboardPostDeletedListener implements MessageDeletedListener {
@Autowired
private StarboardPostManagementService starboardPostManagementService;
@Override
public void execute(CachedMessage messageBefore) {
Optional<StarboardPost> byStarboardPostId = starboardPostManagementService.findByStarboardPostId(messageBefore.getMessageId());
if(byStarboardPostId.isPresent()) {
starboardPostManagementService.setStarboardPostIgnored(messageBefore.getMessageId(), true);
}
}
}

View File

@@ -7,6 +7,7 @@ import java.util.List;
public interface StarboardPostRepository extends JpaRepository<StarboardPost, Long> { public interface StarboardPostRepository extends JpaRepository<StarboardPost, Long> {
StarboardPost findByPostMessageId(Long messageId); StarboardPost findByPostMessageId(Long messageId);
StarboardPost findByStarboardMessageId(Long messageId);
List<StarboardPost> findByStarboardChannelServerId(Long serverId); List<StarboardPost> findByStarboardChannelServerId(Long serverId);
} }

View File

@@ -26,6 +26,7 @@ import org.springframework.transaction.annotation.Transactional;
import java.time.Duration; import java.time.Duration;
import java.time.Instant; import java.time.Instant;
import java.util.Date; import java.util.Date;
import java.util.Optional;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@@ -92,16 +93,21 @@ public class RemindServiceBean implements ReminderService {
Reminder reminderToRemindFor = reminderManagementService.loadReminder(reminderId); Reminder reminderToRemindFor = reminderManagementService.loadReminder(reminderId);
AServer server = reminderToRemindFor.getServer(); AServer server = reminderToRemindFor.getServer();
AChannel channel = reminderToRemindFor.getChannel(); AChannel channel = reminderToRemindFor.getChannel();
AUser userReference = reminderToRemindFor.getToBeReminded().getUserReference(); Optional<TextChannel> channelToAnswerIn = bot.getTextChannelFromServer(server.getId(), channel.getId());
Member memberInServer = bot.getMemberInServer(server.getId(), userReference.getId()); // only send the message if the channel still exists, if not, only set the reminder to reminded.
ExecutedReminderModel build = ExecutedReminderModel if(channelToAnswerIn.isPresent()) {
.builder() AUser userReference = reminderToRemindFor.getToBeReminded().getUserReference();
.reminder(reminderToRemindFor) Member memberInServer = bot.getMemberInServer(server.getId(), userReference.getId());
.member(memberInServer) ExecutedReminderModel build = ExecutedReminderModel
.build(); .builder()
MessageToSend messageToSend = templateService.renderEmbedTemplate("remind_reminder", build); .reminder(reminderToRemindFor)
// todo, if channel does not exist anymore .member(memberInServer)
TextChannel channelToAnswerIn = bot.getTextChannelFromServer(server.getId(), channel.getId()); .build();
channelToAnswerIn.sendMessage(messageToSend.getMessage()).embed(messageToSend.getEmbed()).queue(); MessageToSend messageToSend = templateService.renderEmbedTemplate("remind_reminder", build);
channelToAnswerIn.get().sendMessage(messageToSend.getMessage()).embed(messageToSend.getEmbed()).queue();
} else {
log.warn("Channel {} in server {} to remind user did not exist anymore. Ignoring.", channel.getId(), server.getId());
}
reminderManagementService.setReminded(reminderToRemindFor);
} }
} }

View File

@@ -92,8 +92,8 @@ public class StarboardServiceBean implements StarboardService {
private StarboardPostModel buildStarboardPostModel(CachedMessage message, Integer starCount) { private StarboardPostModel buildStarboardPostModel(CachedMessage message, Integer starCount) {
Member member = bot.getMemberInServer(message.getServerId(), message.getAuthorId()); Member member = bot.getMemberInServer(message.getServerId(), message.getAuthorId());
TextChannel channel = bot.getTextChannelFromServer(message.getServerId(), message.getChannelId()); Optional<TextChannel> channel = bot.getTextChannelFromServer(message.getServerId(), message.getChannelId());
Guild guild = bot.getGuildById(message.getServerId()); Optional<Guild> guild = bot.getGuildById(message.getServerId());
AChannel aChannel = AChannel.builder().id(message.getChannelId()).build(); AChannel aChannel = AChannel.builder().id(message.getChannelId()).build();
AUser user = AUser.builder().id(message.getAuthorId()).build(); AUser user = AUser.builder().id(message.getAuthorId()).build();
AServer server = AServer.builder().id(message.getServerId()).build(); AServer server = AServer.builder().id(message.getServerId()).build();
@@ -110,10 +110,10 @@ public class StarboardServiceBean implements StarboardService {
.builder() .builder()
.message(message) .message(message)
.author(member) .author(member)
.channel(channel) .channel(channel.orElse(null))
.aChannel(aChannel) .aChannel(aChannel)
.starCount(starCount) .starCount(starCount)
.guild(guild) .guild(guild.orElse(null))
.user(user) .user(user)
.server(server) .server(server)
.starLevelEmote(emoteText) .starLevelEmote(emoteText)

View File

@@ -36,4 +36,10 @@ public class ReminderManagementServiceBean implements ReminderManagementService
return reminderRepository.getOne(reminderId); return reminderRepository.getOne(reminderId);
} }
@Override
public void setReminded(Reminder reminder) {
reminder.setReminded(true);
reminderRepository.save(reminder);
}
} }

View File

@@ -29,7 +29,6 @@ public class StarboardPostManagementServiceBean implements StarboardPostManageme
StarboardPost post = StarboardPost StarboardPost post = StarboardPost
.builder() .builder()
.author(starredUser.getUserReference()) .author(starredUser.getUserReference())
.deleted(false)
.postMessageId(starredMessage.getMessageId()) .postMessageId(starredMessage.getMessageId())
.starboardMessageId(starboardPost.getMessageId()) .starboardMessageId(starboardPost.getMessageId())
.starboardChannel(starboardPost.getChannel()) .starboardChannel(starboardPost.getChannel())
@@ -68,5 +67,27 @@ public class StarboardPostManagementServiceBean implements StarboardPostManageme
return Optional.ofNullable(repository.findByPostMessageId(messageId)); return Optional.ofNullable(repository.findByPostMessageId(messageId));
} }
@Override
public Optional<StarboardPost> findByStarboardPostId(Long postId) {
return Optional.ofNullable(repository.findByStarboardMessageId(postId));
}
@Override
public void setStarboardPostIgnored(Long messageId, Boolean newValue) {
StarboardPost post = repository.findByStarboardMessageId(messageId);
post.setIgnored(newValue);
repository.save(post);
}
@Override
public boolean isStarboardPost(Long messageId) {
return repository.findByStarboardMessageId(messageId) != null;
}
@Override
public void removePost(StarboardPost starboardPost) {
repository.deleteById(starboardPost.getId());
}
} }

View File

@@ -60,7 +60,7 @@ public class SuggestionManagementServiceBean implements SuggestionManagementServ
suggestion.setMessageId(message.getIdLong()); suggestion.setMessageId(message.getIdLong());
AChannel channel = channelManagementService.loadChannel(message.getTextChannel().getIdLong()); AChannel channel = channelManagementService.loadChannel(message.getTextChannel().getIdLong());
suggestion.setChannel(channel); suggestion.setChannel(channel);
AServer server = serverManagementService.loadServer(message.getGuild().getIdLong()); AServer server = serverManagementService.loadOrCreate(message.getGuild().getIdLong());
suggestion.setServer(server); suggestion.setServer(server);
suggestionRepository.save(suggestion); suggestionRepository.save(suggestion);
} }

View File

@@ -52,7 +52,7 @@ public class StarboardPost {
private Instant starredDate; private Instant starredDate;
@Column @Column
private boolean deleted; private boolean ignored;
public int getReactionCount() { public int getReactionCount() {
if(this.reactions == null) { if(this.reactions == null) {

View File

@@ -8,4 +8,5 @@ import java.time.Instant;
public interface ReminderManagementService { public interface ReminderManagementService {
Reminder createReminder(AServerAChannelAUser userToBeReminded, String text, Instant timeToBeRemindedAt, Long messageId); Reminder createReminder(AServerAChannelAUser userToBeReminded, String text, Instant timeToBeRemindedAt, Long messageId);
Reminder loadReminder(Long reminderId); Reminder loadReminder(Long reminderId);
void setReminded(Reminder reminder);
} }

View File

@@ -15,4 +15,8 @@ public interface StarboardPostManagementService {
List<StarboardPost> retrieveAllPosts(Long serverId); List<StarboardPost> retrieveAllPosts(Long serverId);
Integer getPostCount(Long serverId); Integer getPostCount(Long serverId);
Optional<StarboardPost> findByMessageId(Long messageId); Optional<StarboardPost> findByMessageId(Long messageId);
Optional<StarboardPost> findByStarboardPostId(Long postId);
void setStarboardPostIgnored(Long starboardPostId, Boolean newValue);
boolean isStarboardPost(Long starboardPostId);
void removePost(StarboardPost starboardPost);
} }

View File

@@ -29,7 +29,6 @@ import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.time.Duration; import java.time.Duration;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;
@Service @Service
public class CommandReceivedHandler extends ListenerAdapter { public class CommandReceivedHandler extends ListenerAdapter {
@@ -91,7 +90,7 @@ public class CommandReceivedHandler extends ListenerAdapter {
private UserInitiatedServerContext buildTemplateParameter(MessageReceivedEvent event) { private UserInitiatedServerContext buildTemplateParameter(MessageReceivedEvent event) {
AChannel channel = channelManagementService.loadChannel(event.getChannel().getIdLong()); AChannel channel = channelManagementService.loadChannel(event.getChannel().getIdLong());
AServer server = serverManagementService.loadServer(event.getGuild().getIdLong()); AServer server = serverManagementService.loadOrCreate(event.getGuild().getIdLong());
AUserInAServer user = userManagementService.loadUser(event.getMember()); AUserInAServer user = userManagementService.loadUser(event.getMember());
return UserInitiatedServerContext return UserInitiatedServerContext
.builder() .builder()

View File

@@ -0,0 +1,10 @@
package dev.sheldan.abstracto.commands.management.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("classpath:commands.properties")
public class CommandConfig {
}

View File

@@ -5,20 +5,28 @@ import dev.sheldan.abstracto.command.PostCommandExecution;
import dev.sheldan.abstracto.command.execution.CommandContext; import dev.sheldan.abstracto.command.execution.CommandContext;
import dev.sheldan.abstracto.command.execution.Result; import dev.sheldan.abstracto.command.execution.Result;
import dev.sheldan.abstracto.command.execution.ResultState; import dev.sheldan.abstracto.command.execution.ResultState;
import dev.sheldan.abstracto.core.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@Service @Service
public class ReactionPostExecution implements PostCommandExecution { public class ReactionPostExecution implements PostCommandExecution {
public static final String WARN_REACTION_EMOTE = "warnReaction";
public static final String SUCCESS_REACTION_EMOTE = "successReaction";
@Autowired
private MessageService messageService;
@Override @Override
public void execute(CommandContext commandContext, Result result, Command command) { public void execute(CommandContext commandContext, Result result, Command command) {
if(result.getResult().equals(ResultState.ERROR)) { if(result.getResult().equals(ResultState.ERROR)) {
commandContext.getMessage().addReaction("⚠️").queue(); messageService.addReactionToMessage(WARN_REACTION_EMOTE, commandContext.getGuild().getIdLong(), commandContext.getMessage());
if(result.getMessage() != null && result.getThrowable() == null){ if(result.getMessage() != null && result.getThrowable() == null){
commandContext.getChannel().sendMessage(result.getMessage()).queue(); commandContext.getChannel().sendMessage(result.getMessage()).queue();
} }
} else { } else {
if(command.getConfiguration().isCausesReaction()){ if(command.getConfiguration().isCausesReaction()){
commandContext.getMessage().addReaction("").queue(); messageService.addReactionToMessage(SUCCESS_REACTION_EMOTE, commandContext.getGuild().getIdLong(), commandContext.getMessage());
} }
} }

View File

@@ -0,0 +1 @@
abstracto.emoteNames.postReaction=warnReaction,successReaction

View File

@@ -1,7 +1,9 @@
package dev.sheldan.abstracto.core.service; package dev.sheldan.abstracto.core.service;
import dev.sheldan.abstracto.core.exception.NotFoundException;
import dev.sheldan.abstracto.core.models.ServerChannelUser; import dev.sheldan.abstracto.core.models.ServerChannelUser;
import dev.sheldan.abstracto.core.models.database.AEmote; import dev.sheldan.abstracto.core.models.database.AEmote;
import lombok.extern.slf4j.Slf4j;
import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Emote; import net.dv8tion.jda.api.entities.Emote;
@@ -13,8 +15,10 @@ import org.springframework.stereotype.Service;
import javax.security.auth.login.LoginException; import javax.security.auth.login.LoginException;
import java.util.EnumSet; import java.util.EnumSet;
import java.util.Optional;
@Service @Service
@Slf4j
public class BotService implements Bot { public class BotService implements Bot {
private JDA instance; private JDA instance;
@@ -36,13 +40,21 @@ public class BotService implements Bot {
@Override @Override
public ServerChannelUser getServerChannelUser(Long serverId, Long channelId, Long userId) { public ServerChannelUser getServerChannelUser(Long serverId, Long channelId, Long userId) {
TextChannel textChannelById = getTextChannelFromServer(serverId, channelId); Optional<Guild> guildOptional = getGuildById(serverId);
Guild guildById = getGuildById(serverId); if(guildOptional.isPresent()) {
if(textChannelById != null) { Guild guild = guildOptional.get();
Member member = guildById.getMemberById(userId); Optional<TextChannel> textChannelOptional = this.getTextChannelFromServer(guild, channelId);
return ServerChannelUser.builder().guild(guildById).textChannel(textChannelById).member(member).build(); if(textChannelOptional.isPresent()) {
TextChannel textChannel = textChannelOptional.get();
Member member = guild.getMemberById(userId);
return ServerChannelUser.builder().guild(guild).textChannel(textChannel).member(member).build();
} else {
throw new NotFoundException(String.format("Text channel %s not found in guild %s", channelId, serverId));
}
}
else {
throw new NotFoundException(String.format("Guild %s not found.", serverId));
} }
throw new RuntimeException(String.format("Member %s or text channel %s not found in guild %s", userId, channelId, serverId));
} }
@@ -59,37 +71,48 @@ public class BotService implements Bot {
@Override @Override
public void deleteMessage(Long serverId, Long channelId, Long messageId) { public void deleteMessage(Long serverId, Long channelId, Long messageId) {
getTextChannelFromServer(serverId, channelId).deleteMessageById(messageId).queue(); Optional<TextChannel> textChannelOptional = getTextChannelFromServer(serverId, channelId);
if(textChannelOptional.isPresent()) {
TextChannel textChannel = textChannelOptional.get();
textChannel.deleteMessageById(messageId).queue(aVoid -> {}, throwable -> {
log.warn("Failed to delete message {} in channel {} in guild {}", messageId, channelId, serverId, throwable);
});
} else {
log.warn("Could not find channel {} in guild {} to delete message {} in.", channelId, serverId, messageId);
}
} }
@Override @Override
public Emote getEmote(Long serverId, AEmote emote) { public Optional<Emote> getEmote(Long serverId, AEmote emote) {
if(!emote.getCustom()) { if(!emote.getCustom()) {
return null; return Optional.empty();
} }
Guild guildById = getGuildById(serverId); Optional<Guild> guildById = getGuildById(serverId);
return guildById.getEmoteById(emote.getEmoteId()); if(guildById.isPresent()) {
Guild guild = guildById.get();
return Optional.ofNullable(guild.getEmoteById(emote.getEmoteId()));
}
throw new NotFoundException(String.format("Not able to find emote %s in server %s", emote.getId(), serverId));
} }
@Override @Override
public TextChannel getTextChannelFromServer(Long serverId, Long textChannelId) { public Optional<TextChannel> getTextChannelFromServer(Guild guild, Long textChannelId) {
Guild guild = getGuildById(serverId); return Optional.ofNullable(guild.getTextChannelById(textChannelId));
TextChannel textChannelById = guild.getTextChannelById(textChannelId);
if(textChannelById != null) {
return textChannelById;
} else {
throw new RuntimeException(String.format("Text channel %s in guild %s not found", textChannelId, serverId));
}
} }
@Override @Override
public Guild getGuildById(Long serverId) { public Optional<TextChannel> getTextChannelFromServer(Long serverId, Long textChannelId) {
Guild guildById = instance.getGuildById(serverId); Optional<Guild> guildOptional = getGuildById(serverId);
if(guildById != null) { if(guildOptional.isPresent()) {
return guildById; Guild guild = guildOptional.get();
} else { return Optional.ofNullable(guild.getTextChannelById(textChannelId));
throw new RuntimeException(String.format("Guild %s not found", serverId));
} }
throw new NotFoundException(String.format("Not able to find guild %s", serverId));
}
@Override
public Optional<Guild> getGuildById(Long serverId) {
return Optional.ofNullable(instance.getGuildById(serverId));
} }
@Override @Override

View File

@@ -8,6 +8,8 @@ import net.dv8tion.jda.api.entities.MessageReaction;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.Optional;
@Component @Component
@Slf4j @Slf4j
public class EmoteServiceBean implements EmoteService { public class EmoteServiceBean implements EmoteService {
@@ -38,9 +40,9 @@ public class EmoteServiceBean implements EmoteService {
@Override @Override
public String getEmoteAsMention(AEmote emote, Long serverId, String defaultText) { public String getEmoteAsMention(AEmote emote, Long serverId, String defaultText) {
if(emote != null && emote.getCustom()) { if(emote != null && emote.getCustom()) {
Emote emote1 = botService.getEmote(serverId, emote); Optional<Emote> emoteOptional = botService.getEmote(serverId, emote);
if (emote1 != null) { if (emoteOptional.isPresent()) {
return emote1.getAsMention(); return emoteOptional.get().getAsMention();
} else { } else {
log.warn("Emote {} with name {} in server {} defined, but not usable.", emote.getEmoteId(), emote.getName(), serverId); log.warn("Emote {} with name {} in server {} defined, but not usable.", emote.getEmoteId(), emote.getName(), serverId);
return defaultText; return defaultText;

View File

@@ -1,5 +1,6 @@
package dev.sheldan.abstracto.core.service; package dev.sheldan.abstracto.core.service;
import dev.sheldan.abstracto.core.exception.NotFoundException;
import dev.sheldan.abstracto.core.management.EmoteManagementService; import dev.sheldan.abstracto.core.management.EmoteManagementService;
import dev.sheldan.abstracto.core.management.UserManagementService; import dev.sheldan.abstracto.core.management.UserManagementService;
import dev.sheldan.abstracto.core.models.CachedMessage; import dev.sheldan.abstracto.core.models.CachedMessage;
@@ -7,10 +8,7 @@ import dev.sheldan.abstracto.core.models.CachedReaction;
import dev.sheldan.abstracto.core.models.database.AUser; import dev.sheldan.abstracto.core.models.database.AUser;
import dev.sheldan.abstracto.core.models.embed.*; import dev.sheldan.abstracto.core.models.embed.*;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.entities.MessageReaction;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.requests.restaction.pagination.ReactionPaginationAction; import net.dv8tion.jda.api.requests.restaction.pagination.ReactionPaginationAction;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.CachePut;
@@ -22,6 +20,7 @@ import org.springframework.stereotype.Component;
import java.awt.*; import java.awt.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
@@ -81,10 +80,23 @@ public class MessageCacheBean implements MessageCache {
@Async @Async
@Override @Override
public void loadMessage(CompletableFuture<CachedMessage> future, Long guildId, Long textChannelId, Long messageId) { public void loadMessage(CompletableFuture<CachedMessage> future, Long guildId, Long textChannelId, Long messageId) {
TextChannel textChannelById = bot.getTextChannelFromServer(guildId, textChannelId); Optional<Guild> guildOptional = bot.getGuildById(guildId);
textChannelById.retrieveMessageById(messageId).queue(message -> { if(guildOptional.isPresent()) {
buildCachedMessageFromMessage(future, message); Optional<TextChannel> textChannelByIdOptional = bot.getTextChannelFromServer(guildOptional.get(), textChannelId);
}); if(textChannelByIdOptional.isPresent()) {
TextChannel textChannel = textChannelByIdOptional.get();
textChannel.retrieveMessageById(messageId).queue(message -> {
buildCachedMessageFromMessage(future, message);
});
} else {
log.warn("Not able to load message {} in channel {} in guild {}. Text channel not found.", messageId, textChannelId, guildId);
future.completeExceptionally(new NotFoundException(String.format("Not able to load message %s. Text channel %s not found in guild %s", messageId, textChannelId, guildId)));
}
} else {
log.warn("Not able to load message {} in channel {} in guild {}. Guild not found.", messageId, textChannelId, guildId);
future.completeExceptionally(new NotFoundException(String.format("Not able to load message %s. Guild %s not found.", messageId, guildId)));
}
} }
@Override @Override

View File

@@ -1,5 +1,6 @@
package dev.sheldan.abstracto.core.service; package dev.sheldan.abstracto.core.service;
import dev.sheldan.abstracto.core.exception.NotFoundException;
import dev.sheldan.abstracto.core.management.EmoteManagementService; import dev.sheldan.abstracto.core.management.EmoteManagementService;
import dev.sheldan.abstracto.core.models.database.AEmote; import dev.sheldan.abstracto.core.models.database.AEmote;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@@ -23,22 +24,30 @@ public class MessageServiceBean implements MessageService {
@Override @Override
public void addReactionToMessage(String emoteKey, Long serverId, Message message) { public void addReactionToMessage(String emoteKey, Long serverId, Message message) {
Guild guildById = bot.getGuildById(serverId); Optional<Guild> guildByIdOptional = bot.getGuildById(serverId);
Optional<AEmote> aEmote = emoteManagementService.loadEmoteByName(emoteKey, serverId); Optional<AEmote> aEmote = emoteManagementService.loadEmoteByName(emoteKey, serverId);
if(aEmote.isPresent()) { if(guildByIdOptional.isPresent()) {
AEmote emote = aEmote.get(); Guild guild = guildByIdOptional.get();
if(emote.getCustom()) { if(aEmote.isPresent()) {
Emote emoteById = guildById.getEmoteById(emote.getEmoteId()); AEmote emote = aEmote.get();
if(emoteById != null) { if(emote.getCustom()) {
message.addReaction(emoteById).queue(); Emote emoteById = guild.getEmoteById(emote.getEmoteId());
if(emoteById != null) {
message.addReaction(emoteById).queue();
} else {
log.warn("Emote with key {} and id {} for guild {} was not found.", emoteKey, emote.getEmoteId(), guild.getId());
throw new NotFoundException(String.format("Emote with key `%s` and id %s in guild %s was not found. Check whether or not the configured emote is available.", emoteKey, emote.getEmoteId(), guild.getIdLong()));
}
} else { } else {
log.warn("Emote with key {} and id {} for guild {} was not found.", emoteKey, emote.getEmoteId(), guildById.getId()); message.addReaction(emote.getEmoteKey()).queue();
} }
} else { } else {
message.addReaction(emote.getEmoteKey()).queue(); log.warn("Cannot add reaction, emote {} not defined for server {}.", emoteKey, serverId);
throw new NotFoundException(String.format("Cannot add reaction. Emote `%s` not defined in server %s. Define the emote via the setEmote command.", emoteKey, serverId));
} }
} else { } else {
log.warn("Cannot add reaction, emote {} not defined for server {}.", emoteKey, serverId); log.warn("Cannot add reaction, guild not found {}", serverId);
throw new NotFoundException(String.format("Cannot add reaction, guild %s not found.", serverId));
} }
} }
} }

View File

@@ -23,6 +23,7 @@ import javax.security.auth.login.LoginException;
import javax.transaction.Transactional; import javax.transaction.Transactional;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors;
@Slf4j @Slf4j
@Service @Service
@@ -66,7 +67,7 @@ public class StartupManager implements Startup {
List<Guild> onlineGuilds = instance.getGuilds(); List<Guild> onlineGuilds = instance.getGuilds();
Set<Long> availableServers = SnowflakeUtils.getSnowflakeIds(onlineGuilds); Set<Long> availableServers = SnowflakeUtils.getSnowflakeIds(onlineGuilds);
availableServers.forEach(aLong -> { availableServers.forEach(aLong -> {
AServer newAServer = serverManagementService.createServer(aLong); AServer newAServer = serverManagementService.loadOrCreate(aLong);
Guild newGuild = instance.getGuildById(aLong); Guild newGuild = instance.getGuildById(aLong);
log.debug("Synchronizing server: {}", aLong); log.debug("Synchronizing server: {}", aLong);
if(newGuild != null){ if(newGuild != null){
@@ -95,10 +96,10 @@ public class StartupManager implements Startup {
private void synchronizeChannelsOf(Guild guild, AServer existingServer){ private void synchronizeChannelsOf(Guild guild, AServer existingServer){
List<GuildChannel> available = guild.getChannels(); List<GuildChannel> available = guild.getChannels();
List<AChannel> knownChannels = existingServer.getChannels(); List<AChannel> knownChannels = existingServer.getChannels().stream().filter(aChannel -> !aChannel.getDeleted()).collect(Collectors.toList());
Set<Long> knownChannelsIds = SnowflakeUtils.getOwnItemsIds(knownChannels); Set<Long> knownChannelsIds = SnowflakeUtils.getOwnItemsIds(knownChannels);
Set<Long> existingChannelsIds = SnowflakeUtils.getSnowflakeIds(available); Set<Long> existingChannelsIds = SnowflakeUtils.getSnowflakeIds(available);
Set<Long> newChannels = SetUtils.disjunction(existingChannelsIds, knownChannelsIds); Set<Long> newChannels = SetUtils.difference(existingChannelsIds, knownChannelsIds);
newChannels.forEach(aLong -> { newChannels.forEach(aLong -> {
GuildChannel channel1 = available.stream().filter(channel -> channel.getIdLong() == aLong).findFirst().get(); GuildChannel channel1 = available.stream().filter(channel -> channel.getIdLong() == aLong).findFirst().get();
log.debug("Adding new channel: {}", aLong); log.debug("Adding new channel: {}", aLong);
@@ -106,5 +107,10 @@ public class StartupManager implements Startup {
AChannel newChannel = channelManagementService.createChannel(channel1.getIdLong(), type); AChannel newChannel = channelManagementService.createChannel(channel1.getIdLong(), type);
serverManagementService.addChannelToServer(existingServer, newChannel); serverManagementService.addChannelToServer(existingServer, newChannel);
}); });
Set<Long> noLongAvailable = SetUtils.difference(knownChannelsIds, existingChannelsIds);
noLongAvailable.forEach(aLong -> {
channelManagementService.markAsDeleted(aLong);
});
} }
} }

View File

@@ -4,10 +4,12 @@ import dev.sheldan.abstracto.core.models.database.AChannel;
import dev.sheldan.abstracto.core.models.AChannelType; import dev.sheldan.abstracto.core.models.AChannelType;
import dev.sheldan.abstracto.core.management.ChannelManagementService; import dev.sheldan.abstracto.core.management.ChannelManagementService;
import dev.sheldan.abstracto.repository.ChannelRepository; import dev.sheldan.abstracto.repository.ChannelRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@Service @Service
@Slf4j
public class ChannelManagementServiceBean implements ChannelManagementService { public class ChannelManagementServiceBean implements ChannelManagementService {
@Autowired @Autowired
@@ -20,6 +22,20 @@ public class ChannelManagementServiceBean implements ChannelManagementService {
@Override @Override
public AChannel createChannel(Long id, AChannelType type) { public AChannel createChannel(Long id, AChannelType type) {
return repository.save(AChannel.builder().id(id).type(type).build()); log.info("Creating channel {} with type {}", id, type);
return repository.save(AChannel.builder().id(id).type(type).deleted(false).build());
}
@Override
public void markAsDeleted(Long id) {
AChannel channel = loadChannel(id);
channel.setDeleted(true);
repository.save(channel);
}
@Override
public void removeChannel(Long id) {
log.info("Deleting channel {}", id);
repository.deleteById(id);
} }
} }

View File

@@ -41,7 +41,7 @@ public class ConfigManagementServiceBean implements ConfigManagementService {
@Override @Override
public AConfig createConfig(Long serverId, String name, String value) { public AConfig createConfig(Long serverId, String name, String value) {
AServer server = serverManagementService.loadServer(serverId); AServer server = serverManagementService.loadOrCreate(serverId);
AConfig config = AConfig AConfig config = AConfig
.builder() .builder()
.stringValue(value) .stringValue(value)
@@ -54,7 +54,7 @@ public class ConfigManagementServiceBean implements ConfigManagementService {
@Override @Override
public AConfig createConfig(Long serverId, String name, Double value) { public AConfig createConfig(Long serverId, String name, Double value) {
AServer server = serverManagementService.loadServer(serverId); AServer server = serverManagementService.loadOrCreate(serverId);
AConfig config = AConfig AConfig config = AConfig
.builder() .builder()
.doubleValue(value) .doubleValue(value)

View File

@@ -33,7 +33,7 @@ public class EmoteManagementServiceBean implements EmoteManagementService {
@Override @Override
public AEmote createCustomEmote(String name, String emoteKey, Long emoteId, Boolean animated, Long serverId) { public AEmote createCustomEmote(String name, String emoteKey, Long emoteId, Boolean animated, Long serverId) {
AServer server = serverManagementService.loadServer(serverId); AServer server = serverManagementService.loadOrCreate(serverId);
return this.createCustomEmote(name, emoteKey, emoteId, animated, server); return this.createCustomEmote(name, emoteKey, emoteId, animated, server);
} }
@@ -55,7 +55,7 @@ public class EmoteManagementServiceBean implements EmoteManagementService {
@Override @Override
public AEmote createDefaultEmote(String name, String emoteKey, Long serverId) { public AEmote createDefaultEmote(String name, String emoteKey, Long serverId) {
AServer server = serverManagementService.loadServer(serverId); AServer server = serverManagementService.loadOrCreate(serverId);
return createDefaultEmote(name, emoteKey, server); return createDefaultEmote(name, emoteKey, server);
} }
@@ -75,7 +75,7 @@ public class EmoteManagementServiceBean implements EmoteManagementService {
@Override @Override
public Optional<AEmote> loadEmoteByName(String name, Long serverId) { public Optional<AEmote> loadEmoteByName(String name, Long serverId) {
AServer server = serverManagementService.loadServer(serverId); AServer server = serverManagementService.loadOrCreate(serverId);
return loadEmoteByName(name, server); return loadEmoteByName(name, server);
} }
@@ -86,7 +86,7 @@ public class EmoteManagementServiceBean implements EmoteManagementService {
@Override @Override
public AEmote setEmoteToCustomEmote(String name, String emoteKey, Long emoteId, Boolean animated, Long serverId) { public AEmote setEmoteToCustomEmote(String name, String emoteKey, Long emoteId, Boolean animated, Long serverId) {
AServer server = serverManagementService.loadServer(serverId); AServer server = serverManagementService.loadOrCreate(serverId);
AEmote emote; AEmote emote;
Optional<AEmote> emoteOptional = loadEmoteByName(name, server); Optional<AEmote> emoteOptional = loadEmoteByName(name, server);
if(!emoteOptional.isPresent()) { if(!emoteOptional.isPresent()) {
@@ -104,7 +104,7 @@ public class EmoteManagementServiceBean implements EmoteManagementService {
@Override @Override
public AEmote setEmoteToCustomEmote(String name, Emote emote, Long serverId) { public AEmote setEmoteToCustomEmote(String name, Emote emote, Long serverId) {
AServer server = serverManagementService.loadServer(serverId); AServer server = serverManagementService.loadOrCreate(serverId);
AEmote emoteBeingSet; AEmote emoteBeingSet;
Optional<AEmote> emoteOptional = loadEmoteByName(name, serverId); Optional<AEmote> emoteOptional = loadEmoteByName(name, serverId);
if(!emoteOptional.isPresent()) { if(!emoteOptional.isPresent()) {
@@ -122,7 +122,7 @@ public class EmoteManagementServiceBean implements EmoteManagementService {
@Override @Override
public AEmote setEmoteToDefaultEmote(String name, String emoteKey, Long serverId) { public AEmote setEmoteToDefaultEmote(String name, String emoteKey, Long serverId) {
AServer server = serverManagementService.loadServer(serverId); AServer server = serverManagementService.loadOrCreate(serverId);
AEmote emoteBeingSet; AEmote emoteBeingSet;
Optional<AEmote> emoteOptional = loadEmoteByName(name, serverId); Optional<AEmote> emoteOptional = loadEmoteByName(name, serverId);
if(!emoteOptional.isPresent()) { if(!emoteOptional.isPresent()) {
@@ -138,7 +138,7 @@ public class EmoteManagementServiceBean implements EmoteManagementService {
@Override @Override
public boolean emoteExists(String name, Long serverId) { public boolean emoteExists(String name, Long serverId) {
AServer server = serverManagementService.loadServer(serverId); AServer server = serverManagementService.loadOrCreate(serverId);
return emoteExists(name, server); return emoteExists(name, server);
} }

View File

@@ -15,8 +15,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.List;
@Service @Service
@Slf4j @Slf4j
public class PostTargetManagementBean implements PostTargetManagement { public class PostTargetManagementBean implements PostTargetManagement {
@@ -63,7 +61,7 @@ public class PostTargetManagementBean implements PostTargetManagement {
@Override @Override
public void createOrUpdate(String name, Long serverId, Long channelId) { public void createOrUpdate(String name, Long serverId, Long channelId) {
AChannel dbChannel = channelManagementService.loadChannel(channelId); AChannel dbChannel = channelManagementService.loadChannel(channelId);
AServer dbServer = serverManagementService.loadServer(serverId); AServer dbServer = serverManagementService.loadOrCreate(serverId);
createOrUpdate(name, dbServer, dbChannel); createOrUpdate(name, dbServer, dbChannel);
} }
@@ -75,7 +73,7 @@ public class PostTargetManagementBean implements PostTargetManagement {
@Override @Override
public PostTarget getPostTarget(String name, Long serverId) { public PostTarget getPostTarget(String name, Long serverId) {
AServer server = serverManagementService.loadServer(serverId); AServer server = serverManagementService.loadOrCreate(serverId);
return getPostTarget(name, server); return getPostTarget(name, server);
} }

View File

@@ -34,7 +34,7 @@ public class ServerManagementServiceBean implements ServerManagementService {
} }
@Override @Override
public AServer loadServer(Long id) { public AServer loadOrCreate(Long id) {
if(repository.existsById(id)) { if(repository.existsById(id)) {
return repository.getOne(id); return repository.getOne(id);
} else { } else {
@@ -66,13 +66,13 @@ public class ServerManagementServiceBean implements ServerManagementService {
@Override @Override
public AChannel getPostTarget(Long serverId, String name) { public AChannel getPostTarget(Long serverId, String name) {
AServer server = this.loadServer(serverId); AServer server = this.loadOrCreate(serverId);
return getPostTarget(server, name); return getPostTarget(server, name);
} }
@Override @Override
public AChannel getPostTarget(Long serverId, PostTarget target) { public AChannel getPostTarget(Long serverId, PostTarget target) {
AServer server = this.loadServer(serverId); AServer server = this.loadOrCreate(serverId);
return getPostTarget(server, target); return getPostTarget(server, target);
} }

View File

@@ -29,7 +29,7 @@ public class UserManagementServiceBean implements UserManagementService {
@Override @Override
public AUserInAServer loadUser(Long serverId, Long userId) { public AUserInAServer loadUser(Long serverId, Long userId) {
AUser user = this.loadUser(userId); AUser user = this.loadUser(userId);
AServer server = serverManagementService.loadServer(serverId); AServer server = serverManagementService.loadOrCreate(serverId);
return loadUser(server, user); return loadUser(server, user);
} }

View File

@@ -1,44 +1,50 @@
package dev.sheldan.abstracto.listener; package dev.sheldan.abstracto.listener;
import dev.sheldan.abstracto.core.management.ChannelManagementService;
import dev.sheldan.abstracto.core.management.ServerManagementService;
import dev.sheldan.abstracto.core.models.AChannelType;
import dev.sheldan.abstracto.core.models.database.AChannel; import dev.sheldan.abstracto.core.models.database.AChannel;
import dev.sheldan.abstracto.core.models.database.AServer; import dev.sheldan.abstracto.core.models.database.AServer;
import dev.sheldan.abstracto.repository.ServerRepository; import dev.sheldan.abstracto.repository.ServerRepository;
import lombok.extern.slf4j.Slf4j;
import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.events.channel.text.TextChannelCreateEvent; import net.dv8tion.jda.api.events.channel.text.TextChannelCreateEvent;
import net.dv8tion.jda.api.events.channel.text.TextChannelDeleteEvent; import net.dv8tion.jda.api.events.channel.text.TextChannelDeleteEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.util.Optional;
@Service @Service
@Slf4j
public class ChannelListener extends ListenerAdapter { public class ChannelListener extends ListenerAdapter {
@Autowired @Autowired
private ServerRepository serverRepository; private ServerRepository serverRepository;
private static Logger logger = LoggerFactory.getLogger(ChannelListener.class); @Autowired
private ChannelManagementService channelManagementService;
@Autowired
private ServerManagementService serverManagementService;
@Override @Override
@Transactional
public void onTextChannelDelete(@Nonnull TextChannelDeleteEvent event) { public void onTextChannelDelete(@Nonnull TextChannelDeleteEvent event) {
AServer serverObject = serverRepository.getOne(event.getGuild().getIdLong()); log.info("Handling channel delete event. Channel {}, Server {}", event.getChannel().getIdLong(), event.getGuild().getIdLong());
serverObject.getChannels().add(AChannel.builder().id(event.getChannel().getIdLong()).build()); channelManagementService.markAsDeleted(event.getChannel().getIdLong());
} }
@Override @Override
@Transactional
public void onTextChannelCreate(@Nonnull TextChannelCreateEvent event) { 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 = serverRepository.getOne(event.getGuild().getIdLong());
TextChannel createdChannel = event.getChannel(); TextChannel createdChannel = event.getChannel();
Optional<AChannel> possibleChannel = serverObject.getChannels().stream().filter(aChannel -> aChannel.id == createdChannel.getIdLong()).findAny(); AChannelType type = AChannel.getAChannelType(createdChannel.getType());
if(possibleChannel.isPresent()){ AChannel newChannel = channelManagementService.createChannel(createdChannel.getIdLong(), type);
serverObject.getChannels().remove(possibleChannel.get()); serverManagementService.addChannelToServer(serverObject, newChannel);
logger.info("Adding channel {} with id {}", createdChannel.getName(), createdChannel.getIdLong());
} else {
logger.warn("Channel removed event for channel which was not in present");
}
} }
} }

View File

@@ -0,0 +1,46 @@
package dev.sheldan.abstracto.listener;
import dev.sheldan.abstracto.core.listener.MessageDeletedListener;
import dev.sheldan.abstracto.core.models.CachedMessage;
import dev.sheldan.abstracto.core.service.MessageCache;
import lombok.extern.slf4j.Slf4j;
import net.dv8tion.jda.api.events.message.guild.GuildMessageDeleteEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Nonnull;
import java.util.List;
@Component
@Slf4j
public class MessageDeletedListenerBean extends ListenerAdapter {
@Autowired
private List<MessageDeletedListener> listener;
@Autowired
private MessageCache messageCache;
@Autowired
private MessageDeletedListenerBean self;
@Override
@Transactional
public void onGuildMessageDelete(@Nonnull GuildMessageDeleteEvent event) {
messageCache.getMessageFromCache(event.getGuild().getIdLong(), event.getChannel().getIdLong(), event.getMessageIdLong()).thenAccept(cachedMessage -> {
self.executeListener(cachedMessage);
});
}
@Transactional
public void executeListener(CachedMessage cachedMessage) {
listener.forEach(messageDeletedListener -> {
try {
messageDeletedListener.execute(cachedMessage);
} catch (Exception e) {
log.warn("Listener {} failed with exception:", messageDeletedListener.getClass().getName(), e);
}
});
}
}

View File

@@ -24,7 +24,6 @@ import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import java.util.concurrent.ExecutionException;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@@ -99,7 +98,7 @@ public class MessageEmbedListener extends ListenerAdapter {
private MessageEmbeddedModel buildTemplateParameter(GuildMessageReceivedEvent event, CachedMessage embeddedMessage) { private MessageEmbeddedModel buildTemplateParameter(GuildMessageReceivedEvent event, CachedMessage embeddedMessage) {
AChannel channel = channelManagementService.loadChannel(event.getChannel().getIdLong()); AChannel channel = channelManagementService.loadChannel(event.getChannel().getIdLong());
AServer server = serverManagementService.loadServer(event.getGuild().getIdLong()); AServer server = serverManagementService.loadOrCreate(event.getGuild().getIdLong());
AUserInAServer user = userManagementService.loadUser(event.getMember()); AUserInAServer user = userManagementService.loadUser(event.getMember());
Member author = bot.getMemberInServer(embeddedMessage.getServerId(), embeddedMessage.getAuthorId()); Member author = bot.getMemberInServer(embeddedMessage.getServerId(), embeddedMessage.getAuthorId());
return MessageEmbeddedModel return MessageEmbeddedModel

View File

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

View File

@@ -0,0 +1,7 @@
package dev.sheldan.abstracto.core.listener;
import dev.sheldan.abstracto.core.models.CachedMessage;
public interface MessageDeletedListener {
void execute(CachedMessage messageBefore);
}

View File

@@ -6,4 +6,6 @@ import dev.sheldan.abstracto.core.models.AChannelType;
public interface ChannelManagementService { public interface ChannelManagementService {
AChannel loadChannel(Long id); AChannel loadChannel(Long id);
AChannel createChannel(Long id, AChannelType type); AChannel createChannel(Long id, AChannelType type);
void markAsDeleted(Long id);
void removeChannel(Long id);
} }

View File

@@ -6,7 +6,7 @@ import java.util.List;
public interface ServerManagementService { public interface ServerManagementService {
AServer createServer(Long id); AServer createServer(Long id);
AServer loadServer(Long id); AServer loadOrCreate(Long id);
void addChannelToServer(AServer server, AChannel channel); void addChannelToServer(AServer server, AChannel channel);
AUserInAServer addUserToServer(AServer server, AUser user); AUserInAServer addUserToServer(AServer server, AUser user);
AUserInAServer addUserToServer(Long serverId, Long userId); AUserInAServer addUserToServer(Long serverId, Long userId);

View File

@@ -34,6 +34,11 @@ public class AChannel implements SnowFlake {
@Enumerated(EnumType.STRING) @Enumerated(EnumType.STRING)
private AChannelType type; private AChannelType type;
@Getter
@Setter
@Column
private Boolean deleted;
public static AChannelType getAChannelType(ChannelType type) { public static AChannelType getAChannelType(ChannelType type) {
switch (type) { switch (type) {
case TEXT: return AChannelType.TEXT; case TEXT: return AChannelType.TEXT;

View File

@@ -10,6 +10,7 @@ import net.dv8tion.jda.api.entities.TextChannel;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.security.auth.login.LoginException; import javax.security.auth.login.LoginException;
import java.util.Optional;
@Service @Service
public interface Bot { public interface Bot {
@@ -18,8 +19,9 @@ public interface Bot {
ServerChannelUser getServerChannelUser(Long serverId, Long channelId, Long userId); ServerChannelUser getServerChannelUser(Long serverId, Long channelId, Long userId);
Member getMemberInServer(Long serverId, Long memberId); Member getMemberInServer(Long serverId, Long memberId);
void deleteMessage(Long serverId, Long channelId, Long messageId); void deleteMessage(Long serverId, Long channelId, Long messageId);
Emote getEmote(Long serverId, AEmote emote); Optional<Emote> getEmote(Long serverId, AEmote emote);
TextChannel getTextChannelFromServer(Long serverId, Long textChannelId); Optional<TextChannel> getTextChannelFromServer(Guild serverId, Long textChannelId);
Guild getGuildById(Long serverId); Optional<TextChannel> getTextChannelFromServer(Long serverId, Long textChannelId);
Optional<Guild> getGuildById(Long serverId);
void shutdown(); void shutdown();
} }

View File

@@ -43,7 +43,7 @@ public class ContextUtils {
.guild(serverChannelUser.getGuild()) .guild(serverChannelUser.getGuild())
.textChannel(serverChannelUser.getTextChannel()) .textChannel(serverChannelUser.getTextChannel())
.channel(channelManagementService.loadChannel(message.getChannelId())) .channel(channelManagementService.loadChannel(message.getChannelId()))
.server(serverManagementService.loadServer(message.getServerId())) .server(serverManagementService.loadOrCreate(message.getServerId()))
.aUserInAServer(aUserInAServer) .aUserInAServer(aUserInAServer)
.user(aUserInAServer.getUserReference()) .user(aUserInAServer.getUserReference())
.build(); .build();

View File

@@ -10,10 +10,9 @@ import java.util.Optional;
public class EmoteUtils { public class EmoteUtils {
public static boolean isReactionEmoteAEmote(MessageReaction.ReactionEmote reaction, AEmote emote, Optional<Emote> emoteInGuildOptional) { public static boolean isReactionEmoteAEmote(MessageReaction.ReactionEmote reaction, AEmote emote, Emote emoteInGuild) {
if(reaction.isEmote() && emote.getCustom()) { if(reaction.isEmote() && emote.getCustom()) {
if(emoteInGuildOptional.isPresent()) { if(emoteInGuild != null) {
Emote emoteInGuild = emoteInGuildOptional.get();
return emoteInGuild.equals(reaction.getEmote()); return emoteInGuild.equals(reaction.getEmote());
} else { } else {
return false; return false;

View File

@@ -1,2 +1,16 @@
spring.quartz.job-store-type=jdbc spring.quartz.job-store-type=jdbc
spring.quartz.jdbc.initialize-schema=never spring.quartz.jdbc.initialize-schema=never
spring.quartz.properties.org.quartz.scheduler.instanceName=quartz-abstracto-app
spring.quartz.properties.org.quartz.scheduler.instanceId=AUTO
spring.quartz.properties.org.quartz.scheduler.instanceIdGenerator.class=dev.sheldan.abstracto.scheduling.service.IdGenerationService
spring.quartz.properties.org.quartz.threadPool.threadCount=20
spring.quartz.properties.org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX
spring.quartz.properties.org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.PostgreSQLDelegate
spring.quartz.properties.org.quartz.jobStore.useProperties=true
spring.quartz.properties.org.quartz.jobStore.misfireThreshold=60000
spring.quartz.properties.org.quartz.jobStore.tablePrefix=qrtz_
spring.quartz.properties.org.quartz.jobStore.isClustered=false
spring.quartz.properties.org.quartz.plugin.shutdownHook.class=org.quartz.plugins.management.ShutdownHookPlugin
spring.quartz.properties.org.quartz.plugin.shutdownHook.cleanShutdown=TRUE

View File

@@ -1,12 +0,0 @@
spring.quartz.properties.org.quartz.scheduler.instanceName=quartz-abstracto-app
spring.quartz.properties.org.quartz.scheduler.instanceId=AUTO
spring.quartz.properties.org.quartz.scheduler.instanceIdGenerator.class=dev.sheldan.abstracto.scheduling.service.IdGenerationService
spring.quartz.properties.org.quartz.threadPool.threadCount=20
spring.quartz.properties.org.quartz.jobStore.class=org.quartz.impl.jdbcjobstore.JobStoreTX
spring.quartz.properties.org.quartz.jobStore.driverDelegateClass=org.quartz.impl.jdbcjobstore.PostgreSQLDelegate
spring.quartz.properties.org.quartz.jobStore.useProperties=true
spring.quartz.properties.org.quartz.jobStore.misfireThreshold=60000
spring.quartz.properties.org.quartz.jobStore.tablePrefix=qrtz_
spring.quartz.properties.org.quartz.jobStore.isClustered=false
spring.quartz.properties.org.quartz.plugin.shutdownHook.class=org.quartz.plugins.management.ShutdownHookPlugin
spring.quartz.properties.org.quartz.plugin.shutdownHook.cleanShutdown=TRUE