Compare commits

...

9 Commits

Author SHA1 Message Date
Sheldan
3313daa3fa [maven-release-plugin] prepare release abstracto-application-1.2.6 2021-03-29 03:17:34 +02:00
Sheldan
8c026d3547 [AB-82] adding feature mode to make it configurable whether or not the youtube video will show details or not
adding convenience method to config service
2021-03-29 03:02:46 +02:00
Sheldan
8a8e6b2347 [maven-release-plugin] prepare for next development iteration 2021-03-29 01:38:28 +02:00
Sheldan
14b2d78a3b [maven-release-plugin] prepare release abstracto-application-1.2.5 2021-03-29 01:38:22 +02:00
Sheldan
45c1df0d44 [AB-82] adding urban dictionary api with a command
adding Instant handling to GSON
2021-03-29 01:13:46 +02:00
Sheldan
c2b413e4b9 [AB-82] adding youtube video search 2021-03-28 23:29:51 +02:00
Sheldan
9541f907b8 [AB-215] adding create alias and delete alias commands to create service specific aliases for commands
renaming package in commands package
defaulting to latest in docker compose build for deployment container
fixing jacoco configuration
changing that if there are no parameters required, parameters are accepted
2021-03-28 16:46:21 +02:00
Sheldan
a494d4d2f2 [AB-213] fixing not properly creating a channel in case the event is sent 2021-03-25 01:14:06 +01:00
Sheldan
9735f52df5 [maven-release-plugin] prepare for next development iteration 2021-03-24 22:14:03 +01:00
226 changed files with 4274 additions and 430 deletions

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>assignable-roles</artifactId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>assignable-roles</artifactId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>assignable-roles-int</artifactId>

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>abstracto-modules</artifactId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>entertainment</artifactId>
<groupId>dev.sheldan.abstracto.modules</groupId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -49,7 +49,7 @@ public class RollTest {
Long serverId = 3L;
Integer max = 10;
when(noParameters.getGuild().getIdLong()).thenReturn(serverId);
when(configService.getLongValue(ROLL_DEFAULT_HIGH_KEY, serverId)).thenReturn(max.longValue());
when(configService.getLongValueOrConfigDefault(ROLL_DEFAULT_HIGH_KEY, serverId)).thenReturn(max.longValue());
when(entertainmentService.calculateRollResult(1, max)).thenReturn(result);
when(channelService.sendEmbedTemplateInTextChannelList(eq(Roll.ROLL_RESPONSE_TEMPLATE_KEY), responseModelArgumentCaptor.capture(), eq(noParameters.getChannel()))).thenReturn(CommandTestUtilities.messageFutureList());
CompletableFuture<CommandResult> futureResult = testUnit.executeAsync(noParameters);

View File

@@ -79,7 +79,7 @@ public class EntertainmentServiceBeanTest {
when(guild.getIdLong()).thenReturn(serverId);
when(member.getGuild()).thenReturn(guild);
Long sides = 6L;
when(configService.getLongValue(EntertainmentFeatureConfig.ROULETTE_BULLETS_CONFIG_KEY, serverId)).thenReturn(sides);
when(configService.getLongValueOrConfigDefault(EntertainmentFeatureConfig.ROULETTE_BULLETS_CONFIG_KEY, serverId)).thenReturn(sides);
when(secureRandom.nextInt(sides.intValue())).thenReturn(randomValue);
boolean shot = testUnit.executeRoulette(member);
Assert.assertEquals(randomValue == 0, shot);

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>entertainment</artifactId>
<groupId>dev.sheldan.abstracto.modules</groupId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>abstracto-modules</artifactId>
<groupId>dev.sheldan.abstracto.modules</groupId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>experience-tracking</artifactId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -37,11 +37,10 @@ public class JoiningUserRoleListener implements AsyncJoinListener {
public DefaultListenerResult execute(MemberJoinModel model) {
AUserInAServer userInAServer = userInServerManagementService.loadOrCreateUser(model.getServerId(), model.getJoiningUser().getUserId());
AUserExperience userExperience = userExperienceManagementService.findUserInServer(userInAServer);
Long userInServerId = userInAServer.getUserInServerId();
if(userExperience != null) {
log.info("User {} joined {} with previous experience. Setting up experience role again (if necessary).", model.getJoiningUser().getUserId(), model.getServerId());
userExperienceService.syncForSingleUser(userExperience).thenAccept(result ->
log.info("Finished re-assigning experience for re-joining user {} in server {}.", userInServerId, model.getServerId())
log.info("Finished re-assigning experience for re-joining user {} in server {}.", model.getJoiningUser().getUserId(), model.getServerId())
);
} else {
log.info("Joined user {} in server {} does not have any previous experience. Not setting up anything.", model.getJoiningUser().getUserId(), model.getServerId());

View File

@@ -1,5 +1,7 @@
package dev.sheldan.abstracto.experience.listener;
import dev.sheldan.abstracto.core.listener.DefaultListenerResult;
import dev.sheldan.abstracto.core.listener.ListenerExecutionResult;
import dev.sheldan.abstracto.core.models.ServerUser;
import dev.sheldan.abstracto.core.models.database.AUserInAServer;
import dev.sheldan.abstracto.core.models.listener.MemberJoinModel;
@@ -7,6 +9,7 @@ import dev.sheldan.abstracto.core.service.management.UserInServerManagementServi
import dev.sheldan.abstracto.experience.model.database.AUserExperience;
import dev.sheldan.abstracto.experience.service.AUserExperienceService;
import dev.sheldan.abstracto.experience.service.management.UserExperienceManagementService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -48,9 +51,9 @@ public class JoiningUserRoleListenerTest {
@Before
public void setup() {
when(serverUser.getServerId()).thenReturn(SERVER_ID);
when(serverUser.getUserId()).thenReturn(USER_ID);
when(model.getJoiningUser()).thenReturn(serverUser);
when(model.getServerId()).thenReturn(SERVER_ID);
when(userInServerManagementService.loadOrCreateUser(SERVER_ID, USER_ID)).thenReturn(aUserInAServer);
}
@@ -59,7 +62,8 @@ public class JoiningUserRoleListenerTest {
AUserExperience experience = Mockito.mock(AUserExperience.class);
when(userExperienceManagementService.findUserInServer(aUserInAServer)).thenReturn(experience);
when(userExperienceService.syncForSingleUser(experience)).thenReturn(CompletableFuture.completedFuture(null));
testUnit.execute(model);
DefaultListenerResult result = testUnit.execute(model);
Assert.assertEquals(DefaultListenerResult.PROCESSED, result);
}
@Test

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>experience-tracking</artifactId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>abstracto-modules</artifactId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>link-embed</artifactId>
<groupId>dev.sheldan.abstracto.modules</groupId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -59,7 +59,6 @@ public class MessageEmbedPostManagementServiceBeanTest {
AUserInAServer embeddedUser = Mockito.mock(AUserInAServer.class);
AChannel channel = Mockito.mock(AChannel.class);
AServer server = Mockito.mock(AServer.class);
when(server.getId()).thenReturn(SERVER_ID);
when(serverManagementService.loadOrCreate(SERVER_ID)).thenReturn(server);
when(channelManagementService.loadChannel(EMBEDDING_CHANNEL_ID)).thenReturn(channel);
CachedMessage cachedMessage = Mockito.mock(CachedMessage.class);
@@ -69,7 +68,6 @@ public class MessageEmbedPostManagementServiceBeanTest {
CachedAuthor cachedAuthor = Mockito.mock(CachedAuthor.class);
when(cachedAuthor.getAuthorId()).thenReturn(EMBEDDED_USER_ID);
when(cachedMessage.getAuthor()).thenReturn(cachedAuthor);
when(cachedMessage.getServerId()).thenReturn(SERVER_ID);
Message embeddingMessage = Mockito.mock(Message.class);
MessageChannel embeddingChannel = Mockito.mock(MessageChannel.class);
when(embeddingChannel.getIdLong()).thenReturn(EMBEDDING_CHANNEL_ID);
@@ -99,7 +97,6 @@ public class MessageEmbedPostManagementServiceBeanTest {
public void testToCreateEmbedForDifferentServers() {
Long originServerId = 4L;
AServer originalServer = Mockito.mock(AServer.class);
when(originalServer.getId()).thenReturn(originServerId);
AServer embeddingServer = Mockito.mock(AServer.class);
when(embeddingServer.getId()).thenReturn(SERVER_ID);
AUserInAServer embeddingUser = Mockito.mock(AUserInAServer.class);

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>link-embed</artifactId>
<groupId>dev.sheldan.abstracto.modules</groupId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>abstracto-modules</artifactId>
<groupId>dev.sheldan.abstracto.modules</groupId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>moderation</artifactId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -51,7 +51,7 @@ public class LeaveLogger implements AsyncLeaveListener {
@Override
public DefaultListenerResult execute(MemberLeaveModel model) {
String text = templateService.renderTemplateWithMap(USER_LEAVE_TEMPLATE, getUserParameter(model.getMember().getUser()), model.getLeavingUser().getServerId());
String text = templateService.renderTemplateWithMap(USER_LEAVE_TEMPLATE, getUserParameter(model.getMember().getUser()), model.getServerId());
postTargetService.sendTextInPostTarget(text, LoggingPostTarget.LEAVE_LOG, model.getServerId());
return DefaultListenerResult.PROCESSED;
}

View File

@@ -45,7 +45,7 @@ public class MessageEditedListener implements AsyncMessageTextUpdatedListener {
log.trace("Message content was the same. Possible reason was: message was not in cache.");
return DefaultListenerResult.IGNORED;
}
log.trace("Message {} in channel {} in guild {} was edited.", messageBefore.getMessageId(), messageBefore.getChannelId(), messageBefore.getServerId());
log.trace("Message {} in channel {} in guild {} was edited.", messageBefore.getMessageId(), messageBefore.getChannelId(), model.getServerId());
TextChannel textChannel = channelService.getTextChannelFromServer(model.getServerId(), messageBefore.getChannelId());
MessageEditedLog log = MessageEditedLog
.builder()
@@ -55,8 +55,8 @@ public class MessageEditedListener implements AsyncMessageTextUpdatedListener {
.guild(textChannel.getGuild())
.member(messageAfter.getMember())
.build();
MessageToSend message = templateService.renderEmbedTemplate(MESSAGE_EDITED_TEMPLATE, log, messageBefore.getServerId());
postTargetService.sendEmbedInPostTarget(message, LoggingPostTarget.EDIT_LOG, messageBefore.getServerId());
MessageToSend message = templateService.renderEmbedTemplate(MESSAGE_EDITED_TEMPLATE, log, model.getServerId());
postTargetService.sendEmbedInPostTarget(message, LoggingPostTarget.EDIT_LOG, model.getServerId());
return DefaultListenerResult.PROCESSED;
}

View File

@@ -49,14 +49,11 @@ public class JoinLoggerTest {
@Test
public void testExecute() {
when(serverUser.getUserId()).thenReturn(USER_ID);
when(serverUser.getServerId()).thenReturn(SERVER_ID);
when(model.getMember()).thenReturn(member);
when(memberService.getMemberInServerAsync(SERVER_ID, USER_ID)).thenReturn(CompletableFuture.completedFuture(member));
testUnit.execute(model);
when(serverUser.getServerId()).thenReturn(SERVER_ID);
when(model.getServerId()).thenReturn(SERVER_ID);
String message = "text";
when(templateService.renderTemplateWithMap(eq(JoinLogger.USER_JOIN_TEMPLATE), any(), eq(SERVER_ID))).thenReturn(message);
testUnit.execute(model);
verify(postTargetService, times(1)).sendTextInPostTarget(message, LoggingPostTarget.JOIN_LOG, SERVER_ID);
}

View File

@@ -31,12 +31,6 @@ public class JoinMuteListenerTest {
@Mock
private UserInServerManagementService userInServerManagementService;
@Mock
private Member member;
@Mock
private Guild guild;
@Mock
private AUserInAServer joiningUser;
@@ -51,22 +45,22 @@ public class JoinMuteListenerTest {
@Test
public void testNonMutedUserJoins() {
when(serverUser.getServerId()).thenReturn(SERVER_ID);
when(serverUser.getUserId()).thenReturn(USER_ID);
when(userInServerManagementService.loadOrCreateUser(SERVER_ID, USER_ID)).thenReturn(joiningUser);
when(muteManagementService.hasActiveMute(joiningUser)).thenReturn(false);
when(model.getMember()).thenReturn(member);
when(model.getServerId()).thenReturn(SERVER_ID);
when(model.getJoiningUser()).thenReturn(serverUser);
testUnit.execute(model);
verify(muteService, times(0)).applyMuteRole(joiningUser);
}
@Test
public void testMutedUserJoins() {
when(serverUser.getServerId()).thenReturn(SERVER_ID);
when(model.getServerId()).thenReturn(SERVER_ID);
when(serverUser.getUserId()).thenReturn(USER_ID);
when(userInServerManagementService.loadOrCreateUser(SERVER_ID, USER_ID)).thenReturn(joiningUser);
when(muteManagementService.hasActiveMute(joiningUser)).thenReturn(true);
when(model.getMember()).thenReturn(member);
when(model.getJoiningUser()).thenReturn(serverUser);
testUnit.execute(model);
verify(muteService, times(1)).applyMuteRole(joiningUser);
}

View File

@@ -51,14 +51,11 @@ public class LeaveLoggerTest {
@Test
public void testExecute() {
when(leavingUser.getUserId()).thenReturn(USER_ID);
when(leavingUser.getServerId()).thenReturn(SERVER_ID);
when(memberService.getMemberInServerAsync(SERVER_ID, USER_ID)).thenReturn(CompletableFuture.completedFuture(member));
when(model.getServerId()).thenReturn(SERVER_ID);
when(model.getMember()).thenReturn(member);
User user = Mockito.mock(User.class);
when(member.getUser()).thenReturn(user);
String message = "text";
when(leavingUser.getServerId()).thenReturn(SERVER_ID);
when(templateService.renderTemplateWithMap(eq(LeaveLogger.USER_LEAVE_TEMPLATE), any(), eq(SERVER_ID))).thenReturn(message);
testUnit.execute(model);
verify(postTargetService, times(1)).sendTextInPostTarget(message, LoggingPostTarget.LEAVE_LOG, SERVER_ID);

View File

@@ -94,7 +94,6 @@ public class MessageDeleteLogListenerTest {
public void testExecuteListener() {
when(deletedMessage.getAuthor()).thenReturn(cachedAuthor);
when(cachedAuthor.getAuthorId()).thenReturn(AUTHOR_ID);
when(deletedMessage.getServerId()).thenReturn(SERVER_ID);
when(memberService.getMemberInServerAsync(SERVER_ID, AUTHOR_ID)).thenReturn(CompletableFuture.completedFuture(member));
when(model.getCachedMessage()).thenReturn(deletedMessage);
when(model.getServerId()).thenReturn(SERVER_ID);

View File

@@ -51,6 +51,7 @@ public class MessageEditedListenerTest {
@Mock
private CachedMessage messageBefore;
@Mock
private MessageTextUpdatedModel model;
private static final Long SERVER_ID = 4L;
@@ -77,17 +78,16 @@ public class MessageEditedListenerTest {
Guild guild = Mockito.mock(Guild.class);
when(channel.getGuild()).thenReturn(guild);
Member author = Mockito.mock(Member.class);
CachedAuthor cachedAuthor = Mockito.mock(CachedAuthor.class);
when(cachedAuthor.getAuthorId()).thenReturn(AUTHOR_ID);
when(messageBefore.getContent()).thenReturn(content);
when(messageBefore.getServerId()).thenReturn(SERVER_ID);
when(messageBefore.getChannelId()).thenReturn(CHANNEL_ID);
MessageToSend messageToSend = Mockito.mock(MessageToSend.class);
ArgumentCaptor<MessageEditedLog> captor = ArgumentCaptor.forClass(MessageEditedLog.class);
when(templateService.renderEmbedTemplate(eq(MessageEditedListener.MESSAGE_EDITED_TEMPLATE), captor.capture(), eq(SERVER_ID))).thenReturn(messageToSend);
when(memberService.getMemberInServerAsync(SERVER_ID, AUTHOR_ID)).thenReturn(CompletableFuture.completedFuture(author));
when(channelService.getTextChannelFromServer(SERVER_ID, CHANNEL_ID)).thenReturn(channel);
when(model.getAfter()).thenReturn(messageAfter);
when(model.getBefore()).thenReturn(messageBefore);
when(messageAfter.getMember()).thenReturn(author);
when(model.getServerId()).thenReturn(SERVER_ID);
testUnit.execute(model);
verify(postTargetService, times(1)).sendEmbedInPostTarget(messageToSend, LoggingPostTarget.EDIT_LOG, SERVER_ID);
MessageEditedLog capturedValue = captor.getValue();

View File

@@ -7,6 +7,7 @@ import dev.sheldan.abstracto.moderation.repository.MuteRoleRepository;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
@@ -46,8 +47,12 @@ public class MuteRoleManagementServiceBeanTest {
@Test
public void testCreateMuteRoleForServer() {
ARole role = Mockito.mock(ARole.class);
ArgumentCaptor<MuteRole> muteRoleCaptor = ArgumentCaptor.forClass(MuteRole.class);
MuteRole savedRole = Mockito.mock(MuteRole.class);
when(muteRoleRepository.save(muteRoleCaptor.capture())).thenReturn(savedRole);
MuteRole muteRoleForServer = testUnit.createMuteRoleForServer(server, role);
verifyRoleSaved(role, muteRoleForServer, 1);
Assert.assertEquals(savedRole, muteRoleForServer);
Assert.assertEquals(role, muteRoleCaptor.getValue().getRole());
}
@Test
@@ -67,8 +72,12 @@ public class MuteRoleManagementServiceBeanTest {
public void testSetMuteRoleWithoutPrevious() {
ARole role = Mockito.mock(ARole.class);
when(muteRoleRepository.existsByRoleServer(server)).thenReturn(false);
ArgumentCaptor<MuteRole> muteRoleCaptor = ArgumentCaptor.forClass(MuteRole.class);
MuteRole savedRole = Mockito.mock(MuteRole.class);
when(muteRoleRepository.save(muteRoleCaptor.capture())).thenReturn(savedRole);
MuteRole muteRole = testUnit.setMuteRoleForServer(server, role);
verifyRoleSaved(role, muteRole, 1);
Assert.assertEquals(savedRole, muteRole);
Assert.assertEquals(role, muteRoleCaptor.getValue().getRole());
}
@Test
@@ -76,16 +85,11 @@ public class MuteRoleManagementServiceBeanTest {
ARole role = Mockito.mock(ARole.class);
when(muteRoleRepository.existsByRoleServer(server)).thenReturn(true);
MuteRole existingRole = Mockito.mock(MuteRole.class);
when(existingRole.getRole()).thenReturn(role);
when(muteRoleRepository.findByRoleServer(server)).thenReturn(existingRole);
MuteRole muteRole = testUnit.setMuteRoleForServer(server, role);
verifyRoleSaved(role, muteRole, 0);
testUnit.setMuteRoleForServer(server, role);
verify(existingRole, times(1)).setRole(role);
}
private void verifyRoleSaved(ARole role, MuteRole muteRoleForServer, Integer saveCount) {
Assert.assertEquals(role, muteRoleForServer.getRole());
verify(muteRoleRepository, times(saveCount)).save(muteRoleForServer);
}
}

View File

@@ -9,6 +9,7 @@ import dev.sheldan.abstracto.moderation.repository.UserNoteRepository;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
@@ -46,10 +47,14 @@ public class UserNoteManagementServiceBeanTest {
AUser user = Mockito.mock(AUser.class);
when(userInAServer.getUserReference()).thenReturn(user);
when(userInAServer.getServerReference()).thenReturn(server);
UserNote savedNote = Mockito.mock(UserNote.class);
ArgumentCaptor<UserNote> noteCaptor = ArgumentCaptor.forClass(UserNote.class);
when(userNoteRepository.save(noteCaptor.capture())).thenReturn(savedNote);
UserNote userNote = testUnit.createUserNote(userInAServer, NOTE_TEXT);
verify(userNoteRepository, times(1)).save(userNote);
Assert.assertEquals(userInAServer, userNote.getUser());
Assert.assertEquals(NOTE_TEXT, userNote.getNote());
Assert.assertEquals(savedNote, userNote);
UserNote capturedNote = noteCaptor.getValue();
Assert.assertEquals(userInAServer, capturedNote.getUser());
Assert.assertEquals(NOTE_TEXT, capturedNote.getNote());
}
@Test

View File

@@ -9,6 +9,7 @@ import dev.sheldan.abstracto.moderation.repository.WarnRepository;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
@@ -47,12 +48,16 @@ public class WarnManagementServiceBeanTest {
when(warningUser.getUserReference()).thenReturn(user);
when(warnedUser.getUserReference()).thenReturn(user);
String reason = "REASON";
ArgumentCaptor<Warning> warningArgumentCaptor = ArgumentCaptor.forClass(Warning.class);
Warning savedWarning = Mockito.mock(Warning.class);
when(warnRepository.save(warningArgumentCaptor.capture())).thenReturn(savedWarning);
Warning warning = testUnit.createWarning(warnedUser, warningUser, reason, 8L);
Assert.assertEquals(warningUser, warning.getWarningUser());
Assert.assertEquals(warnedUser, warning.getWarnedUser());
Assert.assertEquals(reason, warning.getReason());
Assert.assertFalse(warning.getDecayed());
verify(warnRepository, times(1)).save(warning);
Assert.assertEquals(savedWarning, warning);
Warning capturedWarning = warningArgumentCaptor.getValue();
Assert.assertEquals(warningUser, capturedWarning.getWarningUser());
Assert.assertEquals(warnedUser, capturedWarning.getWarnedUser());
Assert.assertEquals(reason, capturedWarning.getReason());
Assert.assertFalse(capturedWarning.getDecayed());
}
@Test

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>moderation</artifactId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>abstracto-modules</artifactId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>modmail</artifactId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -83,7 +83,6 @@ public class ModMailMessageDeletedListenerTest {
@Test
public void testDeleteNonDuplicatedMessage() {
when(deletedMessage.getMessageId()).thenReturn(DELETED_MESSAGE_ID);
when(deletedMessage.getServerId()).thenReturn(SERVER_ID);
when(modMailMessageManagementService.getByMessageIdOptional(DELETED_MESSAGE_ID)).thenReturn(Optional.of(modMailMessage));
ModMailThread thread = Mockito.mock(ModMailThread.class);
AUserInAServer targetUsInAServer = Mockito.mock(AUserInAServer.class);
@@ -100,6 +99,7 @@ public class ModMailMessageDeletedListenerTest {
when(memberService.getMemberInServerAsync(SERVER_ID, USER_ID)).thenReturn(CompletableFuture.completedFuture(targetMember));
when(messageService.deleteMessageInChannelWithUser(targetUser, CREATED_MESSAGE_ID_2)).thenReturn(CompletableFuture.completedFuture(null));
when(model.getCachedMessage()).thenReturn(deletedMessage);
when(model.getServerId()).thenReturn(SERVER_ID);
testUnit.execute(model);
verify(messageService, times(0)).deleteMessageInChannelInServer(eq(SERVER_ID), anyLong(), any());
verify(self, times(1)).removeMessageFromThread(DELETED_MESSAGE_ID);
@@ -108,7 +108,6 @@ public class ModMailMessageDeletedListenerTest {
@Test
public void testDeleteDuplicatedMessage() {
when(deletedMessage.getMessageId()).thenReturn(DELETED_MESSAGE_ID);
when(deletedMessage.getServerId()).thenReturn(SERVER_ID);
when(modMailMessageManagementService.getByMessageIdOptional(DELETED_MESSAGE_ID)).thenReturn(Optional.of(modMailMessage));
ModMailThread thread = Mockito.mock(ModMailThread.class);
AUserInAServer targetUsInAServer = Mockito.mock(AUserInAServer.class);
@@ -127,6 +126,7 @@ public class ModMailMessageDeletedListenerTest {
when(memberService.getMemberInServerAsync(SERVER_ID, USER_ID)).thenReturn(CompletableFuture.completedFuture(targetMember));
when(messageService.deleteMessageInChannelWithUser(targetUser, CREATED_MESSAGE_ID_2)).thenReturn(CompletableFuture.completedFuture(null));
when(messageService.deleteMessageInChannelInServer(SERVER_ID, CHANNEL_ID, CREATED_MESSAGE_ID_1)).thenReturn(CompletableFuture.completedFuture(null));
when(model.getServerId()).thenReturn(SERVER_ID);
when(model.getCachedMessage()).thenReturn(deletedMessage);
testUnit.execute(model);
verify(self, times(1)).removeMessageFromThread(DELETED_MESSAGE_ID);

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>modmail</artifactId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>abstracto-modules</artifactId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>dev.sheldan.abstracto</groupId>
<artifactId>abstracto-application</artifactId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -23,6 +23,7 @@
<module>remind</module>
<module>suggestion</module>
<module>repost-detection</module>
<module>webservices</module>
</modules>

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>abstracto-modules</artifactId>
<groupId>dev.sheldan.abstracto.modules</groupId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>remind</artifactId>
<groupId>dev.sheldan.abstracto.modules</groupId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -10,6 +10,7 @@ import dev.sheldan.abstracto.remind.repository.ReminderRepository;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
@@ -56,15 +57,19 @@ public class ReminderManagementServiceBeanTest {
String reminderText = "text";
Instant reminderTargetDate = Instant.ofEpochSecond(1590615937);
Long messageId = 5L;
ArgumentCaptor<Reminder> reminderArgumentCaptor = ArgumentCaptor.forClass(Reminder.class);
Reminder savedReminder = Mockito.mock(Reminder.class);
when(reminderRepository.save(reminderArgumentCaptor.capture())).thenReturn(savedReminder);
Reminder createdReminder = testUnit.createReminder(serverAChannelAUser, reminderText, reminderTargetDate, messageId);
Assert.assertEquals(messageId, createdReminder.getMessageId());
Assert.assertEquals(aUserInAServer, createdReminder.getRemindedUser());
Assert.assertEquals(server, createdReminder.getServer());
Assert.assertEquals(reminderText, createdReminder.getText());
Assert.assertEquals(reminderTargetDate, createdReminder.getTargetDate());
Assert.assertEquals(channel, createdReminder.getChannel());
Assert.assertFalse(createdReminder.isReminded());
verify(reminderRepository, times(1)).save(createdReminder);
Assert.assertEquals(savedReminder, createdReminder);
Reminder capturedReminder = reminderArgumentCaptor.getValue();
Assert.assertEquals(messageId, capturedReminder.getMessageId());
Assert.assertEquals(aUserInAServer, capturedReminder.getRemindedUser());
Assert.assertEquals(server, capturedReminder.getServer());
Assert.assertEquals(reminderText, capturedReminder.getText());
Assert.assertEquals(reminderTargetDate, capturedReminder.getTargetDate());
Assert.assertEquals(channel, capturedReminder.getChannel());
Assert.assertFalse(capturedReminder.isReminded());
}
@Test

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>remind</artifactId>
<groupId>dev.sheldan.abstracto.modules</groupId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>abstracto-modules</artifactId>
<groupId>dev.sheldan.abstracto.modules</groupId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>repost-detection</artifactId>
<groupId>dev.sheldan.abstracto.modules</groupId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -12,6 +12,7 @@ import dev.sheldan.abstracto.repostdetection.service.RepostServiceBean;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
@@ -55,11 +56,15 @@ public class PostedImageManagementBeanTest {
when(serverAChannelAUser.getGuild()).thenReturn(server);
when(serverAChannelAUser.getChannel()).thenReturn(channel);
when(serverAChannelAUser.getAUserInAServer()).thenReturn(aUserInAServer);
ArgumentCaptor<PostedImage> postedImageArgumentCaptor = ArgumentCaptor.forClass(PostedImage.class);
PostedImage savedPost = Mockito.mock(PostedImage.class);
when(postedImageRepository.save(postedImageArgumentCaptor.capture())).thenReturn(savedPost);
PostedImage createdPost = testUnit.createPost(serverAChannelAUser, MESSAGE_ID, HASH, INDEX);
Assert.assertEquals(HASH, createdPost.getImageHash());
Assert.assertEquals(INDEX, createdPost.getPostId().getPosition());
Assert.assertEquals(MESSAGE_ID, createdPost.getPostId().getMessageId());
verify(postedImageRepository, times(1)).save(createdPost);
Assert.assertEquals(savedPost, createdPost);
PostedImage capturedPost = postedImageArgumentCaptor.getValue();
Assert.assertEquals(HASH, capturedPost.getImageHash());
Assert.assertEquals(INDEX, capturedPost.getPostId().getPosition());
Assert.assertEquals(MESSAGE_ID, capturedPost.getPostId().getMessageId());
}
@Test

View File

@@ -7,10 +7,7 @@ import dev.sheldan.abstracto.repostdetection.repository.RepostCheckChannelReposi
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.*;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.Optional;
@@ -105,12 +102,14 @@ public class RepostCheckChannelGroupManagementBeanTest {
@Test
public void testCreateRepostCheckChannelGroup() {
when(aChannelGroup.getId()).thenReturn(CHANNEL_GROUP_ID);
RepostCheckChannelGroup savedGroup = Mockito.mock(RepostCheckChannelGroup.class);
when(repository.save(checkChannelGroupArgumentCaptor.capture())).thenReturn(savedGroup);
RepostCheckChannelGroup createdCheckChannelGroup = testUnit.createRepostCheckChannelGroup(aChannelGroup);
verify(repository, times(1)).save(checkChannelGroupArgumentCaptor.capture());
Assert.assertEquals(checkChannelGroupArgumentCaptor.getValue(), createdCheckChannelGroup);
Assert.assertTrue(createdCheckChannelGroup.getCheckEnabled());
Assert.assertEquals(CHANNEL_GROUP_ID, createdCheckChannelGroup.getId());
Assert.assertEquals(aChannelGroup, createdCheckChannelGroup.getChannelGroup());
Assert.assertEquals(savedGroup, createdCheckChannelGroup);
RepostCheckChannelGroup capturedGroup = checkChannelGroupArgumentCaptor.getValue();
Assert.assertTrue(capturedGroup.getCheckEnabled());
Assert.assertEquals(CHANNEL_GROUP_ID, capturedGroup.getId());
Assert.assertEquals(aChannelGroup, capturedGroup.getChannelGroup());
}
@Test(expected = RepostCheckChannelGroupNotFoundException.class)

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>repost-detection</artifactId>
<groupId>dev.sheldan.abstracto.modules</groupId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>abstracto-modules</artifactId>
<groupId>dev.sheldan.abstracto.modules</groupId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>starboard</artifactId>
<groupId>dev.sheldan.abstracto.modules</groupId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -25,6 +25,7 @@ import org.mockito.junit.MockitoJUnitRunner;
import java.util.Arrays;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import static org.mockito.Mockito.*;
@@ -149,9 +150,9 @@ public class StarAddedListenerTest {
public void testAddingEmoteReachingThreshold() {
Long requiredStars = 1L;
setupActingAndAuthor();
when(starboardService.createStarboardPost(any(CachedMessage.class), anyList(), eq(userInServerActing), eq(userInAServer))).thenReturn(CompletableFuture.completedFuture(null));
executeAddingTest(requiredStars, null);
verify(metricService, times(2)).incrementCounter(any());
verify(starboardService, times(1)).createStarboardPost(any(CachedMessage.class), anyList(), eq(userInServerActing), eq(userInAServer));
}
@Test

View File

@@ -117,6 +117,9 @@ public class StarboardServiceBeanTest {
@Mock
private AUser aUser;
@Mock
private StarboardPostCreatedListenerManager starboardPostCreatedListenerManager;
private static final Long STARRED_USER_ID = 5L;
private static final Long STARRED_SERVER_USER_ID = 2L;
private static final Long SERVER_ID = 6L;
@@ -194,13 +197,10 @@ public class StarboardServiceBeanTest {
CachedMessage message = Mockito.mock(CachedMessage.class);
List<Long> userExceptAuthorIds = Arrays.asList(FIRST_USER_IN_SERVER_ID, SECOND_USER_IN_SERVER_ID);
List<CompletableFuture<Message>> futures = Arrays.asList(CompletableFuture.completedFuture(sendPost));
when(sendPost.getGuild()).thenReturn(guild);
when(sendPost.getChannel()).thenReturn(mockedTextChannel);
when(sendPost.getIdLong()).thenReturn(MESSAGE_ID);
when(userInServerManagementService.loadUserOptional(STARRED_SERVER_USER_ID)).thenReturn(Optional.of(starredUser));
when(userInServerManagementService.loadUserOptional(FIRST_USER_IN_SERVER_ID)).thenReturn(Optional.of(userReacting));
when(userReacting.getUserInServerId()).thenReturn(FIRST_USER_IN_SERVER_ID);
when(userReacting.getUserReference()).thenReturn(aUser);
AChannel channel = Mockito.mock(AChannel.class);
when(channelManagementService.loadChannel(CHANNEL_ID)).thenReturn(channel);
StarboardPost post = Mockito.mock(StarboardPost.class);
@@ -208,13 +208,13 @@ public class StarboardServiceBeanTest {
AUserInAServer secondStarrerUserObj = Mockito.mock(AUserInAServer.class);
when(userInServerManagementService.loadUserOptional(SECOND_USER_IN_SERVER_ID)).thenReturn(Optional.of(secondStarrerUserObj));
when(secondStarrerUserObj.getUserInServerId()).thenReturn(SECOND_USER_IN_SERVER_ID);
when(secondStarrerUserObj.getUserReference()).thenReturn(aUser);
testUnit.persistPost(message, userExceptAuthorIds, futures, CHANNEL_ID, STARRED_SERVER_USER_ID, STARRING_USER_ID);
verify(starboardPostReactorManagementService, times(2)).addReactor(eq(post), userInAServerArgumentCaptor.capture());
List<AUserInAServer> addedReactors = userInAServerArgumentCaptor.getAllValues();
Assert.assertEquals(FIRST_USER_IN_SERVER_ID, addedReactors.get(0).getUserInServerId());
Assert.assertEquals(SECOND_USER_IN_SERVER_ID, addedReactors.get(1).getUserInServerId());
Assert.assertEquals(2, addedReactors.size());
verify(starboardPostCreatedListenerManager, times(1)).sendStarboardPostCreatedEvent(STARRING_USER_ID, post);
}
@Test
@@ -242,7 +242,7 @@ public class StarboardServiceBeanTest {
when(config.getLongValue()).thenReturn(1L);
when(defaultConfigManagementService.getDefaultConfig(StarboardFeatureConfig.STAR_LEVELS_CONFIG_KEY)).thenReturn(config);
when(defaultConfigManagementService.getDefaultConfig(StarboardFeatureConfig.STAR_LVL_CONFIG_PREFIX + 1)).thenReturn(config);
when(starboardPostManagementService.findByStarboardPostMessageId(starboardPostId)).thenReturn(Optional.of(post));
when(starboardPostManagementService.findByStarboardPostId(starboardPostId)).thenReturn(Optional.of(post));
when(userService.retrieveUserForId(STARRED_USER_ID)).thenReturn(CompletableFuture.completedFuture(starredJdaUser));
List<AUserInAServer > userExceptAuthor = new ArrayList<>();
CompletableFuture<Void> future = testUnit.updateStarboardPost(post, message, userExceptAuthor);
@@ -280,17 +280,16 @@ public class StarboardServiceBeanTest {
Integer limit = 3;
AChannel channel = Mockito.mock(AChannel.class);
when(server.getId()).thenReturn(SERVER_ID);
StarboardPostReaction reaction = Mockito.mock(StarboardPostReaction.class);
StarboardPost post1 = Mockito.mock(StarboardPost.class);
when(post1.getReactions()).thenReturn(Arrays.asList(reaction));
when(post1.getPostMessageId()).thenReturn(MESSAGE_ID);
when(post1.getServer()).thenReturn(server);
when(post1.getStarboardChannel()).thenReturn(channel);
StarboardPost post2 = Mockito.mock(StarboardPost.class);
when(post2.getPostMessageId()).thenReturn(SECOND_MESSAGE_ID);
when(post2.getReactions()).thenReturn(new ArrayList<>());
when(post2.getServer()).thenReturn(server);
when(post2.getStarboardChannel()).thenReturn(channel);
when(starboardPostReactorManagementService.getReactorCountOfPost(post1)).thenReturn(1L);
when(starboardPostReactorManagementService.getReactorCountOfPost(post2)).thenReturn(0L);
List<StarboardPost> topPosts = Arrays.asList(post1, post2);
when(starboardPostManagementService.retrieveTopPosts(SERVER_ID, limit)).thenReturn(topPosts);
CompletableFuture<StarStatsUser> statsUser = CompletableFuture.completedFuture(Mockito.mock(StarStatsUser.class));
@@ -339,10 +338,9 @@ public class StarboardServiceBeanTest {
AServer server = Mockito.mock(AServer.class);
when(server.getId()).thenReturn(SERVER_ID);
when(post.getServer()).thenReturn(server);
StarboardPostReaction reaction = Mockito.mock(StarboardPostReaction.class);
when(post.getReactions()).thenReturn(Collections.singletonList(reaction));
when(starboardChannel.getId()).thenReturn(STARBOARD_CHANNEL_ID);
when(post.getPostMessageId()).thenReturn(MESSAGE_ID);
when(starboardPostReactorManagementService.getReactorCountOfPost(post)).thenReturn(1L);
when(starboardPostManagementService.retrieveTopPostsForUserInServer(SERVER_ID, STARRED_USER_ID, 3)).thenReturn(Collections.singletonList(post));
MemberStarStatsModel returnedModel = testUnit.retrieveStarStatsForMember(starredMember);
Assert.assertEquals(receivedStars, returnedModel.getReceivedStars());

View File

@@ -13,6 +13,7 @@ import dev.sheldan.abstracto.starboard.repository.StarboardPostRepository;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
@@ -67,14 +68,18 @@ public class StarboardPostManagementServiceBeanTest {
when(channelManagementService.loadChannel(SOURCE_CHANNEL_ID)).thenReturn(sourceChannel);
AUser aUser = Mockito.mock(AUser.class);
when(aUserInAServer.getUserReference()).thenReturn(aUser);
ArgumentCaptor<StarboardPost> argumentCaptor = ArgumentCaptor.forClass(StarboardPost.class);
StarboardPost savedPost = Mockito.mock(StarboardPost.class);
when(repository.save(argumentCaptor.capture())).thenReturn(savedPost);
StarboardPost createdStarboardPost = testUnit.createStarboardPost(starredMessage, aUserInAServer, postInStarboard);
verify(repository, times(1)).save(createdStarboardPost);
Assert.assertEquals(starboardChannel, createdStarboardPost.getStarboardChannel());
Assert.assertEquals(starboardPostId, createdStarboardPost.getStarboardMessageId());
Assert.assertEquals(starredMessageId, createdStarboardPost.getPostMessageId());
Assert.assertEquals(aUserInAServer, createdStarboardPost.getAuthor());
Assert.assertEquals(sourceChannel, createdStarboardPost.getSourceChannel());
Assert.assertFalse(createdStarboardPost.isIgnored());
Assert.assertEquals(savedPost, createdStarboardPost);
StarboardPost capturedPost = argumentCaptor.getValue();
Assert.assertEquals(starboardChannel, capturedPost.getStarboardChannel());
Assert.assertEquals(starboardPostId, capturedPost.getStarboardMessageId());
Assert.assertEquals(starredMessageId, capturedPost.getPostMessageId());
Assert.assertEquals(aUserInAServer, capturedPost.getAuthor());
Assert.assertEquals(sourceChannel, capturedPost.getSourceChannel());
Assert.assertFalse(capturedPost.isIgnored());
}
@Test
@@ -83,20 +88,21 @@ public class StarboardPostManagementServiceBeanTest {
Long messageId = 6L;
testUnit.setStarboardPostMessageId(post, messageId);
verify(post, times(1)).setStarboardMessageId(messageId);
verify(repository, times(1)).save(post);
}
@Test
public void testRetrieveTopPosts() {
Integer count = 2;
Long postId = 1L;
Long postId2 = 3L;
StarboardPost starboardPost1 = Mockito.mock(StarboardPost.class);
when(starboardPost1.getReactions()).thenReturn(Arrays.asList(Mockito.mock(StarboardPostReaction.class), Mockito.mock(StarboardPostReaction.class)));
StarboardPost starboardPost2 = Mockito.mock(StarboardPost.class);
when(starboardPost2.getReactions()).thenReturn(Arrays.asList(Mockito.mock(StarboardPostReaction.class)));
StarboardPost starboardPost3 = Mockito.mock(StarboardPost.class);
when(starboardPost3.getReactions()).thenReturn(new ArrayList<>());
List<StarboardPost> posts = Arrays.asList(starboardPost1, starboardPost2, starboardPost3);
when(repository.findByServer_Id(SERVER_ID)).thenReturn(posts);
List<StarboardPost> posts = Arrays.asList(starboardPost1, starboardPost2);
List<Long> postIds = Arrays.asList(postId, postId2);
when(repository.getTopStarboardPostsForServer(SERVER_ID, count)).thenReturn(postIds);
when(repository.findAllById(postIds)).thenReturn(posts);
List<StarboardPost> topPosts = testUnit.retrieveTopPosts(SERVER_ID, count);
Assert.assertEquals(count.intValue(), topPosts.size());
StarboardPost topMostPost = topPosts.get(0);
@@ -109,6 +115,9 @@ public class StarboardPostManagementServiceBeanTest {
@Test
public void testRetrieveMoreThanAvailable() {
Integer count = 5;
Long postId = 1L;
Long postId2 = 2L;
Long postId3 = 3L;
StarboardPost starboardPost1 = Mockito.mock(StarboardPost.class);
when(starboardPost1.getReactions()).thenReturn(Arrays.asList(Mockito.mock(StarboardPostReaction.class), Mockito.mock(StarboardPostReaction.class)));
StarboardPost starboardPost2 = Mockito.mock(StarboardPost.class);
@@ -116,7 +125,9 @@ public class StarboardPostManagementServiceBeanTest {
StarboardPost starboardPost3 = Mockito.mock(StarboardPost.class);
when(starboardPost3.getReactions()).thenReturn(new ArrayList<>());
List<StarboardPost> posts = Arrays.asList(starboardPost1, starboardPost2, starboardPost3);
when(repository.findByServer_Id(SERVER_ID)).thenReturn(posts);
List<Long> postIds = Arrays.asList(postId, postId2, postId3);
when(repository.getTopStarboardPostsForServer(SERVER_ID, 5)).thenReturn(postIds);
when(repository.findAllById(postIds)).thenReturn(posts);
List<StarboardPost> topPosts = testUnit.retrieveTopPosts(SERVER_ID, count);
StarboardPost topMostPost = topPosts.get(0);
StarboardPost secondTop = topPosts.get(1);
@@ -194,11 +205,9 @@ public class StarboardPostManagementServiceBeanTest {
@Test
public void testRetrievePostCount() {
StarboardPost starboardPost1 = Mockito.mock(StarboardPost.class);
StarboardPost starboardPost2 = Mockito.mock(StarboardPost.class);
List<StarboardPost> posts = Arrays.asList(starboardPost1, starboardPost2);
when(repository.findByServer_Id(SERVER_ID)).thenReturn(posts);
Long expectedCount = 2L;
when(repository.countByServer_Id(SERVER_ID)).thenReturn(expectedCount);
Long retrievedPostCount = testUnit.getPostCount(SERVER_ID);
Assert.assertEquals(posts.size(), retrievedPostCount.intValue());
Assert.assertEquals(expectedCount, retrievedPostCount);
}
}

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>starboard</artifactId>
<groupId>dev.sheldan.abstracto.modules</groupId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>abstracto-modules</artifactId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>statistic</artifactId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -26,17 +26,12 @@ public class DeleteTrackedEmoteListenerTest {
@Mock
private EmoteDeletedModel model;
private static final Long SERVER_ID = 4L;
private static final Long EMOTE_ID = 4L;
@Test
public void testEmoteDeleted() {
Emote emote = Mockito.mock(Emote.class);
when(emote.getIdLong()).thenReturn(EMOTE_ID);
when(model.getEmote()).thenReturn(emote);
when(model.getServerId()).thenReturn(SERVER_ID);
testUnit.execute(model);
verify(trackedEmoteManagementService, times(1)).markAsDeleted(SERVER_ID, EMOTE_ID);
verify(trackedEmoteManagementService, times(1)).markAsDeleted(emote);
}
@Test

View File

@@ -8,6 +8,8 @@ import dev.sheldan.abstracto.statistic.emote.service.TrackedEmoteService;
import net.dv8tion.jda.api.entities.Emote;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Message;
import org.apache.commons.collections4.Bag;
import org.apache.commons.collections4.bag.HashBag;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -52,19 +54,19 @@ public class EmoteTrackingListenerTest {
@Test
public void testExecuteOneEmote() {
List<Emote> emotesBag = new ArrayList<>();
Bag<Emote> emotesBag = new HashBag<>();
emotesBag.add(emote1);
when(guildService.getGuildById(SERVER_ID)).thenReturn(guild);
when(messageReceivedModel.getMessage()).thenReturn(message);
when(messageReceivedModel.getServerId()).thenReturn(SERVER_ID);
when(message.getEmotes()).thenReturn(emotesBag);
when(message.getEmotesBag()).thenReturn(emotesBag);
testUnit.execute(messageReceivedModel);
verify(trackedEmoteService, times(1)).addEmoteToRuntimeStorage(emote1, guild, 1L);
}
@Test
public void testExecuteOneEmoteMultipleTimes() {
List<Emote> emotesBag = new ArrayList<>();
Bag<Emote> emotesBag = new HashBag<>();
when(emote1.getIdLong()).thenReturn(EMOTE_ID);
when(emote2.getIdLong()).thenReturn(EMOTE_ID);
emotesBag.add(emote1);
@@ -72,14 +74,14 @@ public class EmoteTrackingListenerTest {
when(guildService.getGuildById(SERVER_ID)).thenReturn(guild);
when(messageReceivedModel.getServerId()).thenReturn(SERVER_ID);
when(messageReceivedModel.getMessage()).thenReturn(message);
when(message.getEmotes()).thenReturn(emotesBag);
when(message.getEmotesBag()).thenReturn(emotesBag);
testUnit.execute(messageReceivedModel);
verify(trackedEmoteService, times(1)).addEmoteToRuntimeStorage(any(CachedEmote.class), eq(guild), eq(2L));
verify(trackedEmoteService, times(1)).addEmoteToRuntimeStorage(any(Emote.class), eq(guild), eq(2L));
}
@Test
public void testExecuteMultipleEmotes() {
List<Emote> emotesBag = new ArrayList<>();
Bag<Emote> emotesBag = new HashBag<>();
when(emote1.getIdLong()).thenReturn(EMOTE_ID);
when(emote2.getIdLong()).thenReturn(EMOTE_ID + 1);
emotesBag.add(emote1);
@@ -87,7 +89,7 @@ public class EmoteTrackingListenerTest {
when(guildService.getGuildById(SERVER_ID)).thenReturn(guild);
when(messageReceivedModel.getServerId()).thenReturn(SERVER_ID);
when(messageReceivedModel.getMessage()).thenReturn(message);
when(message.getEmotes()).thenReturn(emotesBag);
when(message.getEmotesBag()).thenReturn(emotesBag);
testUnit.execute(messageReceivedModel);
verify(trackedEmoteService, times(1)).addEmoteToRuntimeStorage(emote1, guild, 1L);
verify(trackedEmoteService, times(1)).addEmoteToRuntimeStorage(emote2, guild, 1L);
@@ -95,7 +97,7 @@ public class EmoteTrackingListenerTest {
@Test
public void testExecuteNoEmote() {
when(message.getEmotes()).thenReturn(new ArrayList<>());
when(message.getEmotesBag()).thenReturn(new HashBag<>());
when(messageReceivedModel.getMessage()).thenReturn(message);
testUnit.execute(messageReceivedModel);
verify(trackedEmoteService, times(0)).addEmoteToRuntimeStorage(any(Emote.class), any(), anyLong());

View File

@@ -29,12 +29,9 @@ public class UpdateTrackedEmoteListenerTest {
@Test
public void testEmoteUpdated() {
Long serverId = 1L;
Long emoteId = 2L;
Emote changedEmote = Mockito.mock(Emote.class);
when(changedEmote.getIdLong()).thenReturn(emoteId);
TrackedEmote trackedEmote = Mockito.mock(TrackedEmote.class);
when(trackedEmoteManagementService.loadByEmoteId(emoteId, serverId)).thenReturn(trackedEmote);
when(trackedEmoteManagementService.loadByEmote(changedEmote)).thenReturn(trackedEmote);
String newValue = "AFTER";
when(model.getEmote()).thenReturn(changedEmote);
when(model.getNewValue()).thenReturn(newValue);

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>statistic</artifactId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>abstracto-modules</artifactId>
<groupId>dev.sheldan.abstracto.modules</groupId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>suggestion</artifactId>
<groupId>dev.sheldan.abstracto.modules</groupId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -17,6 +17,7 @@ import net.dv8tion.jda.api.entities.MessageChannel;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
@@ -70,11 +71,15 @@ public class SuggestionManagementServiceBeanTest {
when(message.getGuild()).thenReturn(guild);
when(guild.getId()).thenReturn("8");
long suggestionId = 1L;
ArgumentCaptor<Suggestion> suggestionArgumentCaptor = ArgumentCaptor.forClass(Suggestion.class);
Suggestion savedSuggestion = Mockito.mock(Suggestion.class);
when(suggestionRepository.save(suggestionArgumentCaptor.capture())).thenReturn(savedSuggestion);
Suggestion createdSuggestion = testUnit.createSuggestion(aUserInAServer, text, message, suggestionId);
verify(suggestionRepository, times(1)).save(createdSuggestion);
Assert.assertEquals(SuggestionState.NEW, createdSuggestion.getState());
Assert.assertEquals(aUserInAServer, createdSuggestion.getSuggester());
Assert.assertEquals(server, createdSuggestion.getServer());
Assert.assertEquals(savedSuggestion, createdSuggestion);
Suggestion capturedSuggestion = suggestionArgumentCaptor.getValue();
Assert.assertEquals(SuggestionState.NEW, capturedSuggestion.getState());
Assert.assertEquals(aUserInAServer, capturedSuggestion.getSuggester());
Assert.assertEquals(server, capturedSuggestion.getServer());
}
@Test
@@ -92,11 +97,15 @@ public class SuggestionManagementServiceBeanTest {
when(guild.getId()).thenReturn("5");
when(userInServerManagementService.loadOrCreateUser(member)).thenReturn(aUserInAServer);
long suggestionId = 1L;
ArgumentCaptor<Suggestion> suggestionArgumentCaptor = ArgumentCaptor.forClass(Suggestion.class);
Suggestion savedSuggestion = Mockito.mock(Suggestion.class);
when(suggestionRepository.save(suggestionArgumentCaptor.capture())).thenReturn(savedSuggestion);
Suggestion createdSuggestion = testUnit.createSuggestion(member, text, message, suggestionId);
verify(suggestionRepository, times(1)).save(createdSuggestion);
Assert.assertEquals(SuggestionState.NEW, createdSuggestion.getState());
Assert.assertEquals(aUserInAServer, createdSuggestion.getSuggester());
Assert.assertEquals(server, createdSuggestion.getServer());
Assert.assertEquals(savedSuggestion, createdSuggestion);
Suggestion capturedSuggestion = suggestionArgumentCaptor.getValue();
Assert.assertEquals(SuggestionState.NEW, capturedSuggestion.getState());
Assert.assertEquals(aUserInAServer, capturedSuggestion.getSuggester());
Assert.assertEquals(server, capturedSuggestion.getServer());
}
@Test

View File

@@ -3,7 +3,7 @@
<parent>
<artifactId>suggestion</artifactId>
<groupId>dev.sheldan.abstracto.modules</groupId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>abstracto-modules</artifactId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>utility</artifactId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>utility</artifactId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>abstracto-modules</artifactId>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>webservices</artifactId>
<packaging>pom</packaging>
<modules>
<module>webservices-int</module>
<module>webservices-impl</module>
</modules>
<dependencies>
<dependency>
<groupId>dev.sheldan.abstracto.core</groupId>
<artifactId>core-int</artifactId>
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>webservices</artifactId>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>webservices-impl</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptors>
<descriptor>src/main/assembly/liquibase.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>webservices-int</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-youtube</artifactId>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,18 @@
<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.1.0 http://maven.apache.org/xsd/assembly-2.1.0.xsd">
<id>liquibase</id>
<formats>
<format>zip</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<fileSets>
<fileSet>
<outputDirectory>.</outputDirectory>
<directory>${project.basedir}/src/main/resources/migrations</directory>
<includes>
<include>**/*</include>
</includes>
</fileSet>
</fileSets>
</assembly>

View File

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

View File

@@ -0,0 +1,82 @@
package dev.sheldan.abstracto.webservices.urban.command;
import dev.sheldan.abstracto.core.command.UtilityModuleDefinition;
import dev.sheldan.abstracto.core.command.condition.AbstractConditionableCommand;
import dev.sheldan.abstracto.core.command.config.CommandConfiguration;
import dev.sheldan.abstracto.core.command.config.HelpInfo;
import dev.sheldan.abstracto.core.command.config.Parameter;
import dev.sheldan.abstracto.core.command.execution.CommandContext;
import dev.sheldan.abstracto.core.command.execution.CommandResult;
import dev.sheldan.abstracto.core.command.execution.ContextConverter;
import dev.sheldan.abstracto.core.config.FeatureDefinition;
import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException;
import dev.sheldan.abstracto.core.service.ChannelService;
import dev.sheldan.abstracto.core.templating.model.MessageToSend;
import dev.sheldan.abstracto.core.templating.service.TemplateService;
import dev.sheldan.abstracto.core.utils.FutureUtils;
import dev.sheldan.abstracto.webservices.config.WebserviceFeatureDefinition;
import dev.sheldan.abstracto.webservices.urban.model.UrbanDefinition;
import dev.sheldan.abstracto.webservices.urban.model.UrbanResponseModel;
import dev.sheldan.abstracto.webservices.urban.service.UrbanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@Component
public class UrbanDefine extends AbstractConditionableCommand {
@Autowired
private UrbanService urbanService;
@Autowired
private TemplateService templateService;
@Autowired
private ChannelService channelService;
private static final String URBAN_DEFINE_RESPONSE_MODEL_TEMPLATE_KEY = "urban_define_response_model";
@Override
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
String parameter = (String) commandContext.getParameters().getParameters().get(0);
try {
UrbanDefinition definition = urbanService.getUrbanDefinition(parameter);
UrbanResponseModel model = (UrbanResponseModel) ContextConverter.slimFromCommandContext(commandContext, UrbanResponseModel.class);
model.setDefinition(definition);
MessageToSend message = templateService.renderEmbedTemplate(URBAN_DEFINE_RESPONSE_MODEL_TEMPLATE_KEY, model);
return FutureUtils.toSingleFutureGeneric(channelService.sendMessageToSendToChannel(message, commandContext.getChannel()))
.thenApply(unused -> CommandResult.fromSuccess());
} catch (IOException e) {
throw new AbstractoRunTimeException(e);
}
}
@Override
public CommandConfiguration getConfiguration() {
List<Parameter> parameters = new ArrayList<>();
parameters.add(Parameter.builder().name("searchQuery").type(String.class).remainder(true).templated(true).build());
HelpInfo helpInfo = HelpInfo.builder().templated(true).build();
List<String> aliases = Arrays.asList("ud");
return CommandConfiguration.builder()
.name("urbanDefine")
.module(UtilityModuleDefinition.UTILITY)
.templated(true)
.async(true)
.aliases(aliases)
.supportsEmbedException(true)
.causesReaction(false)
.parameters(parameters)
.help(helpInfo)
.build();
}
@Override
public FeatureDefinition getFeature() {
return WebserviceFeatureDefinition.URBAN_DICTIONARY;
}
}

View File

@@ -0,0 +1,14 @@
package dev.sheldan.abstracto.webservices.urban.model;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
@Builder
public class UrbanResponse {
private List<UrbanResponseDefinition> list;
}

View File

@@ -0,0 +1,22 @@
package dev.sheldan.abstracto.webservices.urban.model;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import java.time.Instant;
@Getter
@Setter
@Builder
public class UrbanResponseDefinition {
private String definition;
private String permalink;
private Long thumbs_up;
private Long thumbs_down;
private String author;
private String word;
private Long defid;
private Instant written_on;
private String example;
}

View File

@@ -0,0 +1,50 @@
package dev.sheldan.abstracto.webservices.urban.service;
import com.google.gson.Gson;
import dev.sheldan.abstracto.webservices.urban.exception.NoUrbanDefinitionFoundException;
import dev.sheldan.abstracto.webservices.urban.model.UrbanDefinition;
import dev.sheldan.abstracto.webservices.urban.model.UrbanResponse;
import dev.sheldan.abstracto.webservices.urban.model.UrbanResponseDefinition;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;
@Component
public class UrbanServiceBean implements UrbanService {
@Autowired
private OkHttpClient okHttpClient;
@Value("${abstracto.feature.webservices.urban.requestURL}")
private String requestUrl;
@Autowired
private Gson gson;
@Override
public UrbanDefinition getUrbanDefinition(String query) throws IOException {
Request request = new Request.Builder().url(String.format(requestUrl, query)).get().build();
Response response = okHttpClient.newCall(request).execute();
UrbanResponse urbanResponse = gson.fromJson(response.body().string(), UrbanResponse.class);
if(urbanResponse.getList().isEmpty()) {
throw new NoUrbanDefinitionFoundException();
} else {
UrbanResponseDefinition definition = urbanResponse.getList().get(0);
return UrbanDefinition
.builder()
.definition(definition.getDefinition())
.author(definition.getAuthor())
.url(definition.getPermalink())
.creationDate(definition.getWritten_on())
.downVoteCount(definition.getThumbs_down())
.upvoteCount(definition.getThumbs_up())
.example(definition.getExample())
.build();
}
}
}

View File

@@ -0,0 +1,87 @@
package dev.sheldan.abstracto.webservices.youtube.command;
import dev.sheldan.abstracto.core.command.UtilityModuleDefinition;
import dev.sheldan.abstracto.core.command.condition.AbstractConditionableCommand;
import dev.sheldan.abstracto.core.command.config.CommandConfiguration;
import dev.sheldan.abstracto.core.command.config.HelpInfo;
import dev.sheldan.abstracto.core.command.config.Parameter;
import dev.sheldan.abstracto.core.command.execution.CommandContext;
import dev.sheldan.abstracto.core.command.execution.CommandResult;
import dev.sheldan.abstracto.core.command.execution.ContextConverter;
import dev.sheldan.abstracto.core.config.FeatureDefinition;
import dev.sheldan.abstracto.core.service.ChannelService;
import dev.sheldan.abstracto.core.service.FeatureModeService;
import dev.sheldan.abstracto.core.templating.model.MessageToSend;
import dev.sheldan.abstracto.core.templating.service.TemplateService;
import dev.sheldan.abstracto.core.utils.FutureUtils;
import dev.sheldan.abstracto.webservices.config.WebserviceFeatureDefinition;
import dev.sheldan.abstracto.webservices.youtube.config.YoutubeWebServiceFeatureMode;
import dev.sheldan.abstracto.webservices.youtube.model.YoutubeVideo;
import dev.sheldan.abstracto.webservices.youtube.model.command.YoutubeVideoSearchCommandModel;
import dev.sheldan.abstracto.webservices.youtube.service.YoutubeSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@Component
public class YoutubeVideoSearch extends AbstractConditionableCommand {
@Autowired
private YoutubeSearchService youtubeSearchService;
@Autowired
private TemplateService templateService;
@Autowired
private ChannelService channelService;
@Autowired
private FeatureModeService featureModeService;
@Override
public CompletableFuture<CommandResult> executeAsync(CommandContext commandContext) {
String query = (String) commandContext.getParameters().getParameters().get(0);
YoutubeVideo foundVideo = youtubeSearchService.searchOneVideoForQuery(query);
YoutubeVideoSearchCommandModel model = (YoutubeVideoSearchCommandModel) ContextConverter.slimFromCommandContext(commandContext, YoutubeVideoSearchCommandModel.class);
model.setVideo(foundVideo);
CompletableFuture<Void> infoEmbedFuture;
if(featureModeService.featureModeActive(WebserviceFeatureDefinition.YOUTUBE, commandContext.getGuild().getIdLong(), YoutubeWebServiceFeatureMode.VIDEO_DETAILS)) {
MessageToSend message = templateService.renderEmbedTemplate("youtube_search_command_response", model);
infoEmbedFuture = FutureUtils.toSingleFutureGeneric(channelService.sendMessageToSendToChannel(message, commandContext.getChannel()));
} else {
infoEmbedFuture = CompletableFuture.completedFuture(null);
}
MessageToSend linkEmbed = templateService.renderEmbedTemplate("youtube_search_command_response_link", model);
CompletableFuture<Void> linkEmbedFuture = FutureUtils.toSingleFutureGeneric(channelService.sendMessageToSendToChannel(linkEmbed, commandContext.getChannel()));
return CompletableFuture.allOf(infoEmbedFuture, linkEmbedFuture)
.thenApply(unused -> CommandResult.fromSuccess());
}
@Override
public CommandConfiguration getConfiguration() {
List<Parameter> parameters = new ArrayList<>();
parameters.add(Parameter.builder().name("searchQuery").type(String.class).remainder(true).templated(true).build());
HelpInfo helpInfo = HelpInfo.builder().templated(true).build();
List<String> aliases = Arrays.asList("yt");
return CommandConfiguration.builder()
.name("youtubeSearch")
.module(UtilityModuleDefinition.UTILITY)
.templated(true)
.async(true)
.aliases(aliases)
.supportsEmbedException(true)
.causesReaction(false)
.parameters(parameters)
.help(helpInfo)
.build();
}
@Override
public FeatureDefinition getFeature() {
return WebserviceFeatureDefinition.YOUTUBE;
}
}

View File

@@ -0,0 +1,39 @@
package dev.sheldan.abstracto.webservices.youtube.config;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.YouTubeRequestInitializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class YoutubeServiceBeans {
@Value("${abstracto.feature.youtube.apiKey}")
private String youtubeApiKey;
@Value("${spring.application.name}")
private String applicationName;
@Bean
public YouTube getYouTubeBean() {
return new YouTube.Builder(getHttpTransport(), getJsonFactory(), request -> {}).setApplicationName(applicationName)
.setYouTubeRequestInitializer(new YouTubeRequestInitializer(youtubeApiKey)).build();
}
@Bean
public HttpTransport getHttpTransport() {
return new NetHttpTransport();
}
@Bean
public JsonFactory getJsonFactory() {
return new GsonFactory();
}
}

View File

@@ -0,0 +1,41 @@
package dev.sheldan.abstracto.webservices.youtube.service;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.SearchListResponse;
import com.google.api.services.youtube.model.SearchResult;
import dev.sheldan.abstracto.webservices.youtube.exception.YoutubeAPIException;
import dev.sheldan.abstracto.webservices.youtube.exception.YoutubeVideoNotFoundException;
import dev.sheldan.abstracto.webservices.youtube.model.YoutubeVideo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.List;
@Component
public class YoutubeSearchServiceBean implements YoutubeSearchService {
@Autowired
private YouTube youTube;
@Autowired
private YoutubeVideoService youtubeVideoService;
@Override
public YoutubeVideo searchOneVideoForQuery(String query) {
try {
YouTube.Search.List search = youTube.search().list("id,snippet");
search.setQ(query);
search.setType("video");
search.setMaxResults(1L);
SearchListResponse execute = search.execute();
List<SearchResult> items = execute.getItems();
if(items.isEmpty()) {
throw new YoutubeVideoNotFoundException();
}
return youtubeVideoService.getVideoInfo(items.get(0).getId().getVideoId());
} catch (IOException e) {
throw new YoutubeAPIException(e);
}
}
}

View File

@@ -0,0 +1,53 @@
package dev.sheldan.abstracto.webservices.youtube.service;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.*;
import dev.sheldan.abstracto.webservices.youtube.exception.YoutubeAPIException;
import dev.sheldan.abstracto.webservices.youtube.exception.YoutubeVideoNotFoundException;
import dev.sheldan.abstracto.webservices.youtube.model.YoutubeVideo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
@Component
public class YoutubeVideoServiceBean implements YoutubeVideoService {
@Autowired
private YouTube youTube;
@Override
public YoutubeVideo getVideoInfo(String id) {
try {
VideoListResponse videoListResponse = youTube
.videos()
.list("statistics,contentDetails,snippet")
.setId(id)
.execute();
List<Video> items = videoListResponse.getItems();
if(items.isEmpty()) {
throw new YoutubeVideoNotFoundException();
}
Video videoInfo = items.get(0);
VideoStatistics statistics = videoInfo.getStatistics();
VideoSnippet snipped = videoInfo.getSnippet();
VideoContentDetails contentDetails = videoInfo.getContentDetails();
return YoutubeVideo
.builder()
.channelTitle(snipped.getChannelTitle())
.commentCount(statistics.getCommentCount())
.dislikes(statistics.getDislikeCount())
.likes(statistics.getLikeCount())
.views(statistics.getViewCount())
.duration(Duration.parse(contentDetails.getDuration()))
.publishedAt(Instant.ofEpochMilli(snipped.getPublishedAt().getValue()))
.url(String.format("https://youtu.be/%s", videoInfo.getId()))
.build();
} catch (IOException e) {
throw new YoutubeAPIException(e);
}
}
}

View File

@@ -0,0 +1,10 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
xmlns:pro="http://www.liquibase.org/xml/ns/pro"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog ../dbchangelog-3.8.xsd
http://www.liquibase.org/xml/ns/dbchangelog-ext ../dbchangelog-3.8.xsd
http://www.liquibase.org/xml/ns/pro ../dbchangelog-3.8.xsd" >
<include file="webservices-seedData/data.xml" relativeToChangelogFile="true"/>
</databaseChangeLog>

View File

@@ -0,0 +1,29 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
xmlns:pro="http://www.liquibase.org/xml/ns/pro"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog ../../dbchangelog-3.8.xsd
http://www.liquibase.org/xml/ns/dbchangelog-ext ../../dbchangelog-3.8.xsd
http://www.liquibase.org/xml/ns/pro ../../dbchangelog-3.8.xsd" >
<property name="utilityModule" value="(SELECT id FROM module WHERE name = 'utility')"/>
<property name="youtubeFeature" value="(SELECT id FROM feature WHERE key = 'youtube')"/>
<property name="urbanFeature" value="(SELECT id FROM feature WHERE key = 'urban')"/>
<changeSet author="Sheldan" id="webservices_youtube-commands">
<insert tableName="command">
<column name="name" value="youtubeSearch"/>
<column name="module_id" valueComputed="${utilityModule}"/>
<column name="feature_id" valueComputed="${youtubeFeature}"/>
</insert>
</changeSet>
<changeSet author="Sheldan" id="webservices_urban-commands">
<insert tableName="command">
<column name="name" value="urbanDefine"/>
<column name="module_id" valueComputed="${utilityModule}"/>
<column name="feature_id" valueComputed="${urbanFeature}"/>
</insert>
</changeSet>
</databaseChangeLog>

View File

@@ -0,0 +1,11 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
xmlns:pro="http://www.liquibase.org/xml/ns/pro"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog ../../dbchangelog-3.8.xsd
http://www.liquibase.org/xml/ns/dbchangelog-ext ../../dbchangelog-3.8.xsd
http://www.liquibase.org/xml/ns/pro ../../dbchangelog-3.8.xsd" >
<include file="feature.xml" relativeToChangelogFile="true"/>
<include file="command.xml" relativeToChangelogFile="true"/>
</databaseChangeLog>

View File

@@ -0,0 +1,17 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
xmlns:pro="http://www.liquibase.org/xml/ns/pro"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog ../../dbchangelog-3.8.xsd
http://www.liquibase.org/xml/ns/dbchangelog-ext ../../dbchangelog-3.8.xsd
http://www.liquibase.org/xml/ns/pro ../../dbchangelog-3.8.xsd" >
<changeSet author="Sheldan" id="webservices_feature-insertion">
<insert tableName="feature">
<column name="key" value="youtube"/>
</insert>
<insert tableName="feature">
<column name="key" value="urban"/>
</insert>
</changeSet>
</databaseChangeLog>

View File

@@ -0,0 +1,10 @@
<?xml version="1.1" encoding="UTF-8" standalone="no"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
xmlns:ext="http://www.liquibase.org/xml/ns/dbchangelog-ext"
xmlns:pro="http://www.liquibase.org/xml/ns/pro"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog dbchangelog-3.8.xsd
http://www.liquibase.org/xml/ns/dbchangelog-ext dbchangelog-3.8.xsd
http://www.liquibase.org/xml/ns/pro dbchangelog-3.8.xsd" >
<include file="1.2.5-webservices/collection.xml" relativeToChangelogFile="true"/>
</databaseChangeLog>

View File

@@ -0,0 +1,13 @@
abstracto.featureFlags.youtube.featureName=youtube
abstracto.featureFlags.youtube.enabled=false
abstracto.featureFlags.urban.featureName=urban
abstracto.featureFlags.urban.enabled=false
abstracto.feature.youtube.apiKey=${YOUTUBE_API_KEY}
abstracto.feature.webservices.urban.requestURL=https://api.urbandictionary.com/v0/define?term=%s
abstracto.featureModes.videoDetails.featureName=youtube
abstracto.featureModes.videoDetails.mode=videoDetails
abstracto.featureModes.videoDetails.enabled=false

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>webservices</artifactId>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>webservices-int</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>

View File

@@ -0,0 +1,15 @@
package dev.sheldan.abstracto.webservices.config;
import dev.sheldan.abstracto.core.config.FeatureDefinition;
import lombok.Getter;
@Getter
public enum WebserviceFeatureDefinition implements FeatureDefinition {
YOUTUBE("youtube"), URBAN_DICTIONARY("urban");
private String key;
WebserviceFeatureDefinition(String key) {
this.key = key;
}
}

View File

@@ -0,0 +1,14 @@
package dev.sheldan.abstracto.webservices.urban.config;
import dev.sheldan.abstracto.core.config.FeatureConfig;
import dev.sheldan.abstracto.core.config.FeatureDefinition;
import dev.sheldan.abstracto.webservices.config.WebserviceFeatureDefinition;
import org.springframework.stereotype.Component;
@Component
public class UrbanFeatureConfig implements FeatureConfig {
@Override
public FeatureDefinition getFeature() {
return WebserviceFeatureDefinition.URBAN_DICTIONARY;
}
}

View File

@@ -0,0 +1,16 @@
package dev.sheldan.abstracto.webservices.urban.exception;
import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException;
import dev.sheldan.abstracto.core.templating.Templatable;
public class NoUrbanDefinitionFoundException extends AbstractoRunTimeException implements Templatable {
@Override
public String getTemplateName() {
return "no_urban_definition_found_exception";
}
@Override
public Object getTemplateModel() {
return new Object();
}
}

View File

@@ -0,0 +1,20 @@
package dev.sheldan.abstracto.webservices.urban.model;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import java.time.Instant;
@Getter
@Setter
@Builder
public class UrbanDefinition {
private String definition;
private String author;
private String example;
private Instant creationDate;
private String url;
private Long upvoteCount;
private Long downVoteCount;
}

View File

@@ -0,0 +1,13 @@
package dev.sheldan.abstracto.webservices.urban.model;
import dev.sheldan.abstracto.core.models.context.SlimUserInitiatedServerContext;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
@Getter
@Setter
@SuperBuilder
public class UrbanResponseModel extends SlimUserInitiatedServerContext {
private UrbanDefinition definition;
}

View File

@@ -0,0 +1,9 @@
package dev.sheldan.abstracto.webservices.urban.service;
import dev.sheldan.abstracto.webservices.urban.model.UrbanDefinition;
import java.io.IOException;
public interface UrbanService {
UrbanDefinition getUrbanDefinition(String query) throws IOException;
}

View File

@@ -0,0 +1,23 @@
package dev.sheldan.abstracto.webservices.youtube.config;
import dev.sheldan.abstracto.core.config.FeatureConfig;
import dev.sheldan.abstracto.core.config.FeatureDefinition;
import dev.sheldan.abstracto.core.config.FeatureMode;
import dev.sheldan.abstracto.webservices.config.WebserviceFeatureDefinition;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.List;
@Component
public class YoutubeFeatureConfig implements FeatureConfig {
@Override
public FeatureDefinition getFeature() {
return WebserviceFeatureDefinition.YOUTUBE;
}
@Override
public List<FeatureMode> getAvailableModes() {
return Arrays.asList(YoutubeWebServiceFeatureMode.VIDEO_DETAILS);
}
}

View File

@@ -0,0 +1,15 @@
package dev.sheldan.abstracto.webservices.youtube.config;
import dev.sheldan.abstracto.core.config.FeatureMode;
import lombok.Getter;
@Getter
public enum YoutubeWebServiceFeatureMode implements FeatureMode {
VIDEO_DETAILS("videoDetails");
private final String key;
YoutubeWebServiceFeatureMode(String key) {
this.key = key;
}
}

View File

@@ -0,0 +1,27 @@
package dev.sheldan.abstracto.webservices.youtube.exception;
import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException;
import dev.sheldan.abstracto.core.templating.Templatable;
import dev.sheldan.abstracto.webservices.youtube.model.exception.YoutubeAPIExceptionModel;
public class YoutubeAPIException extends AbstractoRunTimeException implements Templatable {
private final YoutubeAPIExceptionModel model;
public YoutubeAPIException(Throwable throwable) {
this.model = YoutubeAPIExceptionModel
.builder()
.exception(throwable)
.build();
}
@Override
public String getTemplateName() {
return "webservices_youtube_api_exception";
}
@Override
public Object getTemplateModel() {
return model;
}
}

View File

@@ -0,0 +1,17 @@
package dev.sheldan.abstracto.webservices.youtube.exception;
import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException;
import dev.sheldan.abstracto.core.templating.Templatable;
public class YoutubeVideoNotFoundException extends AbstractoRunTimeException implements Templatable {
@Override
public String getTemplateName() {
return "webservices_youtube_video_not_found_exception";
}
@Override
public Object getTemplateModel() {
return new Object();
}
}

View File

@@ -0,0 +1,23 @@
package dev.sheldan.abstracto.webservices.youtube.model;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import java.math.BigInteger;
import java.time.Duration;
import java.time.Instant;
@Getter
@Setter
@Builder
public class YoutubeVideo {
private String url;
private BigInteger views;
private Instant publishedAt;
private Duration duration;
private String channelTitle;
private BigInteger likes;
private BigInteger dislikes;
private BigInteger commentCount;
}

View File

@@ -0,0 +1,14 @@
package dev.sheldan.abstracto.webservices.youtube.model.command;
import dev.sheldan.abstracto.core.models.context.SlimUserInitiatedServerContext;
import dev.sheldan.abstracto.webservices.youtube.model.YoutubeVideo;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
@Getter
@SuperBuilder
@Setter
public class YoutubeVideoSearchCommandModel extends SlimUserInitiatedServerContext {
private YoutubeVideo video;
}

View File

@@ -0,0 +1,14 @@
package dev.sheldan.abstracto.webservices.youtube.model.exception;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
@Getter
@Setter
@Builder
public class YoutubeAPIExceptionModel implements Serializable {
private Throwable exception;
}

View File

@@ -0,0 +1,7 @@
package dev.sheldan.abstracto.webservices.youtube.service;
import dev.sheldan.abstracto.webservices.youtube.model.YoutubeVideo;
public interface YoutubeSearchService {
YoutubeVideo searchOneVideoForQuery(String query);
}

View File

@@ -0,0 +1,7 @@
package dev.sheldan.abstracto.webservices.youtube.service;
import dev.sheldan.abstracto.webservices.youtube.model.YoutubeVideo;
public interface YoutubeVideoService {
YoutubeVideo getVideoInfo(String id);
}

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>dev.sheldan.abstracto</groupId>
<artifactId>abstracto-application</artifactId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -191,6 +191,18 @@
<artifactId>suggestion-int</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>webservices-int</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>dev.sheldan.abstracto.modules</groupId>
<artifactId>webservices-impl</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</dependencyManagement>

View File

@@ -3,7 +3,7 @@
<parent>
<groupId>dev.sheldan.abstracto.core</groupId>
<artifactId>core</artifactId>
<version>1.2.4</version>
<version>1.2.6</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>

Some files were not shown because too many files have changed in this diff Show More