Components, components everywhere #56
39 changed files with 1332 additions and 941 deletions
15
.editorconfig
Normal file
15
.editorconfig
Normal file
|
@ -0,0 +1,15 @@
|
|||
[*]
|
||||
charset=utf-8
|
||||
end_of_line=lf
|
||||
insert_final_newline=false
|
||||
indent_style=space
|
||||
indent_size=4
|
||||
|
||||
[*.java]
|
||||
indent_style=tab
|
||||
tab_width=4
|
||||
|
||||
[{*.yml,*.yaml}]
|
||||
indent_style=space
|
||||
indent_size=2
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="WeakerAccess" enabled="true" level="WARNING" enabled_by_default="true">
|
||||
<inspection_tool class="WeakerAccess" enabled="false" level="WARNING" enabled_by_default="false">
|
||||
<option name="SUGGEST_PACKAGE_LOCAL_FOR_MEMBERS" value="false" />
|
||||
<option name="SUGGEST_PACKAGE_LOCAL_FOR_TOP_CLASSES" value="false" />
|
||||
<option name="SUGGEST_PRIVATE_FOR_INNERS" value="false" />
|
||||
|
|
|
@ -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>
|
||||
|
|
|
@ -4,7 +4,6 @@
|
|||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/BuildConfigUpdater/BuildConfigUpdater.iml" filepath="$PROJECT_DIR$/BuildConfigUpdater/BuildConfigUpdater.iml" />
|
||||
<module fileurl="file://$PROJECT_DIR$/ButtonCore/ButtonCore (1) (com.github.TBMCPlugins.ButtonCore).iml" filepath="$PROJECT_DIR$/ButtonCore/ButtonCore (1) (com.github.TBMCPlugins.ButtonCore).iml" />
|
||||
<module fileurl="file://$PROJECT_DIR$/ButtonCore/ButtonCore (1) (com.github.TBMCPlugins.ButtonCore).iml" filepath="$PROJECT_DIR$/ButtonCore/ButtonCore (1) (com.github.TBMCPlugins.ButtonCore).iml" />
|
||||
<module fileurl="file://$PROJECT_DIR$/ButtonProcessor/ButtonProcessor.iml" filepath="$PROJECT_DIR$/ButtonProcessor/ButtonProcessor.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
|
|
|
@ -1,175 +1,231 @@
|
|||
package buttondevteam.lib.chat;
|
||||
|
||||
import buttondevteam.core.MainPlugin;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.BiPredicate;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
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}
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
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
|
||||
*/
|
||||
public static final String GROUP_EVERYONE = "everyone";
|
||||
public final String DisplayName;
|
||||
public final Color color;
|
||||
public final String ID;
|
||||
@Nullable
|
||||
public 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) {
|
||||
DisplayName = displayname;
|
||||
this.color = color;
|
||||
ID = command;
|
||||
this.filteranderrormsg = filteranderrormsg;
|
||||
}
|
||||
|
||||
/**
|
||||
* Must be only called from a subclass - otherwise it'll throw an exception.
|
||||
*
|
||||
* @see Channel#Channel(String, Color, String, Function)
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
protected <T extends Channel> Channel(String displayname, Color color, String command,
|
||||
BiFunction<T, CommandSender, RecipientTestResult> filteranderrormsg) {
|
||||
DisplayName = displayname;
|
||||
this.color = 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
|
||||
*
|
||||
* @param sender The user we're sending to
|
||||
* @param score The (source) score to compare with the user's
|
||||
*/
|
||||
public boolean shouldSendTo(CommandSender sender, int score) {
|
||||
return score == getMCScore(sender); //If there's any error, the score won't be equal
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<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);
|
||||
}
|
||||
|
||||
public static List<Channel> getChannels() {
|
||||
return 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
|
||||
* generated automatically.
|
||||
*
|
||||
* @param permgroup The group that can access the channel or <b>null</b> to only allow OPs.
|
||||
* @return If has access
|
||||
*/
|
||||
public static Function<CommandSender, RecipientTestResult> inGroupFilter(String permgroup) {
|
||||
return noScoreResult(
|
||||
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.");
|
||||
}
|
||||
|
||||
public static Function<CommandSender, RecipientTestResult> noScoreResult(Predicate<CommandSender> filter,
|
||||
String 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(
|
||||
BiPredicate<T, CommandSender> filter, String 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 AdminChat;
|
||||
public static Channel ModChat;
|
||||
|
||||
static void RegisterChannel(Channel channel) {
|
||||
channels.add(channel);
|
||||
Bukkit.getScheduler().runTask(MainPlugin.Instance, () -> Bukkit.getPluginManager().callEvent(new ChatChannelRegisterEvent(channel))); // Wait for server start
|
||||
}
|
||||
|
||||
public static class RecipientTestResult {
|
||||
public final String errormessage;
|
||||
public final int score; // Anything below 0 is "never send"
|
||||
public final String groupID;
|
||||
public static final RecipientTestResult ALL = new RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE);
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
public RecipientTestResult(String errormessage) {
|
||||
this.errormessage = errormessage;
|
||||
this.score = SCORE_SEND_NOPE;
|
||||
this.groupID = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 groupID The ID of the target group.
|
||||
*/
|
||||
public RecipientTestResult(int score, String groupID) {
|
||||
if (score < 0) throw new IllegalArgumentException("Score must be non-negative!");
|
||||
this.score = score;
|
||||
this.groupID = groupID;
|
||||
this.errormessage = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
package buttondevteam.component.channel;
|
||||
|
||||
import buttondevteam.core.ComponentManager;
|
||||
import buttondevteam.core.MainPlugin;
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import buttondevteam.lib.architecture.ConfigData;
|
||||
import buttondevteam.lib.chat.Color;
|
||||
import com.google.common.collect.Lists;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.function.BiFunction;
|
||||
import java.util.function.BiPredicate;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
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}
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
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
|
||||
*/
|
||||
public static final String GROUP_EVERYONE = "everyone";
|
||||
|
||||
private static ChannelComponent component;
|
||||
|
||||
private String defDisplayName;
|
||||
private Color defColor;
|
||||
|
||||
private void throwGame() {
|
||||
if (component == null) throw new RuntimeException("Cannot access channel properties until registered!");
|
||||
}
|
||||
|
||||
public final ConfigData<Boolean> Enabled() {
|
||||
throwGame();
|
||||
return component.getConfig().getData(ID + ".enabled", true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Must start with a color code
|
||||
*/
|
||||
public final ConfigData<String> DisplayName() {
|
||||
throwGame();
|
||||
return component.getConfig().getData(ID + ".displayName", defDisplayName);
|
||||
}
|
||||
|
||||
public final ConfigData<Color> Color() {
|
||||
throwGame();
|
||||
return component.getConfig().getData(ID + ".color", defColor, c -> Color.valueOf((String) c), Enum::toString);
|
||||
}
|
||||
public final String ID;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public ConfigData<String[]> IDs() {
|
||||
throwGame();
|
||||
return 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<>();
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Must be only called from a subclass - otherwise it'll throw an exception.
|
||||
*
|
||||
* @see Channel#Channel(String, Color, String, Function)
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
protected <T extends Channel> Channel(String displayname, Color color, String command,
|
||||
BiFunction<T, CommandSender, RecipientTestResult> filteranderrormsg) {
|
||||
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
|
||||
*
|
||||
* @param sender The user we're sending to
|
||||
* @param score The (source) score to compare with the user's
|
||||
*/
|
||||
public boolean shouldSendTo(CommandSender sender, int score) {
|
||||
return score == getMCScore(sender); //If there's any error, the score won't be equal
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<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
|
||||
*
|
||||
* @return Only the enabled channels
|
||||
*/
|
||||
public static Stream<Channel> getChannels() {
|
||||
return channels.stream().filter(ch -> ch.Enabled().get());
|
||||
}
|
||||
|
||||
/**
|
||||
* Return all channels whether they're enabled or not
|
||||
*
|
||||
* @return A list of all channels
|
||||
*/
|
||||
public static List<Channel> getChannelList() {
|
||||
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
|
||||
* generated automatically.
|
||||
*
|
||||
* @param permgroup The group that can access the channel or <b>null</b> to only allow OPs.
|
||||
* @return If has access
|
||||
*/
|
||||
public static Function<CommandSender, RecipientTestResult> inGroupFilter(String permgroup) {
|
||||
return noScoreResult(
|
||||
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.");
|
||||
}
|
||||
|
||||
public static Function<CommandSender, RecipientTestResult> noScoreResult(Predicate<CommandSender> filter,
|
||||
String 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(
|
||||
BiPredicate<T, CommandSender> filter, String 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 AdminChat;
|
||||
public static Channel ModChat;
|
||||
|
||||
public static void RegisterChannel(Channel channel) {
|
||||
if (!channel.isGlobal() && !ComponentManager.isEnabled(ChannelComponent.class))
|
||||
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);
|
||||
Bukkit.getScheduler().runTask(MainPlugin.Instance, () -> Bukkit.getPluginManager().callEvent(new ChatChannelRegisterEvent(channel))); // Wait for server start
|
||||
}
|
||||
|
||||
public static class RecipientTestResult {
|
||||
public final String errormessage;
|
||||
public final int score; // Anything below 0 is "never send"
|
||||
public final String groupID;
|
||||
public static final RecipientTestResult ALL = new RecipientTestResult(SCORE_SEND_OK, GROUP_EVERYONE);
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
public RecipientTestResult(String errormessage) {
|
||||
this.errormessage = errormessage;
|
||||
this.score = SCORE_SEND_NOPE;
|
||||
this.groupID = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 groupID The ID of the target group.
|
||||
*/
|
||||
public RecipientTestResult(int score, String groupID) {
|
||||
if (score < 0) throw new IllegalArgumentException("Score must be non-negative!");
|
||||
this.score = score;
|
||||
this.groupID = groupID;
|
||||
this.errormessage = null;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package buttondevteam.component.channel;
|
||||
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
public class ChannelComponent extends Component {
|
||||
@Override
|
||||
protected void register(JavaPlugin plugin) {
|
||||
super.register(plugin);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void unregister(JavaPlugin plugin) {
|
||||
super.unregister(plugin);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void enable() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void disable() {
|
||||
|
||||
}
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package buttondevteam.lib.chat;
|
||||
package buttondevteam.component.channel;
|
||||
|
||||
import org.bukkit.event.Event;
|
||||
import org.bukkit.event.HandlerList;
|
|
@ -1,5 +1,7 @@
|
|||
package buttondevteam.lib.chat;
|
||||
package buttondevteam.component.channel;
|
||||
|
||||
import buttondevteam.lib.chat.Color;
|
||||
import buttondevteam.lib.chat.TBMCChatAPI;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
import java.util.ArrayList;
|
|
@ -1,15 +0,0 @@
|
|||
package buttondevteam.component.commands;
|
||||
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
|
||||
public class CommandComponent extends Component { //TODO: Do we just move everything here?
|
||||
@Override
|
||||
public void enable() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disable() {
|
||||
|
||||
}
|
||||
}
|
|
@ -1,5 +1,6 @@
|
|||
package buttondevteam.core;
|
||||
package buttondevteam.component.members;
|
||||
|
||||
import buttondevteam.core.MainPlugin;
|
||||
import buttondevteam.lib.chat.CommandClass;
|
||||
import buttondevteam.lib.chat.TBMCCommandBase;
|
||||
import lombok.val;
|
|
@ -0,0 +1,42 @@
|
|||
package buttondevteam.component.members;
|
||||
|
||||
import buttondevteam.core.MainPlugin;
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import buttondevteam.lib.architecture.ConfigData;
|
||||
import org.bukkit.Statistic;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Date;
|
||||
|
||||
import static buttondevteam.core.MainPlugin.permission;
|
||||
|
||||
public class MemberComponent extends Component implements Listener {
|
||||
private ConfigData<String> memberGroup() {
|
||||
return getConfig().getData("memberGroup", "member");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void enable() {
|
||||
registerListener(this);
|
||||
registerCommand(new MemberCommand());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void disable() {
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerJoin(PlayerJoinEvent event) {
|
||||
if (permission != null && !permission.playerInGroup(event.getPlayer(), memberGroup().get())
|
||||
&& (new Date(event.getPlayer().getFirstPlayed()).toInstant().plus(7, ChronoUnit.DAYS).isBefore(Instant.now())
|
||||
|| event.getPlayer().getStatistic(Statistic.PLAY_ONE_TICK) > 20 * 3600 * 12)) {
|
||||
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.");
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,15 +1,15 @@
|
|||
package buttondevteam.core;
|
||||
package buttondevteam.component.randomtp;
|
||||
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import buttondevteam.lib.chat.CommandClass;
|
||||
import buttondevteam.lib.chat.TBMCChatAPI;
|
||||
import buttondevteam.lib.chat.TBMCCommandBase;
|
||||
import org.bukkit.*;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
// @formatter:off
|
||||
@CommandClass
|
||||
@SuppressWarnings("FieldCanBeLocal")@CommandClass
|
||||
public class RandomTP extends TBMCCommandBase
|
||||
{
|
||||
private final int radius = 70; //set how far apart the five teleport positions are
|
||||
|
@ -51,9 +51,9 @@ public class RandomTP extends TBMCCommandBase
|
|||
|
||||
/*================================================================================================*/
|
||||
|
||||
public void onEnable(JavaPlugin plugin)
|
||||
public void onEnable(Component component)
|
||||
{
|
||||
TBMCChatAPI.AddCommand(plugin, this);
|
||||
TBMCChatAPI.AddCommand(component, this);
|
||||
|
||||
world = Bukkit.getWorld("World");
|
||||
border = world.getWorldBorder();
|
|
@ -0,0 +1,15 @@
|
|||
package buttondevteam.component.randomtp;
|
||||
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
|
||||
public class RandomTPComponent extends Component {
|
||||
@Override
|
||||
protected void enable() {
|
||||
new RandomTP().onEnable(this); //It registers it's command
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void disable() {
|
||||
|
||||
}
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package buttondevteam.core;
|
||||
package buttondevteam.component.restart;
|
||||
|
||||
import buttondevteam.lib.chat.CommandClass;
|
||||
import buttondevteam.lib.chat.TBMCCommandBase;
|
|
@ -1,20 +1,44 @@
|
|||
package buttondevteam.component.restart;
|
||||
|
||||
import buttondevteam.core.PrimeRestartCommand;
|
||||
import buttondevteam.core.ScheduledRestartCommand;
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import buttondevteam.lib.chat.IFakePlayer;
|
||||
import buttondevteam.lib.chat.TBMCChatAPI;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
|
||||
public class RestartComponent extends Component {
|
||||
public class RestartComponent extends Component implements Listener {
|
||||
@Override
|
||||
public void enable() {
|
||||
//TODO: Permissions for the commands
|
||||
TBMCChatAPI.AddCommand(getPlugin(), ScheduledRestartCommand.class);
|
||||
TBMCChatAPI.AddCommand(getPlugin(), PrimeRestartCommand.class);
|
||||
TBMCChatAPI.AddCommand(this, new ScheduledRestartCommand());
|
||||
TBMCChatAPI.AddCommand(this, new PrimeRestartCommand());
|
||||
registerListener(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disable() {
|
||||
|
||||
}
|
||||
|
||||
private long lasttime = 0;
|
||||
|
||||
@EventHandler
|
||||
public void onPlayerLeave(PlayerQuitEvent event) {
|
||||
if (PrimeRestartCommand.isPlsrestart()
|
||||
&& !event.getQuitMessage().equalsIgnoreCase("Server closed")
|
||||
&& !event.getQuitMessage().equalsIgnoreCase("Server is restarting")) {
|
||||
if (Bukkit.getOnlinePlayers().size() <= 1) {
|
||||
if (PrimeRestartCommand.isLoud())
|
||||
Bukkit.broadcastMessage("§cNobody is online anymore. Restarting.");
|
||||
Bukkit.spigot().restart();
|
||||
} else if (!(event.getPlayer() instanceof IFakePlayer) && System.nanoTime() - 10 * 1000000000L - lasttime > 0) { //Ten seconds passed since last reminder
|
||||
lasttime = System.nanoTime();
|
||||
if (PrimeRestartCommand.isLoud())
|
||||
Bukkit.broadcastMessage(ChatColor.DARK_RED + "The server will restart as soon as nobody is online.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
package buttondevteam.core;
|
||||
package buttondevteam.component.restart;
|
||||
|
||||
import buttondevteam.core.MainPlugin;
|
||||
import buttondevteam.lib.ScheduledServerRestartEvent;
|
||||
import buttondevteam.lib.chat.CommandClass;
|
||||
import buttondevteam.lib.chat.TBMCCommandBase;
|
|
@ -0,0 +1,47 @@
|
|||
package buttondevteam.component.towny;
|
||||
|
||||
import buttondevteam.core.ComponentManager;
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import com.palmergames.bukkit.towny.Towny;
|
||||
import com.palmergames.bukkit.towny.exceptions.AlreadyRegisteredException;
|
||||
import com.palmergames.bukkit.towny.exceptions.NotRegisteredException;
|
||||
import com.palmergames.bukkit.towny.object.Resident;
|
||||
import com.palmergames.bukkit.towny.object.TownyUniverse;
|
||||
import org.bukkit.Bukkit;
|
||||
|
||||
public class TownyComponent extends Component {
|
||||
@Override
|
||||
protected void enable() {
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void disable() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Only renames the resident if this component is enabled. Used to handle name changes.
|
||||
*
|
||||
* @param oldName The player's old name as known by us
|
||||
* @param newName The player's new name
|
||||
*/
|
||||
public static void renameInTowny(String oldName, String newName) {
|
||||
if (!ComponentManager.isEnabled(TownyComponent.class))
|
||||
return; TownyUniverse tu = Towny.getPlugin(Towny.class).getTownyUniverse();
|
||||
Resident resident = tu.getResidentMap().get(oldName.toLowerCase()); //The map keys are lowercase
|
||||
if (resident == null) {
|
||||
Bukkit.getLogger().warning("Resident not found - couldn't rename in Towny.");
|
||||
TBMCCoreAPI.sendDebugMessage("Resident not found - couldn't rename in Towny.");
|
||||
} else if (tu.getResidentMap().contains(newName.toLowerCase())) {
|
||||
Bukkit.getLogger().warning("Target resident name is already in use."); // TODO: Handle
|
||||
TBMCCoreAPI.sendDebugMessage("Target resident name is already in use.");
|
||||
} else
|
||||
try {
|
||||
TownyUniverse.getDataSource().renamePlayer(resident, newName); //Fixed in Towny 0.91.1.2
|
||||
} catch (AlreadyRegisteredException e) {
|
||||
TBMCCoreAPI.SendException("Failed to rename resident, there's already one with this name.", e);
|
||||
} catch (NotRegisteredException e) {
|
||||
TBMCCoreAPI.SendException("Failed to rename resident, the resident isn't registered.", e);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -6,11 +6,11 @@ import buttondevteam.lib.chat.TBMCChatAPI;
|
|||
public class PluginUpdaterComponent extends Component {
|
||||
@Override
|
||||
public void enable() {
|
||||
TBMCChatAPI.AddCommand(getPlugin(), UpdatePluginCommand.class);
|
||||
TBMCChatAPI.AddCommand(this, new UpdatePluginCommand());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disable() { //TODO: Unregister commands and such
|
||||
public void disable() { //Commands are automatically unregistered
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
@ -21,41 +21,27 @@ public class CommandCaller implements CommandExecutor {
|
|||
public static void RegisterCommand(TBMCCommandBase cmd) throws Exception {
|
||||
if (instance == null)
|
||||
instance = new CommandCaller();
|
||||
String topcmd = cmd.GetCommandPath();
|
||||
if (topcmd == null)
|
||||
throw new Exception("Command " + cmd.getClass().getSimpleName() + " has no command path!");
|
||||
if (cmd.getPlugin() == null)
|
||||
throw new Exception("Command " + cmd.GetCommandPath() + " has no plugin!");
|
||||
int i;
|
||||
if ((i = topcmd.indexOf(' ')) != -1) // Get top-level command
|
||||
topcmd = topcmd.substring(0, i);
|
||||
{
|
||||
PluginCommand pc = ((JavaPlugin) cmd.getPlugin()).getCommand(topcmd);
|
||||
if (pc == null)
|
||||
throw new Exception("Top level command " + topcmd + " not registered in plugin.yml for plugin: "
|
||||
+ cmd.getPlugin().getName());
|
||||
else {
|
||||
pc.setExecutor(instance);
|
||||
String[] helptext = cmd.GetHelpText(topcmd);
|
||||
if (helptext == null || helptext.length == 0)
|
||||
throw new Exception("Command " + cmd.GetCommandPath() + " has no help text!");
|
||||
pc.setUsage(helptext.length > 1 ? helptext[1] : helptext[0]);
|
||||
}
|
||||
}
|
||||
String[] topcmd = new String[1]; //Holds out param
|
||||
PluginCommand pc = getPluginCommand(cmd, topcmd);
|
||||
pc.setExecutor(instance);
|
||||
String[] helptext = cmd.GetHelpText(topcmd[0]);
|
||||
if (helptext == null || helptext.length == 0)
|
||||
throw new Exception("Command " + cmd.GetCommandPath() + " has no help text!");
|
||||
pc.setUsage(helptext.length > 1 ? helptext[1] : helptext[0]);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) {
|
||||
String path = command.getName().toLowerCase();
|
||||
StringBuilder path = new StringBuilder(command.getName().toLowerCase());
|
||||
for (String arg : args)
|
||||
path += " " + arg;
|
||||
TBMCCommandBase cmd = TBMCChatAPI.GetCommands().get(path);
|
||||
path.append(" ").append(arg);
|
||||
TBMCCommandBase cmd = TBMCChatAPI.GetCommands().get(path.toString());
|
||||
int argc = 0;
|
||||
String[] subcmds = null;
|
||||
while (cmd == null && (subcmds = TBMCChatAPI.GetSubCommands(path, sender)).length == 0 && path.contains(" ")) {
|
||||
path = path.substring(0, path.lastIndexOf(' '));
|
||||
while (cmd == null && (subcmds = TBMCChatAPI.GetSubCommands(path.toString(), sender)).length == 0 && path.toString().contains(" ")) {
|
||||
path = new StringBuilder(path.substring(0, path.toString().lastIndexOf(' ')));
|
||||
argc++;
|
||||
cmd = TBMCChatAPI.GetCommands().get(path);
|
||||
cmd = TBMCChatAPI.GetCommands().get(path.toString());
|
||||
}
|
||||
if (cmd == null) {
|
||||
if (subcmds.length > 0) //Subcmds will always have value here (see assignment above)
|
||||
|
@ -85,4 +71,37 @@ public class CommandCaller implements CommandExecutor {
|
|||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void UnregisterCommand(TBMCCommandBase cmd) throws Exception {
|
||||
PluginCommand pc = getPluginCommand(cmd, null);
|
||||
pc.setExecutor(null); //Sets the executor to this plugin
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the plugin command from the TBMC command.
|
||||
*
|
||||
* @param cmd The TBMC command
|
||||
* @param out_topcmd An array with at least 1 elements or null
|
||||
* @return The Bukkit plugin command - an exception is generated if null
|
||||
* @throws Exception If the command isn't set up properly (or a different error)
|
||||
*/
|
||||
public static PluginCommand getPluginCommand(TBMCCommandBase cmd, String[] out_topcmd) throws Exception {
|
||||
String topcmd = cmd.GetCommandPath();
|
||||
if (topcmd == null)
|
||||
throw new Exception("Command " + cmd.getClass().getSimpleName() + " has no command path!");
|
||||
if (cmd.getPlugin() == null)
|
||||
throw new Exception("Command " + cmd.GetCommandPath() + " has no plugin!");
|
||||
int i;
|
||||
if ((i = topcmd.indexOf(' ')) != -1) // Get top-level command
|
||||
topcmd = topcmd.substring(0, i);
|
||||
if (out_topcmd != null && out_topcmd.length > 0)
|
||||
out_topcmd[0] = topcmd;
|
||||
{
|
||||
PluginCommand pc = ((JavaPlugin) cmd.getPlugin()).getCommand(topcmd);
|
||||
if (pc == null)
|
||||
throw new Exception("Top level command " + topcmd + " not registered in plugin.yml for plugin: "
|
||||
+ cmd.getPlugin().getName());
|
||||
return pc;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,30 +1,63 @@
|
|||
package buttondevteam.core;
|
||||
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import buttondevteam.lib.chat.CommandClass;
|
||||
import buttondevteam.lib.chat.TBMCCommandBase;
|
||||
import lombok.val;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@CommandClass(modOnly = true)
|
||||
public class ComponentCommand extends TBMCCommandBase {
|
||||
@Override
|
||||
public boolean OnCommand(CommandSender sender, String alias, String[] args) {
|
||||
if (args.length < 2)
|
||||
if (args.length < 1)
|
||||
return false;
|
||||
switch (args[0]) {
|
||||
case "enable":
|
||||
break;
|
||||
case "disable":
|
||||
break;
|
||||
case "list":
|
||||
break;
|
||||
default:
|
||||
boolean enable = true;
|
||||
try {
|
||||
switch (args[0]) {
|
||||
case "enable":
|
||||
enable = true;
|
||||
break;
|
||||
case "disable":
|
||||
enable = false;
|
||||
break;
|
||||
case "list":
|
||||
sender.sendMessage("§6List of components:");
|
||||
Component.getComponents().values().stream().map(c -> c.getPlugin().getName() + " - " + c.getClass().getSimpleName() + " - " + (c.isEnabled() ? "en" : "dis") + "abled").forEach(sender::sendMessage);
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
if (args.length < 2)
|
||||
return false;
|
||||
val oc = getComponentOrError(args[1], sender);
|
||||
if (!oc.isPresent())
|
||||
return true;
|
||||
if (enable) //Reload config so the new config values are read
|
||||
getPlugin().reloadConfig(); //All changes are saved to disk on disable
|
||||
Component.setComponentEnabled(oc.get(), enable);
|
||||
sender.sendMessage(oc.get().getClass().getSimpleName() + " " + (enable ? "en" : "dis") + "abled.");
|
||||
} catch (Exception e) {
|
||||
TBMCCoreAPI.SendException("Couldn't " + (enable ? "en" : "dis") + "able component " + args[0] + "!", e);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private Optional<Component> getComponentOrError(String arg, CommandSender sender) {
|
||||
val oc = Component.getComponents().values().stream().filter(c -> c.getClass().getSimpleName().equalsIgnoreCase(arg)).findAny();
|
||||
if (!oc.isPresent())
|
||||
sender.sendMessage("§cComponent not found!");
|
||||
return oc;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] GetHelpText(String alias) {
|
||||
return new String[0];
|
||||
return new String[]{
|
||||
"§6---- Component command ----",
|
||||
"Enable or disable or list components"
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,117 +1,138 @@
|
|||
package buttondevteam.core;
|
||||
|
||||
import buttondevteam.component.restart.RestartComponent;
|
||||
import buttondevteam.component.updater.PluginUpdater;
|
||||
import buttondevteam.component.updater.PluginUpdaterComponent;
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import buttondevteam.lib.chat.Channel;
|
||||
import buttondevteam.lib.chat.ChatRoom;
|
||||
import buttondevteam.lib.chat.Color;
|
||||
import buttondevteam.lib.chat.TBMCChatAPI;
|
||||
import buttondevteam.lib.player.ChromaGamerBase;
|
||||
import buttondevteam.lib.player.TBMCPlayer;
|
||||
import buttondevteam.lib.player.TBMCPlayerBase;
|
||||
import com.earth2me.essentials.Essentials;
|
||||
import net.milkbowl.vault.permission.Permission;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.BlockCommandSender;
|
||||
import org.bukkit.command.ConsoleCommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.PluginDescriptionFile;
|
||||
import org.bukkit.plugin.RegisteredServiceProvider;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class MainPlugin extends JavaPlugin {
|
||||
public static MainPlugin Instance;
|
||||
@Nullable
|
||||
public static Permission permission;
|
||||
public static boolean Test;
|
||||
public static Essentials ess;
|
||||
|
||||
private Logger logger;
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
// Logs "Plugin Enabled", registers commands
|
||||
Instance = this;
|
||||
PluginDescriptionFile pdf = getDescription();
|
||||
logger = getLogger();
|
||||
setupPermissions();
|
||||
Test = getConfig().getBoolean("test", true);
|
||||
saveConfig();
|
||||
Component.registerComponent(this, new PluginUpdaterComponent());
|
||||
Component.registerComponent(this, new RestartComponent());
|
||||
ComponentManager.enableComponents();
|
||||
TBMCChatAPI.AddCommand(this, MemberCommand.class);
|
||||
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
|
||||
ChromaGamerBase.addConverter(sender -> Optional.ofNullable(sender instanceof Player
|
||||
? TBMCPlayer.getPlayer(((Player) sender).getUniqueId(), TBMCPlayer.class) : null)); //Players, has higher priority
|
||||
TBMCCoreAPI.RegisterUserClass(TBMCPlayerBase.class);
|
||||
TBMCChatAPI.RegisterChatChannel(Channel.GlobalChat = new Channel("§fOOC§f", Color.White, "ooc", null));
|
||||
Channel.GlobalChat.IDs = new String[]{"g"}; //Support /g as well
|
||||
TBMCChatAPI.RegisterChatChannel(
|
||||
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"));
|
||||
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);
|
||||
new RandomTP().onEnable(this); //It registers it's command
|
||||
logger.info(pdf.getName() + " has been Enabled (V." + pdf.getVersion() + ") Test: " + Test + ".");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
ComponentManager.disableComponents();
|
||||
logger.info("Saving player data...");
|
||||
TBMCPlayerBase.savePlayers();
|
||||
logger.info("Player data saved.");
|
||||
new Thread(() -> {
|
||||
File[] files = PluginUpdater.updatedir.listFiles();
|
||||
if (files == null)
|
||||
return;
|
||||
System.out.println("Updating " + files.length + " plugins...");
|
||||
for (File file : files) {
|
||||
try {
|
||||
Files.move(file.toPath(), new File("plugins", file.getName()).toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||
System.out.println("Updated " + file.getName());
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
System.out.println("Update complete!");
|
||||
}).start();
|
||||
}
|
||||
|
||||
private boolean setupPermissions() {
|
||||
RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager()
|
||||
.getRegistration(Permission.class);
|
||||
if (permissionProvider != null) {
|
||||
permission = permissionProvider.getProvider();
|
||||
}
|
||||
return (permission != null);
|
||||
}
|
||||
}
|
||||
package buttondevteam.core;
|
||||
|
||||
import buttondevteam.component.channel.Channel;
|
||||
import buttondevteam.component.channel.ChannelComponent;
|
||||
import buttondevteam.component.channel.ChatRoom;
|
||||
import buttondevteam.component.members.MemberComponent;
|
||||
import buttondevteam.component.randomtp.RandomTPComponent;
|
||||
import buttondevteam.component.restart.RestartComponent;
|
||||
import buttondevteam.component.towny.TownyComponent;
|
||||
import buttondevteam.component.updater.PluginUpdater;
|
||||
import buttondevteam.component.updater.PluginUpdaterComponent;
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import buttondevteam.lib.architecture.ButtonPlugin;
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import buttondevteam.lib.architecture.ConfigData;
|
||||
import buttondevteam.lib.chat.Color;
|
||||
import buttondevteam.lib.chat.TBMCChatAPI;
|
||||
import buttondevteam.lib.player.ChromaGamerBase;
|
||||
import buttondevteam.lib.player.TBMCPlayer;
|
||||
import buttondevteam.lib.player.TBMCPlayerBase;
|
||||
import com.earth2me.essentials.Essentials;
|
||||
import net.milkbowl.vault.permission.Permission;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.BlockCommandSender;
|
||||
import org.bukkit.command.Command;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.command.ConsoleCommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.PluginDescriptionFile;
|
||||
import org.bukkit.plugin.RegisteredServiceProvider;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class MainPlugin extends ButtonPlugin {
|
||||
public static MainPlugin Instance;
|
||||
@Nullable
|
||||
public static Permission permission;
|
||||
public static boolean Test;
|
||||
public static Essentials ess;
|
||||
|
||||
private Logger logger;
|
||||
|
||||
private ConfigData<Boolean> writePluginList() {
|
||||
return getIConfig().getData("writePluginList", false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pluginEnable() {
|
||||
// Logs "Plugin Enabled", registers commands
|
||||
Instance = this;
|
||||
PluginDescriptionFile pdf = getDescription();
|
||||
logger = getLogger();
|
||||
setupPermissions();
|
||||
Test = getConfig().getBoolean("test", true);
|
||||
saveConfig();
|
||||
Component.registerComponent(this, new PluginUpdaterComponent());
|
||||
Component.registerComponent(this, new RestartComponent());
|
||||
Component.registerComponent(this, new ChannelComponent());
|
||||
Component.registerComponent(this, new RandomTPComponent());
|
||||
Component.registerComponent(this, new MemberComponent());
|
||||
Component.registerComponent(this, new TownyComponent());
|
||||
ComponentManager.enableComponents();
|
||||
TBMCChatAPI.AddCommand(this, ComponentCommand.class);
|
||||
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
|
||||
ChromaGamerBase.addConverter(sender -> Optional.ofNullable(sender instanceof Player
|
||||
? TBMCPlayer.getPlayer(((Player) sender).getUniqueId(), TBMCPlayer.class) : null)); //Players, has higher priority
|
||||
TBMCCoreAPI.RegisterUserClass(TBMCPlayerBase.class);
|
||||
TBMCChatAPI.RegisterChatChannel(Channel.GlobalChat = new Channel("§fOOC§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)));
|
||||
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"));
|
||||
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 + ".");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void pluginDisable() {
|
||||
ComponentManager.disableComponents();
|
||||
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();
|
||||
}
|
||||
|
||||
private boolean setupPermissions() {
|
||||
RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager()
|
||||
.getRegistration(Permission.class);
|
||||
if (permissionProvider != null) {
|
||||
permission = permissionProvider.getProvider();
|
||||
}
|
||||
return (permission != null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
sender.sendMessage("§cThis command isn't available."); //In theory, unregistered commands use this method
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,61 +1,35 @@
|
|||
package buttondevteam.core;
|
||||
|
||||
import buttondevteam.lib.TBMCSystemChatEvent;
|
||||
import buttondevteam.lib.chat.IFakePlayer;
|
||||
import buttondevteam.lib.player.TBMCPlayerBase;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.ChatColor;
|
||||
import org.bukkit.Statistic;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Date;
|
||||
|
||||
import static buttondevteam.core.MainPlugin.permission;
|
||||
|
||||
public class PlayerListener implements Listener {
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
public void OnPlayerJoin(PlayerJoinEvent event) {
|
||||
TBMCPlayerBase.joinPlayer(event.getPlayer());
|
||||
if (permission != null && !permission.playerInGroup(event.getPlayer(), "member")
|
||||
&& (new Date(event.getPlayer().getFirstPlayed()).toInstant().plus(7, ChronoUnit.DAYS).isBefore(Instant.now())
|
||||
|| event.getPlayer().getStatistic(Statistic.PLAY_ONE_TICK) > 20 * 3600 * 12)) {
|
||||
permission.playerAddGroup(null, event.getPlayer(), "member");
|
||||
event.getPlayer().sendMessage("§bYou are a member now. YEEHAW");
|
||||
MainPlugin.Instance.getLogger().info("Added " + event.getPlayer().getName() + " as a member.");
|
||||
}
|
||||
}
|
||||
|
||||
private long lasttime = 0;
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
public void OnPlayerLeave(PlayerQuitEvent event) {
|
||||
TBMCPlayerBase.quitPlayer(event.getPlayer());
|
||||
if (PrimeRestartCommand.isPlsrestart()
|
||||
&& !event.getQuitMessage().equalsIgnoreCase("Server closed")
|
||||
&& !event.getQuitMessage().equalsIgnoreCase("Server is restarting")) {
|
||||
if (Bukkit.getOnlinePlayers().size() <= 1) {
|
||||
if (PrimeRestartCommand.isLoud())
|
||||
Bukkit.broadcastMessage("§cNobody is online anymore. Restarting.");
|
||||
Bukkit.spigot().restart();
|
||||
} else if (!(event.getPlayer() instanceof IFakePlayer) && System.nanoTime() - 10 * 1000000000L - lasttime > 0) { //Ten seconds passed since last reminder
|
||||
lasttime = System.nanoTime();
|
||||
if (PrimeRestartCommand.isLoud())
|
||||
Bukkit.broadcastMessage(ChatColor.DARK_RED + "The server will restart as soon as nobody is online.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void onSystemChat(TBMCSystemChatEvent event) {
|
||||
if (event.isHandled())
|
||||
return; // Only handle here if ButtonChat couldn't
|
||||
Bukkit.getOnlinePlayers().stream().filter(event::shouldSendTo)
|
||||
.forEach(p -> p.sendMessage(event.getChannel().DisplayName.substring(0, 2) + event.getMessage()));
|
||||
}
|
||||
package buttondevteam.core;
|
||||
|
||||
import buttondevteam.lib.TBMCSystemChatEvent;
|
||||
import buttondevteam.lib.player.TBMCPlayerBase;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.event.player.PlayerJoinEvent;
|
||||
import org.bukkit.event.player.PlayerQuitEvent;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
public class PlayerListener implements Listener {
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
public void OnPlayerJoin(PlayerJoinEvent event) {
|
||||
TBMCPlayerBase.joinPlayer(event.getPlayer());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.NORMAL)
|
||||
public void OnPlayerLeave(PlayerQuitEvent event) {
|
||||
TBMCPlayerBase.quitPlayer(event.getPlayer());
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void onSystemChat(TBMCSystemChatEvent event) {
|
||||
if (event.isHandled())
|
||||
return; // Only handle here if ButtonChat couldn't - ButtonChat doesn't even handle this
|
||||
if (Arrays.stream(event.getExceptions()).anyMatch("Minecraft"::equalsIgnoreCase))
|
||||
return;
|
||||
Bukkit.getOnlinePlayers().stream().filter(event::shouldSendTo)
|
||||
.forEach(p -> p.sendMessage(event.getChannel().DisplayName().get().substring(0, 2) + event.getMessage()));
|
||||
}
|
||||
}
|
|
@ -1,6 +1,8 @@
|
|||
package buttondevteam.core;
|
||||
|
||||
import buttondevteam.lib.chat.Channel;
|
||||
import buttondevteam.component.channel.Channel;
|
||||
import buttondevteam.component.channel.ChannelComponent;
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import buttondevteam.lib.chat.Color;
|
||||
import buttondevteam.lib.chat.TBMCChatAPI;
|
||||
import org.bukkit.Bukkit;
|
||||
|
@ -38,6 +40,7 @@ public class TestPrepare {
|
|||
return cl.isAssignableFrom(invocation.getMethod().getReturnType());
|
||||
}
|
||||
}));
|
||||
Component.registerComponent(Mockito.mock(MainPlugin.class), new ChannelComponent());
|
||||
TBMCChatAPI.RegisterChatChannel(Channel.GlobalChat = new Channel("§fg§f", Color.White, "g", null));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
package buttondevteam.lib;
|
||||
|
||||
import buttondevteam.lib.chat.Channel;
|
||||
import buttondevteam.component.channel.Channel;
|
||||
import buttondevteam.lib.chat.ChatMessage;
|
||||
import lombok.Getter;
|
||||
import lombok.experimental.Delegate;
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
package buttondevteam.lib;
|
||||
|
||||
import buttondevteam.lib.chat.Channel;
|
||||
import buttondevteam.component.channel.Channel;
|
||||
import lombok.Getter;
|
||||
import lombok.NonNull;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
package buttondevteam.lib;
|
||||
|
||||
import buttondevteam.lib.chat.Channel;
|
||||
import buttondevteam.component.channel.Channel;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
package buttondevteam.lib;
|
||||
|
||||
import buttondevteam.lib.chat.Channel;
|
||||
import buttondevteam.component.channel.Channel;
|
||||
import lombok.Getter;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.event.HandlerList;
|
||||
|
@ -13,14 +13,16 @@ import org.bukkit.event.HandlerList;
|
|||
*/
|
||||
@Getter
|
||||
public class TBMCSystemChatEvent extends TBMCChatEventBase {
|
||||
private final String[] exceptions;
|
||||
private boolean handled;
|
||||
|
||||
public void setHandled() {
|
||||
handled = true;
|
||||
}
|
||||
|
||||
public TBMCSystemChatEvent(Channel channel, String message, int score, String groupid) { // TODO: Rich message
|
||||
public TBMCSystemChatEvent(Channel channel, String message, int score, String groupid, String[] exceptions) { // TODO: Rich message
|
||||
super(channel, message, score, groupid);
|
||||
this.exceptions = exceptions;
|
||||
}
|
||||
|
||||
private static final HandlerList handlers = new HandlerList();
|
||||
|
|
|
@ -1,25 +1,25 @@
|
|||
package buttondevteam.lib.architecture;
|
||||
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import buttondevteam.lib.chat.TBMCChatAPI;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.experimental.var;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
public abstract class ButtonPlugin extends JavaPlugin {
|
||||
private final HashMap<String, ConfigData<?>> datamap = new HashMap<>();
|
||||
private ConfigurationSection section;
|
||||
@Getter(AccessLevel.PROTECTED)
|
||||
private IHaveConfig iConfig;
|
||||
|
||||
protected abstract void pluginEnable();
|
||||
|
||||
protected abstract void pluginDisable();
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
section = getConfig().getConfigurationSection("global");
|
||||
if (section == null) section = getConfig().createSection("global");
|
||||
public final void onEnable() {
|
||||
var section = super.getConfig().getConfigurationSection("global");
|
||||
if (section == null) section = super.getConfig().createSection("global");
|
||||
iConfig = new IHaveConfig(section);
|
||||
try {
|
||||
pluginEnable();
|
||||
} catch (Exception e) {
|
||||
|
@ -28,25 +28,14 @@ public abstract class ButtonPlugin extends JavaPlugin {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void onDisable() {
|
||||
public final void onDisable() {
|
||||
try {
|
||||
pluginDisable();
|
||||
saveConfig();
|
||||
iConfig = null; //Clearing the hashmap is not enough, we need to update the section as well
|
||||
TBMCChatAPI.RemoveCommands(this);
|
||||
} catch (Exception e) {
|
||||
TBMCCoreAPI.SendException("Error while disabling plugin " + getName() + "!", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @see IHaveConfig#getData(Map, ConfigurationSection, String, Object)
|
||||
*/
|
||||
protected <T> ConfigData<T> getData(String path, T def) {
|
||||
return IHaveConfig.getData(datamap, section, path, def);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see IHaveConfig#getData(Map, ConfigurationSection, String, Object, Function, Function)
|
||||
*/
|
||||
protected <T> ConfigData<T> getData(String path, T def, Function<Object, T> getter, Function<T, Object> setter) {
|
||||
return IHaveConfig.getData(datamap, section, path, def, getter, setter);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -5,19 +5,16 @@ import buttondevteam.lib.TBMCCoreAPI;
|
|||
import buttondevteam.lib.architecture.exceptions.UnregisteredComponentException;
|
||||
import buttondevteam.lib.chat.TBMCChatAPI;
|
||||
import buttondevteam.lib.chat.TBMCCommandBase;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.NonNull;
|
||||
import lombok.experimental.var;
|
||||
import lombok.val;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* Configuration is based on class name
|
||||
|
@ -27,30 +24,15 @@ public abstract class Component {
|
|||
|
||||
@Getter
|
||||
private boolean enabled = false;
|
||||
@Getter(value = AccessLevel.PROTECTED)
|
||||
@Getter
|
||||
@NonNull
|
||||
private JavaPlugin plugin;
|
||||
@NonNull
|
||||
private ConfigurationSection config;
|
||||
private @Getter
|
||||
IHaveConfig config;
|
||||
|
||||
public ConfigData<Boolean> shouldBeEnabled() {
|
||||
return getData("enabled", true);
|
||||
}
|
||||
|
||||
private HashMap<String, ConfigData<?>> datamap = new HashMap<>();
|
||||
|
||||
/**
|
||||
* @see IHaveConfig#getData(Map, ConfigurationSection, String, Object)
|
||||
*/
|
||||
protected <T> ConfigData<T> getData(String path, T def) {
|
||||
return IHaveConfig.getData(datamap, config, path, def);
|
||||
}
|
||||
|
||||
/**
|
||||
* @see IHaveConfig#getData(Map, ConfigurationSection, String, Object, Function, Function)
|
||||
*/
|
||||
protected <T> ConfigData<T> getData(String path, T def, Function<Object, T> getter, Function<T, Object> setter) {
|
||||
return IHaveConfig.getData(datamap, config, path, def, getter, setter);
|
||||
public final ConfigData<Boolean> shouldBeEnabled() {
|
||||
return config.getData("enabled", true);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -84,7 +66,7 @@ public abstract class Component {
|
|||
val metaAnn = component.getClass().getAnnotation(ComponentMetadata.class);
|
||||
if (metaAnn != null) {
|
||||
Class<? extends Component>[] dependencies = metaAnn.depends();
|
||||
for (val dep : dependencies) {
|
||||
for (val dep : dependencies) { //TODO: Support dependencies at enable/disable as well
|
||||
if (!components.containsKey(dep)) {
|
||||
plugin.getLogger().warning("Failed to " + (register ? "" : "un") + "register component " + component.getClassName() + " as a required dependency is missing/disabled: " + dep.getSimpleName());
|
||||
return false;
|
||||
|
@ -93,10 +75,7 @@ public abstract class Component {
|
|||
}
|
||||
if (register) {
|
||||
component.plugin = plugin;
|
||||
var compconf = plugin.getConfig().getConfigurationSection("components");
|
||||
if (compconf == null) compconf = plugin.getConfig().createSection("components");
|
||||
component.config = compconf.getConfigurationSection(component.getClassName());
|
||||
if (component.config == null) component.config = compconf.createSection(component.getClassName());
|
||||
updateConfig(plugin, component);
|
||||
component.register(plugin);
|
||||
components.put(component.getClass(), component);
|
||||
if (ComponentManager.areComponentsEnabled() && component.shouldBeEnabled().get()) {
|
||||
|
@ -108,12 +87,11 @@ public abstract class Component {
|
|||
return true;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
return true; //Component shouldn't be enabled
|
||||
} else {
|
||||
if (component.enabled) {
|
||||
try {
|
||||
component.disable();
|
||||
component.enabled = false;
|
||||
setComponentEnabled(component, false);
|
||||
} catch (Exception | NoClassDefFoundError e) {
|
||||
TBMCCoreAPI.SendException("Failed to disable component " + component.getClassName() + "!", e);
|
||||
return false; //If failed to disable, won't unregister either
|
||||
|
@ -138,10 +116,27 @@ public abstract class Component {
|
|||
public static void setComponentEnabled(Component component, boolean enabled) throws UnregisteredComponentException {
|
||||
if (!components.containsKey(component.getClass()))
|
||||
throw new UnregisteredComponentException(component);
|
||||
if (component.enabled = enabled)
|
||||
if (component.enabled == enabled) return; //Don't do anything
|
||||
if (component.enabled = enabled) {
|
||||
updateConfig(component.getPlugin(), component);
|
||||
component.enable();
|
||||
else
|
||||
} else {
|
||||
component.disable();
|
||||
component.plugin.saveConfig();
|
||||
TBMCChatAPI.RemoveCommands(component);
|
||||
}
|
||||
}
|
||||
|
||||
private static void updateConfig(JavaPlugin plugin, Component component) {
|
||||
if (plugin.getConfig() != null) { //Production
|
||||
var compconf = plugin.getConfig().getConfigurationSection("components");
|
||||
if (compconf == null) compconf = plugin.getConfig().createSection("components");
|
||||
var configSect = compconf.getConfigurationSection(component.getClassName());
|
||||
if (configSect == null)
|
||||
configSect = compconf.createSection(component.getClassName());
|
||||
component.config = new IHaveConfig(configSect);
|
||||
} else //Testing
|
||||
component.config = new IHaveConfig(null);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -159,6 +154,7 @@ public abstract class Component {
|
|||
*
|
||||
* @param plugin Plugin object
|
||||
*/
|
||||
@SuppressWarnings({"unused", "WeakerAccess"})
|
||||
protected void register(JavaPlugin plugin) {
|
||||
}
|
||||
|
||||
|
@ -169,6 +165,7 @@ public abstract class Component {
|
|||
*
|
||||
* @param plugin Plugin object
|
||||
*/
|
||||
@SuppressWarnings({"WeakerAccess", "unused"})
|
||||
protected void unregister(JavaPlugin plugin) {
|
||||
}
|
||||
|
||||
|
@ -187,35 +184,26 @@ public abstract class Component {
|
|||
protected abstract void disable();
|
||||
|
||||
/**
|
||||
* Registers a TBMCCommand to the plugin. Make sure to add it to plugin.yml and use {@link buttondevteam.lib.chat.CommandClass}.
|
||||
* Registers a TBMCCommand to the component. Make sure to add it to plugin.yml and use {@link buttondevteam.lib.chat.CommandClass}.
|
||||
*
|
||||
* @param plugin Main plugin responsible for stuff
|
||||
* @param commandBase Custom coded command class
|
||||
*/
|
||||
protected void registerCommand(JavaPlugin plugin, TBMCCommandBase commandBase) {
|
||||
TBMCChatAPI.AddCommand(plugin, commandBase);
|
||||
protected final void registerCommand(TBMCCommandBase commandBase) {
|
||||
TBMCChatAPI.AddCommand(this, commandBase);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a Listener to this plugin
|
||||
* Registers a Listener to this component
|
||||
*
|
||||
* @param plugin Main plugin responsible for stuff
|
||||
* @param listener The event listener to register
|
||||
* @return The provided listener
|
||||
*/
|
||||
protected Listener registerListener(JavaPlugin plugin, Listener listener) {
|
||||
protected final Listener registerListener(Listener listener) {
|
||||
TBMCCoreAPI.RegisterEventsForExceptions(listener, plugin);
|
||||
return listener;
|
||||
}
|
||||
|
||||
private String getClassName() {
|
||||
Class<?> enclosingClass = getClass().getEnclosingClass();
|
||||
String className;
|
||||
if (enclosingClass != null) {
|
||||
className = (enclosingClass.getName());
|
||||
} else {
|
||||
className = (getClass().getName());
|
||||
}
|
||||
return className;
|
||||
return getClass().getSimpleName();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,23 +1,27 @@
|
|||
package buttondevteam.lib.architecture;
|
||||
|
||||
import lombok.AccessLevel;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* Use the getter/setter constructor if {@link T} isn't a primitive type or String.<br>
|
||||
* Use {@link Component#getData(String, Object)} or {@link ButtonPlugin#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)
|
||||
//@AllArgsConstructor(access = AccessLevel.PACKAGE)
|
||||
public class ConfigData<T> { //TODO: Save after a while
|
||||
/**
|
||||
* May be null for testing
|
||||
*/
|
||||
private final ConfigurationSection config;
|
||||
private final String path;
|
||||
private final T def;
|
||||
private final Object primitiveDef;
|
||||
/**
|
||||
* The parameter is of a primitive type as returned by {@link YamlConfiguration#get(String)}
|
||||
*/
|
||||
|
@ -27,9 +31,32 @@ public class ConfigData<T> { //TODO: Save after a while
|
|||
*/
|
||||
private Function<T, Object> setter;
|
||||
|
||||
/**
|
||||
* The config value should not change outside this instance
|
||||
*/
|
||||
private T value;
|
||||
private boolean saved = false;
|
||||
|
||||
public ConfigData(ConfigurationSection config, String path, T def, Object primitiveDef, Function<Object, T> getter, Function<T, Object> setter) {
|
||||
this.config = config;
|
||||
this.path = path;
|
||||
this.def = def;
|
||||
this.primitiveDef = primitiveDef;
|
||||
this.getter = getter;
|
||||
this.setter = setter;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public T get() {
|
||||
Object val = config.get(path, def);
|
||||
if (value != null) return value; //Speed things up
|
||||
Object val = config == null ? null : config.get(path); //config==null: testing
|
||||
if (val == null) {
|
||||
val = primitiveDef;
|
||||
}
|
||||
if (!saved && Objects.equals(val, primitiveDef)) { //String needs .equals()
|
||||
set(def); //Save default value - def is always set
|
||||
saved = true;
|
||||
}
|
||||
if (getter != null) {
|
||||
T hmm = getter.apply(val);
|
||||
if (hmm == null) hmm = def; //Set if the getter returned null
|
||||
|
@ -43,6 +70,8 @@ public class ConfigData<T> { //TODO: Save after a while
|
|||
if (setter != null)
|
||||
val = setter.apply(value);
|
||||
else val = value;
|
||||
config.set(path, val);
|
||||
if (config != null)
|
||||
config.set(path, val);
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,15 +1,27 @@
|
|||
package buttondevteam.lib.architecture;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* Members of this interface should be protected (access level)
|
||||
*/
|
||||
final class IHaveConfig {
|
||||
private IHaveConfig() {}
|
||||
public final class IHaveConfig {
|
||||
private final HashMap<String, ConfigData<?>> datamap = new HashMap<>();
|
||||
@Getter
|
||||
private ConfigurationSection config;
|
||||
|
||||
/**
|
||||
* May be used in testing
|
||||
*
|
||||
* @param section May be null for testing
|
||||
*/
|
||||
IHaveConfig(ConfigurationSection section) {
|
||||
config = section;
|
||||
}
|
||||
|
||||
/**
|
||||
* This method overload should only be used with primitves or String.
|
||||
|
@ -20,9 +32,9 @@ final class IHaveConfig {
|
|||
* @return The data object that can be used to get or set the value
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
protected static <T> ConfigData<T> getData(Map<String, ConfigData<?>> datamap, ConfigurationSection config, String path, T def) {
|
||||
public <T> ConfigData<T> getData(String path, T def) {
|
||||
ConfigData<?> data = datamap.get(path);
|
||||
if (data == null) datamap.put(path, data = new ConfigData<>(config, path, def));
|
||||
if (data == null) datamap.put(path, data = new ConfigData<>(config, path, def, def));
|
||||
return (ConfigData<T>) data;
|
||||
}
|
||||
|
||||
|
@ -37,9 +49,28 @@ final class IHaveConfig {
|
|||
* @return The data object that can be used to get or set the value
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
protected static <T> ConfigData<T> getData(Map<String, ConfigData<?>> datamap, ConfigurationSection config, String path, T def, Function<Object, T> getter, Function<T, Object> setter) {
|
||||
public <T> ConfigData<T> getData(String path, T def, Function<Object, T> getter, Function<T, Object> setter) {
|
||||
ConfigData<?> data = datamap.get(path);
|
||||
if (data == null) datamap.put(path, data = new ConfigData<>(config, path, def, getter, setter));
|
||||
if (data == null)
|
||||
datamap.put(path, data = new ConfigData<>(config, path, def, setter.apply(def), getter, setter));
|
||||
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> ConfigData<T> getDataPrimDef(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 ConfigData<>(config, path, getter.apply(primitiveDef), primitiveDef, getter, setter));
|
||||
return (ConfigData<T>) data;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,31 @@
|
|||
package buttondevteam.lib.chat;
|
||||
|
||||
import org.bukkit.command.CommandSender;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
public abstract class Command2 {
|
||||
/**
|
||||
* Default handler for commands, can be used to copy the args too.
|
||||
*
|
||||
* @param sender The sender which ran the command
|
||||
* @param command The (sub)command ran by the user
|
||||
* @param args All of the arguments passed as is
|
||||
* @return
|
||||
*/
|
||||
public boolean def(CommandSender sender, String command, @TextArg String args) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* TODO: @CommandClass(helpText=...)
|
||||
* Parameters annotated with this receive all of the remaining arguments
|
||||
*/
|
||||
@Target(ElementType.PARAMETER)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface TextArg {
|
||||
}
|
||||
}
|
|
@ -36,4 +36,11 @@ public @interface CommandClass {
|
|||
* Exclude this class from the path. Useful if more commands share some property but aren't subcommands of a common command. See {@link CommandClass} for more details.
|
||||
*/
|
||||
boolean excludeFromPath() default false;
|
||||
|
||||
/**
|
||||
* The help text to show for the players.
|
||||
*
|
||||
* @return The help text
|
||||
*/
|
||||
String[] helpText() default {};
|
||||
}
|
||||
|
|
|
@ -1,282 +1,340 @@
|
|||
package buttondevteam.lib.chat;
|
||||
|
||||
import buttondevteam.core.CommandCaller;
|
||||
import buttondevteam.core.MainPlugin;
|
||||
import buttondevteam.lib.TBMCChatEvent;
|
||||
import buttondevteam.lib.TBMCChatPreprocessEvent;
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import buttondevteam.lib.TBMCSystemChatEvent;
|
||||
import buttondevteam.lib.chat.Channel.RecipientTestResult;
|
||||
import lombok.val;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.reflections.Reflections;
|
||||
import org.reflections.scanners.SubTypesScanner;
|
||||
import org.reflections.util.ClasspathHelper;
|
||||
import org.reflections.util.ConfigurationBuilder;
|
||||
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class TBMCChatAPI {
|
||||
|
||||
private static final HashMap<String, TBMCCommandBase> commands = new HashMap<>();
|
||||
|
||||
public static HashMap<String, TBMCCommandBase> GetCommands() {
|
||||
return commands;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns messages formatted for Minecraft chat listing the subcommands of the command.
|
||||
*
|
||||
* @param command
|
||||
* The command which we want the subcommands of
|
||||
* @param sender
|
||||
* The sender for permissions
|
||||
* @return The subcommands
|
||||
*/
|
||||
public static String[] GetSubCommands(TBMCCommandBase command, CommandSender sender) {
|
||||
return GetSubCommands(command.GetCommandPath(), sender);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns messages formatted for Minecraft chat listing the subcommands of the command.<br>
|
||||
* Returns a header if subcommands were found, otherwise returns an empty array.
|
||||
*
|
||||
* @param command
|
||||
* The command which we want the subcommands of
|
||||
* @param sender
|
||||
* The sender for permissions
|
||||
* @return The subcommands
|
||||
*/
|
||||
public static String[] GetSubCommands(String command, CommandSender sender) {
|
||||
ArrayList<String> cmds = new ArrayList<String>();
|
||||
Consumer<String> addToCmds = cmd -> {
|
||||
if (cmds.size() == 0)
|
||||
cmds.add("§6---- Subcommands ----");
|
||||
cmds.add(cmd);
|
||||
};
|
||||
for (Entry<String, TBMCCommandBase> cmd : TBMCChatAPI.GetCommands().entrySet()) {
|
||||
if (cmd.getKey().startsWith(command + " ")) {
|
||||
if (cmd.getValue().isPlayerOnly() && !(sender instanceof Player))
|
||||
continue;
|
||||
if (cmd.getValue().isModOnly() && (MainPlugin.permission != null ? !MainPlugin.permission.has(sender, "tbmc.admin") : !sender.isOp()))
|
||||
continue;
|
||||
int ind = cmd.getKey().indexOf(' ', command.length() + 2);
|
||||
if (ind >= 0) {
|
||||
String newcmd = cmd.getKey().substring(0, ind);
|
||||
if (!cmds.contains("/" + newcmd))
|
||||
addToCmds.accept("/" + newcmd);
|
||||
} else
|
||||
addToCmds.accept("/" + cmd.getKey());
|
||||
}
|
||||
}
|
||||
return cmds.toArray(new String[0]); //Apparently it's faster to use an empty array in modern Java
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* This method adds a plugin's commands to help and sets their executor.
|
||||
* </p>
|
||||
* <p>
|
||||
* </p>
|
||||
* <b>The command classes have to have a constructor each with no parameters</b>
|
||||
* <p>
|
||||
* The <u>command must be registered</u> in the caller plugin's plugin.yml. Otherwise the plugin will output a messsage to console.
|
||||
* </p>
|
||||
* <p>
|
||||
* <i>Using this method after the server is done loading will have no effect.</i>
|
||||
* </p>
|
||||
*
|
||||
* @param plugin
|
||||
* The caller plugin
|
||||
* @param acmdclass
|
||||
* A command's class to get the package name for commands. The provided class's package and subpackages are scanned for commands.
|
||||
*/
|
||||
public static synchronized void AddCommands(JavaPlugin plugin, Class<? extends TBMCCommandBase> acmdclass) {
|
||||
plugin.getLogger().info("Registering commands from " + acmdclass.getPackage().getName());
|
||||
Reflections rf = new Reflections(new ConfigurationBuilder()
|
||||
.setUrls(ClasspathHelper.forPackage(acmdclass.getPackage().getName(),
|
||||
plugin.getClass().getClassLoader()))
|
||||
.addUrls(
|
||||
ClasspathHelper.forClass(OptionallyPlayerCommandBase.class,
|
||||
OptionallyPlayerCommandBase.class.getClassLoader()),
|
||||
ClasspathHelper.forClass(PlayerCommandBase.class, PlayerCommandBase.class.getClassLoader())) // http://stackoverflow.com/questions/12917417/using-reflections-for-finding-the-transitive-subtypes-of-a-class-when-not-all
|
||||
.addClassLoader(plugin.getClass().getClassLoader()).addScanners(new SubTypesScanner()));
|
||||
Set<Class<? extends TBMCCommandBase>> cmds = rf.getSubTypesOf(TBMCCommandBase.class);
|
||||
for (Class<? extends TBMCCommandBase> cmd : cmds) {
|
||||
try {
|
||||
if (!cmd.getPackage().getName().startsWith(acmdclass.getPackage().getName()))
|
||||
continue; // It keeps including the commands from here
|
||||
if (Modifier.isAbstract(cmd.getModifiers()))
|
||||
continue;
|
||||
TBMCCommandBase c = cmd.newInstance();
|
||||
c.plugin = plugin;
|
||||
if (HasNulls(plugin, c))
|
||||
continue;
|
||||
commands.put(c.GetCommandPath(), c);
|
||||
CommandCaller.RegisterCommand(c);
|
||||
} catch (Exception e) {
|
||||
TBMCCoreAPI.SendException("An error occured while registering command " + cmd.getName(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* This method adds a plugin's command to help and sets it's executor.
|
||||
* </p>
|
||||
* <p>
|
||||
* The <u>command must be registered</u> in the caller plugin's plugin.yml. Otherwise the plugin will output a messsage to console.
|
||||
* </p>
|
||||
* <p>
|
||||
* <i>Using this method after the server is done loading will have no effect.</i>
|
||||
* </p>
|
||||
*
|
||||
* @param plugin
|
||||
* The caller plugin
|
||||
* @param thecmdclass
|
||||
* The command's class to create it (because why let you create the command class)
|
||||
*/
|
||||
public static void AddCommand(JavaPlugin plugin, Class<? extends TBMCCommandBase> thecmdclass, Object... params) {
|
||||
// plugin.getLogger().info("Registering command " + thecmdclass.getSimpleName() + " for " + plugin.getName());
|
||||
try {
|
||||
TBMCCommandBase c;
|
||||
if (params.length > 0)
|
||||
c = thecmdclass.getConstructor(Arrays.stream(params).map(Object::getClass).toArray(Class[]::new))
|
||||
.newInstance(params);
|
||||
else
|
||||
c = thecmdclass.newInstance();
|
||||
c.plugin = plugin;
|
||||
if (HasNulls(plugin, c))
|
||||
return;
|
||||
commands.put(c.GetCommandPath(), c);
|
||||
CommandCaller.RegisterCommand(c);
|
||||
} catch (Exception e) {
|
||||
TBMCCoreAPI.SendException("An error occured while registering command " + thecmdclass.getSimpleName(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* This method adds a plugin's command to help and sets it's executor.
|
||||
* </p>
|
||||
* <p>
|
||||
* The <u>command must be registered</u> in the caller plugin's plugin.yml. Otherwise the plugin will output a messsage to console.
|
||||
* </p>
|
||||
* <p>
|
||||
* <i>Using this method after the server is done loading will have no effect.</i>
|
||||
* </p>
|
||||
*
|
||||
* @param plugin
|
||||
* The caller plugin
|
||||
* @param cmd
|
||||
* The command to add
|
||||
*/
|
||||
public static void AddCommand(JavaPlugin plugin, TBMCCommandBase cmd) {
|
||||
if (HasNulls(plugin, cmd))
|
||||
return;
|
||||
// plugin.getLogger().info("Registering command /" + cmd.GetCommandPath() + " for " + plugin.getName());
|
||||
try {
|
||||
cmd.plugin = plugin;
|
||||
commands.put(cmd.GetCommandPath(), cmd);
|
||||
CommandCaller.RegisterCommand(cmd);
|
||||
} catch (Exception e) {
|
||||
TBMCCoreAPI.SendException("An error occured while registering command " + cmd.GetCommandPath(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean HasNulls(JavaPlugin plugin, TBMCCommandBase cmd) {
|
||||
if (cmd == null) {
|
||||
TBMCCoreAPI.SendException("An error occured while registering a command for plugin " + plugin.getName(),
|
||||
new Exception("The command is null!"));
|
||||
return true;
|
||||
} else if (cmd.GetCommandPath() == null) {
|
||||
TBMCCoreAPI.SendException("An error occured while registering command " + cmd.getClass().getSimpleName()
|
||||
+ " for plugin " + plugin.getName(), new Exception("The command path is null!"));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a chat message to Minecraft. Make sure that the channel is registered with {@link #RegisterChatChannel(Channel)}.<br>
|
||||
* This will also send the error message to the sender, if they can't send the message.
|
||||
*
|
||||
* @param cm The message to send
|
||||
* @return The event cancelled state
|
||||
*/
|
||||
public static boolean SendChatMessage(ChatMessage cm) {
|
||||
return SendChatMessage(cm, cm.getUser().channel().get());
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a chat message to Minecraft. Make sure that the channel is registered with {@link #RegisterChatChannel(Channel)}.<br>
|
||||
* This will also send the error message to the sender, if they can't send the message.
|
||||
*
|
||||
* @param cm The message to send
|
||||
* @param channel The MC channel to send in
|
||||
* @return The event cancelled state
|
||||
*/
|
||||
public static boolean SendChatMessage(ChatMessage cm, Channel channel) {
|
||||
if (!Channel.getChannels().contains(channel))
|
||||
throw new RuntimeException("Channel " + channel.DisplayName + " not registered!");
|
||||
val permcheck = cm.getPermCheck();
|
||||
RecipientTestResult rtr = getScoreOrSendError(channel, permcheck);
|
||||
int score = rtr.score;
|
||||
if (score == Channel.SCORE_SEND_NOPE || rtr.groupID == null)
|
||||
return true;
|
||||
TBMCChatPreprocessEvent eventPre = new TBMCChatPreprocessEvent(cm.getSender(), channel, cm.getMessage());
|
||||
Bukkit.getPluginManager().callEvent(eventPre);
|
||||
if (eventPre.isCancelled())
|
||||
return true;
|
||||
cm.setMessage(eventPre.getMessage());
|
||||
TBMCChatEvent event;
|
||||
event = new TBMCChatEvent(channel, cm, rtr);
|
||||
Bukkit.getPluginManager().callEvent(event);
|
||||
return event.isCancelled();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a regular message to Minecraft. Make sure that the channel is registered with {@link #RegisterChatChannel(Channel)}.
|
||||
*
|
||||
* @param channel
|
||||
* The channel to send to
|
||||
* @param rtr
|
||||
* The score&group to use to find the group - use {@link RecipientTestResult#ALL} if the channel doesn't have scores
|
||||
* @param message
|
||||
* The message to send
|
||||
* @return The event cancelled state
|
||||
*/
|
||||
public static boolean SendSystemMessage(Channel channel, RecipientTestResult rtr, String message) {
|
||||
if (!Channel.getChannels().contains(channel))
|
||||
throw new RuntimeException("Channel " + channel.DisplayName + " not registered!");
|
||||
TBMCSystemChatEvent event = new TBMCSystemChatEvent(channel, message, rtr.score, rtr.groupID);
|
||||
Bukkit.getPluginManager().callEvent(event);
|
||||
return event.isCancelled();
|
||||
}
|
||||
|
||||
private static RecipientTestResult getScoreOrSendError(Channel channel, CommandSender sender) {
|
||||
RecipientTestResult result = channel.getRTR(sender);
|
||||
if (result.errormessage != null)
|
||||
sender.sendMessage("§c" + result.errormessage);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a chat channel. See {@link Channel#Channel(String, Color, String, java.util.function.Function)} for details.
|
||||
*
|
||||
* @param channel
|
||||
* A new {@link Channel} to register
|
||||
*/
|
||||
public static void RegisterChatChannel(Channel channel) {
|
||||
Channel.RegisterChannel(channel);
|
||||
}
|
||||
}
|
||||
package buttondevteam.lib.chat;
|
||||
|
||||
import buttondevteam.component.channel.Channel;
|
||||
import buttondevteam.component.channel.Channel.RecipientTestResult;
|
||||
import buttondevteam.core.CommandCaller;
|
||||
import buttondevteam.core.MainPlugin;
|
||||
import buttondevteam.lib.TBMCChatEvent;
|
||||
import buttondevteam.lib.TBMCChatPreprocessEvent;
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import buttondevteam.lib.TBMCSystemChatEvent;
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import lombok.val;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.reflections.Reflections;
|
||||
import org.reflections.scanners.SubTypesScanner;
|
||||
import org.reflections.util.ClasspathHelper;
|
||||
import org.reflections.util.ConfigurationBuilder;
|
||||
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class TBMCChatAPI {
|
||||
|
||||
private static final HashMap<String, TBMCCommandBase> commands = new HashMap<>();
|
||||
|
||||
public static HashMap<String, TBMCCommandBase> GetCommands() {
|
||||
return commands;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns messages formatted for Minecraft chat listing the subcommands of the command.
|
||||
*
|
||||
* @param command
|
||||
* The command which we want the subcommands of
|
||||
* @param sender
|
||||
* The sender for permissions
|
||||
* @return The subcommands
|
||||
*/
|
||||
public static String[] GetSubCommands(TBMCCommandBase command, CommandSender sender) {
|
||||
return GetSubCommands(command.GetCommandPath(), sender);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns messages formatted for Minecraft chat listing the subcommands of the command.<br>
|
||||
* Returns a header if subcommands were found, otherwise returns an empty array.
|
||||
*
|
||||
* @param command
|
||||
* The command which we want the subcommands of
|
||||
* @param sender
|
||||
* The sender for permissions
|
||||
* @return The subcommands
|
||||
*/
|
||||
public static String[] GetSubCommands(String command, CommandSender sender) {
|
||||
ArrayList<String> cmds = new ArrayList<String>();
|
||||
Consumer<String> addToCmds = cmd -> {
|
||||
if (cmds.size() == 0)
|
||||
cmds.add("§6---- Subcommands ----");
|
||||
cmds.add(cmd);
|
||||
};
|
||||
for (Entry<String, TBMCCommandBase> cmd : TBMCChatAPI.GetCommands().entrySet()) {
|
||||
if (cmd.getKey().startsWith(command + " ")) {
|
||||
if (cmd.getValue().isPlayerOnly() && !(sender instanceof Player))
|
||||
continue;
|
||||
if (cmd.getValue().isModOnly() && (MainPlugin.permission != null ? !MainPlugin.permission.has(sender, "tbmc.admin") : !sender.isOp()))
|
||||
continue;
|
||||
int ind = cmd.getKey().indexOf(' ', command.length() + 2);
|
||||
if (ind >= 0) {
|
||||
String newcmd = cmd.getKey().substring(0, ind);
|
||||
if (!cmds.contains("/" + newcmd))
|
||||
addToCmds.accept("/" + newcmd);
|
||||
} else
|
||||
addToCmds.accept("/" + cmd.getKey());
|
||||
}
|
||||
}
|
||||
return cmds.toArray(new String[0]); //Apparently it's faster to use an empty array in modern Java
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* This method adds a plugin's commands to help and sets their executor.
|
||||
* </p>
|
||||
* <p>
|
||||
* </p>
|
||||
* <b>The command classes have to have a constructor each with no parameters</b>
|
||||
* <p>
|
||||
* The <u>command must be registered</u> in the caller plugin's plugin.yml. Otherwise the plugin will output a messsage to console.
|
||||
* </p>
|
||||
* <p>
|
||||
* <i>Using this method after the server is done loading will have no effect.</i>
|
||||
* </p>
|
||||
*
|
||||
* @param plugin
|
||||
* The caller plugin
|
||||
* @param acmdclass
|
||||
* A command's class to get the package name for commands. The provided class's package and subpackages are scanned for commands.
|
||||
*/
|
||||
public static synchronized void AddCommands(JavaPlugin plugin, Class<? extends TBMCCommandBase> acmdclass) {
|
||||
plugin.getLogger().info("Registering commands from " + acmdclass.getPackage().getName());
|
||||
Reflections rf = new Reflections(new ConfigurationBuilder()
|
||||
.setUrls(ClasspathHelper.forPackage(acmdclass.getPackage().getName(),
|
||||
plugin.getClass().getClassLoader()))
|
||||
.addUrls(
|
||||
ClasspathHelper.forClass(OptionallyPlayerCommandBase.class,
|
||||
OptionallyPlayerCommandBase.class.getClassLoader()),
|
||||
ClasspathHelper.forClass(PlayerCommandBase.class, PlayerCommandBase.class.getClassLoader())) // http://stackoverflow.com/questions/12917417/using-reflections-for-finding-the-transitive-subtypes-of-a-class-when-not-all
|
||||
.addClassLoader(plugin.getClass().getClassLoader()).addScanners(new SubTypesScanner()));
|
||||
Set<Class<? extends TBMCCommandBase>> cmds = rf.getSubTypesOf(TBMCCommandBase.class);
|
||||
for (Class<? extends TBMCCommandBase> cmd : cmds) {
|
||||
try {
|
||||
if (!cmd.getPackage().getName().startsWith(acmdclass.getPackage().getName()))
|
||||
continue; // It keeps including the commands from here
|
||||
if (Modifier.isAbstract(cmd.getModifiers()))
|
||||
continue;
|
||||
TBMCCommandBase c = cmd.newInstance();
|
||||
c.plugin = plugin;
|
||||
CommandCaller.RegisterCommand(c); //Will check for nulls
|
||||
commands.put(c.GetCommandPath(), c);
|
||||
} catch (Exception e) {
|
||||
TBMCCoreAPI.SendException("An error occured while registering command " + cmd.getName(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* This method adds a plugin's command to help and sets it's executor. They will be automatically unregistered on plugin disable.
|
||||
* </p>
|
||||
* <p>
|
||||
* The <u>command must be registered</u> in the caller plugin's plugin.yml. Otherwise the plugin will output a messsage to console.
|
||||
* </p>
|
||||
* <p>
|
||||
* <i>Using this method after the server is done loading will have no effect.</i>
|
||||
* </p>
|
||||
*
|
||||
* @param plugin
|
||||
* The caller plugin
|
||||
* @param thecmdclass
|
||||
* The command's class to create it (because why let you create the command class)
|
||||
*/
|
||||
public static void AddCommand(JavaPlugin plugin, Class<? extends TBMCCommandBase> thecmdclass, Object... params) {
|
||||
// plugin.getLogger().info("Registering command " + thecmdclass.getSimpleName() + " for " + plugin.getName());
|
||||
try {
|
||||
TBMCCommandBase c;
|
||||
if (params.length > 0)
|
||||
c = thecmdclass.getConstructor(Arrays.stream(params).map(Object::getClass).toArray(Class[]::new))
|
||||
.newInstance(params);
|
||||
else
|
||||
c = thecmdclass.newInstance();
|
||||
c.plugin = plugin;
|
||||
CommandCaller.RegisterCommand(c); //Will check for nulls
|
||||
commands.put(c.GetCommandPath(), c);
|
||||
} catch (Exception e) {
|
||||
TBMCCoreAPI.SendException("An error occured while registering command " + thecmdclass.getSimpleName(), e);
|
||||
}
|
||||
} //TODO: onCommand(CommandSender sender, String alias, int arg1, String arg2) (planned for a while)
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* This method adds a plugin's command to help and sets its executor. They will be automatically unregistered on plugin disable.
|
||||
* </p>
|
||||
* <p>
|
||||
* The <u>command must be registered</u> in the caller plugin's plugin.yml. Otherwise the plugin will output a message to console.
|
||||
* </p>
|
||||
* <p>
|
||||
* <i>Using this method after the server is done loading will have no effect.</i>
|
||||
* </p>
|
||||
*
|
||||
* @param plugin
|
||||
* The caller plugin
|
||||
* @param cmd
|
||||
* The command to add
|
||||
*/
|
||||
public static void AddCommand(JavaPlugin plugin, TBMCCommandBase cmd) {
|
||||
try {
|
||||
if (plugin == null) throw new IllegalArgumentException("The plugin is null!");
|
||||
if (cmd == null) throw new IllegalArgumentException("The command is null!");
|
||||
cmd.plugin = plugin;
|
||||
CommandCaller.RegisterCommand(cmd); //Checks for other nulls
|
||||
commands.put(cmd.GetCommandPath(), cmd);
|
||||
} catch (Exception e) {
|
||||
TBMCCoreAPI.SendException("An error occured while registering command " + (cmd == null ? "n u l l" : cmd.GetCommandPath()), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* This method adds a plugin's command to help and sets its executor. They will be automatically unregistered on component disable.
|
||||
* </p>
|
||||
* <p>
|
||||
* The <u>command must be registered</u> in the caller plugin's plugin.yml. Otherwise the plugin will output a message to console.
|
||||
* </p>
|
||||
* <p>
|
||||
* <i>Using this method after the server is done loading will have no effect.</i>
|
||||
* </p>
|
||||
*
|
||||
* @param component The caller component
|
||||
* @param cmd The command to add
|
||||
*/
|
||||
public static void AddCommand(Component component, TBMCCommandBase cmd) {
|
||||
try {
|
||||
if (component == null) throw new IllegalArgumentException("The component is null!");
|
||||
if (cmd == null) throw new IllegalArgumentException("The command is null!");
|
||||
cmd.plugin = component.getPlugin();
|
||||
cmd.component = component;
|
||||
CommandCaller.RegisterCommand(cmd); //Checks for other nulls
|
||||
commands.put(cmd.GetCommandPath(), cmd);
|
||||
} catch (Exception e) {
|
||||
TBMCCoreAPI.SendException("An error occured while registering command " + (cmd == null ? "n u l l" : cmd.GetCommandPath()), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes all commands from the plugin
|
||||
*
|
||||
* @param plugin The plugin to remove commands from
|
||||
*/
|
||||
public static void RemoveCommands(JavaPlugin plugin) {
|
||||
commands.values().removeIf(c -> {
|
||||
try {
|
||||
if (c.plugin == plugin) {
|
||||
CommandCaller.UnregisterCommand(c);
|
||||
return true; //Remove
|
||||
}
|
||||
return false;
|
||||
} catch (Exception e) {
|
||||
TBMCCoreAPI.SendException("An error occured while unregistering commands for " + plugin.getName(), e);
|
||||
return true; //Remove if it couldn't get the plugin command
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes all commands from the component
|
||||
*
|
||||
* @param component The component to remove commands from
|
||||
*/
|
||||
public static void RemoveCommands(Component component) {
|
||||
commands.values().removeIf(c -> {
|
||||
try {
|
||||
if (c.component == component) {
|
||||
CommandCaller.UnregisterCommand(c);
|
||||
return true; //Remove
|
||||
}
|
||||
return false;
|
||||
} catch (Exception e) {
|
||||
TBMCCoreAPI.SendException("An error occured while unregistering commands for " + component.getClass().getSimpleName(), e);
|
||||
return true; //Remove if it couldn't get the plugin command
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a chat message to Minecraft. Make sure that the channel is registered with {@link #RegisterChatChannel(Channel)}.<br>
|
||||
* This will also send the error message to the sender, if they can't send the message.
|
||||
*
|
||||
* @param cm The message to send
|
||||
* @return The event cancelled state
|
||||
*/
|
||||
public static boolean SendChatMessage(ChatMessage cm) {
|
||||
return SendChatMessage(cm, cm.getUser().channel().get());
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a chat message to Minecraft. Make sure that the channel is registered with {@link #RegisterChatChannel(Channel)}.<br>
|
||||
* This will also send the error message to the sender, if they can't send the message.
|
||||
*
|
||||
* @param cm The message to send
|
||||
* @param channel The MC channel to send in
|
||||
* @return The event cancelled state
|
||||
*/
|
||||
public static boolean SendChatMessage(ChatMessage cm, Channel channel) {
|
||||
if (!Channel.getChannelList().contains(channel))
|
||||
throw new RuntimeException("Channel " + channel.DisplayName().get() + " not registered!");
|
||||
if (!channel.Enabled().get()) {
|
||||
cm.getSender().sendMessage("§cThe channel '" + channel.DisplayName().get() + "' is disabled!");
|
||||
return true; //Cancel sending if channel is disabled
|
||||
}
|
||||
val permcheck = cm.getPermCheck();
|
||||
RecipientTestResult rtr = getScoreOrSendError(channel, permcheck);
|
||||
int score = rtr.score;
|
||||
if (score == Channel.SCORE_SEND_NOPE || rtr.groupID == null)
|
||||
return true;
|
||||
TBMCChatPreprocessEvent eventPre = new TBMCChatPreprocessEvent(cm.getSender(), channel, cm.getMessage());
|
||||
Bukkit.getPluginManager().callEvent(eventPre);
|
||||
if (eventPre.isCancelled())
|
||||
return true;
|
||||
cm.setMessage(eventPre.getMessage());
|
||||
TBMCChatEvent event;
|
||||
event = new TBMCChatEvent(channel, cm, rtr);
|
||||
Bukkit.getPluginManager().callEvent(event);
|
||||
return event.isCancelled();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a regular message to Minecraft. Make sure that the channel is registered with {@link #RegisterChatChannel(Channel)}.
|
||||
*
|
||||
* @param channel
|
||||
* The channel to send to
|
||||
* @param rtr
|
||||
* The score&group to use to find the group - use {@link RecipientTestResult#ALL} if the channel doesn't have scores
|
||||
* @param message
|
||||
* The message to send
|
||||
* @param exceptions Platforms where this message shouldn't be sent (same as {@link ChatMessage#getOrigin()}
|
||||
* @return The event cancelled state
|
||||
*/
|
||||
public static boolean SendSystemMessage(Channel channel, RecipientTestResult rtr, String message, String... exceptions) {
|
||||
if (!Channel.getChannelList().contains(channel))
|
||||
throw new RuntimeException("Channel " + channel.DisplayName().get() + " not registered!");
|
||||
if (!channel.Enabled().get())
|
||||
return true; //Cancel sending
|
||||
TBMCSystemChatEvent event = new TBMCSystemChatEvent(channel, message, rtr.score, rtr.groupID, exceptions);
|
||||
Bukkit.getPluginManager().callEvent(event);
|
||||
return event.isCancelled();
|
||||
}
|
||||
|
||||
private static RecipientTestResult getScoreOrSendError(Channel channel, CommandSender sender) {
|
||||
RecipientTestResult result = channel.getRTR(sender);
|
||||
if (result.errormessage != null)
|
||||
sender.sendMessage("§c" + result.errormessage);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a chat channel. See {@link Channel#Channel(String, Color, String, java.util.function.Function)} for details.
|
||||
*
|
||||
* @param channel
|
||||
* A new {@link Channel} to register
|
||||
*/
|
||||
public static void RegisterChatChannel(Channel channel) {
|
||||
Channel.RegisterChannel(channel);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,106 +1,111 @@
|
|||
package buttondevteam.lib.chat;
|
||||
|
||||
import javassist.Modifier;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* Extend this class to create new TBMCCommand and use {@link TBMCChatAPI#AddCommand(org.bukkit.plugin.java.JavaPlugin, TBMCCommandBase)} to add it. <u><b>Note:</b></u> The command path (command name
|
||||
* and subcommand arguments) will be the class name by default, removing any "command" from it. To change it (especially for subcommands), use the path field in the {@link CommandClass} annotation.
|
||||
*
|
||||
* @author Norbi
|
||||
*
|
||||
*/
|
||||
@TBMCCommandEnforcer
|
||||
public abstract class TBMCCommandBase {
|
||||
|
||||
public TBMCCommandBase() {
|
||||
path = getcmdpath();
|
||||
modonly = ismodonly();
|
||||
}
|
||||
|
||||
public abstract boolean OnCommand(CommandSender sender, String alias, String[] args);
|
||||
|
||||
public abstract String[] GetHelpText(String alias);
|
||||
|
||||
private final String path;
|
||||
|
||||
/**
|
||||
* The command's path, or name if top-level command.<br>
|
||||
* For example:<br>
|
||||
* "u admin updateplugin" or "u" for the top level one<br>
|
||||
* <u>The path must be lowercase!</u><br>
|
||||
* <b>Abstract classes with no {@link CommandClass} annotations will be ignored.</b>
|
||||
*
|
||||
* @return The command path, <i>which is the command class name by default</i> (removing any "command" from it) - Change via the {@link CommandClass} annotation
|
||||
*/
|
||||
public final String GetCommandPath() {
|
||||
return path;
|
||||
}
|
||||
|
||||
private String getcmdpath() {
|
||||
if (!getClass().isAnnotationPresent(CommandClass.class))
|
||||
throw new RuntimeException(
|
||||
"No @CommandClass annotation on command class " + getClass().getSimpleName() + "!");
|
||||
Function<Class<?>, String> getFromClass = cl -> cl.getSimpleName().toLowerCase().replace("commandbase", "") // <-- ...
|
||||
.replace("command", "");
|
||||
String path = getClass().getAnnotation(CommandClass.class).path(),
|
||||
prevpath = path = path.length() == 0 ? getFromClass.apply(getClass()) : path;
|
||||
for (Class<?> cl = getClass().getSuperclass(); cl != null
|
||||
&& !cl.getPackage().getName().equals(TBMCCommandBase.class.getPackage().getName()); cl = cl
|
||||
.getSuperclass()) { //
|
||||
String newpath;
|
||||
if (!cl.isAnnotationPresent(CommandClass.class)
|
||||
|| (newpath = cl.getAnnotation(CommandClass.class).path()).length() == 0
|
||||
|| newpath.equals(prevpath)) {
|
||||
if ((Modifier.isAbstract(cl.getModifiers()) && !cl.isAnnotationPresent(CommandClass.class))
|
||||
|| cl.getAnnotation(CommandClass.class).excludeFromPath()) // <--
|
||||
continue;
|
||||
newpath = getFromClass.apply(cl);
|
||||
}
|
||||
path = (prevpath = newpath) + " " + path;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
Plugin plugin; // Used By TBMCChatAPI
|
||||
|
||||
public final Plugin getPlugin() { // Used by CommandCaller (ButtonChat)
|
||||
return plugin;
|
||||
}
|
||||
|
||||
public final boolean isPlayerOnly() {
|
||||
return this instanceof PlayerCommandBase ||
|
||||
(this instanceof OptionallyPlayerCommandBase &&
|
||||
(!getClass().isAnnotationPresent(OptionallyPlayerCommandClass.class)
|
||||
|| getClass().getAnnotation(OptionallyPlayerCommandClass.class).playerOnly()));
|
||||
}
|
||||
|
||||
private final boolean modonly;
|
||||
|
||||
/**
|
||||
* Returns true if this class' or any superclass' modOnly property is set to true.
|
||||
*/
|
||||
public final boolean isModOnly() {
|
||||
return modonly;
|
||||
}
|
||||
|
||||
private boolean ismodonly() {
|
||||
if (!getClass().isAnnotationPresent(CommandClass.class))
|
||||
throw new RuntimeException(
|
||||
"No @CommandClass annotation on command class " + getClass().getSimpleName() + "!");
|
||||
boolean modOnly = getClass().getAnnotation(CommandClass.class).modOnly();
|
||||
for (Class<?> cl = getClass().getSuperclass(); cl != null
|
||||
&& !cl.getPackage().getName().equals(TBMCCommandBase.class.getPackage().getName()); cl = cl
|
||||
.getSuperclass()) { //
|
||||
if (cl.isAnnotationPresent(CommandClass.class) && !modOnly
|
||||
&& cl.getAnnotation(CommandClass.class).modOnly()) {
|
||||
modOnly = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return modOnly;
|
||||
}
|
||||
}
|
||||
package buttondevteam.lib.chat;
|
||||
|
||||
import buttondevteam.lib.architecture.Component;
|
||||
import javassist.Modifier;
|
||||
import lombok.Getter;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* Extend this class to create new TBMCCommand and use {@link TBMCChatAPI#AddCommand(org.bukkit.plugin.java.JavaPlugin, TBMCCommandBase)} to add it. <u><b>Note:</b></u> The command path (command name
|
||||
* and subcommand arguments) will be the class name by default, removing any "command" from it. To change it (especially for subcommands), use the path field in the {@link CommandClass} annotation.
|
||||
*
|
||||
* @author Norbi
|
||||
*
|
||||
*/
|
||||
@TBMCCommandEnforcer
|
||||
public abstract class TBMCCommandBase {
|
||||
|
||||
public TBMCCommandBase() {
|
||||
path = getcmdpath();
|
||||
modonly = ismodonly();
|
||||
}
|
||||
|
||||
public abstract boolean OnCommand(CommandSender sender, String alias, String[] args);
|
||||
|
||||
public abstract String[] GetHelpText(String alias);
|
||||
|
||||
private final String path;
|
||||
|
||||
/**
|
||||
* The command's path, or name if top-level command.<br>
|
||||
* For example:<br>
|
||||
* "u admin updateplugin" or "u" for the top level one<br>
|
||||
* <u>The path must be lowercase!</u><br>
|
||||
* <b>Abstract classes with no {@link CommandClass} annotations will be ignored.</b>
|
||||
*
|
||||
* @return The command path, <i>which is the command class name by default</i> (removing any "command" from it) - Change via the {@link CommandClass} annotation
|
||||
*/
|
||||
public final String GetCommandPath() {
|
||||
return path;
|
||||
}
|
||||
|
||||
private String getcmdpath() {
|
||||
if (!getClass().isAnnotationPresent(CommandClass.class))
|
||||
throw new RuntimeException(
|
||||
"No @CommandClass annotation on command class " + getClass().getSimpleName() + "!");
|
||||
Function<Class<?>, String> getFromClass = cl -> cl.getSimpleName().toLowerCase().replace("commandbase", "") // <-- ...
|
||||
.replace("command", "");
|
||||
String path = getClass().getAnnotation(CommandClass.class).path(),
|
||||
prevpath = path = path.length() == 0 ? getFromClass.apply(getClass()) : path;
|
||||
for (Class<?> cl = getClass().getSuperclass(); cl != null
|
||||
&& !cl.getPackage().getName().equals(TBMCCommandBase.class.getPackage().getName()); cl = cl
|
||||
.getSuperclass()) { //
|
||||
String newpath;
|
||||
if (!cl.isAnnotationPresent(CommandClass.class)
|
||||
|| (newpath = cl.getAnnotation(CommandClass.class).path()).length() == 0
|
||||
|| newpath.equals(prevpath)) {
|
||||
if ((Modifier.isAbstract(cl.getModifiers()) && !cl.isAnnotationPresent(CommandClass.class))
|
||||
|| cl.getAnnotation(CommandClass.class).excludeFromPath()) // <--
|
||||
continue;
|
||||
newpath = getFromClass.apply(cl);
|
||||
}
|
||||
path = (prevpath = newpath) + " " + path;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
Plugin plugin; // Used By TBMCChatAPI
|
||||
|
||||
public final Plugin getPlugin() { // Used by CommandCaller (ButtonChat)
|
||||
return plugin;
|
||||
}
|
||||
|
||||
public final boolean isPlayerOnly() {
|
||||
return this instanceof PlayerCommandBase ||
|
||||
(this instanceof OptionallyPlayerCommandBase &&
|
||||
(!getClass().isAnnotationPresent(OptionallyPlayerCommandClass.class)
|
||||
|| getClass().getAnnotation(OptionallyPlayerCommandClass.class).playerOnly()));
|
||||
}
|
||||
|
||||
private final boolean modonly;
|
||||
|
||||
/**
|
||||
* Returns true if this class' or any superclass' modOnly property is set to true.
|
||||
*/
|
||||
public final boolean isModOnly() {
|
||||
return modonly;
|
||||
}
|
||||
|
||||
private boolean ismodonly() {
|
||||
if (!getClass().isAnnotationPresent(CommandClass.class))
|
||||
throw new RuntimeException(
|
||||
"No @CommandClass annotation on command class " + getClass().getSimpleName() + "!");
|
||||
boolean modOnly = getClass().getAnnotation(CommandClass.class).modOnly();
|
||||
for (Class<?> cl = getClass().getSuperclass(); cl != null
|
||||
&& !cl.getPackage().getName().equals(TBMCCommandBase.class.getPackage().getName()); cl = cl
|
||||
.getSuperclass()) { //
|
||||
if (cl.isAnnotationPresent(CommandClass.class) && !modOnly
|
||||
&& cl.getAnnotation(CommandClass.class).modOnly()) {
|
||||
modOnly = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return modOnly;
|
||||
}
|
||||
|
||||
@Getter
|
||||
Component component; //May be null
|
||||
}
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
package buttondevteam.lib.player;
|
||||
|
||||
import buttondevteam.lib.chat.Channel;
|
||||
import buttondevteam.component.channel.Channel;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
|
||||
public class ChannelPlayerData { //I just want this to work
|
||||
|
@ -16,7 +16,7 @@ public class ChannelPlayerData { //I just want this to work
|
|||
String str = data.get();
|
||||
if (str.isEmpty())
|
||||
return def;
|
||||
return Channel.getChannels().stream().filter(c -> str.equals(c.ID)).findAny().orElse(def);
|
||||
return Channel.getChannels().filter(c -> str.equals(c.ID)).findAny().orElse(def);
|
||||
}
|
||||
|
||||
public void set(Channel value) {
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
package buttondevteam.lib.player;
|
||||
|
||||
import buttondevteam.component.channel.Channel;
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import buttondevteam.lib.chat.Channel;
|
||||
import com.google.common.collect.HashBiMap;
|
||||
import lombok.val;
|
||||
import org.bukkit.Bukkit;
|
||||
|
|
|
@ -1,11 +1,7 @@
|
|||
package buttondevteam.lib.player;
|
||||
|
||||
import buttondevteam.component.towny.TownyComponent;
|
||||
import buttondevteam.lib.TBMCCoreAPI;
|
||||
import com.palmergames.bukkit.towny.Towny;
|
||||
import com.palmergames.bukkit.towny.exceptions.AlreadyRegisteredException;
|
||||
import com.palmergames.bukkit.towny.exceptions.NotRegisteredException;
|
||||
import com.palmergames.bukkit.towny.object.Resident;
|
||||
import com.palmergames.bukkit.towny.object.TownyUniverse;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.entity.Player;
|
||||
|
@ -127,22 +123,7 @@ public abstract class TBMCPlayerBase extends ChromaGamerBase {
|
|||
Bukkit.getLogger().info("Player name saved: " + player.PlayerName().get());
|
||||
} else if (!p.getName().equals(player.PlayerName().get())) {
|
||||
Bukkit.getLogger().info("Renaming " + player.PlayerName().get() + " to " + p.getName());
|
||||
TownyUniverse tu = Towny.getPlugin(Towny.class).getTownyUniverse();
|
||||
Resident resident = tu.getResidentMap().get(player.PlayerName().get().toLowerCase()); //The map keys are lowercase
|
||||
if (resident == null) {
|
||||
Bukkit.getLogger().warning("Resident not found - couldn't rename in Towny.");
|
||||
TBMCCoreAPI.sendDebugMessage("Resident not found - couldn't rename in Towny.");
|
||||
} else if (tu.getResidentMap().contains(p.getName().toLowerCase())) {
|
||||
Bukkit.getLogger().warning("Target resident name is already in use."); // TODO: Handle
|
||||
TBMCCoreAPI.sendDebugMessage("Target resident name is already in use.");
|
||||
} else
|
||||
try {
|
||||
TownyUniverse.getDataSource().renamePlayer(resident, p.getName()); //Fixed in Towny 0.91.1.2
|
||||
} catch (AlreadyRegisteredException e) {
|
||||
TBMCCoreAPI.SendException("Failed to rename resident, there's already one with this name.", e);
|
||||
} catch (NotRegisteredException e) {
|
||||
TBMCCoreAPI.SendException("Failed to rename resident, the resident isn't registered.", e);
|
||||
}
|
||||
TownyComponent.renameInTowny(player.PlayerName().get(), p.getName());
|
||||
player.PlayerName().set(p.getName());
|
||||
Bukkit.getLogger().info("Renaming done.");
|
||||
}
|
||||
|
|
|
@ -1,15 +1,17 @@
|
|||
name: ButtonCore
|
||||
main: buttondevteam.core.MainPlugin
|
||||
version: 1.0
|
||||
author: TBMCPlugins
|
||||
commands:
|
||||
updateplugin:
|
||||
description: Update a TBMC plugin
|
||||
schrestart:
|
||||
description: Schedules a restart for a given time.
|
||||
primerestart:
|
||||
description: Restarts the server as soon as nobody is online.
|
||||
randomtp:
|
||||
description: teleport player to random location within world border. Every five players teleport to the same general area, and then a new general area is randomly selected for the next five players.
|
||||
member:
|
||||
description: Add or remove a member
|
||||
name: ButtonCore
|
||||
main: buttondevteam.core.MainPlugin
|
||||
version: 1.0
|
||||
author: TBMCPlugins
|
||||
commands:
|
||||
updateplugin:
|
||||
description: Update a TBMC plugin
|
||||
schrestart:
|
||||
description: Schedules a restart for a given time.
|
||||
primerestart:
|
||||
description: Restarts the server as soon as nobody is online.
|
||||
randomtp:
|
||||
description: teleport player to random location within world border. Every five players teleport to the same general area, and then a new general area is randomly selected for the next five players.
|
||||
member:
|
||||
description: Add or remove a member
|
||||
component:
|
||||
description: Enable or disable or list components
|
||||
|
|
Loading…
Reference in a new issue