Skip to content
This repository has been archived by the owner on Nov 25, 2022. It is now read-only.

Commit

Permalink
1.0!
Browse files Browse the repository at this point in the history
Changes:
- Update project version to 1.0
- Add ModuleAbout, ModuleScreenshare (#8)
- Migrate ModuleInfo aliases from String[] to immutable List<String>
- Enforce all-lowercase command names / aliases
- Handle aliases in CommandRegistry (#3)
- Move InvalidModuleExceptionTest to correct package
- Reformat some code
- Fix permission check to consider Permission.ADMINISTRATOR
- Update Travis release uploads to support refactored build tools
- Add Linux ARM32 build
  • Loading branch information
zocat64 committed Jul 22, 2019
1 parent e7689ed commit 6f55b0b
Show file tree
Hide file tree
Showing 18 changed files with 148 additions and 76 deletions.
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ deploy:
api_key:
secure: xg9bEDqfPBO9eAIyv+qpXx3fQGIX9u4cKeGoSvwsTtHIv9OimVJMBSG+/iVGUiNqEZMCngZA3kh8wZn6Qftw/+Tel9dSDJykVCKAuIhhX0ZdIVjJ3gH0W+qUpBYdCMj04niP8DKQktfUrNc3geGGYFQF4cw7FfvTLIjkMfGQVlWEvzrHWlw1zKRtVwWavJ1uFh7vX4sDiKtuZOshfRBlZn1RVtz44DoQV98+sjRK9ppRKaMfT8ZGuDpCyZHLXxeG90yX2SRJoxv0E+8xyv/UjyzH78e7WtW3BGpHzGAGhbRbpIDZ5YmBITmN8Coadmy5svhgs/Kv5Gk+ki7VNNRNNaSVJ9BoSdCTe0QTQxkSg4Sw57GLHJUbefb1HsPxYP01g0SEQZkQdL1b/xmO53jKcZxPiEk0Ajv/CIpZkTl5LX4Nk4K4lN9RTAwWK3rCuTPy9EtOHB4w29wV8DmqZojF8BBgnfaYWmXyRhBofA4BGUF3IYao6o4EYteFcafgpNB03GUJRIAHpGB1Q+dzYQJmttDU5wsNXK2TbQTnVk2s4SibLSStSmkpbcgk38fBWPa6hVi1mwMi1Q2qtYUT/PUfRp0WE36YqAmrkmnSh0OBjx+dfcMAqRxfqxN/sodJrE4dhnYJ5wTmBneyqUVZjcFZvD71OxYOvvt0vn1a1mOmgrE=
file_glob: true
file: $TRAVIS_BUILD_DIR/bt_output/*.zip
file: $TRAVIS_BUILD_DIR/bt_out/*.zip
skip_cleanup: true
on:
repo: cbryant02/ghost2
Expand Down
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ plugins {
apply plugin: 'io.spring.dependency-management'

group 'com.github.coleb1911'
version '0.1'
version '1.0'

sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ private void registerListeners(DiscordClient client) {
Long id = event.getGuild().getId().asLong();
idsToRemove.remove(id);
if (!guildRepo.existsById(id)) {
guildRepo.save(new GuildMeta(id, GuildMeta.DEFAULT_PREFIX));
guildRepo.save(new GuildMeta(id));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
import static com.github.coleb1911.ghost2.buildtools.SystemUtils.USER_AGENT;

class JDKDownloadUtils {
private static final String URL_FORMAT = "https://api.adoptopenjdk.net/v2/info/releases/openjdk11?openjdk_impl=hotspot&arch=x64&type=jdk&heap_size=normal&release=latest&os=";
private static final String URL_FORMAT = "https://api.adoptopenjdk.net/v2/info/releases/openjdk11?openjdk_impl=hotspot&type=jdk&heap_size=normal&release=latest&arch={ARCH}&os={OS}";

/**
* Download the latest Java 11 JDK for a platform.<br>
Expand Down Expand Up @@ -64,7 +64,8 @@ private static URI fetchDownloadUri(final Platform platform) throws IOException
.build()) {

// Make initial link request to AdoptOpenJDK API
HttpGet request = new HttpGet(URL_FORMAT + platform.apiName);
String requestString = URL_FORMAT.replace("{ARCH}", platform.osArch).replace("{OS}", platform.osName);
HttpGet request = new HttpGet(requestString);
try (CloseableHttpResponse response = client.execute(request)) {
// Check status
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
Expand All @@ -91,17 +92,24 @@ private static URI fetchDownloadUri(final Platform platform) throws IOException
* Enum of supported platforms
*/
public enum Platform {
WINDOWS("windows"),
LINUX("linux"),
OSX("mac");
WINDOWS("windows", "x64"),
LINUX("linux", "x64"),
OSX("mac", "x64"),
ARM32("linux", "arm");

/**
* Name of this platform in the AdoptOpenJDK API
*/
private final String apiName;
private final String osName;

Platform(final String apiName) {
this.apiName = apiName;
/**
* Architecture of this platform in the AdoptOpenJDK API
*/
private final String osArch;

Platform(final String osName, final String osArch) {
this.osName = osName;
this.osArch = osArch;
}

/**
Expand All @@ -111,10 +119,11 @@ public enum Platform {
* @return Enum value
* @throws IllegalArgumentException If the platform is unsupported or nonexistent
*/
public static Platform fromPlatformString(final String name) {
public static Platform fromPlatformString(final String name, final String arch) {
if (name.startsWith("Windows")) return WINDOWS;
else if (name.startsWith("Mac")) return OSX;
else if (name.contains("Linux")) return LINUX;
else if (name.contains("Linux") && arch.contains("amd64")) return LINUX;
else if (name.contains("Linux") && arch.contains("arm")) return ARM32;
throw new IllegalArgumentException("Unsupported or nonexistent platform");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@
*/
final class SystemUtils {
static final int BUFFER_SIZE = 8192;
static final String USER_AGENT = System.getProperty("java.version") + "/" + "Apache HttpClient 4.5.9";
static final Platform PLATFORM = Platform.fromPlatformString(System.getProperty("os.name"));
static final String USER_AGENT = "Java " + System.getProperty("java.version") + "/" + "Apache HttpClient 4.5.9";
static final Platform PLATFORM = Platform.fromPlatformString(System.getProperty("os.name"), System.getProperty("os.arch"));
static final String CLASSPATH = System.getProperty("java.class.path");
static final boolean VERBOSE = "true".equals(System.getenv("BT_VERBOSE"));

Expand Down Expand Up @@ -266,7 +266,7 @@ static void cleanAndCreate(final File... directories) throws IOException {
*
* @param directory Directory to list files from
* @throws IllegalArgumentException If the file given is not a directory
* @throws IOException If an I/O exception occurs while attempting to list the files
* @throws IOException If an I/O exception occurs while attempting to list the files
*/
static List<File> listFiles(final File directory) throws IOException {
if (!directory.isDirectory()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,12 @@ public void onMessageEvent(MessageCreateEvent ev) {
ctx.reply(Module.REPLY_GENERAL_ERROR);
return;
}
for (Permission required : module.getInfo().getUserPermissions()) {
if (!invokerPerms.contains(required)) {
ctx.reply(Module.REPLY_INSUFFICIENT_PERMISSIONS_USER);
return;
if (!invokerPerms.contains(Permission.ADMINISTRATOR)) {
for (Permission required : module.getInfo().getUserPermissions()) {
if (!invokerPerms.contains(required)) {
ctx.reply(Module.REPLY_INSUFFICIENT_PERMISSIONS_USER);
return;
}
}
}

Expand All @@ -102,10 +104,12 @@ public void onMessageEvent(MessageCreateEvent ev) {
ctx.reply(Module.REPLY_GENERAL_ERROR);
return;
}
for (Permission required : module.getInfo().getBotPermissions()) {
if (!botPerms.contains(required)) {
ctx.reply(Module.REPLY_INSUFFICIENT_PERMISSIONS_BOT);
return;
if (!botPerms.contains(Permission.ADMINISTRATOR)) {
for (Permission required : module.getInfo().getBotPermissions()) {
if (!botPerms.contains(required)) {
ctx.reply(Module.REPLY_INSUFFICIENT_PERMISSIONS_BOT);
return;
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,8 @@ public final class CommandRegistry implements ApplicationListener<ContextRefresh
*/
Module getCommandInstance(String name) {
for (Module module : instances) {
if (name.equals(module.getInfo().getName())) {
ModuleInfo info = module.getInfo();
if (name.equals(info.getName()) || info.getAliases().contains(name)) {
instances.remove(module);
instances.add(createInstance(module.getClass()));
return module;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,21 @@ public InvalidModuleException(Class<? extends Module> module, Throwable exceptio
this.reasons = Set.of(Reason.EXCEPTION_IN_CONSTRUCTOR);
}

/**
* Formats the error message.
*
* @param moduleName The module name
* @param reasons The reasons description. Might contain more than one reason.
*/
private static String formatErrorMessage(String moduleName, String reasons) {
return "Module subclass "
+ moduleName
+ " is written incorrectly. Refer to the wiki for help. (Reason(s): "
+ reasons
+ ")";

}

/**
* @return A {@code String} containing all the messages of each {@code Reason} for this {@code InvalidModuleException}
*/
Expand All @@ -64,19 +79,6 @@ public Class<? extends Module> getModule() {
return module;
}

/**
* Formats the error message.
* @param moduleName The module name
* @param reasons The reasons description. Might contain more than one reason.
*/
private static String formatErrorMessage(String moduleName, String reasons){
return "Module subclass "
+ moduleName
+ " is written incorrectly. Refer to the wiki for help. (Reason(s): "
+ reasons
+ ")";

}
/**
* The many causes of an {@code InvalidModuleException}.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
* Contains metadata for a Module.
Expand All @@ -27,15 +30,15 @@ public final class ModuleInfo {
private final PermissionSet botPermissions;
private final PermissionSet userPermissions;
private final CommandType type;
private final String[] aliases;
private final List<String> aliases;

private ModuleInfo(String name, String description, PermissionSet botPermissions, PermissionSet userPermissions, CommandType type, String[] aliases) {
this.name = name;
this.name = name.toLowerCase();
this.description = description;
this.botPermissions = botPermissions;
this.userPermissions = userPermissions;
this.type = type;
this.aliases = aliases;
this.aliases = Arrays.stream(aliases).map(String::toLowerCase).collect(Collectors.toUnmodifiableList());
}

/**
Expand Down Expand Up @@ -74,9 +77,9 @@ public CommandType getType() {
}

/**
* @return Command aliases
* @return Immutable list of aliases
*/
public String[] getAliases() {
public List<String> getAliases() {
return aliases;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,14 @@ public void invoke(@NotNull final CommandContext ctx) {
// Get prefix and check length
String prefix = ctx.getArgs().get(0);
if (prefix.length() > GuildMeta.PREFIX_LENGTH) {
ctx.reply("That prefix is too long. The maximum prefix length is " + GuildMeta.PREFIX_LENGTH +".");
ctx.reply("That prefix is too long. The maximum prefix length is " + GuildMeta.PREFIX_LENGTH + ".");
return;
}

// Save prefix
guildRepo.save(new GuildMeta(ctx.getGuild().getId().asLong(), prefix));
ctx.reply("Set prefix to `"+ prefix + "`.");
GuildMeta meta = guildRepo.findById(ctx.getGuild().getId().asLong()).orElseThrow();
meta.setPrefix(prefix);
guildRepo.save(meta);
ctx.reply("Set prefix to `" + prefix + "`.");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.github.coleb1911.ghost2.commands.modules.info;

import com.github.coleb1911.ghost2.commands.meta.CommandContext;
import com.github.coleb1911.ghost2.commands.meta.Module;
import com.github.coleb1911.ghost2.commands.meta.ModuleInfo;
import com.github.coleb1911.ghost2.shared.Constants;
import discord4j.core.object.entity.Member;
import org.apache.commons.lang3.time.DurationFormatUtils;

import javax.validation.constraints.NotNull;
import java.time.Duration;
import java.time.Instant;

public final class ModuleAbout extends Module {
private static final String GITHUB_URL = "https://github.com/cbryant02/ghost2";
private static final String FLAVOR_TEXT = "Want to help contribute? Visit our GitHub: " + GITHUB_URL + "\n" +
"You can also report bugs there by opening an issue, or by messaging yaboired#8927.";
private static final String FIELD_ID = "\uD83C\uDD94 My ID";
private static final String FIELD_TAG = "\u0023\u20E3 My tag";
private static final String FIELD_SERVER_TIME = "\u23F1 Time in this server";
private static final String FOOTER = "ghost2 v" + Constants.VERSION_STRING;

public ModuleAbout() {
super(new ModuleInfo.Builder(ModuleAbout.class)
.withName("about")
.withDescription("Information about the bot"));
}

@Override
public void invoke(@NotNull CommandContext ctx) {
Member me = ctx.getSelf();

Duration timeInServer = Duration.between(me.getJoinTime(), Instant.now());
String timeFormatted = DurationFormatUtils.formatDuration(timeInServer.toMillis(), "dd 'days', HH 'hours', mm 'minutes'");

ctx.getChannel().createEmbed(embedCreateSpec -> embedCreateSpec
.setAuthor(me.getUsername(), "https://github.com/cbryant02/ghost2", me.getAvatarUrl())
.setTitle("About")
.setDescription(FLAVOR_TEXT)
.addField(FIELD_ID, me.getId().asString(), false)
.addField(FIELD_TAG, me.getUsername() + "#" + me.getDiscriminator(), false)
.addField(FIELD_SERVER_TIME, timeFormatted, false)
.setFooter(FOOTER, null)).subscribe();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public void invoke(@NotNull final CommandContext ctx) {
// Build and send embed
ctx.getChannel().createMessage(messageSpec -> messageSpec.setEmbed(embedSpec -> {
String aliasList;
if (info.getAliases().length == 0) {
if (info.getAliases().size() == 0) {
aliasList = "n/a";
} else {
StringJoiner joiner = new StringJoiner(", ");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ public ModuleBan() {
@Override
public void invoke(@NotNull CommandContext ctx) {
//Check for args
try{
try {
ctx.getArgs().get(0);
} catch(IndexOutOfBoundsException e) {
} catch (IndexOutOfBoundsException e) {
ctx.reply("Please specify a user.");
return;
}
Expand All @@ -36,7 +36,7 @@ public void invoke(@NotNull CommandContext ctx) {
}).subscribe())
.hasElements()
.flatMap(aBoolean -> {
if(!aBoolean) ctx.reply("User not found.");
if (!aBoolean) ctx.reply("User not found.");
return Mono.just(aBoolean);
})
.subscribe();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ public ModuleMute() {
@Override
public void invoke(@NotNull CommandContext ctx) {
//Check for args
try{
try {
ctx.getArgs().get(0);
} catch(IndexOutOfBoundsException e) {
} catch (IndexOutOfBoundsException e) {
ctx.reply("Please specify a user.");
return;
}
Expand All @@ -36,7 +36,7 @@ public void invoke(@NotNull CommandContext ctx) {
}).subscribe())
.hasElements()
.flatMap(aBoolean -> {
if(!aBoolean) ctx.reply("User not found.");
if (!aBoolean) ctx.reply("User not found.");
return Mono.just(aBoolean);
})
.subscribe();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
import java.util.Optional;

public final class ModuleScreenshare extends Module {

private static final String NOVOICE = "You are not in a voice channel. Please join a voice channel to use the `screenshare` command.";
private static final String REPLY_NO_VOICE_CHANNEL = "You are not in a voice channel. Please join a voice channel to use the `screenshare` command.";

public ModuleScreenshare() {
super(new ModuleInfo.Builder(ModuleScreenshare.class)
Expand All @@ -22,11 +21,12 @@ public ModuleScreenshare() {
@Override
public void invoke(@NotNull CommandContext ctx) {
// Check if user is connected to a voice channel
Optional<Snowflake> state = ctx.getInvoker().getVoiceState().map(VoiceState::getChannelId).block();
if(state.isPresent())
ctx.reply("https://discordapp.com/channels/" + ctx.getGuild().getId().asLong() + "/" + ctx.getInvoker().getVoiceState().block().getChannelId().get().asLong());
else {
ctx.reply(NOVOICE);
Optional<Snowflake> channelIdOptional = ctx.getInvoker().getVoiceState().map(VoiceState::getChannelId).block();
if (Optional.empty().equals(channelIdOptional)) {
ctx.reply(REPLY_NO_VOICE_CHANNEL);
return;
}

ctx.reply("https://discordapp.com/channels/" + ctx.getGuild().getId().asLong() + "/" + channelIdOptional);
}
}
}
Loading

0 comments on commit 6f55b0b

Please sign in to comment.