Stop using methods for configs

This commit is contained in:
Norbi Peti 2020-10-26 17:44:11 +01:00
parent 267a350473
commit 51e0ca4f4c
No known key found for this signature in database
GPG key ID: DBA4C4549A927E56
17 changed files with 213 additions and 233 deletions

View file

@ -80,7 +80,7 @@ public class ComponentCommand extends ICommand2MC {
return true; return true;
Component.setComponentEnabled(oc.get(), enable); Component.setComponentEnabled(oc.get(), enable);
if (permanent) if (permanent)
oc.get().shouldBeEnabled().set(enable); oc.get().shouldBeEnabled.set(enable);
sender.sendMessage(oc.get().getClass().getSimpleName() + " " + (enable ? "en" : "dis") + "abled " + (permanent ? "permanently" : "temporarily") + "."); sender.sendMessage(oc.get().getClass().getSimpleName() + " " + (enable ? "en" : "dis") + "abled " + (permanent ? "permanently" : "temporarily") + ".");
} catch (Exception e) { } catch (Exception e) {
TBMCCoreAPI.SendException("Couldn't " + (enable ? "en" : "dis") + "able component " + component + "!", e, (JavaPlugin) plugin); TBMCCoreAPI.SendException("Couldn't " + (enable ? "en" : "dis") + "able component " + component + "!", e, (JavaPlugin) plugin);

View file

@ -21,7 +21,7 @@ public final class ComponentManager {
*/ */
public static void enableComponents() { public static void enableComponents() {
//Component.getComponents().values().stream().filter(c->cs.getConfigurationSection(c.getClass().getSimpleName()).getBoolean("enabled")).forEach(c-> { //Component.getComponents().values().stream().filter(c->cs.getConfigurationSection(c.getClass().getSimpleName()).getBoolean("enabled")).forEach(c-> {
Component.getComponents().values().stream().filter(c -> c.shouldBeEnabled().get()).forEach(c -> { Component.getComponents().values().stream().filter(c -> c.shouldBeEnabled.get()).forEach(c -> {
try { try {
Component.setComponentEnabled(c, true); Component.setComponentEnabled(c, true);
} catch (Exception | NoClassDefFoundError e) { } catch (Exception | NoClassDefFoundError e) {

View file

@ -65,31 +65,23 @@ public class MainPlugin extends ButtonPlugin {
* Sets whether the plugin should write a list of installed plugins in a txt file. * Sets whether the plugin should write a list of installed plugins in a txt file.
* It can be useful if some other software needs to know the plugins. * It can be useful if some other software needs to know the plugins.
*/ */
private ConfigData<Boolean> writePluginList() { private final ConfigData<Boolean> writePluginList = getIConfig().getData("writePluginList", false);
return getIConfig().getData("writePluginList", false);
}
/** /**
* The chat format to use for messages from other platforms if Chroma-Chat is not installed. * The chat format to use for messages from other platforms if Chroma-Chat is not installed.
*/ */
ConfigData<String> chatFormat() { ConfigData<String> chatFormat = getIConfig().getData("chatFormat", "[{origin}|" +
return getIConfig().getData("chatFormat", "[{origin}|" + "{channel}] <{name}> {message}");
"{channel}] <{name}> {message}");
}
/** /**
* Print some debug information. * Print some debug information.
*/ */
public ConfigData<Boolean> test() { public final ConfigData<Boolean> test = getIConfig().getData("test", false);
return getIConfig().getData("test", false);
}
/** /**
* If a Chroma command clashes with another plugin's command, this setting determines whether the Chroma command should be executed or the other plugin's. * If a Chroma command clashes with another plugin's command, this setting determines whether the Chroma command should be executed or the other plugin's.
*/ */
public ConfigData<Boolean> prioritizeCustomCommands() { public final ConfigData<Boolean> prioritizeCustomCommands = getIConfig().getData("prioritizeCustomCommands", false);
return getIConfig().getData("prioritizeCustomCommands", false);
}
@Override @Override
public void pluginEnable() { public void pluginEnable() {
@ -103,7 +95,6 @@ public class MainPlugin extends ButtonPlugin {
getLogger().warning("No economy plugin found! Components using economy will not be registered."); getLogger().warning("No economy plugin found! Components using economy will not be registered.");
saveConfig(); saveConfig();
Component.registerComponent(this, new RestartComponent()); Component.registerComponent(this, new RestartComponent());
//noinspection unchecked - needed for testing
Component.registerComponent(this, new ChannelComponent()); Component.registerComponent(this, new ChannelComponent());
Component.registerComponent(this, new RandomTPComponent()); Component.registerComponent(this, new RandomTPComponent());
Component.registerComponent(this, new MemberComponent()); Component.registerComponent(this, new MemberComponent());
@ -138,7 +129,7 @@ public class MainPlugin extends ButtonPlugin {
Supplier<Iterable<String>> playerSupplier = () -> Bukkit.getOnlinePlayers().stream().map(HumanEntity::getName)::iterator; Supplier<Iterable<String>> playerSupplier = () -> Bukkit.getOnlinePlayers().stream().map(HumanEntity::getName)::iterator;
getCommand2MC().addParamConverter(OfflinePlayer.class, Bukkit::getOfflinePlayer, "Player not found!", playerSupplier); getCommand2MC().addParamConverter(OfflinePlayer.class, Bukkit::getOfflinePlayer, "Player not found!", playerSupplier);
getCommand2MC().addParamConverter(Player.class, Bukkit::getPlayer, "Online player not found!", playerSupplier); getCommand2MC().addParamConverter(Player.class, Bukkit::getPlayer, "Online player not found!", playerSupplier);
if (writePluginList().get()) { if (writePluginList.get()) {
try { try {
Files.write(new File("plugins", "plugins.txt").toPath(), Arrays.stream(Bukkit.getPluginManager().getPlugins()).map(p -> (CharSequence) p.getDataFolder().getName())::iterator); Files.write(new File("plugins", "plugins.txt").toPath(), Arrays.stream(Bukkit.getPluginManager().getPlugins()).map(p -> (CharSequence) p.getDataFolder().getName())::iterator);
} catch (IOException e) { } catch (IOException e) {
@ -147,7 +138,7 @@ public class MainPlugin extends ButtonPlugin {
} }
if (getServer().getPluginManager().isPluginEnabled("Essentials")) if (getServer().getPluginManager().isPluginEnabled("Essentials"))
ess = Essentials.getPlugin(Essentials.class); ess = Essentials.getPlugin(Essentials.class);
logger.info(pdf.getName() + " has been Enabled (V." + pdf.getVersion() + ") Test: " + test().get() + "."); logger.info(pdf.getName() + " has been Enabled (V." + pdf.getVersion() + ") Test: " + test.get() + ".");
} }
@Override @Override

View file

@ -31,13 +31,13 @@ public class PlayerListener implements Listener {
public void OnPlayerJoin(PlayerJoinEvent event) { public void OnPlayerJoin(PlayerJoinEvent event) {
var p = event.getPlayer(); var p = event.getPlayer();
TBMCPlayer player = TBMCPlayerBase.getPlayer(p.getUniqueId(), TBMCPlayer.class); TBMCPlayer player = TBMCPlayerBase.getPlayer(p.getUniqueId(), TBMCPlayer.class);
if (player.PlayerName().get() == null) { if (player.PlayerName.get() == null) {
player.PlayerName().set(p.getName()); player.PlayerName.set(p.getName());
MainPlugin.Instance.getLogger().info("Player name saved: " + player.PlayerName().get()); MainPlugin.Instance.getLogger().info("Player name saved: " + player.PlayerName.get());
} else if (!p.getName().equals(player.PlayerName().get())) { } else if (!p.getName().equals(player.PlayerName.get())) {
TownyComponent.renameInTowny(player.PlayerName().get(), p.getName()); TownyComponent.renameInTowny(player.PlayerName.get(), p.getName());
MainPlugin.Instance.getLogger().info(player.PlayerName().get() + " renamed to " + p.getName()); MainPlugin.Instance.getLogger().info(player.PlayerName.get() + " renamed to " + p.getName());
player.PlayerName().set(p.getName()); player.PlayerName.set(p.getName());
} }
} }
@ -53,7 +53,7 @@ public class PlayerListener implements Listener {
if (Arrays.stream(event.getExceptions()).anyMatch("Minecraft"::equalsIgnoreCase)) if (Arrays.stream(event.getExceptions()).anyMatch("Minecraft"::equalsIgnoreCase))
return; return;
Bukkit.getOnlinePlayers().stream().filter(event::shouldSendTo) Bukkit.getOnlinePlayers().stream().filter(event::shouldSendTo)
.forEach(p -> p.sendMessage(event.getChannel().DisplayName().get().substring(0, 2) + event.getMessage())); .forEach(p -> p.sendMessage(event.getChannel().DisplayName.get().substring(0, 2) + event.getMessage()));
} }
@EventHandler @EventHandler
@ -108,11 +108,11 @@ public class PlayerListener implements Listener {
if (!MainPlugin.Instance.isChatHandlerEnabled()) return; if (!MainPlugin.Instance.isChatHandlerEnabled()) return;
if (event.getOrigin().equals("Minecraft")) return; //Let other plugins handle MC messages if (event.getOrigin().equals("Minecraft")) return; //Let other plugins handle MC messages
var channel = event.getChannel(); var channel = event.getChannel();
String msg = MainPlugin.Instance.chatFormat().get() String msg = MainPlugin.Instance.chatFormat.get()
.replace("{channel}", channel.DisplayName().get()) .replace("{channel}", channel.DisplayName.get())
.replace("{origin}", event.getOrigin().substring(0, 1)) .replace("{origin}", event.getOrigin().substring(0, 1))
.replace("{name}", ChromaUtils.getDisplayName(event.getSender())) .replace("{name}", ChromaUtils.getDisplayName(event.getSender()))
.replace("{message}", String.format("§%x%s", channel.Color().get().ordinal(), event.getMessage())); .replace("{message}", String.format("§%x%s", channel.Color.get().ordinal(), event.getMessage()));
for (Player player : Bukkit.getOnlinePlayers()) for (Player player : Bukkit.getOnlinePlayers())
if (event.shouldSendTo(player)) if (event.shouldSendTo(player))
player.sendMessage(msg); player.sendMessage(msg);

View file

@ -44,7 +44,6 @@ public class TestPrepare {
return cl.isAssignableFrom(invocation.getMethod().getReturnType()); return cl.isAssignableFrom(invocation.getMethod().getReturnType());
} }
})); }));
//noinspection unchecked
Component.registerComponent(Mockito.mock(JavaPlugin.class), new ChannelComponent()); Component.registerComponent(Mockito.mock(JavaPlugin.class), new ChannelComponent());
TBMCChatAPI.RegisterChatChannel(Channel.GlobalChat = new Channel("§fg§f", Color.White, "g", null)); TBMCChatAPI.RegisterChatChannel(Channel.GlobalChat = new Channel("§fg§f", Color.White, "g", null));
} }

View file

@ -4,6 +4,7 @@ import buttondevteam.core.ComponentManager;
import buttondevteam.core.MainPlugin; import buttondevteam.core.MainPlugin;
import buttondevteam.lib.architecture.Component; import buttondevteam.lib.architecture.Component;
import buttondevteam.lib.architecture.ConfigData; import buttondevteam.lib.architecture.ConfigData;
import buttondevteam.lib.architecture.IHaveConfig;
import buttondevteam.lib.chat.Color; import buttondevteam.lib.chat.Color;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
@ -20,127 +21,135 @@ import java.util.function.Function;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.stream.Stream; import java.util.stream.Stream;
/**
* Represents a chat channel. May only be instantiated after the channel component is registered.
*/
public class Channel { public class Channel {
/** /**
* Specifies a score that means it's OK to send - but it does not define any groups, only send or not send. See {@link #GROUP_EVERYONE} * Specifies a score that means it's OK to send - but it does not define any groups, only send or not send. See {@link #GROUP_EVERYONE}
*/ */
public static final int SCORE_SEND_OK = 0; public static final int SCORE_SEND_OK = 0;
/** /**
* Specifies a score that means the user doesn't have permission to see or send the message. Any negative value has the same effect. * Specifies a score that means the user doesn't have permission to see or send the message. Any negative value has the same effect.
*/ */
public static final int SCORE_SEND_NOPE = -1; public static final int SCORE_SEND_NOPE = -1;
/** /**
* Send the message to everyone <i>who has access to the channel</i> - this does not necessarily mean all players * Send the message to everyone <i>who has access to the channel</i> - this does not necessarily mean all players
*/ */
public static final String GROUP_EVERYONE = "everyone"; public static final String GROUP_EVERYONE = "everyone";
private static ChannelComponent component; private static ChannelComponent component;
private String defDisplayName; private String defDisplayName;
private Color defColor; private Color defColor;
private void throwGame() { private IHaveConfig config;
if (component == null) throw new RuntimeException("Cannot access channel properties until registered!");
}
public final ConfigData<Boolean> Enabled() { public final ConfigData<Boolean> Enabled;
throwGame();
return component.getConfig().getData(ID + ".enabled", true);
}
/** /**
* Must start with a color code * Must start with a color code
*/ */
public final ConfigData<String> DisplayName() { public final ConfigData<String> DisplayName;
throwGame();
return component.getConfig().getData(ID + ".displayName", defDisplayName); //TODO: Use config map public final ConfigData<Color> Color;
public final String ID;
public ConfigData<String[]> IDs;
/**
* Filters both the sender and the targets
*/
private final Function<CommandSender, RecipientTestResult> filteranderrormsg;
private static final List<Channel> channels = new ArrayList<>();
/**
* Creates a channel.
*
* @param displayname The name that should appear at the start of the message. <b>A chat color is expected at the beginning (§9).</b>
* @param color The default color of the messages sent in the channel
* @param command The command to be used for the channel <i>without /</i>. For example "mod". It's also used for scoreboard objective names.
* @param filteranderrormsg Checks all senders against the criteria provided here and sends the message if the index matches the sender's - if no score at all, displays the error.<br>
* May be null to send to everyone.
*/
public Channel(String displayname, Color color, String command,
Function<CommandSender, RecipientTestResult> filteranderrormsg) {
defDisplayName = displayname;
defColor = color;
ID = command;
this.filteranderrormsg = filteranderrormsg;
init();
Enabled = component.getConfig().getData(ID + ".enabled", true);
DisplayName = component.getConfig().getData(ID + ".displayName", defDisplayName);
Color = component.getConfig().getData(ID + ".color", defColor, c -> buttondevteam.lib.chat.Color.valueOf((String) c), Enum::toString);
//noinspection unchecked
IDs = component.getConfig().getData(ID + ".IDs", new String[0], l -> ((List<String>) l).toArray(new String[0]), Lists::newArrayList);
} }
public final ConfigData<Color> Color() { /**
throwGame(); * Must be only called from a subclass - otherwise it'll throw an exception.
return component.getConfig().getData(ID + ".color", defColor, c -> Color.valueOf((String) c), Enum::toString); *
} * @see Channel#Channel(String, Color, String, Function)
public final String ID; */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public ConfigData<String[]> IDs() { protected <T extends Channel> Channel(String displayname, Color color, String command,
throwGame(); BiFunction<T, CommandSender, RecipientTestResult> filteranderrormsg) {
return component.getConfig().getData(ID + ".IDs", new String[0], l -> ((List<String>) l).toArray(new String[0]), Lists::newArrayList); defDisplayName = displayname;
defColor = color;
ID = command;
this.filteranderrormsg = s -> filteranderrormsg.apply((T) this, s);
init();
Enabled = component.getConfig().getData(ID + ".enabled", true);
DisplayName = component.getConfig().getData(ID + ".displayName", defDisplayName);
Color = component.getConfig().getData(ID + ".color", defColor, c -> buttondevteam.lib.chat.Color.valueOf((String) c), Enum::toString);
//noinspection unchecked
IDs = component.getConfig().getData(ID + ".IDs", new String[0], l -> ((List<String>) l).toArray(new String[0]), Lists::newArrayList);
} }
/**
* Filters both the sender and the targets
*/
private final Function<CommandSender, RecipientTestResult> filteranderrormsg;
private static final List<Channel> channels = new ArrayList<>(); private static void init() {
if (component == null)
component = (ChannelComponent) Component.getComponents().get(ChannelComponent.class);
if (component == null)
throw new RuntimeException("Attempting to create a channel before the component is registered!");
}
/** public boolean isGlobal() {
* Creates a channel. return filteranderrormsg == null;
* }
* @param displayname The name that should appear at the start of the message. <b>A chat color is expected at the beginning (§9).</b>
* @param color The default color of the messages sent in the channel
* @param command The command to be used for the channel <i>without /</i>. For example "mod". It's also used for scoreboard objective names.
* @param filteranderrormsg Checks all senders against the criteria provided here and sends the message if the index matches the sender's - if no score at all, displays the error.<br>
* May be null to send to everyone.
*/
public Channel(String displayname, Color color, String command,
Function<CommandSender, RecipientTestResult> filteranderrormsg) {
defDisplayName = displayname;
defColor = color;
ID = command;
this.filteranderrormsg = filteranderrormsg;
}
/** /**
* Must be only called from a subclass - otherwise it'll throw an exception. * Note: Errors are sent to the sender automatically
* *
* @see Channel#Channel(String, Color, String, Function) * @param sender The user we're sending to
*/ * @param score The (source) score to compare with the user's
@SuppressWarnings("unchecked") */
protected <T extends Channel> Channel(String displayname, Color color, String command, public boolean shouldSendTo(CommandSender sender, int score) {
BiFunction<T, CommandSender, RecipientTestResult> filteranderrormsg) { return score == getMCScore(sender); //If there's any error, the score won't be equal
defDisplayName = displayname; }
defColor = color;
ID = command;
this.filteranderrormsg = s -> filteranderrormsg.apply((T) this, s);
}
public boolean isGlobal() { /**
return filteranderrormsg == null; * Note: Errors are sent to the sender automatically
} */
public int getMCScore(CommandSender sender) {
return getRTR(sender).score; //No need to check if there was an error
}
/** /**
* Note: Errors are sent to the sender automatically * Note: Errors are sent to the sender automatically<br>
* * <p>
* @param sender The user we're sending to * Null means don't send
* @param score The (source) score to compare with the user's */
*/ @Nullable
public boolean shouldSendTo(CommandSender sender, int score) { public String getGroupID(CommandSender sender) {
return score == getMCScore(sender); //If there's any error, the score won't be equal return getRTR(sender).groupID; //No need to check if there was an error
} }
/** public RecipientTestResult getRTR(CommandSender sender) {
* Note: Errors are sent to the sender automatically if (filteranderrormsg == null)
*/ return new RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE);
public int getMCScore(CommandSender sender) { return filteranderrormsg.apply(sender);
return getRTR(sender).score; //No need to check if there was an error }
}
/**
* Note: Errors are sent to the sender automatically<br>
* <p>
* Null means don't send
*/
@Nullable
public String getGroupID(CommandSender sender) {
return getRTR(sender).groupID; //No need to check if there was an error
}
public RecipientTestResult getRTR(CommandSender sender) {
if (filteranderrormsg == null)
return new RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE);
return filteranderrormsg.apply(sender);
}
/** /**
* Get a stream of the enabled channels * Get a stream of the enabled channels
@ -148,7 +157,7 @@ public class Channel {
* @return Only the enabled channels * @return Only the enabled channels
*/ */
public static Stream<Channel> getChannels() { public static Stream<Channel> getChannels() {
return channels.stream().filter(ch -> ch.Enabled().get()); return channels.stream().filter(ch -> ch.Enabled.get());
} }
/** /**
@ -160,73 +169,69 @@ public class Channel {
return Collections.unmodifiableList(channels); return Collections.unmodifiableList(channels);
} }
/** /**
* Convenience method for the function parameter of {@link #Channel(String, Color, String, Function)}. It checks if the sender is OP or optionally has the specified group. The error message is * Convenience method for the function parameter of {@link #Channel(String, Color, String, Function)}. It checks if the sender is OP or optionally has the specified group. The error message is
* generated automatically. * generated automatically.
* *
* @param permgroup The group that can access the channel or <b>null</b> to only allow OPs. * @param permgroup The group that can access the channel or <b>null</b> to only allow OPs.
* @return If has access * @return If has access
*/ */
public static Function<CommandSender, RecipientTestResult> inGroupFilter(String permgroup) { public static Function<CommandSender, RecipientTestResult> inGroupFilter(String permgroup) {
return noScoreResult( return noScoreResult(
s -> s.isOp() || (permgroup != null && (s instanceof Player && MainPlugin.permission != null && MainPlugin.permission.playerInGroup((Player) s, permgroup))), s -> s.isOp() || (permgroup != null && (s instanceof Player && MainPlugin.permission != null && MainPlugin.permission.playerInGroup((Player) s, permgroup))),
"You need to be a(n) " + (permgroup != null ? permgroup : "OP") + " to use this channel."); "You need to be a(n) " + (permgroup != null ? permgroup : "OP") + " to use this channel.");
} }
public static Function<CommandSender, RecipientTestResult> noScoreResult(Predicate<CommandSender> filter, public static Function<CommandSender, RecipientTestResult> noScoreResult(Predicate<CommandSender> filter,
String errormsg) { String errormsg) {
return s -> filter.test(s) ? new RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE) : new RecipientTestResult(errormsg); return s -> filter.test(s) ? new RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE) : new RecipientTestResult(errormsg);
} }
public static <T extends Channel> BiFunction<T, CommandSender, RecipientTestResult> noScoreResult( public static <T extends Channel> BiFunction<T, CommandSender, RecipientTestResult> noScoreResult(
BiPredicate<T, CommandSender> filter, String errormsg) { BiPredicate<T, CommandSender> filter, String errormsg) {
return (this_, s) -> filter.test(this_, s) ? new RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE) : new RecipientTestResult(errormsg); return (this_, s) -> filter.test(this_, s) ? new RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE) : new RecipientTestResult(errormsg);
} }
public static Channel GlobalChat; public static Channel GlobalChat;
public static Channel AdminChat; public static Channel AdminChat;
public static Channel ModChat; public static Channel ModChat;
public static void RegisterChannel(Channel channel) { public static void RegisterChannel(Channel channel) {
if (!channel.isGlobal() && !ComponentManager.isEnabled(ChannelComponent.class)) if (!channel.isGlobal() && !ComponentManager.isEnabled(ChannelComponent.class))
return; //Allow registering the global chat (and I guess other chats like the RP chat) return; //Allow registering the global chat (and I guess other chats like the RP chat)
if (component == null)
component = (ChannelComponent) Component.getComponents().get(ChannelComponent.class);
if (component == null)
throw new RuntimeException("Attempting to register a channel before the component is registered!");
channels.add(channel); channels.add(channel);
component.registerChannelCommand(channel); component.registerChannelCommand(channel);
Bukkit.getScheduler().runTask(MainPlugin.Instance, () -> Bukkit.getPluginManager().callEvent(new ChatChannelRegisterEvent(channel))); // Wait for server start Bukkit.getScheduler().runTask(MainPlugin.Instance, () -> Bukkit.getPluginManager().callEvent(new ChatChannelRegisterEvent(channel))); // Wait for server start
} }
public static class RecipientTestResult { public static class RecipientTestResult {
public final String errormessage; public final String errormessage;
public final int score; // Anything below 0 is "never send" public final int score; // Anything below 0 is "never send"
public final String groupID; public final String groupID;
public static final RecipientTestResult ALL = new RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE); public static final RecipientTestResult ALL = new RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE);
/** /**
* Creates a result that indicates an <b>error</b> * Creates a result that indicates an <b>error</b>
* *
* @param errormessage The error message to show the sender if they don't meet the criteria. * @param errormessage The error message to show the sender if they don't meet the criteria.
*/ */
public RecipientTestResult(String errormessage) { public RecipientTestResult(String errormessage) {
this.errormessage = errormessage; this.errormessage = errormessage;
this.score = SCORE_SEND_NOPE; this.score = SCORE_SEND_NOPE;
this.groupID = null; this.groupID = null;
} }
/** /**
* Creates a result that indicates a <b>success</b> * Creates a result that indicates a <b>success</b>
* *
* @param score The score that identifies the target group. <b>Must be non-negative.</b> For example, the index of the town or nation to send to. * @param score The score that identifies the target group. <b>Must be non-negative.</b> For example, the index of the town or nation to send to.
* @param groupID The ID of the target group. * @param groupID The ID of the target group.
*/ */
public RecipientTestResult(int score, String groupID) { public RecipientTestResult(int score, String groupID) {
if (score < 0) throw new IllegalArgumentException("Score must be non-negative!"); if (score < 0) throw new IllegalArgumentException("Score must be non-negative!");
this.score = score; this.score = score;
this.groupID = groupID; this.groupID = groupID;
this.errormessage = null; this.errormessage = null;
} }
} }
} }

View file

@ -11,7 +11,7 @@ import org.bukkit.plugin.java.JavaPlugin;
/** /**
* Manages chat channels. If disabled, only global channels will be registered. * Manages chat channels. If disabled, only global channels will be registered.
*/ */
public class ChannelComponent extends Component { public class ChannelComponent extends Component<JavaPlugin> {
static TBMCSystemChatEvent.BroadcastTarget roomJoinLeave; static TBMCSystemChatEvent.BroadcastTarget roomJoinLeave;
@Override @Override
@ -69,7 +69,7 @@ public class ChannelComponent extends Component {
if (channel instanceof ChatRoom) if (channel instanceof ChatRoom)
((ChatRoom) channel).joinRoom(sender); ((ChatRoom) channel).joinRoom(sender);
} }
sender.sendMessage("§6You are now talking in: §b" + user.channel.get().DisplayName().get()); sender.sendMessage("§6You are now talking in: §b" + user.channel.get().DisplayName.get());
} else } else
TBMCChatAPI.SendChatMessage(ChatMessage.builder(sender, user, message).fromCommand(true) TBMCChatAPI.SendChatMessage(ChatMessage.builder(sender, user, message).fromCommand(true)
.permCheck(senderMC.getPermCheck()).build(), channel); .permCheck(senderMC.getPermCheck()).build(), channel);

View file

@ -38,8 +38,8 @@ public class MemberCommand extends ICommand2MC {
sender.sendMessage("§cCannot find player or haven't played before."); sender.sendMessage("§cCannot find player or haven't played before.");
return; return;
} }
if (add ? MainPlugin.permission.playerAddGroup(null, op, component.memberGroup().get()) if (add ? MainPlugin.permission.playerAddGroup(null, op, component.memberGroup.get())
: MainPlugin.permission.playerRemoveGroup(null, op, component.memberGroup().get())) : MainPlugin.permission.playerRemoveGroup(null, op, component.memberGroup.get()))
sender.sendMessage("§b" + op.getName() + " " + (add ? "added" : "removed") + " as a member!"); sender.sendMessage("§b" + op.getName() + " " + (add ? "added" : "removed") + " as a member!");
else else
sender.sendMessage("§cFailed to " + (add ? "add" : "remove") + " " + op.getName() + " as a member!"); sender.sendMessage("§cFailed to " + (add ? "add" : "remove") + " " + op.getName() + " as a member!");

View file

@ -25,23 +25,17 @@ public class MemberComponent extends Component<MainPlugin> implements Listener {
/** /**
* The permission group to give to the player * The permission group to give to the player
*/ */
ConfigData<String> memberGroup() { final ConfigData<String> memberGroup = getConfig().getData("memberGroup", "member");
return getConfig().getData("memberGroup", "member");
}
/** /**
* The amount of hours needed to play before promotion * The amount of hours needed to play before promotion
*/ */
private ConfigData<Integer> playedHours() { private final ConfigData<Integer> playedHours = getConfig().getData("playedHours", 12);
return getConfig().getData("playedHours", 12);
}
/** /**
* The amount of days passed since first login * The amount of days passed since first login
*/ */
private ConfigData<Integer> registeredForDays() { private final ConfigData<Integer> registeredForDays = getConfig().getData("registeredForDays", 7);
return getConfig().getData("registeredForDays", 7);
}
private AbstractMap.SimpleEntry<Statistic, Integer> playtime; private AbstractMap.SimpleEntry<Statistic, Integer> playtime;
@ -69,7 +63,7 @@ public class MemberComponent extends Component<MainPlugin> implements Listener {
public Boolean addPlayerAsMember(Player player) { public Boolean addPlayerAsMember(Player player) {
try { try {
if (permission.playerAddGroup(null, player, memberGroup().get())) { if (permission.playerAddGroup(null, player, memberGroup.get())) {
player.sendMessage("§bYou are a member now!"); player.sendMessage("§bYou are a member now!");
log("Added " + player.getName() + " as a member."); log("Added " + player.getName() + " as a member.");
return true; return true;
@ -84,7 +78,7 @@ public class MemberComponent extends Component<MainPlugin> implements Listener {
} }
public boolean checkNotMember(Player player) { public boolean checkNotMember(Player player) {
return permission != null && !permission.playerInGroup(player, memberGroup().get()); return permission != null && !permission.playerInGroup(player, memberGroup.get());
} }
public boolean checkRegTime(Player player) { public boolean checkRegTime(Player player) {
@ -92,14 +86,14 @@ public class MemberComponent extends Component<MainPlugin> implements Listener {
} }
public boolean checkPlayTime(Player player) { public boolean checkPlayTime(Player player) {
return getPlayTime(player) > playtime.getValue() * playedHours().get(); return getPlayTime(player) > playtime.getValue() * playedHours.get();
} }
/** /**
* Returns milliseconds * Returns milliseconds
*/ */
public long getRegTime(Player player) { public long getRegTime(Player player) {
Instant date = new Date(player.getFirstPlayed()).toInstant().plus(registeredForDays().get(), ChronoUnit.DAYS); Instant date = new Date(player.getFirstPlayed()).toInstant().plus(registeredForDays.get(), ChronoUnit.DAYS);
if (date.isAfter(Instant.now())) if (date.isAfter(Instant.now()))
return date.toEpochMilli() - Instant.now().toEpochMilli(); return date.toEpochMilli() - Instant.now().toEpochMilli();
return -1; return -1;
@ -113,7 +107,7 @@ public class MemberComponent extends Component<MainPlugin> implements Listener {
* Returns hours * Returns hours
*/ */
public double getPlayTime(Player player) { public double getPlayTime(Player player) {
double pt = playedHours().get() - (double) getPlayTimeTotal(player) / playtime.getValue(); double pt = playedHours.get() - (double) getPlayTimeTotal(player) / playtime.getValue();
if (pt < 0) return -1; if (pt < 0) return -1;
return pt; return pt;
} }

View file

@ -33,7 +33,7 @@ public class RestartComponent extends Component<MainPlugin> implements Listener
registerListener(this); registerListener(this);
restartBroadcast = TBMCSystemChatEvent.BroadcastTarget.add("restartCountdown"); restartBroadcast = TBMCSystemChatEvent.BroadcastTarget.add("restartCountdown");
int restartAt = restartAt().get(); int restartAt = this.restartAt.get();
if (restartAt < 0) return; if (restartAt < 0) return;
int restart = syncStart(restartAt); int restart = syncStart(restartAt);
log("Scheduled restart " + (restart / 3600. / 20.) + " hours from now"); log("Scheduled restart " + (restart / 3600. / 20.) + " hours from now");
@ -48,9 +48,7 @@ public class RestartComponent extends Component<MainPlugin> implements Listener
/** /**
* Specifies the hour of day when the server should be restarted. Set to -1 to disable. * Specifies the hour of day when the server should be restarted. Set to -1 to disable.
*/ */
private ConfigData<Integer> restartAt() { private final ConfigData<Integer> restartAt = getConfig().getData("restartAt", 12);
return getConfig().getData("restartAt", 12);
}
private long lasttime = 0; private long lasttime = 0;
@Getter @Getter

View file

@ -29,7 +29,7 @@ public class SpawnComponent extends Component<MainPlugin> implements PluginMessa
@Override @Override
protected void enable() { protected void enable() {
registerCommand(new SpawnCommand()); registerCommand(new SpawnCommand());
if (targetServer().get().length() == 0) { if (targetServer.get().length() == 0) {
spawnloc = MultiverseCore.getPlugin(MultiverseCore.class).getMVWorldManager().getFirstSpawnWorld() spawnloc = MultiverseCore.getPlugin(MultiverseCore.class).getMVWorldManager().getFirstSpawnWorld()
.getSpawnLocation(); .getSpawnLocation();
} }
@ -49,7 +49,7 @@ public class SpawnComponent extends Component<MainPlugin> implements PluginMessa
if (!channel.equals("BungeeCord")) { if (!channel.equals("BungeeCord")) {
return; return;
} }
if (targetServer().get().length() != 0) if (targetServer.get().length() != 0)
return; return;
ByteArrayDataInput in = ByteStreams.newDataInput(message); ByteArrayDataInput in = ByteStreams.newDataInput(message);
String subchannel = in.readUTF(); String subchannel = in.readUTF();
@ -78,9 +78,7 @@ public class SpawnComponent extends Component<MainPlugin> implements PluginMessa
/** /**
* The BungeeCord server that has the spawn. Set to empty if this server is the target. * The BungeeCord server that has the spawn. Set to empty if this server is the target.
*/ */
private ConfigData<String> targetServer() { private final ConfigData<String> targetServer = getConfig().getData("targetServer", "");
return getConfig().getData("targetServer", "");
}
private Location spawnloc; private Location spawnloc;
@ -92,7 +90,7 @@ public class SpawnComponent extends Component<MainPlugin> implements PluginMessa
@SuppressWarnings("UnstableApiUsage") @SuppressWarnings("UnstableApiUsage")
@Command2.Subcommand @Command2.Subcommand
public void def(Player player) { public void def(Player player) {
if (targetServer().get().length() == 0) { if (targetServer.get().length() == 0) {
player.sendMessage("§bTeleporting to spawn..."); player.sendMessage("§bTeleporting to spawn...");
try { try {
if (MainPlugin.ess != null) if (MainPlugin.ess != null)
@ -107,7 +105,7 @@ public class SpawnComponent extends Component<MainPlugin> implements PluginMessa
} }
ByteArrayDataOutput out = ByteStreams.newDataOutput(); ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Connect"); out.writeUTF("Connect");
out.writeUTF(targetServer().get()); out.writeUTF(targetServer.get());
player.sendPluginMessage(getPlugin(), "BungeeCord", out.toByteArray()); player.sendPluginMessage(getPlugin(), "BungeeCord", out.toByteArray());

View file

@ -20,9 +20,7 @@ import org.bukkit.event.EventHandler;
public class VotifierComponent extends Component<MainPlugin> { public class VotifierComponent extends Component<MainPlugin> {
private final Economy economy; private final Economy economy;
private ConfigData<Double> rewardAmount() { private final ConfigData<Double> rewardAmount = getConfig().getData("rewardAmount", 0.0);
return getConfig().getData("rewardAmount", 0.0);
}
@Override @Override
protected void enable() { protected void enable() {

View file

@ -171,6 +171,6 @@ public class TBMCCoreAPI {
public static boolean IsTestServer() { public static boolean IsTestServer() {
if (MainPlugin.Instance == null) return true; if (MainPlugin.Instance == null) return true;
return MainPlugin.Instance.test().get(); return MainPlugin.Instance.test.get();
} }
} }

View file

@ -34,9 +34,8 @@ public abstract class Component<TP extends JavaPlugin> {
private @Getter final IHaveConfig config = new IHaveConfig(null); private @Getter final IHaveConfig config = new IHaveConfig(null);
private @Getter IHaveConfig data; //TODO private @Getter IHaveConfig data; //TODO
public final ConfigData<Boolean> shouldBeEnabled() { public final ConfigData<Boolean> shouldBeEnabled = config.getData("enabled",
return config.getData("enabled", Optional.ofNullable(getClass().getAnnotation(ComponentMetadata.class)).map(ComponentMetadata::enabledByDefault).orElse(true)); Optional.ofNullable(getClass().getAnnotation(ComponentMetadata.class)).map(ComponentMetadata::enabledByDefault).orElse(true));
}
/** /**
* Registers a component checking it's dependencies and calling {@link #register(JavaPlugin)}.<br> * Registers a component checking it's dependencies and calling {@link #register(JavaPlugin)}.<br>
@ -87,7 +86,7 @@ public abstract class Component<TP extends JavaPlugin> {
components.put(component.getClass(), component); components.put(component.getClass(), component);
if (plugin instanceof ButtonPlugin) if (plugin instanceof ButtonPlugin)
((ButtonPlugin) plugin).getComponentStack().push(component); ((ButtonPlugin) plugin).getComponentStack().push(component);
if (ComponentManager.areComponentsEnabled() && component.shouldBeEnabled().get()) { if (ComponentManager.areComponentsEnabled() && component.shouldBeEnabled.get()) {
try { //Enable components registered after the previous ones getting enabled try { //Enable components registered after the previous ones getting enabled
setComponentEnabled(component, true); setComponentEnabled(component, true);
return true; return true;

View file

@ -199,7 +199,7 @@ public class Command2MC extends Command2<ICommand2MC, Command2MCSender> implemen
if (pcmd != null) if (pcmd != null)
System.out.println("ButtonPlugin: " + (pcmd.getPlugin() instanceof ButtonPlugin));*/ System.out.println("ButtonPlugin: " + (pcmd.getPlugin() instanceof ButtonPlugin));*/
if (!checkPlugin if (!checkPlugin
|| MainPlugin.Instance.prioritizeCustomCommands().get() || MainPlugin.Instance.prioritizeCustomCommands.get()
|| (pcmd = Bukkit.getPluginCommand(mainpath)) == null //Our commands aren't PluginCommands || (pcmd = Bukkit.getPluginCommand(mainpath)) == null //Our commands aren't PluginCommands
|| pcmd.getPlugin() instanceof ButtonPlugin) //Unless it's specified in the plugin.yml || pcmd.getPlugin() instanceof ButtonPlugin) //Unless it's specified in the plugin.yml
return super.handleCommand(sender, commandline); return super.handleCommand(sender, commandline);

View file

@ -35,9 +35,9 @@ public class TBMCChatAPI {
*/ */
public static boolean SendChatMessage(ChatMessage cm, Channel channel) { public static boolean SendChatMessage(ChatMessage cm, Channel channel) {
if (!Channel.getChannelList().contains(channel)) if (!Channel.getChannelList().contains(channel))
throw new RuntimeException("Channel " + channel.DisplayName().get() + " not registered!"); throw new RuntimeException("Channel " + channel.DisplayName.get() + " not registered!");
if (!channel.Enabled().get()) { if (!channel.Enabled.get()) {
cm.getSender().sendMessage("§cThe channel '" + channel.DisplayName().get() + "' is disabled!"); cm.getSender().sendMessage("§cThe channel '" + channel.DisplayName.get() + "' is disabled!");
return true; //Cancel sending if channel is disabled return true; //Cancel sending if channel is disabled
} }
Supplier<Boolean> task = () -> { Supplier<Boolean> task = () -> {
@ -70,11 +70,11 @@ public class TBMCChatAPI {
*/ */
public static boolean SendSystemMessage(Channel channel, RecipientTestResult rtr, String message, TBMCSystemChatEvent.BroadcastTarget target, String... exceptions) { public static boolean SendSystemMessage(Channel channel, RecipientTestResult rtr, String message, TBMCSystemChatEvent.BroadcastTarget target, String... exceptions) {
if (!Channel.getChannelList().contains(channel)) if (!Channel.getChannelList().contains(channel))
throw new RuntimeException("Channel " + channel.DisplayName().get() + " not registered!"); throw new RuntimeException("Channel " + channel.DisplayName.get() + " not registered!");
if (!channel.Enabled().get()) if (!channel.Enabled.get())
return true; //Cancel sending return true; //Cancel sending
if (!Arrays.asList(exceptions).contains("Minecraft")) if (!Arrays.asList(exceptions).contains("Minecraft"))
Bukkit.getConsoleSender().sendMessage("[" + channel.DisplayName().get() + "] " + message); Bukkit.getConsoleSender().sendMessage("[" + channel.DisplayName.get() + "] " + message);
TBMCSystemChatEvent event = new TBMCSystemChatEvent(channel, message, rtr.score, rtr.groupID, exceptions, target); TBMCSystemChatEvent event = new TBMCSystemChatEvent(channel, message, rtr.score, rtr.groupID, exceptions, target);
return ChromaUtils.callEventAsync(event); return ChromaUtils.callEventAsync(event);
} }

View file

@ -23,9 +23,7 @@ public abstract class TBMCPlayerBase extends ChromaGamerBase {
return uuid; return uuid;
} }
public ConfigData<String> PlayerName() { public final ConfigData<String> PlayerName = super.config.getData("PlayerName", "");
return super.config.getData("PlayerName", "");
}
/** /**
* Get player as a plugin player. * Get player as a plugin player.