Permission and config improvements, fixes #66

Merged
NorbiPeti merged 13 commits from dev into master 2019-06-06 18:39:52 +00:00
18 changed files with 394 additions and 166 deletions

View file

@ -1,5 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EntryPointsManager">
<list size="1">
<item index="0" class="java.lang.String" itemvalue="org.bukkit.event.EventHandler" />
</list>
</component>
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>

View file

@ -13,6 +13,12 @@
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module" module-name="ButtonCore (1) (com.github.TBMCPlugins.ButtonCore)" />
<orderEntry type="module" module-name="ButtonCore (1) (com.github.TBMCPlugins.ButtonCore)" />
<orderEntry type="module" module-name="ButtonCore (1) (com.github.TBMCPlugins.ButtonCore)" />
<orderEntry type="module" module-name="ButtonCore (1) (com.github.TBMCPlugins.ButtonCore)" />
<orderEntry type="module" module-name="ButtonCore (1) (com.github.TBMCPlugins.ButtonCore)" />
<orderEntry type="module" module-name="ButtonCore (1) (com.github.TBMCPlugins.ButtonCore)" />
<orderEntry type="module" module-name="ButtonCore (1) (com.github.TBMCPlugins.ButtonCore)" />
<orderEntry type="module" module-name="ButtonCore (1) (com.github.TBMCPlugins.ButtonCore)" />
<orderEntry type="library" name="Maven: org.reflections:reflections:0.9.10" level="project" />
<orderEntry type="library" name="Maven: com.google.code.findbugs:annotations:2.0.1" level="project" />
<orderEntry type="library" name="Maven: org.javassist:javassist:3.20.0-GA" level="project" />

View file

@ -1,38 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: org.reflections:reflections:0.9.10" level="project" />
<orderEntry type="library" name="Maven: com.google.guava:guava:15.0" level="project" />
<orderEntry type="library" name="Maven: com.google.code.findbugs:annotations:2.0.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.spigotmc:spigot-api:1.12.2-R0.1-SNAPSHOT" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-lang:commons-lang:2.6" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.googlecode.json-simple:json-simple:1.1.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.google.code.gson:gson:2.8.0" level="project" />
<orderEntry type="library" name="Maven: org.yaml:snakeyaml:1.19" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.md-5:bungeecord-chat:1.12-SNAPSHOT" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: commons-io:commons-io:1.3.2" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.github.TBMCPlugins.ButtonCore:Towny:master-f8fd481f46-1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.github.milkbowl:VaultAPI:master-68f14eca20-1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.bukkit:bukkit:1.13.1-R0.1-SNAPSHOT" level="project" />
<orderEntry type="library" name="Maven: org.javassist:javassist:3.20.0-GA" level="project" />
<orderEntry type="library" name="Maven: org.mockito:mockito-core:2.7.20" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: net.bytebuddy:byte-buddy:1.6.11" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: net.bytebuddy:byte-buddy-agent:1.6.11" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.objenesis:objenesis:2.5" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.projectlombok:lombok:1.16.16" level="project" />
<orderEntry type="module" module-name="ButtonProcessor" />
<orderEntry type="library" scope="PROVIDED" name="Maven: net.ess3:Essentials:2.13.1" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.vexsoftware:nuvotifier-universal:2.3.4" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: junit:junit:3.8.1" level="project" />
</component>
</module>

View file

@ -38,7 +38,7 @@ public final class ComponentManager {
public static <T extends ButtonPlugin> void unregComponents(T plugin) {
while (!plugin.getComponentStack().empty()) //Unregister in reverse order
Component.unregisterComponent(plugin, (Component<T>) plugin.getComponentStack().pop()); //Components are pushed on register
componentsEnabled = false;
//componentsEnabled = false; - continue enabling new components after a plugin gets disabled
}
/**

View file

@ -45,9 +45,8 @@ import java.util.logging.Logger;
public class MainPlugin extends ButtonPlugin {
public static MainPlugin Instance;
public static Permission permission;
public static boolean Test;
public static Essentials ess;
public static Permission permission;
public static Essentials ess;
private Logger logger;
@Nullable
@ -69,17 +68,20 @@ public class MainPlugin extends ButtonPlugin {
"{channel}] <{name}> {message}");
}
public ConfigData<Boolean> test() {
return getIConfig().getData("test", true);
}
@Override
public void pluginEnable() {
// Logs "Plugin Enabled", registers commands
Instance = this;
PluginDescriptionFile pdf = getDescription();
PluginDescriptionFile pdf = getDescription();
logger = getLogger();
if (!setupPermissions())
throw new NullPointerException("No permission plugin found!");
if (!setupEconomy()) //Though Essentials always provides economy so this shouldn't happen
getLogger().warning("No economy plugin found! Components using economy will not be registered.");
Test = getConfig().getBoolean("test", true);
saveConfig();
Component.registerComponent(this, new PluginUpdaterComponent());
Component.registerComponent(this, new RestartComponent());
@ -96,31 +98,31 @@ public class MainPlugin extends ButtonPlugin {
getCommand2MC().registerCommand(new ThorpeCommand());
TBMCCoreAPI.RegisterEventsForExceptions(new PlayerListener(), this);
ChromaGamerBase.addConverter(commandSender -> Optional.ofNullable(commandSender instanceof ConsoleCommandSender || commandSender instanceof BlockCommandSender
? TBMCPlayer.getPlayer(new UUID(0, 0), TBMCPlayer.class) : null)); //Console & cmdblocks
? TBMCPlayer.getPlayer(new UUID(0, 0), TBMCPlayer.class) : null)); //Console & cmdblocks
ChromaGamerBase.addConverter(sender -> Optional.ofNullable(sender instanceof Player
? TBMCPlayer.getPlayer(((Player) sender).getUniqueId(), TBMCPlayer.class) : null)); //Players, has higher priority
? TBMCPlayer.getPlayer(((Player) sender).getUniqueId(), TBMCPlayer.class) : null)); //Players, has higher priority
TBMCCoreAPI.RegisterUserClass(TBMCPlayerBase.class);
TBMCChatAPI.RegisterChatChannel(Channel.GlobalChat = new Channel("§fg§f", Color.White, "g", null)); //The /ooc ID has moved to the config
TBMCChatAPI.RegisterChatChannel(
Channel.AdminChat = new Channel("§cADMIN§f", Color.Red, "a", Channel.inGroupFilter(null)));
Channel.AdminChat = new Channel("§cADMIN§f", Color.Red, "a", Channel.inGroupFilter(null)));
TBMCChatAPI.RegisterChatChannel(
Channel.ModChat = new Channel("§9MOD§f", Color.Blue, "mod", Channel.inGroupFilter("mod")));
TBMCChatAPI.RegisterChatChannel(new Channel("§6DEV§f", Color.Gold, "dev", Channel.inGroupFilter("developer")));
TBMCChatAPI.RegisterChatChannel(new ChatRoom("§cRED§f", Color.DarkRed, "red"));
TBMCChatAPI.RegisterChatChannel(new ChatRoom("§6ORANGE§f", Color.Gold, "orange"));
TBMCChatAPI.RegisterChatChannel(new ChatRoom("§eYELLOW§f", Color.Yellow, "yellow"));
TBMCChatAPI.RegisterChatChannel(new ChatRoom("§aGREEN§f", Color.Green, "green"));
TBMCChatAPI.RegisterChatChannel(new ChatRoom("§bBLUE§f", Color.Blue, "blue"));
TBMCChatAPI.RegisterChatChannel(new ChatRoom("§5PURPLE§f", Color.DarkPurple, "purple"));
Channel.ModChat = new Channel("§9MOD§f", Color.Blue, "mod", Channel.inGroupFilter("mod")));
TBMCChatAPI.RegisterChatChannel(new Channel("§6DEV§f", Color.Gold, "dev", Channel.inGroupFilter("developer")));
TBMCChatAPI.RegisterChatChannel(new ChatRoom("§cRED§f", Color.DarkRed, "red"));
TBMCChatAPI.RegisterChatChannel(new ChatRoom("§6ORANGE§f", Color.Gold, "orange"));
TBMCChatAPI.RegisterChatChannel(new ChatRoom("§eYELLOW§f", Color.Yellow, "yellow"));
TBMCChatAPI.RegisterChatChannel(new ChatRoom("§aGREEN§f", Color.Green, "green"));
TBMCChatAPI.RegisterChatChannel(new ChatRoom("§bBLUE§f", Color.Blue, "blue"));
TBMCChatAPI.RegisterChatChannel(new ChatRoom("§5PURPLE§f", Color.DarkPurple, "purple"));
if (writePluginList().get()) {
try {
Files.write(new File("plugins", "plugins.txt").toPath(), Arrays.stream(Bukkit.getPluginManager().getPlugins()).map(p -> (CharSequence) p.getDataFolder().getName())::iterator);
} catch (IOException e) {
TBMCCoreAPI.SendException("Failed to write plugin list!", e);
}
}
ess = Essentials.getPlugin(Essentials.class);
logger.info(pdf.getName() + " has been Enabled (V." + pdf.getVersion() + ") Test: " + Test + ".");
}
ess = Essentials.getPlugin(Essentials.class);
logger.info(pdf.getName() + " has been Enabled (V." + pdf.getVersion() + ") Test: " + test().get() + ".");
}
@Override
@ -128,21 +130,21 @@ public class MainPlugin extends ButtonPlugin {
logger.info("Saving player data...");
TBMCPlayerBase.savePlayers();
logger.info("Player data saved.");
new Thread(() -> {
File[] files = PluginUpdater.updatedir.listFiles();
if (files == null)
return;
logger.info("Updating " + files.length + " plugins...");
for (File file : files) {
try {
Files.move(file.toPath(), new File("plugins", file.getName()).toPath(), StandardCopyOption.REPLACE_EXISTING);
logger.info("Updated " + file.getName());
} catch (IOException e) {
e.printStackTrace();
}
}
logger.info("Update complete!");
}).start();
new Thread(() -> {
File[] files = PluginUpdater.updatedir.listFiles();
if (files == null)
return;
logger.info("Updating " + files.length + " plugins...");
for (File file : files) {
try {
Files.move(file.toPath(), new File("plugins", file.getName()).toPath(), StandardCopyOption.REPLACE_EXISTING);
logger.info("Updated " + file.getName());
} catch (IOException e) {
e.printStackTrace();
}
}
logger.info("Update complete!");
}).start();
}
private boolean setupPermissions() {

View file

@ -53,7 +53,7 @@ public class Channel {
*/
public final ConfigData<String> DisplayName() {
throwGame();
return component.getConfig().getData(ID + ".displayName", defDisplayName);
return component.getConfig().getData(ID + ".displayName", defDisplayName); //TODO: Use config map
}
public final ConfigData<Color> Color() {

View file

@ -54,9 +54,12 @@ public class MemberComponent extends Component<MainPlugin> implements Listener {
if (permission != null && !permission.playerInGroup(event.getPlayer(), memberGroup().get())
&& (new Date(event.getPlayer().getFirstPlayed()).toInstant().plus(registeredForDays().get(), ChronoUnit.DAYS).isBefore(Instant.now())
|| event.getPlayer().getStatistic(Statistic.PLAY_ONE_TICK) > 20 * 3600 * playedHours().get())) {
permission.playerAddGroup(null, event.getPlayer(), memberGroup().get());
event.getPlayer().sendMessage("§bYou are a member now. YEEHAW");
MainPlugin.Instance.getLogger().info("Added " + event.getPlayer().getName() + " as a member.");
if (permission.playerAddGroup(null, event.getPlayer(), memberGroup().get())) {
event.getPlayer().sendMessage("§bYou are a member now. YEEHAW");
MainPlugin.Instance.getLogger().info("Added " + event.getPlayer().getName() + " as a member.");
} else {
MainPlugin.Instance.getLogger().warning("Failed to assign the member role! Please make sure the member group exists or disable the component if it's unused.");
}
}
}
}

View file

@ -22,8 +22,9 @@ import java.util.List;
import java.util.Map.Entry;
public class TBMCCoreAPI {
static final List<String> coders = new ArrayList<String>() {
static final List<String> coders = new ArrayList<String>() {
private static final long serialVersionUID = -4462159250738367334L;
{
add("Alisolarflare");
add("NorbiPeti");
@ -35,11 +36,9 @@ public class TBMCCoreAPI {
/**
* Updates or installs the specified plugin. The plugin must use Maven.
*
* @param name
* The plugin's repository name.
* @param sender
* The command sender (if not console, messages will be printed to console as well).
*
* @param name The plugin's repository name.
* @param sender The command sender (if not console, messages will be printed to console as well).
*/
public static void UpdatePlugin(String name, CommandSender sender) {
UpdatePlugin(name, sender, "master");
@ -47,20 +46,17 @@ public class TBMCCoreAPI {
/**
* Updates or installs the specified plugin from the specified branch. The plugin must use Maven.
*
* @param name
* The plugin's repository name.
* @param sender
* The command sender (if not console, messages will be printed to console as well).
* @param branch
* The branch to download the plugin from.
*
* @param name The plugin's repository name.
* @param sender The command sender (if not console, messages will be printed to console as well).
* @param branch The branch to download the plugin from.
* @return Success or not
*/
public static boolean UpdatePlugin(String name, CommandSender sender, String branch) {
return PluginUpdater.UpdatePlugin(name, sender, branch);
}
public static String DownloadString(String urlstr) throws IOException {
public static String DownloadString(String urlstr) throws IOException {
URL url = new URL(urlstr);
URLConnection con = url.openConnection();
con.setRequestProperty("User-Agent", "TBMCPlugins");
@ -72,16 +68,14 @@ public class TBMCCoreAPI {
return body;
}
private static final HashMap<String, Throwable> exceptionsToSend = new HashMap<>();
private static final List<String> debugMessagesToSend = new ArrayList<>();
private static final HashMap<String, Throwable> exceptionsToSend = new HashMap<>();
private static final List<String> debugMessagesToSend = new ArrayList<>();
/**
* Send exception to the {@link TBMCExceptionEvent}.
*
* @param sourcemsg
* A message that is shown at the top of the exception (before the exception's message)
* @param e
* The exception to send
*
* @param sourcemsg A message that is shown at the top of the exception (before the exception's message)
* @param e The exception to send
*/
public static void SendException(String sourcemsg, Throwable e) {
SendException(sourcemsg, e, false);
@ -98,7 +92,7 @@ public class TBMCCoreAPI {
Bukkit.getLogger().warning(sourcemsg);
e.printStackTrace();
if (debugPotato) {
List<Player> devsOnline = new ArrayList<Player>();
List<Player> devsOnline = new ArrayList<>();
for (Player player : Bukkit.getOnlinePlayers()) {
if (coders.contains(player.getName())) {
devsOnline.add(player);
@ -106,14 +100,14 @@ public class TBMCCoreAPI {
}
if (!devsOnline.isEmpty()) {
DebugPotato potato = new DebugPotato()
.setMessage(new String[] { //
"§b§o" + e.getClass().getSimpleName(), //
"§c§o" + sourcemsg, //
"§a§oFind a dev to fix this issue" })
.setType(e instanceof IOException ? "Throwable Potato"
: e instanceof ClassCastException ? "Squished Potato"
: e instanceof NullPointerException ? "Plain Potato"
: e instanceof StackOverflowError ? "Chips" : "Error Potato");
.setMessage(new String[]{ //
"§b§o" + e.getClass().getSimpleName(), //
"§c§o" + sourcemsg, //
"§a§oFind a dev to fix this issue"})
.setType(e instanceof IOException ? "Throwable Potato"
: e instanceof ClassCastException ? "Squished Potato"
: e instanceof NullPointerException ? "Plain Potato"
: e instanceof StackOverflowError ? "Chips" : "Error Potato");
for (Player dev : devsOnline) {
potato.Send(dev);
}
@ -133,11 +127,9 @@ public class TBMCCoreAPI {
/**
* Registers Bukkit events, handling the exceptions occurring in those events
*
* @param listener
* The class that handles the events
* @param plugin
* The plugin which the listener belongs to
*
* @param listener The class that handles the events
* @param plugin The plugin which the listener belongs to
*/
public static void RegisterEventsForExceptions(Listener listener, Plugin plugin) {
EventExceptionHandler.registerEvents(listener, plugin, new EventExceptionCoreHandler());
@ -183,6 +175,7 @@ public class TBMCCoreAPI {
}
public static boolean IsTestServer() {
return MainPlugin.Test;
if (MainPlugin.Instance == null) return true;
return MainPlugin.Instance.test().get();
}
}

View file

@ -9,6 +9,11 @@ import lombok.Getter;
import lombok.experimental.var;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Optional;
import java.util.Stack;
@HasConfig
@ -47,6 +52,8 @@ public abstract class ButtonPlugin extends JavaPlugin {
} catch (Exception e) {
TBMCCoreAPI.SendException("Error while enabling plugin " + getName() + "!", e);
}
if (configGenAllowed(this)) //If it's not disabled (by default it's not)
IHaveConfig.pregenConfig(this, null);
}
private void loadConfig() {
@ -90,4 +97,15 @@ public abstract class ButtonPlugin extends JavaPlugin {
loaded = true; //Needed because for the first time it uses reloadConfig() to load it
return true;
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface ConfigOpts {
boolean disableConfigGen() default false;
}
public static boolean configGenAllowed(Object obj) {
return !Optional.ofNullable(obj.getClass().getAnnotation(ConfigOpts.class))
.map(ConfigOpts::disableConfigGen).orElse(false);
}
}

View file

@ -45,7 +45,7 @@ public abstract class Component<TP extends JavaPlugin> {
* Registers a component checking it's dependencies and calling {@link #register(JavaPlugin)}.<br>
* Make sure to register the dependencies first.<br>
* The component will be enabled automatically, regardless of when it was registered.<br>
* <b>If not using {@link ButtonPlugin}, call {@link ComponentManager#unregComponents(ButtonPlugin)} on plugin disable.</b>
* <b>If not using {@link ButtonPlugin}, call {@link ComponentManager#unregComponents(ButtonPlugin)} on plugin disable.</b>
*
* @param component The component to register
* @return Whether the component is registered successfully (it may have failed to enable)
@ -57,7 +57,7 @@ public abstract class Component<TP extends JavaPlugin> {
/**
* Unregisters a component by calling {@link #unregister(JavaPlugin)}.<br>
* Make sure to unregister the dependencies last.<br>
* <b>Components will be unregistered in opposite order of registering by default by {@link ButtonPlugin} or {@link ComponentManager#unregComponents(ButtonPlugin)}.</b>
* <b>Components will be unregistered in opposite order of registering by default by {@link ButtonPlugin} or {@link ComponentManager#unregComponents(ButtonPlugin)}.</b>
*
* @param component The component to unregister
* @return Whether the component is unregistered successfully (it also got disabled)
@ -133,6 +133,8 @@ public abstract class Component<TP extends JavaPlugin> {
if (component.enabled = enabled) {
updateConfig(component.getPlugin(), component);
component.enable();
if (ButtonPlugin.configGenAllowed(component))
IHaveConfig.pregenConfig(component, null);
} else {
component.disable();
component.plugin.saveConfig();
@ -192,7 +194,7 @@ public abstract class Component<TP extends JavaPlugin> {
/**
* Disables the module, when called by the JavaPlugin class. Do
* any cleanups needed within this method.
* To access the plugin, use {@link #getPlugin()}.
* To access the plugin, use {@link #getPlugin()}.
*/
protected abstract void disable();
@ -228,14 +230,15 @@ public abstract class Component<TP extends JavaPlugin> {
/**
* Returns a map of configs that are under the given key.
* @param key The key to use
*
* @param key The key to use
* @param defaultProvider A mapping between config paths and config generators
* @return A map containing configs
*/
protected Map<String, IHaveConfig> getConfigMap(String key, Map<String, Consumer<IHaveConfig>> defaultProvider) {
val c=getConfig().getConfig();
var cs=c.getConfigurationSection(key);
if(cs==null) cs=c.createSection(key);
val c = getConfig().getConfig();
var cs = c.getConfigurationSection(key);
if (cs == null) cs = c.createSection(key);
val res = cs.getValues(false).entrySet().stream().filter(e -> e.getValue() instanceof ConfigurationSection)
.collect(Collectors.toMap(Map.Entry::getKey, kv -> new IHaveConfig((ConfigurationSection) kv.getValue(), getPlugin()::saveConfig)));
if (res.size() == 0) {

View file

@ -4,7 +4,8 @@ import buttondevteam.core.MainPlugin;
import buttondevteam.lib.ThorpeUtils;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.Bukkit;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.ConfigurationSection;
@ -19,9 +20,8 @@ import java.util.function.Function;
/**
* Use the getter/setter constructor if {@link T} isn't a primitive type or String.<br>
* Use {@link Component#getConfig()} or {@link ButtonPlugin#getIConfig()} then {@link IHaveConfig#getData(String, Object)} to get an instance.
* Use {@link Component#getConfig()} or {@link ButtonPlugin#getIConfig()} then {@link IHaveConfig#getData(String, Object)} to get an instance.
*/
@RequiredArgsConstructor(access = AccessLevel.PACKAGE)
//@AllArgsConstructor(access = AccessLevel.PACKAGE)
public class ConfigData<T> {
private static final HashMap<Configuration, SaveTask> saveTasks = new HashMap<>();
@ -29,7 +29,9 @@ public class ConfigData<T> {
* May be null for testing
*/
private final ConfigurationSection config;
private final String path;
@Getter
@Setter(AccessLevel.PACKAGE)
private String path;
private final T def;
private final Object primitiveDef;
private final Runnable saveAction;
@ -52,14 +54,23 @@ public class ConfigData<T> {
private boolean saved = false;
//This constructor is needed because it sets the getter and setter
public ConfigData(ConfigurationSection config, String path, T def, Object primitiveDef, Function<Object, T> getter, Function<T, Object> setter, Runnable saveAction) {
ConfigData(ConfigurationSection config, String path, T def, Object primitiveDef, Function<Object, T> getter, Function<T, Object> setter, Runnable saveAction) {
this.config = config;
this.path = path;
this.def = def;
this.primitiveDef = primitiveDef;
this.getter = getter;
this.setter = setter;
this.saveAction=saveAction;
this.saveAction = saveAction;
}
@java.beans.ConstructorProperties({"config", "path", "def", "primitiveDef", "saveAction"})
ConfigData(ConfigurationSection config, String path, T def, Object primitiveDef, Runnable saveAction) {
this.config = config;
this.path = path;
this.def = def;
this.primitiveDef = primitiveDef;
this.saveAction = saveAction;
}
@Override
@ -98,13 +109,15 @@ public class ConfigData<T> {
}
public void set(T value) {
if (this instanceof ReadOnlyConfigData)
return; //Safety for Discord channel/role data
Object val;
if (setter != null && value != null)
val = setter.apply(value);
else val = value;
if (config != null) {
config.set(path, val);
if(!saveTasks.containsKey(config.getRoot())) {
if (!saveTasks.containsKey(config.getRoot())) {
synchronized (saveTasks) {
saveTasks.put(config.getRoot(), new SaveTask(Bukkit.getScheduler().runTaskLaterAsynchronously(MainPlugin.Instance, () -> {
synchronized (saveTasks) {

View file

@ -1,14 +1,17 @@
package buttondevteam.lib.architecture;
import buttondevteam.core.MainPlugin;
import buttondevteam.lib.TBMCCoreAPI;
import lombok.Getter;
import lombok.val;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import java.util.HashMap;
import javax.annotation.Nullable;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* A config system
@ -26,7 +29,7 @@ public final class IHaveConfig {
*/
IHaveConfig(ConfigurationSection section, Runnable saveAction) {
config = section;
this.saveAction=saveAction;
this.saveAction = saveAction;
}
/**
@ -65,11 +68,11 @@ public final class IHaveConfig {
/**
* This method overload may be used with any class. The given default value will be run through the getter.
*
* @param path The path in config to use
* @param primitiveDef The <b>primitive</b> value to use by default
* @param getter A function that converts a primitive representation to the correct value
* @param setter A function that converts a value to a primitive representation
* @param <T> The type of this variable (can be any class)
* @param path The path in config to use
* @param primitiveDef The <b>primitive</b> value to use by default
* @param getter A function that converts a primitive representation to the correct value
* @param setter A function that converts a value to a primitive representation
* @param <T> The type of this variable (can be any class)
* @return The data object that can be used to get or set the value
*/
@SuppressWarnings("unchecked")
@ -80,6 +83,24 @@ public final class IHaveConfig {
return (ConfigData<T>) data;
}
/**
* This method overload may be used with any class. The given default value will be run through the getter.
*
* @param path The path in config to use
* @param primitiveDef The <b>primitive</b> value to use by default
* @param getter A function that converts a primitive representation to the correct value
* @param setter A function that converts a value to a primitive representation
* @param <T> The type of this variable (can be any class)
* @return The data object that can be used to get or set the value
*/
@SuppressWarnings("unchecked")
public <T> ReadOnlyConfigData<T> getReadOnlyDataPrimDef(String path, Object primitiveDef, Function<Object, T> getter, Function<T, Object> setter) {
ConfigData<?> data = datamap.get(path);
if (data == null)
datamap.put(path, data = new ReadOnlyConfigData<>(config, path, getter.apply(primitiveDef), primitiveDef, getter, setter, saveAction));
return (ReadOnlyConfigData<T>) data;
}
/**
* This method overload should only be used with primitves or String.
*
@ -117,4 +138,47 @@ public final class IHaveConfig {
}
return (ConfigData<T>) data;
}
/**
* Generates the config YAML.
*
* @param obj The object which has config methods
* @param configMap The result from {@link Component#getConfigMap(String, Map)}. May be null.
*/
public static void pregenConfig(Object obj, @Nullable Map<String, IHaveConfig> configMap) {
val ms = obj.getClass().getDeclaredMethods();
for (val m : ms) {
if (!m.getReturnType().getName().equals(ConfigData.class.getName())) continue;
try {
m.setAccessible(true);
List<ConfigData<?>> configList;
if (m.getParameterCount() == 0) {
configList = Collections.singletonList((ConfigData<?>) m.invoke(obj));
} else if (m.getParameterCount() == 1 && m.getParameterTypes()[0] == IHaveConfig.class) {
if (configMap == null) continue; //Hope it will get called with the param later
configList = configMap.entrySet().stream().map(kv ->
{
try {
return (ConfigData<?>) m.invoke(obj, kv.getValue());
} catch (IllegalAccessException | InvocationTargetException e) {
TBMCCoreAPI.SendException("Failed to pregenerate " + m.getName() + " for " + obj + " using config " + kv.getKey() + "!", e);
return null;
}
}).filter(Objects::nonNull).collect(Collectors.toList());
} else {
MainPlugin.Instance.getLogger().warning("Method " + m.getName() + " returns a config but its parameters are unknown: " + Arrays.toString(m.getParameterTypes()));
continue;
}
for (val c : configList) {
if (c.getPath().length() == 0)
c.setPath(m.getName());
else if (!c.getPath().equals(m.getName()))
MainPlugin.Instance.getLogger().warning("Config name does not match: " + c.getPath() + " instead of " + m.getName());
c.get(); //Saves the default value if needed - also checks validity
}
} catch (Exception e) {
TBMCCoreAPI.SendException("Failed to pregenerate " + m.getName() + " for " + obj + "!", e);
}
}
}
}

View file

@ -0,0 +1,15 @@
package buttondevteam.lib.architecture;
import org.bukkit.configuration.ConfigurationSection;
import java.util.function.Function;
public class ReadOnlyConfigData<T> extends ConfigData<T> {
ReadOnlyConfigData(ConfigurationSection config, String path, T def, Object primitiveDef, Function<Object, T> getter, Function<T, Object> setter, Runnable saveAction) {
super(config, path, def, primitiveDef, getter, setter, saveAction);
}
ReadOnlyConfigData(ConfigurationSection config, String path, T def, Object primitiveDef, Runnable saveAction) {
super(config, path, def, primitiveDef, saveAction);
}
}

View file

@ -1,5 +1,6 @@
package buttondevteam.lib.chat;
import buttondevteam.core.MainPlugin;
import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.ThorpeUtils;
import buttondevteam.lib.player.ChromaGamerBase;
@ -9,7 +10,9 @@ import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.experimental.var;
import lombok.val;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.scheduler.BukkitTask;
import java.io.InputStreamReader;
import java.lang.annotation.ElementType;
@ -20,9 +23,7 @@ import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.*;
import java.util.function.Function;
/**
@ -48,10 +49,21 @@ public abstract class Command2<TC extends ICommand2, TP extends Command2Sender>
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Subcommand {
/**
* Allowed for OPs only by default
*/
String MOD_GROUP = "mod";
/**
* Help text to show players. A usage message will be also shown below it.
*/
String[] helpText() default {};
/**
* The main permission which allows using this command (individual access can be still granted with "thorpe.command.X").
* Used to be "tbmc.admin". The {@link #MOD_GROUP} is provided to use with this.
*/
String permGroup() default ""; //TODO
}
@Target(ElementType.PARAMETER)
@ -66,6 +78,31 @@ public abstract class Command2<TC extends ICommand2, TP extends Command2Sender>
public String[] helpText;
}
protected static class SubcommandHelpData<T extends ICommand2> extends SubcommandData<T> {
private final TreeSet<String> ht = new TreeSet<>();
private BukkitTask task;
public SubcommandHelpData(Method method, T command, String[] helpText) {
super(method, command, helpText);
}
public void addSubcommand(String command) {
ht.add(command);
if (task == null)
task = Bukkit.getScheduler().runTask(MainPlugin.Instance, () -> {
helpText = new String[ht.size() + 1]; //This will only run after the server is started List<E> list = new ArrayList<E>(size());
helpText[0] = "§6---- Subcommands ----"; //TODO: There may be more to the help text
int i = 1;
for (Iterator<String> iterator = ht.iterator();
iterator.hasNext() && i < helpText.length; i++) {
String e = iterator.next();
helpText[i] = e;
}
task = null; //Run again, if needed
});
}
}
@RequiredArgsConstructor
protected static class ParamConverter<T> {
public final Function<String, T> converter;
@ -98,7 +135,7 @@ public abstract class Command2<TC extends ICommand2, TP extends Command2Sender>
sender.sendMessage(sd.helpText);
return true;
}
if (!hasPermission(sender, sd.command)) {
if (!hasPermission(sender, sd.command, sd.method)) {
sender.sendMessage("§cYou don't have permission to use this command");
return true;
}
@ -155,10 +192,8 @@ public abstract class Command2<TC extends ICommand2, TP extends Command2Sender>
continue;
} else if (Number.class.isAssignableFrom(cl) || cl.isPrimitive()) {
try {
//System.out.println("Converting "+param+" param to "+cl.getSimpleName());
//noinspection unchecked
Number n = ThorpeUtils.convertNumber(NumberFormat.getInstance().parse(param), (Class<? extends Number>) cl);
//System.out.println(n.getClass().getSimpleName()+" with value "+n);
params.add(n);
} catch (ParseException e) {
sender.sendMessage("§c'" + param + "' is not a number.");
@ -176,7 +211,6 @@ public abstract class Command2<TC extends ICommand2, TP extends Command2Sender>
}
params.add(cparam);
}
//System.out.println("Our params: "+params);
try {
val ret = sd.method.invoke(sd.command, params.toArray()); //I FORGOT TO TURN IT INTO AN ARRAY (for a long time)
if (ret instanceof Boolean) {
@ -276,7 +310,7 @@ public abstract class Command2<TC extends ICommand2, TP extends Command2Sender>
return ht;
}
public abstract boolean hasPermission(TP sender, TC command);
public abstract boolean hasPermission(TP sender, TC command, Method subcommand);
public String[] getCommandsText() {
return commandHelp.toArray(new String[0]);

View file

@ -1,21 +1,60 @@
package buttondevteam.lib.chat;
import buttondevteam.core.MainPlugin;
import lombok.experimental.var;
import lombok.val;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.UUID;
import java.util.function.Function;
public class Command2MC extends Command2<ICommand2MC, Command2MCSender> {
@Override
public void registerCommand(ICommand2MC command) {
super.registerCommand(command, '/');
var perm = "thorpe.command." + command.getCommandPath().replace(' ', '.');
if (Bukkit.getPluginManager().getPermission(perm) == null) //Check needed for plugin reset
Bukkit.getPluginManager().addPermission(new Permission(perm,
modOnly(command) ? PermissionDefault.OP : PermissionDefault.TRUE)); //Allow commands by default, unless it's mod only - TODO: Test
for (val method : command.getClass().getMethods()) {
if (!method.isAnnotationPresent(Subcommand.class)) continue;
String pg = permGroup(command, method);
if (pg.length() == 0) continue;
perm = "thorpe." + pg;
if (Bukkit.getPluginManager().getPermission(perm) == null) //It may occur multiple times
Bukkit.getPluginManager().addPermission(new Permission(perm,
//pg.equals(Subcommand.MOD_GROUP) ? PermissionDefault.OP : PermissionDefault.TRUE)); //Allow commands by default, unless it's mod only
PermissionDefault.OP)); //Do not allow any commands that belong to a group
}
}
@Override
public boolean hasPermission(Command2MCSender sender, ICommand2MC command) {
return modOnly(command)
? MainPlugin.permission.has(sender.getSender(), "tbmc.admin") //TODO: Change when groups are implemented
: MainPlugin.permission.has(sender.getSender(), "thorpe.command." + command.getCommandPath().replace(' ', '.'));
public boolean hasPermission(Command2MCSender sender, ICommand2MC command, Method method) {
if (sender.getSender() instanceof ConsoleCommandSender) return true; //Always allow the console
String pg;
boolean p = true;
String[] perms = {
"thorpe.command." + command.getCommandPath().replace(' ', '.'),
(pg = permGroup(command, method)).length() > 0 ? "thorpe." + pg : null,
modOnly(command) ? "tbmc.admin" : null
};
for (String perm : perms) {
if (perm != null) {
if (p) { //Use OfflinePlayer to avoid fetching player data
if (sender.getSender() instanceof OfflinePlayer)
p = MainPlugin.permission.playerHas(null, (OfflinePlayer) sender.getSender(), perm);
else
p = MainPlugin.permission.playerHas(null, Bukkit.getOfflinePlayer(new UUID(0, 0)), perm);
} else break; //If any of the permissions aren't granted then don't allow
}
}
return p;
}
/**
@ -25,11 +64,41 @@ public class Command2MC extends Command2<ICommand2MC, Command2MCSender> {
* @return Whether the command is mod only
*/
private boolean modOnly(ICommand2MC command) {
for (Class<?> cl = command.getClass(); cl != null; cl = cl.getSuperclass()) {
val cc = command.getClass().getAnnotation(CommandClass.class);
if (cc != null && cc.modOnly()) return true;
return getAnnForValue(command.getClass(), CommandClass.class, CommandClass::modOnly, false);
}
/**
* Returns true if this class or <u>any</u> of the superclasses are mod only.
*
* @param method The subcommand to check
* @return The permission group for the subcommand or empty string
*/
private String permGroup(ICommand2MC command, Method method) {
val sc = method.getAnnotation(Subcommand.class);
if (sc != null && sc.permGroup().length() > 0) {
return sc.permGroup();
}
return false;
return getAnnForValue(command.getClass(), CommandClass.class, CommandClass::permGroup, "");
}
/**
* Loops until it finds a value that is <b>not</b> the same as def
*
* @param sourceCl The class which has the annotation
* @param annCl The annotation to get
* @param annMethod The annotation method to check
* @param def The value to ignore when looking for the result
* @param <T> The annotation type
* @param <V> The type of the value
* @return The value returned by the first superclass or def
*/
private <T extends Annotation, V> V getAnnForValue(Class<?> sourceCl, Class<T> annCl, Function<T, V> annMethod, V def) {
for (Class<?> cl = sourceCl; cl != null; cl = cl.getSuperclass()) {
val cc = cl.getAnnotation(annCl);
V r;
if (cc != null && (r = annMethod.apply(cc)) != def) return r;
}
return def;
}
/**

View file

@ -44,4 +44,10 @@ public @interface CommandClass {
* @return The help text
*/
String[] helpText() default {};
/**
* The main permission which allows using this command (individual access can be still granted with "thorpe.command.X").
* Used to be "tbmc.admin"
*/
String permGroup() default ""; //TODO: A single annotation instead of these two
}

View file

@ -2,7 +2,7 @@ package buttondevteam.lib.chat;
import buttondevteam.lib.architecture.ButtonPlugin;
public class ICommand2MC extends ICommand2<Command2MCSender> {
public abstract class ICommand2MC extends ICommand2<Command2MCSender> {
public ICommand2MC() {
super(ButtonPlugin.getCommand2MC());
}

View file

@ -1,43 +1,78 @@
package buttondevteam.buttonproc;
import org.bukkit.configuration.file.YamlConfiguration;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.tools.FileObject;
import javax.tools.StandardLocation;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class ConfigProcessor {
private final ProcessingEnvironment procEnv;
private final YamlConfiguration yaml;
private final File file;
private final FileWriter sw;
public ConfigProcessor(ProcessingEnvironment procEnv) {
this.procEnv = procEnv;
FileObject file = null;
FileWriter sw = null;
try {
file = procEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", "config.yml");
FileObject file = procEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", "configHelp.md");
sw = new FileWriter(new File(file.toUri()));
System.out.println(file.toUri());
} catch (IOException e) {
e.printStackTrace();
}
yaml = new YamlConfiguration();
this.file = new File(file.toUri());
this.sw = sw;
}
public void process(Element targetcl) {
if (targetcl.getModifiers().contains(Modifier.ABSTRACT)) return;
final String path = "components." + targetcl.getSimpleName();
for (Element e : targetcl.getEnclosedElements()) {
/*System.out.println("Element: "+e);
System.out.println("Type: "+e.getClass()+" - "+e.getKind());
if(e instanceof ExecutableElement)
System.out.println("METHOD!");*/
if (!(e instanceof ExecutableElement)) continue;
TypeMirror tm = ((ExecutableElement) e).getReturnType();
if (tm.getKind() != TypeKind.DECLARED) continue;
DeclaredType dt = (DeclaredType) tm;
if (!dt.asElement().getSimpleName().contentEquals("ConfigData"))
continue; //Ahhha! There was a return here! (MinecraftChatModule getListener())
System.out.println("Config: " + e.getSimpleName());
String doc = procEnv.getElementUtils().getDocComment(e);
if (doc == null) continue;
System.out.println("DOC: " + doc);
try {
sw.append(path).append(".").append(String.valueOf(e.getSimpleName())).append(System.lineSeparator()).append(System.lineSeparator());
sw.append(doc.trim()).append(System.lineSeparator()).append(System.lineSeparator());
} catch (IOException e1) {
e1.printStackTrace();
}
}
String javadoc = procEnv.getElementUtils().getDocComment(targetcl);
if (javadoc == null) return;
System.out.println("JAVADOC"); //TODO: Config methods
System.out.println(javadoc);
yaml.set("components." + targetcl.getSimpleName() + "._doc", javadoc);
try {
yaml.save(file);
if (javadoc != null) {
System.out.println("JAVADOC");
System.out.println(javadoc.trim());
sw.append(path).append(System.lineSeparator()).append(System.lineSeparator());
sw.append(javadoc).append(System.lineSeparator()).append(System.lineSeparator());
}
sw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void finalize() throws Throwable {
sw.close();
super.finalize();
}
}