Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
47a3bd6
Initial Commit (Unit Testing)
Jacrispys Oct 6, 2023
0d36224
Add testing package
Jacrispys Oct 6, 2023
bcfd201
SecretData first test
Jacrispys Oct 6, 2023
771b60a
Spotify Manager Async Impl + Tests
Jacrispys Oct 10, 2023
023857d
Better logging for SpotifyManager
Jacrispys Oct 11, 2023
b11039d
Missing override tag
Jacrispys Oct 13, 2023
6bb5a65
Mockito JDA Framework
Jacrispys Oct 16, 2023
fb9c7d9
Adding ReadyEvent + Command register (Unfinished)
Jacrispys Oct 16, 2023
b3e37c4
New error, will finish later.
Jacrispys Oct 16, 2023
4f435fd
Fix maven test & build workflows
Jacrispys Oct 16, 2023
f43382a
Fix maven test & build workflows
Jacrispys Oct 16, 2023
7a7959a
Fix maven test & build workflows
Jacrispys Oct 16, 2023
7eaff8e
Fix maven test & build workflows
Jacrispys Oct 16, 2023
5ba831c
Fix maven test & build workflows
Jacrispys Oct 16, 2023
cee423d
Fixing github actions
Jacrispys Oct 16, 2023
4de9952
add test plugin
Jacrispys Oct 16, 2023
bca8d53
remove tests with tokens
Jacrispys Oct 16, 2023
d43c35e
remove tests with tokens
Jacrispys Oct 16, 2023
e151e72
Mock database
Jacrispys Oct 16, 2023
f4dd3eb
Mock database
Jacrispys Oct 16, 2023
e585f85
Mock database, change to spy
Jacrispys Oct 16, 2023
9c917f4
Mock database, change to spy
Jacrispys Oct 16, 2023
8e16827
Mock database, change to spy
Jacrispys Oct 16, 2023
a10efd2
Finally block calls to real DB in testing
Jacrispys Oct 16, 2023
da62fbd
Remove Token dependent test & fix StartupTests
Jacrispys Oct 16, 2023
f868cee
Add status test
Jacrispys Oct 16, 2023
ac50ef8
Begin mocking for slash commands, members, and messages.
Jacrispys Oct 17, 2023
f359dc3
Broken Test, will fix later.
Jacrispys Oct 18, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 3 additions & 16 deletions .github/workflows/maven.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ on:
branches: [ master ]

jobs:
build:
build-test:

runs-on: ubuntu-latest

Expand All @@ -22,18 +22,5 @@ jobs:
java-version: '17'
distribution: 'temurin'
cache: maven
- name: Build with Maven
run: mvn package --file pom.xml
test:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v3
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
cache: maven
- name: Build with Maven
run: mvn test --file pom.xml
- name: Build & Test with Maven
run: mvn --batch-mode --update-snapshots verify
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
/target/
/src/main/resources/loginInfo.yml
/.idea/
/src/test/
/src/test/java/api
/out/
26 changes: 23 additions & 3 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,20 @@
<groupId>dev.Jacrispys</groupId>
<artifactId>InsideAgentDev</artifactId>
<version>0.1.9-beta.1</version>

<build>
<testSourceDirectory>${project.basedir}/src/test/java/</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.1.2</version>
<configuration>
<excludes>
<exclude>**/SpManTests.java</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
Expand Down Expand Up @@ -67,6 +79,7 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<author>Jacrispys</author>
<mainClass>dev.jacrispys.JavaBot.JavaBotMain</mainClass>
<testSourceDirectory>${project.basedir}/src/test/java/</testSourceDirectory>
</properties>

<repositories>
Expand Down Expand Up @@ -185,9 +198,16 @@
</dependency>

<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>5.0.1</version>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.10.0</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>5.6.0</version>
</dependency>

</dependencies>
Expand Down
3 changes: 1 addition & 2 deletions src/main/java/dev/jacrispys/JavaBot/JavaBotMain.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,7 @@
*/
public class JavaBotMain {

// TODO: 1/26/2023 Add Documentation to all functions

// TODO: 10/6/2023 Add unit testing to most classes
private static final Logger logger = LoggerFactory.getLogger(JavaBotMain.class);
private static final String className = JavaBotMain.class.getSimpleName();
public static AudioPlayerManager audioManager;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
package dev.jacrispys.JavaBot.api.libs.utils.async;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;

/**
* Async method handler
*/
public abstract class AsyncHandlerImpl implements AsyncHandler{
public abstract class AsyncHandlerImpl implements AsyncHandler {

private static final Logger logger = LoggerFactory.getLogger(AsyncHandlerImpl.class);

public record VoidMethodRunner(Runnable runnable, CompletableFuture<Void> cf) {}
public record MethodRunner(Runnable runnable, CompletableFuture<?> cf) {}
Expand All @@ -26,6 +31,7 @@ public void completeVoid() {
runner.cf().complete(null);
}
} catch (InterruptedException e) {
logger.error("Method runner was interrupted! Please report this.", e);
Thread.currentThread().interrupt();
}
}
Expand All @@ -44,6 +50,7 @@ public void completeMethod() {
}
}
} catch (InterruptedException e) {
logger.error("Method runner was interrupted! Please report this.", e);
Thread.currentThread().interrupt();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
public class AudioPlayerButtons extends ListenerAdapter {

private GuildAudioManager audioManager;
private final SpotifyManager man = SpotifyManager.getInstance();

/**
* Listen's for a ButtonInteractionEvent and then checks and edit's an embed according to what each button is mapped to.
Expand Down Expand Up @@ -131,14 +132,14 @@ private EmbedBuilder updateEmbed(MessageEmbed embed, int page) {
} else {
time = ("[" + DurationFormatUtils.formatDuration(track.getDuration(), "HH:mm:ss") + "]");
}
String artistLink = "https://open.spotify.com/artist/" + SpotifyManager.getArtistId(track.getIdentifier());
String artistLink = "https://open.spotify.com/artist/" + man.getArtistId(track.getIdentifier());
if (i < 5) {
queue.append((page - 1) * 10 + i + 1).append(". [").append(track.getInfo().author).append("](").append(artistLink).append(") - [").append(track.getInfo().title).append("](").append(track.getInfo().uri).append(") ").append(time).append(" \n");
} else {
queue2.append((page - 1) * 10 + i + 1).append(". [").append(track.getInfo().author).append("](").append(artistLink).append(") - [").append(track.getInfo().title).append("](").append(track.getInfo().uri).append(") ").append(time).append(" \n");

}
} catch (IndexOutOfBoundsException | IOException ex) {
} catch (IndexOutOfBoundsException ex) {
break;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@

import com.neovisionaries.i18n.CountryCode;
import dev.jacrispys.JavaBot.audio.objects.Genres;
import dev.jacrispys.JavaBot.utils.mysql.MySQLConnection;
import dev.jacrispys.JavaBot.utils.SpotifyManager;
import dev.jacrispys.JavaBot.utils.mysql.MySQLConnection;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel;
import net.dv8tion.jda.api.entities.emoji.UnicodeEmoji;
Expand All @@ -15,7 +17,6 @@
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.buttons.Button;
import net.dv8tion.jda.api.utils.messages.MessageCreateData;
import net.dv8tion.jda.api.utils.messages.MessageEditData;
import org.apache.hc.core5.http.ParseException;
import org.jetbrains.annotations.NotNull;
Expand All @@ -26,10 +27,11 @@
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;

import static dev.jacrispys.JavaBot.audio.GuildAudioManager.nowPlayingId;

/**
* Util class that uses {@link se.michaelthelin.spotify.SpotifyApi}
* <br> to generate playlists based off of {@link Recommendations}
Expand All @@ -54,8 +56,8 @@ public GenerateGenrePlaylist() {
* @throws ParseException if the spotify request fails
* @throws SpotifyWebApiException if the spotify request fails
*/
public Recommendations generatePlaylistFromGenre(String genres, int limit) throws IOException, ParseException, SpotifyWebApiException {
final GetRecommendationsRequest request = SpotifyManager.getInstance().getSpotifyApi().getRecommendations().market(CountryCode.US).seed_genres(genres).limit(limit).build();
public Recommendations generatePlaylistFromGenre(String genres, int limit) throws IOException, ParseException, SpotifyWebApiException, ExecutionException, InterruptedException, TimeoutException {
final GetRecommendationsRequest request = SpotifyManager.getInstance().getSpotifyApi().get(10000, TimeUnit.MILLISECONDS).getRecommendations().market(CountryCode.US).seed_genres(genres).limit(limit).build();
return request.execute();
}

Expand All @@ -69,9 +71,9 @@ public Recommendations generatePlaylistFromGenre(String genres, int limit) throw
* @throws ParseException if the spotify request fails
* @throws SpotifyWebApiException if the spotify request fails
*/
public Recommendations generatePlaylistFromGenre(String genres, int limit, int popularity) throws IOException, ParseException, SpotifyWebApiException {
public Recommendations generatePlaylistFromGenre(String genres, int limit, int popularity) throws IOException, ParseException, SpotifyWebApiException, ExecutionException, InterruptedException, TimeoutException {
if (popularity > 100 || popularity < 0) popularity = 100;
final GetRecommendationsRequest request = SpotifyManager.getInstance().getSpotifyApi().getRecommendations().market(CountryCode.US).seed_genres(genres).limit(limit).target_popularity(popularity).build();
final GetRecommendationsRequest request = SpotifyManager.getInstance().getSpotifyApi().get(10000, TimeUnit.MILLISECONDS).getRecommendations().market(CountryCode.US).seed_genres(genres).limit(limit).target_popularity(popularity).build();
return request.execute();
}

Expand Down
14 changes: 6 additions & 8 deletions src/main/java/dev/jacrispys/JavaBot/audio/GuildAudioManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
import com.sedmelluq.discord.lavaplayer.player.AudioLoadResultHandler;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayer;
import com.sedmelluq.discord.lavaplayer.player.AudioPlayerManager;
import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager;
import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeHttpContextFilter;
import com.sedmelluq.discord.lavaplayer.tools.FriendlyException;
import com.sedmelluq.discord.lavaplayer.track.AudioPlaylist;
import com.sedmelluq.discord.lavaplayer.track.AudioTrack;
Expand Down Expand Up @@ -42,15 +40,12 @@
import se.michaelthelin.spotify.model_objects.specification.TrackSimplified;

import java.awt.*;
import java.io.IOException;
import java.sql.SQLException;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.util.List;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.*;
import java.util.function.Function;

import static dev.jacrispys.JavaBot.JavaBotMain.audioManager;
Expand All @@ -64,6 +59,8 @@ public class GuildAudioManager {
private static final String className = GuildAudioManager.class.getSimpleName();
private final LoadAudioHandler audioHandler;

private final SpotifyManager man = SpotifyManager.getInstance();

private boolean djEnabled = false;

private static final Map<Guild, GuildAudioManager> audioManagers = new HashMap<>();
Expand Down Expand Up @@ -408,7 +405,7 @@ public MessageData displayQueue() {
for (int i = 1; i <= 10; i++) {
try {
AudioTrack track = trackList.get(i - 1);
String artistLink = "https://open.spotify.com/artist/" + SpotifyManager.getArtistId(track.getIdentifier());
String artistLink = "https://open.spotify.com/artist/" + man.getArtistId(track.getIdentifier()).get(1000, TimeUnit.MILLISECONDS);
String time;
if (track.getDuration() < 3600000) {
time = ("[" + DurationFormatUtils.formatDuration(track.getDuration(), "mm:ss") + "]");
Expand All @@ -420,7 +417,8 @@ public MessageData displayQueue() {
} else {
queue2.append(i).append(". [").append(track.getInfo().author).append("](").append(artistLink).append(") - [").append(track.getInfo().title).append("](").append(track.getInfo().uri).append(") ").append(time).append(" \n");
}
} catch (IndexOutOfBoundsException | IOException ex) {
} catch (IndexOutOfBoundsException | InterruptedException | ExecutionException |
TimeoutException ex) {
break;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,20 @@
*/
public class UnclassifiedSlashCommands extends ListenerAdapter {

private MySqlStats sqlStats;
//private final MySqlStats sqlStats;
private static JDA jda;

public UnclassifiedSlashCommands(JDA jda) {
this.jda = jda;
this.sqlStats = MySqlStats.getInstance();
//this.sqlStats = MySqlStats.getInstance();
}

public void initCommands(List<Guild> guilds) {
updateJdaCommands();
guilds.forEach(this::updateGuildCommands);
}

public List<CommandData> updateJdaCommands() {
public static List<CommandData> updateJdaCommands() {
List<CommandData> commands = new ArrayList<>();
Collections.addAll(commands,
Commands.slash("setnick", "Sets the nickname of this bot, or a user.")
Expand All @@ -60,7 +60,7 @@ protected void updateGuildCommands(Guild guild) {
@SuppressWarnings("all")
public void onSlashCommandInteraction(@NotNull SlashCommandInteractionEvent event) {
// Increment SQL Stat
sqlStats.incrementGuildStat(event.getGuild().getIdLong(), StatType.COMMAND_COUNTER);
//sqlStats.incrementGuildStat(event.getGuild().getIdLong(), StatType.COMMAND_COUNTER);
String commandName = event.getName();
switch (commandName) {
case "setnick" -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public void initCommands(List<Guild> guilds) {
* Generates a list of commands to be updated {@link ListenerAdapter#onReady(ReadyEvent)}
* @return the list of Commands
*/
public List<CommandData> updateJdaCommands() {
public static List<CommandData> updateJdaCommands() {
List<CommandData> commands = new ArrayList<>();
Collections.addAll(commands,
Commands.slash("play", "Add a link to most streaming platforms, or use its name to search!")
Expand Down
13 changes: 8 additions & 5 deletions src/main/java/dev/jacrispys/JavaBot/events/BotStartup.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,26 @@
*/
public class BotStartup extends ListenerAdapter {

private final MySQLConnection connection = MySQLConnection.getInstance();
public MySQLConnection getConnection() {
return MySQLConnection.getInstance();
}

@Override
public void onReady(@NotNull ReadyEvent event) {
List<CommandData> commands = new ArrayList<>();

commands.addAll(new SlashMusicCommands().updateJdaCommands());
commands.addAll(new UnclassifiedSlashCommands(event.getJDA()).updateJdaCommands());
commands.addAll(SlashMusicCommands.updateJdaCommands());
commands.addAll(UnclassifiedSlashCommands.updateJdaCommands());
event.getJDA().addEventListener(new SlashDebugCommands(event.getJDA()));

event.getJDA().updateCommands().addCommands(commands).queue();
for (Guild guild : event.getJDA().getGuilds()) {
connection.registerGuild(guild, guild.getTextChannels().get(0));
getConnection().registerGuild(guild, guild.getTextChannels().get(0));
}
}

@Override
public void onGuildJoin(@NotNull GuildJoinEvent event) {
connection.registerGuild(event.getGuild(), event.getGuild().getTextChannels().get(0));
getConnection().registerGuild(event.getGuild(), event.getGuild().getTextChannels().get(0));
}
}
25 changes: 18 additions & 7 deletions src/main/java/dev/jacrispys/JavaBot/utils/SecretData.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,21 @@ public class SecretData {
private static Yaml yaml = new Yaml();
private static Map<String, Object> loginInfo;

public static void initLoginInfo() throws IOException {
private static final String DEFAULT_PATH_DIR = "src/main/resources/loginInfo.yml";

public static void initLoginInfo(String path) throws IOException {
yaml = new Yaml();
loginInfo = yaml.load(generateSecretData());
loginInfo = yaml.load(generateSecretData(path));
}

public static void initLoginInfo() throws IOException {
initLoginInfo(DEFAULT_PATH_DIR);
}

protected static InputStream generateSecretData() throws IOException {
if (SecretData.class.getClassLoader().getResourceAsStream("loginInfo.yml") == null) {
File file = new File("src/main/resources/loginInfo.yml");
private static InputStream generateSecretData(String path) throws IOException {
File fileExists = new File(path);
if (!fileExists.exists()) {
File file = new File(path);
if (file.getParentFile() != null) file.getParentFile().mkdirs();
if (file.createNewFile()) {
Map<String, Object> fileInfo = getDefaultConfig();
Expand All @@ -38,11 +45,12 @@ protected static InputStream generateSecretData() throws IOException {
return new FileInputStream(file);
} else throw new FileNotFoundException("Could not create required config file!");

} else return SecretData.class.getClassLoader().getResourceAsStream("loginInfo.yml");
} else return new FileInputStream(path);
}

@SafeVarargs
@NotNull
private static Map<String, Object> getDefaultConfig() {
private static Map<String, Object> getDefaultConfig(Map.Entry<String, Object>... entry) {
Map<String, Object> fileInfo = new HashMap<>();
fileInfo.put("DATA_BASE_PASS", " ");
fileInfo.put("TOKEN", " ");
Expand All @@ -55,6 +63,9 @@ private static Map<String, Object> getDefaultConfig() {
fileInfo.put("DB_HOST", "localhost");
fileInfo.put("BOT_CLIENT_ID", " ");
fileInfo.put("BOT_CLIENT_SECRET", " ");
for (Map.Entry<String, Object> entryArgs : entry) {
fileInfo.put(entryArgs.getKey(), entryArgs.getValue());
}
return fileInfo;
}

Expand Down
Loading