This commit is contained in:
disclearing 2019-08-17 21:01:25 +01:00
commit 225fa778ce
34 changed files with 1348 additions and 0 deletions

View File

@ -0,0 +1,2 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4" />

View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cc.kentono.core</groupId>
<artifactId>Core</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.10.2</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,75 @@
package cc.kentono.core;
import cc.kentono.core.command.CommandHandler;
import cc.kentono.core.command.impl.ExampleCommand;
import cc.kentono.core.command.impl.ListCommand;
import cc.kentono.core.command.impl.rank.RankCommand;
import cc.kentono.core.command.impl.rank.args.*;
import cc.kentono.core.command.impl.rank.grants.GrantCommand;
import cc.kentono.core.listener.ChatListeners;
import cc.kentono.core.listener.PlayerListeners;
import cc.kentono.core.profile.Profile;
import cc.kentono.core.rank.Rank;
import cc.kentono.core.util.MongoHandler;
import cc.kentono.core.util.menu.MenuManager;
import lombok.Getter;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.Arrays;
@Getter
public class CorePlugin extends JavaPlugin {
@Getter
private static CorePlugin instance;
private MongoHandler mongoHandler;
private MenuManager menuManager;
public void onEnable() {
instance = this;
this.mongoHandler = new MongoHandler();
this.menuManager = new MenuManager(this);
Rank.load();
Profile.load();
this.registerListeners();
this.registerCommands();
}
private void registerListeners() {
Arrays.asList(
new PlayerListeners(),
new ChatListeners()
).forEach(listener -> Bukkit.getPluginManager().registerEvents(listener, this));
}
private void registerCommands() {
CommandHandler handler = new CommandHandler(this, "moon" /* prefix infront of :, example: /moon:gay */);
handler.registerCommands(
/* ranks */
new RankCommand(),
new RankCreateCommand(),
new RankDeleteCommand(),
new RankSetColorCommand(),
new RankSetPrefixCommand(),
new RankSetSuffixCommand(),
new RankAddPermissionCommand(),
new RankRemovePermissionCommand(),
new RankInfoCommand(),
/* ranks */
new GrantCommand(),
new ListCommand()
);
}
public void onDisable() {
Rank.getRanks().parallelStream().forEach(Rank::save);
mongoHandler.getClient().close();
}
}

View File

@ -0,0 +1,21 @@
package cc.kentono.core.command;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Command {
String name();
String permission() default "";
String usage() default "";
String[] aliases() default {""};
int requiredArgs() default 0;
boolean playerOnly() default false;
}

View File

@ -0,0 +1,133 @@
package cc.kentono.core.command;
import cc.kentono.core.util.CC;
import lombok.Getter;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandMap;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
/**
* Command API
*
* I really need a better Command API, this one is fucking ass....
* It is functional though, and I don't wnat to use an opensource command api.
*
*/
@Getter
public class CommandHandler {
private JavaPlugin plugin;
private String fallbackPrefix;
private Map<Object, Method> commands;
public CommandHandler(JavaPlugin plugin, String fallbackPrefix) {
this.commands = new HashMap<>();
this.plugin = plugin;
this.fallbackPrefix = fallbackPrefix;
}
public void registerCommands(Object... objects) {
Arrays.stream(objects).forEach(object -> Arrays.stream(object.getClass().getMethods()).forEach(method -> {
if (method.getAnnotation(Command.class) != null) {
Command command = method.getAnnotation(Command.class);
commands.put(object, method);
List<String> aliases = new ArrayList<>();
Arrays.stream(command.aliases()).forEach(alias -> aliases.add(alias.replace(".", ",").split(",")[0]));
registerCommand(new org.bukkit.command.Command(command.name().replace(".", ",").split(",")[0], "", command.usage(), aliases) {
@Override
public boolean execute(CommandSender sender, String label, String[] args) {
commands.keySet().parallelStream().forEach(cmd -> {
Method method = commands.get(cmd);
Command command = method.getAnnotation(Command.class);
String[] name = command.name().replace(".", ",").split(",");
handleCommand(method.getAnnotation(Command.class), method, cmd, sender, args, name, label);
});
return true;
}
}, command.permission());
}
}));
}
private void handleCommand(Command command, Method method, Object object, CommandSender sender, String[] args, String[] name, String label) {
if (!(sender instanceof Player) && command.playerOnly()) {
sender.sendMessage(CC.translate("&cYou must be a player to execute this command"));
return;
}
if(!label.equalsIgnoreCase(name[0]) && !isAlias(label, Arrays.asList(command.aliases())))
return;
if(name.length > 1 && args.length > 1 && !args[0].equalsIgnoreCase(name[1]))
return;
if (!sender.hasPermission(command.permission())) {
sender.sendMessage(CC.translate("&cNo permission."));
return;
}
if (args.length < command.requiredArgs()) {
sender.sendMessage(CC.translate("&cUsage: /" + name[0] + ' ' + command.usage()));
return;
}
try {
if (method.getParameterCount() > 1)
method.invoke(object, sender, args);
else
method.invoke(object, sender);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
private void registerCommand(org.bukkit.command.Command command, String permission) {
Field bukkitCommandMap = null;
command.setPermission(permission);
try {
bukkitCommandMap = Bukkit.getServer().getClass().getDeclaredField("commandMap");
bukkitCommandMap.setAccessible(true);
} catch (NoSuchFieldException | SecurityException e) {
e.printStackTrace();
}
if(bukkitCommandMap == null)
return;
CommandMap commandMap;
try {
commandMap = (CommandMap) bukkitCommandMap.get(plugin.getServer());
command.setLabel(plugin.getDescription().getName() + ':' + command.getName());
commandMap.register(plugin.getDescription().getName(), command);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
private boolean isAlias(String string, List<String> aliases) {
return aliases.stream().filter(alias -> alias.replace(".", ",").split(",")[0].equalsIgnoreCase(string)).findFirst().orElse(null) != null;
}
}

View File

@ -0,0 +1,14 @@
package cc.kentono.core.command.impl;
import cc.kentono.core.command.Command;
import cc.kentono.core.util.CC;
import org.bukkit.command.CommandSender;
public class ExampleCommand {
@Command(name="gay", permission="permission.gay")
public void execute(CommandSender sender, String[] args) {
sender.sendMessage(CC.translate("&cgay &aur &eso &kgay"));
}
}

View File

@ -0,0 +1,23 @@
package cc.kentono.core.command.impl;
import cc.kentono.core.command.Command;
import cc.kentono.core.profile.Profile;
import cc.kentono.core.rank.Rank;
import cc.kentono.core.util.CC;
import cc.kentono.core.util.PlayerUtil;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import java.util.stream.Collectors;
public class ListCommand {
@Command(name="list")
public void execute(CommandSender sender) {
sender.sendMessage(CC.translate(Rank.getRanks().parallelStream().map(Rank::getDisplayName).collect(Collectors.joining(CC.WHITE + ","))));
sender.sendMessage(CC.translate("&f(" + PlayerUtil.getOnlinePlayers().size() + '/' + Bukkit.getMaxPlayers() + ") " +
Profile.getProfiles().parallelStream().map(Profile::getDisplayName).collect(Collectors.joining(CC.WHITE+", "))
));
}
}

View File

@ -0,0 +1,21 @@
package cc.kentono.core.command.impl.rank;
import cc.kentono.core.command.Command;
import org.bukkit.command.CommandSender;
import java.util.Arrays;
public class RankCommand {
@Command(name="rank", permission="moon.rank")
public void execute(CommandSender sender) {
Arrays.asList(
"&7&m--------------------------------------------",
"&3&lRank Help ",
"",
"&9/rank create <name> &7(Creates a rank)",
"&7&m--------------------------------------------"
);
}
}

View File

@ -0,0 +1,28 @@
package cc.kentono.core.command.impl.rank.args;
import cc.kentono.core.command.Command;
import cc.kentono.core.rank.Rank;
import cc.kentono.core.util.CC;
import org.bukkit.command.CommandSender;
public class RankAddPermissionCommand {
@Command(name="rank.addpermission", permission="rank.addpermission", usage="addpermission <permission>", requiredArgs=3)
public void execute(CommandSender sender, String[] args) {
if(Rank.getByName(args[1]) == null) {
sender.sendMessage(CC.translate("&cThat rank does not exist."));
return;
}
if(!Rank.getByName(args[1]).getPermissions().parallelStream().filter(permission -> permission.equalsIgnoreCase(args[2])).findFirst().orElse("").equals("")) {
sender.sendMessage(CC.translate("&cFound a duplicate permission."));
return;
}
sender.sendMessage(CC.translate("&3Permission Added!"));
sender.sendMessage(CC.translate("&7To learn more about ranks, type /rank"));
Rank.getByName(args[1]).addPermission(args[2]);
}
}

View File

@ -0,0 +1,24 @@
package cc.kentono.core.command.impl.rank.args;
import cc.kentono.core.command.Command;
import cc.kentono.core.rank.Rank;
import cc.kentono.core.util.CC;
import org.bukkit.command.CommandSender;
public class RankCreateCommand {
@Command(name="rank.create", permission="moon.createrank", usage="create <rank>", requiredArgs=2)
public void execute(CommandSender sender, String[] args) {
if(Rank.getByName(args[1]) != null) {
sender.sendMessage(CC.translate("&cThat rank already exists."));
return;
}
Rank rank = new Rank(null, args[1]);
sender.sendMessage(CC.translate("&3Rank Created!"));
sender.sendMessage(CC.translate("&7To learn more about ranks, type /rank"));
rank.setColor(CC.WHITE);
}
}

View File

@ -0,0 +1,22 @@
package cc.kentono.core.command.impl.rank.args;
import cc.kentono.core.command.Command;
import cc.kentono.core.rank.Rank;
import cc.kentono.core.util.CC;
import org.bukkit.command.CommandSender;
public class RankDeleteCommand {
@Command(name="rank.delete", permission="moon.deleterank", usage="delete <rank>", requiredArgs=2)
public void execute(CommandSender sender, String[] args) {
if(Rank.getByName(args[1]) == null) {
sender.sendMessage(CC.translate("&cThat rank does not exist."));
return;
}
Rank.getByName(args[1]).delete();
sender.sendMessage(CC.translate("&4Rank Deleted!"));
sender.sendMessage(CC.translate("&7To learn more about ranks, type /rank"));
}
}

View File

@ -0,0 +1,36 @@
package cc.kentono.core.command.impl.rank.args;
import cc.kentono.core.command.Command;
import cc.kentono.core.rank.Rank;
import cc.kentono.core.util.CC;
import org.bukkit.command.CommandSender;
import java.util.Arrays;
import java.util.stream.Collectors;
public class RankInfoCommand {
@Command(name = "rank.info", permission = "moon.rankinfo", usage = "info <rank>", requiredArgs = 2)
public void execute(CommandSender sender, String[] args) {
if (Rank.getByName(args[1]) == null) {
sender.sendMessage(CC.translate("&cThat rank does not exist."));
return;
}
Rank rank = Rank.getByName(args[1]);
CC.translate(Arrays.asList(
"&7&m--------------------------------------------",
rank.getDisplayName() + "'s &eInformation",
"",
"&eColor: " + rank.getColor() + rank.getColor().name(),
"&ePrefix: &r" + rank.getPrefix(),
"&eSuffix: &r" + rank.getSuffix(),
"",
"&ePermissions &6(" + rank.getPermissions().size() + ")&f: " + String.join(", ", rank.getPermissions()),
"&eInherits &6(" + rank.getInherits().size() + ")&f: " + rank.getInherits().parallelStream().map(inherit -> Rank.getByUuid(inherit).getDisplayName()).collect(Collectors.joining(CC.WHITE + ", ")),
"&7&m--------------------------------------------"
)).forEach(sender::sendMessage);
}
}

View File

@ -0,0 +1,28 @@
package cc.kentono.core.command.impl.rank.args;
import cc.kentono.core.command.Command;
import cc.kentono.core.rank.Rank;
import cc.kentono.core.util.CC;
import org.bukkit.command.CommandSender;
public class RankRemovePermissionCommand {
@Command(name="rank.removepermission", permission="rank.removepermission", usage="removepermission <permission>", requiredArgs=3)
public void execute(CommandSender sender, String[] args) {
if(Rank.getByName(args[1]) == null) {
sender.sendMessage(CC.translate("&cThat rank does not exist."));
return;
}
if(Rank.getByName(args[1]).getPermissions().parallelStream().filter(permission -> permission.equalsIgnoreCase(args[2])).findFirst().orElse("").equals("")) {
sender.sendMessage(CC.translate("&cRank does not have permission \"" + args[2] + "\""));
return;
}
sender.sendMessage(CC.translate("&3Permission Removed!"));
sender.sendMessage(CC.translate("&7To learn more about ranks, type /rank"));
Rank.getByName(args[1]).removePermission(args[2]);
}
}

View File

@ -0,0 +1,30 @@
package cc.kentono.core.command.impl.rank.args;
import cc.kentono.core.command.Command;
import cc.kentono.core.rank.Rank;
import cc.kentono.core.util.CC;
import org.bukkit.command.CommandSender;
import java.util.Arrays;
public class RankSetColorCommand {
@Command(name="rank.setcolor", permission="moon.setcolor", usage="setcolor <rank> <color>", requiredArgs=3)
public void execute(CommandSender sender, String[] args) {
if(Rank.getByName(args[1]) == null) {
sender.sendMessage(CC.translate("&cThat rank does not exist."));
return;
}
if(Arrays.stream(CC.values()).filter(color -> color.name().equalsIgnoreCase(args[2])).findFirst().orElse(null) == null) {
sender.sendMessage(CC.translate("&c" + args[2] + " is not a color."));
return;
}
sender.sendMessage(CC.translate("&3Color Changed!"));
sender.sendMessage(CC.translate("&7To learn more about ranks, type /rank"));
Rank.getByName(args[1]).setColor(Arrays.stream(CC.values()).filter(color -> color.name().equalsIgnoreCase(args[2])).findFirst().orElse(null));
}
}

View File

@ -0,0 +1,23 @@
package cc.kentono.core.command.impl.rank.args;
import cc.kentono.core.command.Command;
import cc.kentono.core.rank.Rank;
import cc.kentono.core.util.CC;
import org.bukkit.command.CommandSender;
public class RankSetPrefixCommand {
@Command(name="rank.setprefix", permission="moon.setprefix", usage="setprefix <rank> <prefix>", requiredArgs=3)
public void execute(CommandSender sender, String[] args) {
if(Rank.getByName(args[1]) == null) {
sender.sendMessage(CC.translate("&cThat rank does not exist."));
return;
}
sender.sendMessage(CC.translate("&3Prefix Changed!"));
sender.sendMessage(CC.translate("&7To learn more about ranks, type /rank"));
Rank.getByName(args[1]).setPrefix(args[2].replace("_", " "));
}
}

View File

@ -0,0 +1,23 @@
package cc.kentono.core.command.impl.rank.args;
import cc.kentono.core.command.Command;
import cc.kentono.core.rank.Rank;
import cc.kentono.core.util.CC;
import org.bukkit.command.CommandSender;
public class RankSetSuffixCommand {
@Command(name="rank.setsuffix", permission="moon.setsuffix", usage="setsuffix <rank> <suffix>", requiredArgs=3)
public void execute(CommandSender sender, String[] args) {
if(Rank.getByName(args[1]) == null) {
sender.sendMessage(CC.translate("&cThat rank does not exist."));
return;
}
sender.sendMessage(CC.translate("&3Suffix Changed!"));
sender.sendMessage(CC.translate("&7To learn more about ranks, type /rank"));
Rank.getByName(args[1]).setSuffix(args[2].replace("_", " "));
}
}

View File

@ -0,0 +1,23 @@
package cc.kentono.core.command.impl.rank.args;
import cc.kentono.core.command.Command;
import cc.kentono.core.rank.Rank;
import cc.kentono.core.util.CC;
import org.bukkit.command.CommandSender;
public class RankSetWeightCommand {
@Command(name="rank.setweight", permission="moon.setweight", usage="setweight <rank> <weight>", requiredArgs=3)
public void execute(CommandSender sender, String[] args) {
if(Rank.getByName(args[1]) == null) {
sender.sendMessage(CC.translate("&cThat rank does not exist."));
return;
}
sender.sendMessage(CC.translate("&3Weight Changed!"));
sender.sendMessage(CC.translate("&7To learn more about ranks, type /rank"));
Rank.getByName(args[1]).setWeight(Integer.parseInt(args[2]));
}
}

View File

@ -0,0 +1,23 @@
package cc.kentono.core.command.impl.rank.grants;
import cc.kentono.core.command.Command;
import cc.kentono.core.command.impl.rank.grants.menu.GrantMenu;
import cc.kentono.core.profile.Profile;
import cc.kentono.core.util.CC;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class GrantCommand {
@Command(name="grant", permission="moon.grant", usage="<player>", requiredArgs=1)
public void execute(CommandSender sender, String[] args) {
if(Profile.getByName(args[0]) == null) {
sender.sendMessage(CC.translate("&cThat player does not exist."));
return;
}
new GrantMenu(Profile.getByName(args[0]), Profile.getByName(sender.getName())).openMenu((Player) sender);
}
}

View File

@ -0,0 +1,53 @@
package cc.kentono.core.command.impl.rank.grants.menu;
import cc.kentono.core.profile.Profile;
import cc.kentono.core.rank.Rank;
import cc.kentono.core.rank.grant.Grant;
import cc.kentono.core.util.WoolColor;
import cc.kentono.core.util.menu.impl.Button;
import cc.kentono.core.util.menu.impl.Menu;
import lombok.Getter;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
@Getter
public class GrantMenu extends Menu {
private int size;
private boolean placeholder;
private String title;
private Map<Integer, Button> buttons;
public GrantMenu(Profile target, Profile granter) {
this.size = 36;
this.placeholder = true;
this.title = "Grant a Rank";
this.buttons = new HashMap<>();
List<Rank> ranks = Rank.getRanks();
IntStream.range(0, ranks.size()).forEach(i -> {
Rank rank = ranks.get(i);
buttons.put(i, new Button(new ItemStack(Material.WOOL))
.damage(WoolColor.getWoolColor(rank.getColor()))
.displayName(rank.getDisplayName())
.lore("&7&m------------------", "&eClick here to grant " + target.getDisplayName() + " &ethe " + rank.getDisplayName() + " &erank")
.click(new BukkitRunnable() {
@Override
public void run() {
target.addGrant(new Grant(rank, granter));
this.cancel();
}
}).create());
});
}
}

View File

@ -0,0 +1,41 @@
package cc.kentono.core.listener;
import cc.kentono.core.profile.Profile;
import cc.kentono.core.rank.Rank;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
public class ChatListeners implements Listener {
@EventHandler(priority= EventPriority.HIGHEST)
public void onChat(AsyncPlayerChatEvent event) {
if(checkMute(event)) return;
if(checkCooldown(event)) return;
Player player = event.getPlayer();
Profile profile = Profile.getByUuid(player.getUniqueId());
Rank rank = profile.getGrants().get(0).getRank();
String prefix = rank.getPrefix();
String suffix = rank.getSuffix();
String msg = event.getMessage().replace("%", "%%");
event.setFormat(prefix + player.getName() + suffix + "&7: &f" + msg);
}
private boolean checkMute(AsyncPlayerChatEvent event) {
// todo
return false;
}
private boolean checkCooldown(AsyncPlayerChatEvent event) {
// todo
return false;
}
}

View File

@ -0,0 +1,43 @@
package cc.kentono.core.listener;
import cc.kentono.core.profile.Profile;
import cc.kentono.core.rank.Rank;
import cc.kentono.core.rank.grant.Grant;
import org.bukkit.entity.Player;
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;
public class PlayerListeners implements Listener {
@EventHandler(priority= EventPriority.HIGHEST)
public void onJoin(PlayerJoinEvent event) {
event.setJoinMessage(null);
Player player = event.getPlayer();
Profile profile;
if(Profile.getByUuid(player.getUniqueId()) == null) {
profile = new Profile(player.getUniqueId());
profile.addGrant(new Grant(Rank.getDefaultRank(), null));
}
else
profile = Profile.getByUuid(player.getUniqueId());
profile.setPlayer(player);
profile.getGrants().parallelStream().forEach(grant -> grant.getRank().getPermissions().forEach(perm -> grant.getRank().setPermission(perm, true)));
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onQuit(PlayerQuitEvent event) {
event.setQuitMessage(null);
Profile profile = Profile.getByUuid(event.getPlayer().getUniqueId());
profile.setPlayer(null);
profile.save();
}
}

View File

@ -0,0 +1,113 @@
package cc.kentono.core.profile;
import cc.kentono.core.rank.Rank;
import cc.kentono.core.rank.grant.Grant;
import cc.kentono.core.util.MongoHandler;
import com.mongodb.Block;
import com.mongodb.client.model.UpdateOptions;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.util.com.google.gson.JsonArray;
import net.minecraft.util.com.google.gson.JsonObject;
import net.minecraft.util.com.google.gson.JsonParser;
import org.bson.Document;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;
import static com.mongodb.client.model.Filters.eq;
@Getter
@Setter
public class Profile {
private UUID uuid;
private List<Grant> grants;
private Player player;
private String name;
@Getter
private static List<Profile> profiles = new ArrayList<>();
public Profile(UUID uuid) {
this.uuid = uuid;
this.grants = new ArrayList<>();
profiles.add(this);
}
public void save() {
Document document = new Document();
document.put("uuid", uuid.toString());
// TODO: Add grants
JsonArray grantsDoc = new JsonArray();
grants.forEach(grant -> {
JsonObject doc = new JsonObject();
doc.addProperty("rank", grant.getRank().getUuid().toString());
if(grant.getGranter() != null) {
doc.addProperty("granter", grant.getGranter().getUuid().toString());
}
grantsDoc.add(doc);
});
document.put("grants", grants.toString());
MongoHandler.PROFILE_COLLECTION.replaceOne(eq("uuid", uuid.toString()), document, new UpdateOptions().upsert(true));
}
public static void load() {
MongoHandler.PROFILE_COLLECTION.find().forEach((Block) block -> {
Document document = (Document) block;
UUID uuid = UUID.fromString(document.getString("uuid"));
Profile profile = new Profile(uuid);
new JsonParser().parse(document.getString("grants")).getAsJsonArray().forEach(element -> {
JsonObject object = element.getAsJsonObject();
UUID rankUuid = UUID.fromString(object.get("rank").getAsString());
UUID granter = null;
if(object.get("granter") != null)
granter = UUID.fromString(object.get("granter").getAsString());
profile.getGrants().add(new Grant(Rank.getByUuid(rankUuid), Profile.getByUuid(granter)));
});
});
}
public void addGrant(Grant grant) {
Comparator<Grant> comparator = Comparator.comparing(grent -> grent.getRank().getWeight());
grants.add(grant);
grants.sort(comparator);
}
public void removeGrant(Grant grant) {
Comparator<Grant> comparator = Comparator.comparing(grent -> grent.getRank().getWeight());
grants.remove(grant);
grants.sort(comparator);
}
public String getDisplayName() {
return grants.get(0).getRank().getColor() + name;
}
public static Profile getByName(String name) { return profiles.stream().filter(profile -> profile.getName().toLowerCase().startsWith(name.toLowerCase())).findFirst().orElse(null); }
public static Profile getByUuid(UUID uuid) { return profiles.stream().filter(profile -> profile.getUuid().equals(uuid)).findFirst().orElse(null); }
}

View File

@ -0,0 +1,126 @@
package cc.kentono.core.rank;
import cc.kentono.core.CorePlugin;
import cc.kentono.core.profile.Profile;
import cc.kentono.core.util.CC;
import cc.kentono.core.util.MongoHandler;
import com.google.gson.JsonParser;
import com.mongodb.Block;
import com.mongodb.client.model.UpdateOptions;
import lombok.Getter;
import lombok.Setter;
import org.bson.Document;
import org.bukkit.permissions.PermissionAttachment;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import static com.mongodb.client.model.Filters.eq;
@Getter
@Setter
public class Rank {
private String name, prefix, suffix;
private UUID uuid;
private int weight;
private List<String> permissions;
private List<UUID> inherits;
private CC color;
@Getter
private static List<Rank> ranks = new ArrayList<>();
public Rank(UUID uuid, String name) {
this.uuid = uuid == null ? UUID.randomUUID() : uuid;
this.name = name;
this.permissions = new ArrayList<>();
this.inherits = new ArrayList<>();
ranks.add(this);
}
public void save() {
Document document = new Document();
document.put("uuid", uuid.toString());
document.put("name", name);
document.put("color", color.name());
document.put("permissions", permissions.toString());
document.put("inherits", inherits.toString());
MongoHandler.RANK_COLLECTION.replaceOne(eq("uuid", uuid.toString()), document, new UpdateOptions().upsert(true));
}
public static void load() {
MongoHandler.RANK_COLLECTION.find().forEach((Block) block -> {
Document document = (Document) block;
UUID uuid = UUID.fromString(document.getString("uuid"));
String name = document.getString("name");
CC color = CC.valueOf(document.getString("color"));
List<String> permissions = new ArrayList<>();
List<UUID> inherits = new ArrayList<>();
new JsonParser().parse(document.getString("permissions")).getAsJsonArray().forEach(element -> permissions.add(element.getAsString()));
new JsonParser().parse(document.getString("inherits")).getAsJsonArray().forEach(element -> inherits.add(UUID.fromString(element.getAsString())));
Rank rank = new Rank(uuid, name);
rank.setColor(color);
rank.setPermissions(permissions);
rank.setInherits(inherits);
});
}
public void addPermission(String permission) {
setPermission(permission, true);
this.permissions.add(permission);
}
public void removePermission(String permission) {
setPermission(permission, false);
this.permissions.remove(permission);
}
public void setPermission(String permission, boolean value) {
Profile.getProfiles().stream().filter(profile -> profile.getGrants().stream().filter(grant ->
grant.getRank().equals(Rank.this)
|| grant.getRank().getInherits().contains(Rank.this.uuid)).findFirst().orElse(null) != null
&& profile.getPlayer() != null).forEach(profile -> {
PermissionAttachment attachment = profile.getPlayer().addAttachment(CorePlugin.getInstance());
attachment.setPermission(permission, value);
profile.getPlayer().recalculatePermissions();
});
}
public void delete() {
Profile.getProfiles().stream().filter(profile -> profile.getGrants().stream().filter(grant -> grant.getRank().equals(this)).findFirst().orElse(null) != null).forEach(profile -> {
profile.getGrants().stream().filter(grant -> grant.getRank().equals(this)).forEach(grant -> profile.getGrants().remove(grant));
// add new grant blablabla
});
MongoHandler.RANK_COLLECTION.deleteOne(eq("uuid", uuid.toString()));
}
public static Rank getDefaultRank() {
if(getByName("Default") == null) {
Rank rank = new Rank(null, "Default");
rank.setColor(CC.WHITE);
return rank;
}
return getByName("Default");
}
public String getDisplayName() { return color + name.replace("-", " "); }
public static Rank getByName(String rankName) { return ranks.parallelStream().filter(rank -> rank.getName().equalsIgnoreCase(rankName)).findFirst().orElse(null); }
public static Rank getByUuid(UUID uuid) { return ranks.parallelStream().filter(rank -> rank.getUuid().equals(uuid)).findFirst().orElse(null); }
}

View File

@ -0,0 +1,18 @@
package cc.kentono.core.rank.grant;
import cc.kentono.core.profile.Profile;
import cc.kentono.core.rank.Rank;
import lombok.Getter;
@Getter
public class Grant {
private Rank rank;
private Profile granter;
public Grant(Rank rank, Profile granter) {
this.rank = rank;
this.granter = granter;
}
}

View File

@ -0,0 +1,4 @@
package cc.kentono.core.rank.grant;
public class GrantProcedure {
}

View File

@ -0,0 +1,125 @@
package cc.kentono.core.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
public enum CC {
BLACK('0', "black"),
DARK_BLUE('1', "dark_blue"),
DARK_GREEN('2', "dark_green"),
DARK_AQUA('3', "dark_aqua"),
DARK_RED('4', "dark_red"),
PURPLE('5', "dark_purple"),
DARK_PURPLE('5', "dark_purple"),
GOLD('6', "gold"),
ORANGE('6', "gold"),
GRAY('7', "gray"),
DARK_GRAY('8', "dark_gray"),
BLUE('9', "blue"),
GREEN('a', "green"),
AQUA('b', "aqua"),
RED('c', "red"),
LIGHT_PURPLE('d', "light_purple"),
PINK('d', "light_purple"),
YELLOW('e', "yellow"),
WHITE('f', "white"),
MAGIC('k', "obfuscated"),
BOLD('l', "bold"),
STRIKETHROUGH('m', "strikethrough"),
UNDERLINE('n', "underline"),
ITALIC('o', "italic"),
RESET('r', "reset"),
NONE("none");
public static Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + '§' + "[0-9A-FK-OR]");
private static Map<Character, CC> BY_CHAR = new HashMap<>();
private char code;
private String toString;
private String name;
CC(String name) {
this.name = name;
this.toString = "";
}
CC(char code, String name) {
this.code = code;
this.name = name;
this.toString = new String(new char[]{'§', code});
}
public CC nextCC() {
int o = this.ordinal()+1 >=26 ? 0 : this.ordinal()+1;
return CC.values()[o];
}
public String toString() {
return this.toString;
}
public static String stripColor(String input) {
return input == null ? null : STRIP_COLOR_PATTERN.matcher(input).replaceAll("");
}
public static CC getChatColorByCode(String colorCode){
switch (colorCode){
case "&b" : return CC.AQUA;
case "&0" : return CC.BLACK;
case "&9" : return CC.BLUE;
case "&l" : return CC.BOLD;
case "&3" : return CC.DARK_AQUA;
case "&1" : return CC.DARK_BLUE;
case "&8" : return CC.DARK_GRAY;
case "&2" : return CC.DARK_GREEN;
case "&5" : return CC.DARK_PURPLE;
case "&4" : return CC.DARK_RED;
case "&6" : return CC.GOLD;
case "&7" : return CC.GRAY;
case "&a" : return CC.GREEN;
case "&o" : return CC.ITALIC;
case "&d" : return CC.LIGHT_PURPLE;
case "&k" : return CC.MAGIC;
case "&c" : return CC.RED;
case "&r" : return CC.RESET;
case "&m" : return CC.STRIKETHROUGH;
case "&n" : return CC.UNDERLINE;
case "&e" : return CC.YELLOW;
default: return CC.WHITE;
}
}
public static String translate(String textToTranslate) {
char[] b = textToTranslate.toCharArray();
for(int i = 0; i < b.length - 1; ++i) {
if (b[i] == '&' && "0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(b[i + 1]) > -1) {
b[i] = 167;
b[i + 1] = Character.toLowerCase(b[i + 1]);
}
}
return new String(b);
}
public static List<String> translate(List<String> textToTranslate) {
List<String> translatedStrings = new ArrayList<>();
textToTranslate.forEach(string -> translatedStrings.add(translate(string)));
return translatedStrings;
}
public static CC getByChar(char code) {
return BY_CHAR.get(code);
}
static {
CC[] var0 = values();
for (CC colour : var0) {
BY_CHAR.put(colour.code, colour);
}
}
}

View File

@ -0,0 +1,22 @@
package cc.kentono.core.util;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import lombok.Getter;
@Getter
public class MongoHandler {
public static MongoCollection PROFILE_COLLECTION, RANK_COLLECTION;
private MongoClient client;
public MongoHandler() {
client = new MongoClient("127.0.0.1", 27017);
MongoDatabase db = client.getDatabase("kentono-core");
PROFILE_COLLECTION = db.getCollection("profiles");
RANK_COLLECTION = db.getCollection("ranks");
}
}

View File

@ -0,0 +1,15 @@
package cc.kentono.core.util;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
public class PlayerUtil {
public static List<Player> getOnlinePlayers() {
return new ArrayList<>(Bukkit.getOnlinePlayers());
}
}

View File

@ -0,0 +1,72 @@
package cc.kentono.core.util;
public class WoolColor {
public static int getWoolColor(CC color) {
int c;
switch(color) {
case GOLD:
case ORANGE:
c = 1;
break;
case DARK_PURPLE:
case PURPLE:
c = 2;
break;
case BLUE:
case AQUA:
c = 3;
break;
case YELLOW:
c = 4;
break;
case GREEN:
c = 5;
break;
case PINK:
case LIGHT_PURPLE:
c = 6;
break;
case DARK_GRAY:
c = 7;
break;
case GRAY:
c = 8;
break;
case DARK_AQUA:
c = 9;
break;
case DARK_BLUE:
c = 11;
break;
case DARK_GREEN:
c = 13;
break;
case RED:
case DARK_RED:
c = 14;
break;
case BLACK:
c = 15;
break;
default:
c = 0;
}
return c;
}
}

View File

@ -0,0 +1,20 @@
package cc.kentono.core.util.menu;
import cc.kentono.core.CorePlugin;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
public class InteractListener implements Listener {
@EventHandler
public void onInteract(InventoryClickEvent event) {
if(event.getInventory() != null && event.getCurrentItem() != null) {
CorePlugin.getInstance().getMenuManager().getInventories().keySet()
.parallelStream().filter(inventory -> inventory.equals(event.getInventory())).findFirst().ifPresent(inv ->
CorePlugin.getInstance().getMenuManager().getInventories().get(inv).getButtons().get(event.getSlot()).getClick().run()
);
}
}
}

View File

@ -0,0 +1,23 @@
package cc.kentono.core.util.menu;
import cc.kentono.core.util.menu.impl.Menu;
import lombok.Getter;
import org.bukkit.Bukkit;
import org.bukkit.inventory.Inventory;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Getter
public class MenuManager {
private Map<Inventory, Menu> inventories = new HashMap<>();
public MenuManager(JavaPlugin plugin) {
Bukkit.getPluginManager().registerEvents(new InteractListener(), plugin);
}
}

View File

@ -0,0 +1,59 @@
package cc.kentono.core.util.menu.impl;
import lombok.Getter;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.Arrays;
@Getter
public class Button {
private ItemStack item;
private ItemMeta meta;
private BukkitRunnable click;
public Button(ItemStack item) {
this.item = item;
this.meta = item.getItemMeta();
this.click = new BukkitRunnable() {
public void run() {
this.cancel();
}
};
}
public Button lore(String... lore) {
meta.setLore(Arrays.asList(lore));
return this;
}
public Button displayName(String displayName) {
meta.setDisplayName(displayName);
return this;
}
public Button amount(int amount) {
item.setAmount(amount);
return this;
}
public Button damage(int damage) {
item.setDurability((byte) damage);
return this;
}
public Button click(BukkitRunnable thread) {
this.click = thread;
return this;
}
public Button create() {
this.item.setItemMeta(meta);
return this;
}
}

View File

@ -0,0 +1,36 @@
package cc.kentono.core.util.menu.impl;
import cc.kentono.core.util.CC;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.Map;
import java.util.stream.IntStream;
// TODO: Add pagination
public abstract class Menu {
public abstract boolean isPlaceholder();
public abstract Integer getSize();
public abstract String getTitle();
public abstract Map<Integer, Button> getButtons();
public void openMenu(Player player) {
Inventory inventory = Bukkit.createInventory(null, getSize(), CC.translate(getTitle()));
getButtons().keySet().forEach(key -> inventory.setItem(key, getButtons().get(key).getItem()));
IntStream.range(0, inventory.getSize()).forEach(i -> {
if(inventory.getItem(i) == null || inventory.getItem(i).getType().equals(Material.AIR))
inventory.setItem(i, new Button(new ItemStack(Material.STAINED_GLASS_PANE)).displayName("").lore("").damage(7).getItem());
});
player.openInventory(inventory);
}
}

View File

@ -0,0 +1,4 @@
name: Moon
version: '0.1'
description: Light-weight core saving in MongoDB and syncs through Redis
main: cc.kentono.core.CorePlugin