Skip to content

Commit

Permalink
Merge branch 'release/v5.4.6'
Browse files Browse the repository at this point in the history
  • Loading branch information
Marco (Valandur) committed Aug 11, 2019
2 parents 4d12590 + c71e6c3 commit 2fcfbe7
Show file tree
Hide file tree
Showing 6 changed files with 97 additions and 52 deletions.
4 changes: 2 additions & 2 deletions gradle.properties
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
version=5.4.5
version=5.4.6

minecraftVersion=1.12.2
spongeVersion=7.1.0
spongeVersion=7.2.0-SNAPSHOT

jacksonVersion=2.9.4
jettyVersion=9.4.8.v20171121
2 changes: 1 addition & 1 deletion webapi-sponge/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ dependencies {
compile group: "org.glassfish.jersey.inject", name: "jersey-hk2", version: "2.26"
compile group: "org.bstats", name: "bstats-sponge", version: "1.4"

compileOnly group: "org.spongepowered", name: "spongeapi", version: "${project.spongeVersion}-SNAPSHOT"
compileOnly group: "org.spongepowered", name: "spongeapi", version: project.spongeVersion

compile group: 'redis.clients', name: 'jedis', version: '2.9.0'
compile group: 'com.rabbitmq', name: 'amqp-client', version: '5.3.0'
Expand Down
4 changes: 0 additions & 4 deletions webapi-sponge/src/main/java/valandur/webapi/WebAPI.java
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,6 @@
)
public class WebAPI {

static {
System.out.println("Static initialized");
}

private static WebAPI instance;
public static WebAPI getInstance() {
return WebAPI.instance;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,11 @@
import ninja.leaping.configurate.commented.CommentedConfigurationNode;
import ninja.leaping.configurate.objectmapping.ObjectMappingException;
import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer;
import org.slf4j.Logger;
import valandur.webapi.WebAPI;
import valandur.webapi.hook.filter.BaseWebHookFilter;
import valandur.webapi.security.SecurityService;
import valandur.webapi.util.TreeNode;

import javax.ws.rs.HttpMethod;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
Expand All @@ -22,17 +20,12 @@ public class WebHookSerializer implements TypeSerializer<WebHook> {

@Override
public WebHook deserialize(TypeToken<?> type, ConfigurationNode value) throws ObjectMappingException {
Logger logger = WebAPI.getLogger();

String address = value.getNode("address").getString();

if (address == null) {
logger.error("No address specified for web hook!");
return null;
throw new ObjectMappingException("No address specified for web hook!");
}

logger.info(" - " + address);

boolean enabled = value.getNode("enabled").getBoolean();
String method = value.getNode("method").getString();
WebHook.WebHookDataType dataType = value.getNode("dataType").getValue(TypeToken.of(WebHook.WebHookDataType.class));
Expand All @@ -51,43 +44,35 @@ public WebHook deserialize(TypeToken<?> type, ConfigurationNode value) throws Ob
}

if (method == null) {
method = HttpMethod.POST;
logger.warn(" Does not specify 'method', defaulting to 'POST'");
throw new ObjectMappingException("Webhook " + address + " is missing property 'method'.");
}

if (dataType == null) {
dataType = WebHook.WebHookDataType.JSON;
logger.warn(" Does not specify 'dataType', defaulting to 'JSON'");
throw new ObjectMappingException("Webhook " + address + " is missing property 'dataType'.");
}

if (value.getNode("permissions").isVirtual()) {
logger.warn(" Does not specify 'permissions', defaulting to '*'");
throw new ObjectMappingException("Webhook " + address + " is missing property 'permissions'.");
} else {
permissions = WebAPI.getSecurityService().permissionTreeFromConfig(value.getNode("permissions"));
permissions = SecurityService.permissionTreeFromConfig(value.getNode("permissions"));
}

WebHook hook = new WebHook(address, enabled, method, dataType, form, headers, details, permissions);

if (filterName != null) {
Optional<Class<? extends BaseWebHookFilter>> opt = WebAPI.getWebHookService().getFilter(filterName);
if (!opt.isPresent()) {
logger.error(" Could not find filter with name '" + filterName + "'");
throw new ObjectMappingException("Could not find filter with name '" + filterName + "'");
} else {
try {
Constructor ctor = opt.get().getConstructor(WebHook.class, ConfigurationNode.class);
hook.setFilter((BaseWebHookFilter) ctor.newInstance(hook, filterConfig));
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
logger.error(" Could not setup filter '" + filterName + "': " + e.getMessage());
throw new ObjectMappingException("Could not setup filter '" + filterName + "': " + e.getMessage());
}
}
}

if (enabled) {
logger.info(" -> Ok");
} else {
logger.info(" -> Disabled");
}

return hook;
}

Expand Down Expand Up @@ -130,7 +115,7 @@ public void serialize(TypeToken<?> type, WebHook obj, ConfigurationNode value) t
}
}

WebAPI.getSecurityService().permissionTreeToConfig(value.getNode("permissions"), obj.getPermissions());
SecurityService.permissionTreeToConfig(value.getNode("permissions"), obj.getPermissions());
if (value.getNode("permissions") instanceof CommentedConfigurationNode) {
((CommentedConfigurationNode) value.getNode("permissions")).setComment(
"Permissions node same as the ones in the permissions.conf file,\n" +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import static valandur.webapi.util.Constants.*;

/**
* The web hook service provides access to the Web-API web hooks.
*/
Expand Down Expand Up @@ -94,18 +96,13 @@ public void init() {
" Minecraft/" + mc +
" Java/" + System.getProperty("java.version");

// Load filters
logger.info("Loading filters...");

filters.clear();

// Add some default filters
// Add filters
filters.put(BlockTypeFilter.name, BlockTypeFilter.class);
filters.put(PlayerFilter.name, PlayerFilter.class);
filters.put(ItemTypeFilter.name, ItemTypeFilter.class);

logger.info("Done loading filters");

// Load config
Path configPath = WebAPI.getConfigPath().resolve(configFileName).normalize();
HookConfig config = BaseConfig.load(configPath, new HookConfig());
Expand All @@ -115,41 +112,88 @@ public void init() {
customHooks.clear();
commandHooks.clear();

// Calculate max width of any hook text for printing
int maxAddressLength = 0;
for (CommandWebHook cmdHook : config.command.values()) {
maxAddressLength = Math.max(
maxAddressLength,
cmdHook.getHooks().stream().map(h -> h.getAddress().length()).max(Comparator.comparingInt(a -> a)).orElse(0)
);
}
for (List<WebHook> hooks : config.events.asMap().values()) {
maxAddressLength = Math.max(
maxAddressLength,
hooks.stream().map(h -> h.getAddress().length()).max(Comparator.comparingInt(a -> a)).orElse(0)
);
}
for (List<WebHook> hooks : config.custom.values()) {
maxAddressLength = Math.max(
maxAddressLength,
hooks.stream().map(h -> h.getAddress().length()).max(Comparator.comparingInt(a -> a)).orElse(0)
);
}

// Add command hooks
for (Map.Entry<String, CommandWebHook> entry : config.command.entrySet()) {
if (!entry.getValue().isEnabled())
continue;
commandHooks.put(entry.getKey(), entry.getValue());
String cmd = entry.getKey();
CommandWebHook cmdHook = entry.getValue();

String separator = String.join("", Collections.nCopies(maxAddressLength - cmd.length() - 7, " "));
logger.info(" Command: " + cmd + separator + " [" + (cmdHook.isEnabled() ? ANSI_GREEN + "ON" : ANSI_RED + "DISABLED") + ANSI_RESET + "]");
for (WebHook hook : cmdHook.getHooks()) {
separator = String.join("", Collections.nCopies(maxAddressLength - hook.getAddress().length(), " "));
logger.info(" " + hook.getAddress() + separator + " [" + (hook.isEnabled() ? ANSI_GREEN + "ON" : ANSI_RED + "DISABLED") + ANSI_RESET + "]");
}

if (cmdHook.isEnabled()) {
commandHooks.put(cmd, cmdHook);
}
}

// Add event hooks
for (Map.Entry<WebHookType, List<WebHook>> entry : config.events.asMap().entrySet()) {
eventHooks.put(
entry.getKey(),
entry.getValue().stream().filter(WebHook::isEnabled).collect(Collectors.toList())
);
WebHookType type = entry.getKey();
List<WebHook> hooks = entry.getValue();

eventHooks.put(type, hooks.stream().filter(WebHook::isEnabled).collect(Collectors.toList()));

if (hooks.size() == 0) {
continue;
}

logger.info(" Event: " + type);
for (WebHook hook : hooks) {
String separator = String.join("", Collections.nCopies(maxAddressLength - hook.getAddress().length(), " "));
logger.info(" " + hook.getAddress() + separator + " [" + (hook.isEnabled() ? ANSI_GREEN + "ON" : ANSI_RED + "DISABLED") + ANSI_RESET + "]");
}
}

// Add custom event hooks
for (Map.Entry<String, List<WebHook>> entry : config.custom.entrySet()) {
String className = entry.getKey();
List<WebHook> hooks = entry.getValue();

try {
Class c = Class.forName(className);
if (!Event.class.isAssignableFrom(c))
if (!Event.class.isAssignableFrom(c)) {
throw new InvalidClassException("Class " + c.toString() + " must be a subclass of " +
Event.class.toString() + " so that it can be used as a custom web hook");
}
Class<? extends Event> clazz = (Class<? extends Event>) c;

WebHookEventListener listener = new WebHookEventListener(clazz);
List<WebHook> hooks = entry.getValue().stream().filter(WebHook::isEnabled).collect(Collectors.toList());

Sponge.getEventManager().registerListener(WebAPI.getInstance(), clazz, listener);
customHooks.put(clazz, new Tuple<>(hooks, listener));
customHooks.put(clazz, new Tuple<>(hooks.stream().filter(WebHook::isEnabled).collect(Collectors.toList()), listener));

logger.info(" Custom Event: " + c.getName());
for (WebHook hook : hooks) {
String separator = String.join("", Collections.nCopies(maxAddressLength - hook.getAddress().length(), " "));
logger.info(" " + hook.getAddress() + separator + " [" + (hook.isEnabled() ? ANSI_GREEN + "ON" : ANSI_RED + "DISABLED") + ANSI_RESET + "]");
}
} catch (ClassNotFoundException e) {
logger.error("Could not find class for custom web hook: " + className);
logger.error(" Could not find class for custom web hook: " + className);
} catch (InvalidClassException e) {
logger.error(e.getMessage());
logger.error(" " + e.getMessage());
}
}
}
Expand All @@ -166,8 +210,18 @@ public Optional<Class<? extends BaseWebHookFilter>> getFilter(String name) {
public void notifyHooks(WebHookType type, Object data) {
Timings.WEBHOOK_NOTIFY.startTimingIfSync();

List<WebHook> notifyHooks = new ArrayList<>(eventHooks.get(type));
notifyHooks.addAll(eventHooks.get(WebHookType.ALL));
List<WebHook> notifyHooks = new ArrayList<>();

List<WebHook> origHooks = eventHooks.get(type);
if (origHooks != null) {
notifyHooks.addAll(origHooks);
}

List<WebHook> allHooks = eventHooks.get(WebHookType.ALL);
if (allHooks != null) {
notifyHooks.addAll(allHooks);
}

for (WebHook hook : notifyHooks) {
notifyHook(hook, type, null, data);
}
Expand All @@ -192,7 +246,7 @@ public void notifyHook(CommandWebHook cmdHook, String source, Map<String, Object
public void notifyHooks(Class<? extends Event> clazz, Object data) {
Timings.WEBHOOK_NOTIFY.startTimingIfSync();

List<WebHook> notifyHooks = new ArrayList<>(customHooks.get(clazz).getFirst());
List<WebHook> notifyHooks = customHooks.get(clazz).getFirst();
for (WebHook hook : notifyHooks) {
notifyHook(hook, WebHookType.CUSTOM_EVENT, null, data);
}
Expand Down
10 changes: 10 additions & 0 deletions webapi-sponge/src/main/java/valandur/webapi/util/Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,14 @@ public class Constants {
public static final String UPDATE_URL = "https://api.github.com/repos/Valandur/Web-API/releases/latest";

public static final String BASE_PATH = "/api/v5";

public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLACK = "\u001B[30m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_YELLOW = "\u001B[33m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_PURPLE = "\u001B[35m";
public static final String ANSI_CYAN = "\u001B[36m";
public static final String ANSI_WHITE = "\u001B[37m";
}

0 comments on commit 2fcfbe7

Please sign in to comment.