This commit is contained in:
femsci 2023-04-21 22:56:48 +02:00
commit 56d69abdc0
Signed by: femsci
GPG key ID: 08F7911F0E650C67
203 changed files with 15543 additions and 0 deletions

6
.gitignore vendored Normal file
View file

@ -0,0 +1,6 @@
**/.idea
**/out
**/target
**/build
**/*.iml
YAPI/

83
AuthentiCat/src/config.yml Executable file
View file

@ -0,0 +1,83 @@
#Force all players to log in after server reload (not restart)
reset-on-reload: true
#If set to true, prevents players from chat usage before authentication
disallow-speech: false
#Time (in seconds) until player is kicked due to authentication fail (set to -1 to disable)
#It is recommended to set the time as greater than 15s
kick-timeout: 20
#The "reason" message of kicking after timeout (set to 'null' in order to disable)
kick-timeout-message: "&cAuthentication timeout!"
#The delay (in seconds) after which prompt messages will be sent to the player (set to -1 in order to disable)
prompt-initial-delay: 3
#The delay (in seconds) between prompt messages (set to -1 in order to disable)
prompt-repeat-delay: 5
#The prompt messages (set to 'null' in order to disable):
#
#The register prompt message
prompt-message-register: "&aType &6/register <password> &ato register yourself"
#
#The login prompt message
prompt-message-login: "&aType &6/login <password> &ato log in yourself"
#Command messages (message is shown *when [...]*)
#Successes
#When successfully changed the password
cmd-success-changepass: "&aYour password has been successfully changed!"
#When successfully logged out
cmd-success-logout: "&aLogged out!"
#When successfully logged in
cmd-success-login: "&aLogged in!"
#When successfully registered
cmd-success-register: "&aRegistered! From now on, every time you join this server, use &6/login <password>&a!"
#Fails
#When player uses too many arguments
cmd-fail-general-overargs: "&cToo many arguments!"
#When the passwords do not match
cmd-fail-passwords-mismatch: "&cYour old password argument does not match the actual password!"
#When the new password is not specified
cmd-fail-nonewpassword: "&cYou need to specify the new password!"
#When neither the old nor the new password is specified
cmd-fail-nobothpasswords: "&cYou need to specify the passwords!"
#When player does not have any password set and tries to change their password
cmd-fail-nopassset: "&cYou don't have any password set!"
#When player passes arguments to a command that does not accept any
cmd-fail-noargsallowed: "&cThis command does not allow any arguments!"
#When player needs to login instead of registering
cmd-fail-just-login: "&cYou need to login!"
#When player uses an incorrect password
cmd-fail-badpassword: "&cIncorrect password!"
#When player uses more than one argument for a
cmd-fail-nopassword-overargs: "&cYou need to specify the password as a single argument!"
#When the password is not specified
cmd-fail-nopassword: "&cYou need to specify the password!"
#When player tries to authenticate while being already authenticated
cmd-fail-already-authenticated: "&cYou are already authenticated!"
#When player uses /login without being registered
cmd-fail-register-first: "&cYou need to register first!"
#When the player is not authenticated and tries to use commands other than /login or /register
cmd-prompt-badcommand: "§cAuthenticate before you can speak!"

View file

@ -0,0 +1,115 @@
package me.yuri.authcat;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.player.*;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.ArrayList;
import java.util.List;
public class CatGirls implements Listener {
protected static List<Player> catgirls = new ArrayList<>();
@EventHandler
public void ohayou(PlayerJoinEvent e) {
catgirls.add(e.getPlayer());
brian(e.getPlayer());
}
static void brian(Player p) {
new BukkitRunnable() {
final int delay = Neko.prmdelay;
final int repeat = Neko.prmrepeat;
final int kick = Neko.timeout;
final String km = Neko.timeoutmsg;
int cnt = 0;
final String msg = (Neko.getCatEars().oof(p.getName()) == null) ? Neko.promptreg : Neko.promptlog;
@Override
public void run() {
if (!catgirls.contains(p)) {
cancel();
return;
}
if (cnt == delay) {
p.sendMessage(msg);
}
if ((cnt + delay) % repeat == 0 && cnt > delay) {
p.sendMessage(msg);
}
if (cnt >= kick) {
p.kickPlayer(km.equalsIgnoreCase("null") ? null : km);
}
cnt++;
}
}.runTaskTimer(Neko.getCatEars(), 0L, 20L);
}
@EventHandler
public void matanedesune(PlayerQuitEvent e) {
catgirls.remove(e.getPlayer());
}
@EventHandler
public void iiiiiiiiiiine(PlayerInteractEvent e) {
if (catgirls.contains(e.getPlayer())) e.setCancelled(true);
}
@EventHandler
public void yoidesune(PlayerDropItemEvent e) {
if (catgirls.contains(e.getPlayer())) e.setCancelled(true);
}
@EventHandler
public void desudesu(InventoryOpenEvent e) {
if (catgirls.contains(((Player) e.getPlayer()))) e.setCancelled(true);
}
@EventHandler
public void plsstop(PlayerItemConsumeEvent e) {
if (catgirls.contains(e.getPlayer())) e.setCancelled(true);
}
@EventHandler
public void socute(PlayerItemHeldEvent e) {
if (catgirls.contains(e.getPlayer())) e.setCancelled(true);
}
@EventHandler
public void highsocks(EntityDamageEvent e) {
if (e.getEntity() instanceof Player)
if (catgirls.contains(((Player) e.getEntity()))) e.setCancelled(true);
}
@EventHandler
public void thisisirritatingsrsly(PlayerMoveEvent e) {
if (catgirls.contains(e.getPlayer())) e.setCancelled(true);
}
@EventHandler
public void nekoooooo(AsyncPlayerChatEvent e) {
if (Neko.disallowspeech)
if (catgirls.contains(e.getPlayer())) {
e.getPlayer().sendMessage(Neko.cmdpromptbadcmd);
e.setCancelled(true);
}
}
@EventHandler
public void korewoomoitegahoshiiinai(PlayerCommandPreprocessEvent e) {
if (!catgirls.contains(e.getPlayer())) return;
if ((!e.getMessage().startsWith("/login") && !e.getMessage().startsWith("/log")
&& !e.getMessage().startsWith("/register") && !e.getMessage().startsWith("/reg")) || e.getMessage().startsWith("/logout")) {
e.getPlayer().sendMessage(Neko.cmdpromptbadcmd);
e.setCancelled(true);
}
}
}

View file

@ -0,0 +1,130 @@
package me.yuri.authcat;
import me.yuri.yuriapi.api.command.CommandManager;
import me.yuri.yuriapi.api.utils.configuration.ConfigVar;
import me.yuri.yuriapi.api.utils.configuration.ConfigVarExceptionListener;
import me.yuri.yuriapi.api.utils.configuration.ConfigVarManager;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Properties;
public class Neko extends JavaPlugin {
@ConfigVar("reset-on-reload")
protected static boolean resetonreload = false;
@ConfigVar("disallow-speech")
protected static boolean disallowspeech = false;
@ConfigVar("kick-timeout")
protected static int timeout = -1;
@ConfigVar(value = "kick-timeout-message", color = '&')
protected static String timeoutmsg = "null";
@ConfigVar(value = "prompt-message-login", color = '&')
protected static String promptlog = "null";
@ConfigVar(value = "prompt-message-register", color = '&')
protected static String promptreg = "null";
@ConfigVar("prompt-initial-delay")
protected static int prmdelay = 4;
@ConfigVar("prompt-repeat-delay")
protected static int prmrepeat = 5;
@ConfigVar(value = "cmd-prompt-badcommand", color = '&')
protected static String cmdpromptbadcmd = "null";
protected static Neko getCatEars() {
return animeGrill;
}
private static final Otokonomusume otoko = new Otokonomusume();
private static Neko animeGrill;
@ConfigVarExceptionListener
public void onCfgException(me.yuri.yuriapi.api.utils.configuration.ConfigVarException e){
e.printStackTrace();
saveDefaultConfig();
}
@Override
public void onLoad() {
animeGrill = this;
saveDefaultConfig();
ConfigVarManager.register(this, this, otoko);
ConfigVarManager.update(this);
}
@Override
public void onDisable() {
super.onDisable();
}
@Override
public void onEnable() {
CommandManager c = new CommandManager(this);
c.registerCommand(otoko);
this.getServer().getPluginManager().registerEvents(new CatGirls(), this);
log("§aA§bu§ct§dh§ee§fn§1t§2i§3C§4a§5t §aenabled!");
if(resetonreload){
Bukkit.getOnlinePlayers().forEach(p -> {
CatGirls.catgirls.add(p);
CatGirls.brian(p);
});
}
}
private static void log(String... msg) {
Bukkit.getConsoleSender().sendMessage(msg);
}
public void dontspawnkill(String user, String pass){
Properties p = new Properties();
File file = new File(this.getDataFolder().getAbsolutePath() + "/passes.properties");
try {
if(file.exists()) {
FileInputStream fis = new FileInputStream(file);
p.load(fis);
fis.close();
}
//Don't do this unless you are NSA :3
pass = Base64.getEncoder().encodeToString(pass.getBytes());
p.setProperty(user, pass);
FileOutputStream fos = new FileOutputStream(file);
p.store(fos, "KEKS");
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public String oof(String user) {
String pass = null;
Properties p = new Properties();
File file = new File(this.getDataFolder().getAbsolutePath() + "/passes.properties");
if(!file.exists()) return null;
try {
FileInputStream fis = new FileInputStream(file);
p.load(fis);
fis.close();
String tmp = p.getProperty(user);
if(tmp == null) return null;
pass = new String(Base64.getDecoder().decode(tmp));
} catch (IOException ignored) {
}
return pass;
}
}

View file

@ -0,0 +1,192 @@
package me.yuri.authcat;
import me.yuri.yuriapi.api.command.Cmd;
import me.yuri.yuriapi.api.command.CommandEvent;
import me.yuri.yuriapi.api.utils.configuration.ConfigVar;
import org.bukkit.entity.Player;
public class Otokonomusume {
//FAILS
@ConfigVar(value = "cmd-fail-register-first", color = '&')
private static String cmdregfirst = "null";
@ConfigVar(value = "cmd-fail-already-authenticated", color = '&')
private static String cmdalreadyauth = "null";
@ConfigVar(value = "cmd-fail-nopassword", color = '&')
private static String cmdnopass = "null";
@ConfigVar(value = "cmd-fail-badpassword", color = '&')
private static String cmdbadpass= "null";
@ConfigVar(value = "cmd-fail-nopassword-overargs", color = '&')
private static String cmdnopass1 = "null";
@ConfigVar(value = "cmd-fail-just-login", color = '&')
private static String cmdloginprompt = "null";
@ConfigVar(value = "cmd-fail-noargsallowed", color = '&')
private static String cmdnoargsallowed = "null";
@ConfigVar(value = "cmd-fail-nobothpasswords", color = '&')
private static String cmdnoboth = "null";
@ConfigVar(value = "cmd-fail-nonewpassword", color = '&')
private static String cmdnonew = "null";
@ConfigVar(value = "cmd-fail-passwords-mismatch", color = '&')
private static String cmdnomatch = "null";
@ConfigVar(value = "cmd-fail-general-overargs", color = '&')
private static String cmdtoomanyargs = "null";
@ConfigVar(value = "cmd-fail-nopassset", color = '&')
private static String cmdnopasset = "null";
//SUCCESSES
@ConfigVar(value = "cmd-success-register", color = '&')
private static String cmdfirstreg = "null";
@ConfigVar(value = "cmd-success-login", color = '&')
private static String cmdloggedin = "null";
@ConfigVar(value = "cmd-success-logout", color = '&')
private static String cmdloggedout = "null";
@ConfigVar(value = "cmd-success-changepass", color = '&')
private static String cmdchangedpass = "null";
@Cmd(command = "login", aliases = {"log"}, consoleSide = false)
public void rogin(CommandEvent c){
Player s = (Player) c.getSender();
String pass = Neko.getCatEars().oof(s.getName());
if(!CatGirls.catgirls.contains(s)){
s.sendMessage(cmdalreadyauth);
return;
}
if(pass == null){
s.sendMessage(cmdregfirst);
return;
}
if(c.getArgs().length == 0){
s.sendMessage(cmdnopass);
return;
}
if(c.getArgs().length > 1){
s.sendMessage(cmdnopass1);
return;
}
if(pass.equals(c.getArgsString())){
CatGirls.catgirls.remove(s);
s.sendMessage(cmdloggedin);
} else {
s.sendMessage(cmdbadpass);
}
}
@Cmd(command = "register", aliases = {"reg"}, consoleSide = false)
public void hajimemashite(CommandEvent c){
Player s = (Player) c.getSender();
String pass = Neko.getCatEars().oof(s.getName());
if(!CatGirls.catgirls.contains(s)){
s.sendMessage(cmdalreadyauth);
return;
}
if(pass != null){
s.sendMessage(cmdloginprompt);
return;
}
if(c.getArgs().length == 0){
s.sendMessage(cmdnopass);
return;
}
if(c.getArgs().length > 1){
s.sendMessage(cmdnopass1);
return;
}
pass = c.getArgsString();
Neko.getCatEars().dontspawnkill(s.getName(), pass);
s.sendMessage(cmdfirstreg);
CatGirls.catgirls.remove(s);
}
@Cmd(command = "logout", consoleSide = false)
public void iiteyone(CommandEvent c){
Player s = (Player) c.getSender();
if(c.getArgs().length != 0){
s.sendMessage(cmdnoargsallowed);
return;
}
s.sendMessage(cmdloggedout);
deanimenize(s);
}
private void deanimenize(Player p){
CatGirls.catgirls.add(p);
CatGirls.brian(p);
}
@Cmd(command = "changepassword", aliases = {"changepass"}, consoleSide = false)
public void aaaaaaaaaaaaaaaaaaaaaa(CommandEvent c){
Player s = (Player) c.getSender();
String playerpass = Neko.getCatEars().oof(s.getName());
if(playerpass == null){
s.sendMessage(cmdnopasset);
deanimenize(s);
return;
}
switch (c.getArgs().length){
case 0:
s.sendMessage(cmdnopass);
return;
case 1:
s.sendMessage(cmdnonew);
return;
case 2:
String oldpass, newpass;
oldpass = c.getArgs()[0];
newpass = c.getArgs()[1];
if(!oldpass.equals(playerpass)){
s.sendMessage(cmdnomatch);
return;
}
Neko.getCatEars().dontspawnkill(s.getName(), newpass);
s.sendMessage(cmdchangedpass);
return;
default:
s.sendMessage(cmdtoomanyargs);
return;
}
}
}

18
AuthentiCat/src/plugin.yml Executable file
View file

@ -0,0 +1,18 @@
name: AuthentiCat
author: Yuri (Blin)
version: 1.0E
main: me.yuri.authcat.Neko
load: STARTUP
depend:
- YuriAPI
description: A decent auth plugin with terrible variable naming...
commands:
login:
aliases: log
register:
aliases: reg
# authmanager:
# aliases: am
logout:
changepassword:
aliases: changepass

45
ChristmasWarfare/pom.xml Executable file
View file

@ -0,0 +1,45 @@
<?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>me.yuri</groupId>
<artifactId>ChristmasWarfare</artifactId>
<version>1.0-E</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>me.yuri</groupId>
<artifactId>YuriAPI</artifactId>
<scope>system</scope>
<systemPath>/mnt/B65CCF2D5CCEE6E9/Projects/IdeaProjects/YAPI/YuriAPI.jar</systemPath>
</dependency>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.14.4-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View file

@ -0,0 +1,66 @@
package me.yuri.christmaswarfare;
import com.sun.istack.internal.NotNull;
import me.yuri.yuriapi.api.command.CommandManager;
import me.yuri.yuriapi.api.utils.configuration.ConfigVar;
import me.yuri.yuriapi.api.utils.configuration.ConfigVarManager;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
public class CC extends JavaPlugin {
@ConfigVar("grenade-percentage")
public static int _GRENADE_PERC;
@ConfigVar("luckyblocks-enabled")
public static boolean _LUCKYBLOCKS;
@ConfigVar("max-players")
public static int MAX_PLAYERS;
@ConfigVar("prefix")
public static String _PREFIX = "";
public static void sendCns(String msg){
Bukkit.getConsoleSender().sendMessage(ChatColor.translateAlternateColorCodes('&', msg));
}
private static CommandManager cm;
private static CC cc;
public static CC getCC() {
return cc;
}
@Override
public void onLoad() {
cc = this;
}
@Override
public void onDisable() {
if(GameManager.getState() == GameManager.GameState.INGAME){
GameManager.stop(true);
}
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
cm.onCommand(sender, command, label, args);
return true;
}
@Override
public void onEnable() {
saveDefaultConfig();
ConfigVarManager.register(this, this.getClass());
ConfigVarManager.update();
if(_PREFIX.equals("none")) _PREFIX = "";
if(!_LUCKYBLOCKS){
sendCns("&cLuckyBlock integration is disabled!");
}
cm = new CommandManager(this);
cm.registerCommand(new Commands());
getServer().getPluginManager().registerEvents(new ItemsEListeners(), this);
}
}

View file

@ -0,0 +1,118 @@
package me.yuri.christmaswarfare;
import me.yuri.yuriapi.APIBridge;
import me.yuri.yuriapi.api.command.Cmd;
import me.yuri.yuriapi.api.command.CommandClass;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.Arrays;
public class Commands {
@Cmd(command = "cw", desc = "Join game", playerSide = true, consoleSide = true)
public void CmdJoin(CommandClass s){
try {
if (s.getArgs().length == 0) {
s.getSender().sendMessage(printHelp());
return;
}
if (s.getArgs().length > 0) {
if (s.getArgs()[0].equalsIgnoreCase("help")) {
s.getSender().sendMessage(printHelp());
return;
}
if (s.getArgs()[0].equalsIgnoreCase("join")) {
Player p = (Player) s.getSender();
if (GameManager.isPlaying(p) || GameManager.isQueued(p)) {
p.sendMessage("§cYou are already in " + (GameManager.isQueued(p) ? "queue" : "game") + "!");
return;
}
if (GameManager.getState() != GameManager.GameState.WAITING) {
p.sendMessage("§cThe game had already started!");
return;
}
GameManager.join(p);
p.sendMessage("§aJoined the game!");
return;
}
if (s.getArgs()[0].equalsIgnoreCase("leave")) {
Player p = (Player) s.getSender();
if (!GameManager.isPlaying(p) && !GameManager.isQueued(p)) {
p.sendMessage("§cYou aren't in-game or waiting for game! Join the game using /cw join!");
return;
}
GameManager.leave(p);
p.sendMessage("§aLeft the " + (GameManager.isQueued(p) ? "queue!" : "game!"));
return;
}
if (s.getArgs()[0].equalsIgnoreCase("gib")) {
if (s.getSender().isOp()) {
Player p = (Player) s.getSender();
ItemStack nebsnob = ItemsEListeners.SNOWBALL.clone();
nebsnob.setAmount(32);
ItemStack nebgred = ItemsEListeners.GRENADE.clone();
nebgred.setAmount(5);
p.getInventory().addItem(nebsnob, nebsnob, ItemsEListeners.BAYONET, nebgred);
}
return;
}
if (s.getArgs()[0].equalsIgnoreCase("start")) {
if (s.getArgs().length != 1) {
s.getSender().sendMessage("§cUse only /cw start!");
return;
}
s.getSender().sendMessage("§aStarting!");
GameManager.start();
return;
}
if(s.getArgs()[0].equalsIgnoreCase("stop")){
if(GameManager.getState() != GameManager.GameState.INGAME){
s.getSender().sendMessage("§cState is not in-game!");
return;
}
s.getSender().sendMessage("§aStopping game!");
GameManager.stop(false);
return;
}
if (s.getArgs()[0].equalsIgnoreCase("addpos")) {
if (s.getArgs().length < 2) {
s.getSender().sendMessage("§cUse /cw addpos <team> <-flag>");
return;
}
if(s.getArgs().length == 3 && s.getArgs()[2].equalsIgnoreCase("flag")){
CC.getCC().getConfig().set("teams." + s.getArgs()[1].toUpperCase() + ".flag", ((Player) s.getSender()).getLocation().getBlock().getLocation());
} else {
int cnt = 0;
while (CC.getCC().getConfig().isSet("teams." + s.getArgs()[1].toUpperCase() + ".pos" + cnt) && (CC.getCC().getConfig().getLocation("teams." + s.getArgs()[1].toUpperCase() + ".pos" + cnt) != null))
cnt++;
CC.getCC().getConfig().set("teams." + s.getArgs()[1].toUpperCase() + ".pos" + cnt, ((Player) s.getSender()).getLocation());
}
CC.getCC().saveConfig();
return;
}
}
} catch (Exception e){
APIBridge.reportException(e, CC.getCC());
e.printStackTrace();
}
}
private String[] printHelp(){
return (String[]) Arrays.asList("§3--------------------------------§1Help§3--------------------------------",
"§1- §3/cw join §1- join the match",
"§1- §3/cw leave §1- leave the queue",
"§3--------------------------------§1YEET§3--------------------------------").toArray();
}
@Cmd(command = "yeet2", desc = "Yeet2", playerSide = true, consoleSide = true)
public void CmdBruh(CommandClass s){
s.getSender().sendMessage("§4Yeet!2");
}
}

View file

@ -0,0 +1,11 @@
package me.yuri.christmaswarfare;
public enum DeathCause {
SNOWBALL_HIT("{DED} §3got shot by {KILLERQUEEN}§3!"), GRENADE_HIT("{KILLERQUEEN} §3killed {DED} §3with use of his grenade! §eYEET!!!"), STAB("{DED} §cwas stabbed by {KILLERQUEEN}§c!");
public final String msg;
DeathCause(String a) {
msg = a;
}
}

View file

@ -0,0 +1,296 @@
package me.yuri.christmaswarfare;
//import com.sun.applet2.AppletParameters;
import me.yuri.yuriapi.APIBridge;
import me.yuri.yuriapi.api.utils.Colored;
import me.yuri.yuriapi.api.utils.configuration.ConfigVar;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.*;
public class GameManager {
private static GameState _state = GameState.WAITING;
protected static Map<Color, Block> _flags = new HashMap<>();
private static Map<Color, Block> _originalflags = new HashMap<>();
private static Map<Color, Integer> _points = new HashMap<>();
@ConfigVar("time")
static int time = 100;
static int counter = 100;
public static GamePlayer[] getPlayers() {
return players.toArray(new GamePlayer[]{});
}
private static ChatColor _winner = null;
public static void resetFlag(String ccc) {
Block b = _originalflags.get(Colored.getColorFromName(ccc));
_flags.put(Colored.getColorFromName(ccc), b);
try {
b.setType((Material) Material.class.getField(ccc.toUpperCase() + "_BANNER").get(Material.class));
b.setMetadata("team", new FixedMetadataValue(CC.getCC(), ccc.toUpperCase()));
} catch (Exception e){
APIBridge.reportException(e, CC.getCC());
}
}
public static void addPoint(String name) {
Color c = Colored.getColorFromName(name);
int current = _points.get(c);
current++;
_points.put(c, current);
}
public enum GameState {
WAITING, INGAME
}
public static GameState getState(){
return _state;
}
private static List<GamePlayer> players = new ArrayList<>();
static boolean isPlaying(Player p){
return getPlayer(p) != null;
}
private static Map<Player, Location> queued = new HashMap<>();
static boolean isQueued(Player p){
return queued.containsKey(p);
}
static GamePlayer getPlayer(Player p) {
for(GamePlayer gp : players){
if(gp.getPlayer().equals(p)) return gp;
}
return null;
}
static void kill(GamePlayer k, GamePlayer p, DeathCause d){
if(k.isGrace()) return;
for(GamePlayer pp : players){
pp.getPlayer().sendMessage(CC._PREFIX + d.msg.replace("{KILLERQUEEN}", k.getPlayer().getDisplayName()).replace("{DED}", p.getPlayer().getDisplayName()));
}
if(p.getPlayer().getInventory().getHelmet() != null){
p.getPlayer().getLocation().getBlock().setType(p.getPlayer().getInventory().getHelmet().getType());
String sss = p.getPlayer().getInventory().getHelmet().getType().name().toUpperCase().split("_")[0];
p.getPlayer().getLocation().getBlock().setMetadata("team", new FixedMetadataValue(CC.getCC(), sss));
ChatColor ded = Colored.getChatColorFromName(p.getColorName());
ChatColor decap = Colored.getChatColorFromName(sss);
_flags.put(Colored.getColorFromName(sss), p.getPlayer().getLocation().getBlock());
for(GamePlayer pp : players){
pp.getPlayer().sendMessage(CC._PREFIX + "§aTeam " + ded + p.getColorName() +" §ais no longer holding team " + decap + sss +"§a's flag!");
}
}
if(!k.equals(p)) {
Random r = new Random();
k.addKill();
int perc = r.nextInt(101);
if(perc <= CC._GRENADE_PERC){
int amount = 1 + r.nextInt(3);
ItemsEListeners.gibSpecItem(k, ItemsEListeners.GRENADE, amount);
k.getPlayer().sendMessage("§aCongratulations, you have received " + amount + " explosive bois! YEET 'EM!!!");
} else {
int i = 10;
i += r.nextInt(11);
ItemsEListeners.gibSpecItem(k, ItemsEListeners.SNOWBALL, i);
k.getPlayer().sendMessage("§a+" + i + " snowballs. Yeet them wisely...");
}
}
p.addDeath();
p.teleportRandom();
p.setGrace();
ItemsEListeners.gibItems(p);
}
static void start(){
counter = time;
_state = GameState.INGAME;
Map<String, List<Location>> kek = new HashMap<>();
try {
for (String s : CC.getCC().getConfig().getConfigurationSection("teams").getKeys(false)) {
//CC.sendCns("&aTEAM: &c" + s);
List<Location> l = new ArrayList<>();
for (String c : CC.getCC().getConfig().getConfigurationSection("teams."+s).getKeys(false)) {
Location loc = CC.getCC().getConfig().getLocation("teams."+s+"."+c);
if(loc != null) {
if(!c.equalsIgnoreCase("flag"))
l.add(loc);
else {
_flags.put(Colored.getColorFromName(s), loc.getBlock());
_originalflags.put(Colored.getColorFromName(s), loc.getBlock());
loc.getBlock().setType((Material) Material.class.getField(s.toUpperCase()+"_BANNER").get(Material.class));
loc.getBlock().setMetadata("team", new FixedMetadataValue(CC.getCC(), s.toUpperCase()));
}
}
//CC.sendCns("&e - &c" + c+": &a"+CC.getCC().getConfig().getLocation("teams."+s+"."+c));
//CC.sendCns("&a > (teams."+s+"."+c+") &e-> "+CC.getCC().getConfig().getLocation("teams."+s+"."+c));
}
kek.put(s, l);
}
Random r = new Random();
//int max = queued.size();
//int teams = kek.keySet().size();
//int asym = max%teams;
List<Player> pls = new ArrayList<>(queued.keySet());
Collections.shuffle(pls, r);
int cnt = 0;
String[] colors = kek.keySet().toArray(new String[]{});
//CC.sendCns("&6colors: " + colors.length + " queued: " + queued.keySet().size() +" locs: "+kek.keySet().size());
for(Player p : queued.keySet()){
if(cnt >= kek.keySet().size()) cnt = 0;
String cccc = colors[cnt];
GamePlayer gp = new GamePlayer(p, queued.get(p), Colored.getColorFromName(cccc),kek.get(cccc).toArray(new Location[]{}), cccc);
players.add(gp);
p.sendMessage("§aStarting game!");
gp.teleportRandom();
ItemsEListeners.gibItems(gp);
ChatColor cc = Colored.getChatColorFromName(gp.getColorName());
p.setDisplayName(cc+p.getName());
p.setPlayerListName(cc+p.getName());
gp.getPlayer().setHealth(20);
gp.getPlayer().setFoodLevel(20);
gp.getPlayer().setTotalExperience(0);
gp.getPlayer().sendMessage("§a§lStart!!!");
cnt++;
}
for(Color c : _flags.keySet()){
_points.put(c, 0);
}
queued.clear();
new BukkitRunnable () {
@Override
public void run() {
for(GamePlayer gp : players){
gp.getPlayer().setLevel(counter);
}
if(counter <= 0){
cancel();
stop(false);
return;
}
counter--;
}
}.runTaskTimer(CC.getCC(), 20L, 20L);
}catch (Exception e){
CC.sendCns("&4ERROR: ");
e.printStackTrace();
APIBridge.reportException(e, CC.getCC());
return;
}
}
public static void stop(boolean b){
if(!b){
for(GamePlayer gp : players){
if(gp.getPlayer().getInventory().getHelmet() != null){
ItemStack is = gp.getPlayer().getInventory().getHelmet();
if(is.getType().name().endsWith("_BANNER")){
_flags.put(Colored.getColorFromName(gp.getPlayer().getInventory().getHelmet().getType().name().toUpperCase().split("_")[0]), gp.getPlayer().getLocation().getBlock());
}
}
}
int highest = -1;
for(int i : _points.values()){
if(i > highest)
highest = i;
}
List<Color> cols = new ArrayList<>();
for(Color c : _points.keySet()){
if(_points.get(c) == highest)
cols.add(c);
}
if(cols.size() != 1) {
Map<Color, Double> scores = new HashMap<>();
List<Color> torem = new ArrayList<>();
for(Color c : _flags.keySet()){
if(!cols.contains(c)) torem.add(c);
}
torem.forEach(f -> _flags.remove(f));
torem.clear();
for (Block bb : _flags.values()) {
Color c = Colored.getColorFromName(bb.getMetadata("team").get(0).asString());
scores.put(c, bb.getLocation().distance(_originalflags.get(c).getLocation()));
}
double lowest = Double.MAX_VALUE;
for (double d : scores.values()) {
if (d < lowest)
lowest = d;
}
for (Color c : scores.keySet()) {
if (scores.get(c) == lowest) {
_winner = Colored.getChatColorFromName(Colored.getFromColor(c));
}
}
} else _winner = Colored.getChatColorFromName(Colored.getFromColor(cols.get(0)));
for(Block bb : _flags.values()){
bb.setType(Material.AIR);
bb.removeMetadata("team", CC.getCC());
}
for(GamePlayer gp : players){
if(_winner == null)
gp.getPlayer().sendTitle("§c§lStalemate", "§7No team won", 25,120,60);
else
gp.getPlayer().sendTitle((Colored.getChatColorFromName(gp.getColorName()).equals(_winner) ? "§6§lVictory" : "§c§lDefeat"),
(Colored.getChatColorFromName(gp.getColorName()).equals(_winner) ? "§eOur team won!" : _winner + _winner.name() +" TEAM WINS!"), 25, 120, 60);
}
}
for(GamePlayer p : players){
p.getPlayer().teleport(p.getOriginalLocation());
p.getPlayer().setDisplayName(p.getPlayer().getName());
p.getPlayer().setPlayerListName(p.getPlayer().getName());
p.getPlayer().getInventory().clear();
}
players.clear();
queued.clear();
_state = GameState.WAITING;
}
public static void join(Player p) {
if(isQueued(p) || isPlaying(p)) return;
if(queued.size() >= CC.MAX_PLAYERS){
p.sendMessage("§cThe queue has already reached the max player count!");
return;
}
queued.put(p, p.getLocation());
}
public static void leave(Player p) {
if(isQueued(p)){
p.teleport(queued.get(p));
queued.remove(p);
p.setDisplayName(p.getName());
p.setPlayerListName(p.getName());
} else if(isPlaying(p)) {
GamePlayer g = getPlayer(p);
p.teleport(g.getOriginalLocation());
players.remove(g);
p.setDisplayName(p.getName());
p.setPlayerListName(p.getName());
}
}
}

View file

@ -0,0 +1,115 @@
package me.yuri.christmaswarfare;
import com.sun.istack.internal.NotNull;
import org.bukkit.Color;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import me.yuri.yuriapi.api.utils.CustomScoreboard;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scoreboard.DisplaySlot;
import java.util.Random;
public class GamePlayer {
public GamePlayer(Player p, Location o, Color t, Location[] rs, String cn){
player = p;
originalLocation = o;
tc = t;
respawns = rs;
cname = cn;
sbi = new CustomScoreboard(DisplaySlot.SIDEBAR, "§f§lC§4§lH§f§lR§4§lI§f§lS§4§lT§f§lM§4§lA§f§lS §4§lW§f§lA§4§lR§f§lF§4§lA§f§lR§4§lE");
sbi.addScore("kills", "§aYour kills §e>> §b"+kills);
sbi.addScore("deaths", "§aYour deaths §e>> §b"+deaths);
sbi.addToPlayer(p);
}
@NotNull
private Player player;
@NotNull
private Color tc;
@NotNull
private Location[] respawns;
@NotNull
private Location originalLocation;
@NotNull
private String cname;
private int kills = 0;
private int deaths = 0;
private boolean grace = false;
public void setGrace(int time){
grace = true;
new BukkitRunnable(){
@Override
public void run() {
grace = false;
}
}.runTaskLater(CC.getCC(), time*20L);
}
public void setGrace(){
grace = true;
new BukkitRunnable(){
@Override
public void run() {
grace = false;
}
}.runTaskLater(CC.getCC(), 5*20L);
}
private CustomScoreboard sbi;
public Player getPlayer() {
return player;
}
public Color getTeamColor(){
return tc;
}
public CustomScoreboard getSbi() {
return sbi;
}
public int getKills(){
return kills;
}
public void addKill(){
kills++;
sbi.updateScore("kills", "§aYour kills §e>> §b"+kills);
}
public int getDeaths(){
return deaths;
}
public void addDeath(){
deaths++;
sbi.updateScore("deaths", "§aYour deaths §e>> §b"+deaths);
}
public Location getRespawnLocation() {
return respawns[new Random().nextInt(respawns.length)];
}
public Location getOriginalLocation() {
return originalLocation;
}
public void teleportRandom() {
//CC.sendCns("&3len: " + respawns.length);
player.teleport(respawns[new Random().nextInt(respawns.length)]);
}
public String getColorName() {
return cname;
}
public boolean isGrace() {
return grace;
}
}

View file

@ -0,0 +1,365 @@
package me.yuri.christmaswarfare;
import me.yuri.yuriapi.APIBridge;
import me.yuri.yuriapi.api.utils.Colored;
import org.bukkit.*;
import org.bukkit.block.Sign;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.entity.Snowball;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.entity.ProjectileHitEvent;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerEggThrowEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import org.bukkit.util.Vector;
import java.util.Arrays;
import java.util.Random;
public class ItemsEListeners implements Listener {
static ItemStack BAYONET;
static ItemStack SNOWBALL;
static ItemStack GRENADE;
static {
BAYONET = new ItemStack(Material.IRON_SWORD);
SNOWBALL = new ItemStack(Material.SNOWBALL);
GRENADE = new ItemStack(Material.EGG);
ItemMeta imb = BAYONET.getItemMeta();
assert imb != null;
imb.setDisplayName("§3§k000§c Santa's Bayonet §3§k000");
imb.setUnbreakable(true);
BAYONET.setItemMeta(imb);
ItemMeta ims = SNOWBALL.getItemMeta();
assert ims != null;
ims.setDisplayName("§aSnowball");
ims.setLore(Arrays.asList("§eYeet it into someone's face", "§eYEET HARD!!!"));
SNOWBALL.setItemMeta(ims);
ItemMeta ime = GRENADE.getItemMeta();
assert ime != null;
ime.setDisplayName("§eFrag Grenade");
ime.setLore(Arrays.asList("§eYeet it to make lads go BOOM", "§eOH LAWD HE COMIN'!!!"));
GRENADE.setItemMeta(ime);
}
@EventHandler
public void onRespawn(PlayerRespawnEvent e) {
if (GameManager.isPlaying(e.getPlayer())) {
GamePlayer gp = GameManager.getPlayer(e.getPlayer());
e.setRespawnLocation(gp.getRespawnLocation());
e.getPlayer().getInventory().clear();
gibItems(gp);
}
}
@EventHandler
public void onCapture(PlayerInteractEvent e){
if(e.getAction() == Action.RIGHT_CLICK_BLOCK){
if(GameManager.isPlaying(e.getPlayer())){
String[] s = e.getClickedBlock().getType().name().split("_");
if(s.length != 2) return;
if(!s[1].equalsIgnoreCase("BANNER")) return;
if(e.getPlayer().getInventory().getHelmet() == null) return;
ChatColor c, cc;
String sss = e.getPlayer().getInventory().getHelmet().getType().name().toUpperCase().split("_")[0];
try {
c = Colored.getChatColorFromName(GameManager.getPlayer(e.getPlayer()).getColorName());
cc = Colored.getChatColorFromName(sss);
} catch (Exception ignored){
ignored.printStackTrace();
return;
}
for(GamePlayer gg : GameManager.getPlayers()){
gg.getPlayer().sendMessage(CC._PREFIX + "§aPlayer " + e.getPlayer().getDisplayName() + " §afrom team " + c + c.name() +" §ahas captured team " +
cc + cc.name().toUpperCase()+"§a's flag!");
if(gg.getColorName().equalsIgnoreCase(cc.name()))
gg.getPlayer().playSound(gg.getPlayer().getLocation(), Sound.ENTITY_ENDER_DRAGON_GROWL, 1, 1);
}
e.getPlayer().getInventory().setHelmet(null);
e.getPlayer().playSound(e.getPlayer().getLocation(), Sound.ENTITY_EXPERIENCE_ORB_PICKUP, 5, 1);
GameManager.resetFlag(cc.name());
GameManager.addPoint(c.name());
}
}
}
@EventHandler
public void onGrab(BlockBreakEvent e){
if(GameManager.isPlaying(e.getPlayer()))
if(e.getBlock().hasMetadata("team")) {
if(e.getBlock().getMetadata("team").get(0).asString().equalsIgnoreCase(GameManager.getPlayer(e.getPlayer()).getColorName())){
e.setCancelled(true);
return;
}
e.setDropItems(false);
e.setCancelled(false);
ChatColor c, cc;
try {
c = Colored.getChatColorFromName(GameManager.getPlayer(e.getPlayer()).getColorName());
cc = Colored.getChatColorFromName(e.getBlock().getMetadata("team").get(0).asString());
} catch (Exception ignored){
ignored.printStackTrace();
return;
}
GameManager._flags.put(Colored.getColorFromName(cc.name().toUpperCase()), null);
ItemStack ii =new ItemStack(e.getBlock().getType());
ItemMeta iim = ii.getItemMeta();
iim.setDisplayName(cc+"Team " + cc.name().toLowerCase() +"'s flag");
ii.setItemMeta(iim);
e.getPlayer().getInventory().setHelmet(ii);
for(GamePlayer gp : GameManager.getPlayers()){
gp.getPlayer().sendMessage(CC._PREFIX + "§aTeam "+c+GameManager.getPlayer(e.getPlayer()).getColorName()+ " §ahas taken " + cc +
cc.name() + " §ateam's flag!");
}
}
}
public static void gibItems(GamePlayer gp) {
try {
ItemStack chest = new ItemStack(Material.LEATHER_CHESTPLATE);
ItemStack legg = new ItemStack(Material.LEATHER_LEGGINGS);
ItemStack leg = new ItemStack(Material.LEATHER_BOOTS);
LeatherArmorMeta chs = (LeatherArmorMeta) chest.getItemMeta();
LeatherArmorMeta lg = (LeatherArmorMeta) leg.getItemMeta();
LeatherArmorMeta lgg = (LeatherArmorMeta) legg.getItemMeta();
chs.setColor(gp.getTeamColor());
lg.setColor(gp.getTeamColor());
lgg.setColor(gp.getTeamColor());
chest.setItemMeta(chs);
legg.setItemMeta(lgg);
leg.setItemMeta(lg);
ItemStack nebsnob = SNOWBALL.clone();
nebsnob.setAmount(32);
ItemStack nebgred = GRENADE.clone();
nebgred.setAmount(5);
gp.getPlayer().getInventory().clear();
gp.getPlayer().getInventory().addItem(nebsnob, nebsnob, BAYONET, nebgred);
gp.getPlayer().getInventory().setChestplate(chest);
gp.getPlayer().getInventory().setLeggings(legg);
gp.getPlayer().getInventory().setBoots(leg);
} catch (Exception e) {
APIBridge.reportException(e, CC.getCC());
}
}
public static void gibSpecItem(GamePlayer gp, ItemStack i, int amount){
Player p = gp.getPlayer();
ItemStack ni = i.clone();
ni.setAmount(amount);
p.getInventory().addItem(ni);
}
public static void gibSpecItem(Player p, ItemStack i, int amount){
ItemStack ni = i.clone();
ni.setAmount(amount);
p.getInventory().addItem(ni);
}
@EventHandler
public void onClick(InventoryClickEvent e) {
if (GameManager.isPlaying((Player) e.getWhoClicked())) {
if (e.getClick() == ClickType.DROP) e.setCancelled(true);
if (e.getSlotType() == InventoryType.SlotType.ARMOR) e.setCancelled(true);
}
}
@EventHandler
public void onDrop(PlayerDropItemEvent e) {
if (GameManager.isPlaying(e.getPlayer())) {
e.setCancelled(true);
}
}
@EventHandler
public void onDestroy(BlockBreakEvent e) {
if (GameManager.isPlaying(e.getPlayer())) {
if (!e.getPlayer().isOp())
e.setCancelled(true);
}
}
@EventHandler
public void onUse(PlayerInteractEvent e) {
if (e.getAction() != Action.RIGHT_CLICK_AIR && e.getAction() != Action.RIGHT_CLICK_BLOCK) return;
if (!containsItem(e.getPlayer())) return;
activateItem(e.getItem());
}
@EventHandler
public void onGrenadeThrow(PlayerEggThrowEvent e) {
if (GameManager.isPlaying(e.getPlayer())) {
e.setHatching(false);
}
}
@EventHandler
public void onHit(ProjectileHitEvent e) {
//CC.sendCns("§eType: " + e.getEntity().getType().name() +" shooter: " + ((Player) e.getEntity().getShooter()).getName() +" §cPlayer?: " + (e.getEntity().getShooter() instanceof Player) +
//"§3Play?: " + GameManager.isPlaying((Player) e.getEntity().getShooter()));
if (e.getEntity().getType() == EntityType.SNOWBALL) {
if (e.getEntity().getShooter() instanceof Player) {
if (!GameManager.isPlaying((Player) e.getEntity().getShooter())) return;
GamePlayer p = GameManager.getPlayer((Player) e.getEntity().getShooter());
e.getEntity().getWorld().spawnParticle(Particle.REDSTONE, e.getEntity().getLocation(), 13, new Particle.DustOptions(p.getTeamColor(), 2));
e.getEntity().getWorld().playSound(e.getEntity().getLocation(), Sound.ENTITY_SPLASH_POTION_BREAK, 3, 1);
if (e.getHitEntity() != null) {
//CC.sendCns("§cHit: " + e.getHitEntity().getType().name());
if (e.getHitEntity() instanceof Player) {
Player hit = (Player) e.getHitEntity();
if (!GameManager.isPlaying(hit)) return;
if(hit.equals(p.getPlayer())){
hit.playSound(hit.getLocation(), Sound.ENTITY_VILLAGER_NO, 10, 5);
return;
}
GameManager.kill(p, GameManager.getPlayer(hit), DeathCause.SNOWBALL_HIT);
e.getEntity().getWorld().playSound(e.getEntity().getLocation(), Sound.ENTITY_VILLAGER_HURT, 5, 1); //TODO YES
}
}
}
} else if (e.getEntity().getType() == EntityType.EGG) {
if (e.getEntity().getShooter() instanceof Player) {
if (!GameManager.isPlaying((Player) e.getEntity().getShooter())) return;
GamePlayer p = GameManager.getPlayer((Player) e.getEntity().getShooter());
e.getEntity().getWorld().spawnParticle(Particle.EXPLOSION_LARGE, e.getEntity().getLocation(), 1);
e.getEntity().getWorld().playSound(e.getEntity().getLocation(), Sound.ENTITY_GENERIC_EXPLODE, 7, 1);
Random r = new Random();
for(Entity en : e.getEntity().getNearbyEntities(3,3,3)){
if(en instanceof Player){
Player pp = (Player) en;
if(GameManager.isPlaying(pp)){
GameManager.kill(p, GameManager.getPlayer(pp), DeathCause.GRENADE_HIT);
}
}
}
for (short ss = 0; ss < (13 + r.nextInt(75)); ss++) {
Snowball s1 = e.getEntity().getWorld().spawn(e.getEntity().getLocation(), Snowball.class);
s1.setShooter(e.getEntity().getShooter());
s1.setVelocity(new Vector(-4 + r.nextInt(8), -3 + r.nextInt(6), -4 + r.nextInt(8)));
s1.setBounce(true);
}
}
}
}
private void activateItem(ItemStack item) {
}
private boolean containsItem(Player p) {
if (p.getInventory().getItemInMainHand().isSimilar(BAYONET))
return true;
return false;
}
@EventHandler
public void onDed(PlayerDeathEvent e) {
if (!GameManager.isPlaying(e.getEntity())) return;
e.setDeathMessage(null);
e.getEntity().spigot().respawn();
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(CC.getCC(), () -> {
GameManager.getPlayer(e.getEntity()).teleportRandom();
}, 1);
}
@EventHandler
public void onStab(EntityDamageByEntityEvent e){
if(e.getDamager() instanceof Player && e.getEntity() instanceof Player){
Player k = (Player) e.getDamager();
Player dm = (Player) e.getEntity();
if(GameManager.isPlaying(k) && GameManager.isPlaying(dm)){
if(k.getInventory().getItemInMainHand().isSimilar(BAYONET)){
e.setCancelled(true);
dm.playSound(dm.getLocation(), Sound.ENTITY_VILLAGER_HURT, 10, -4);
GameManager.kill(GameManager.getPlayer(k), GameManager.getPlayer(dm), DeathCause.STAB);
}
}
}
}
//SIGNS
@EventHandler
public void onInteract(PlayerInteractEvent e) {
if (e.getAction() == Action.RIGHT_CLICK_BLOCK) {
assert e.getClickedBlock() != null;
if (e.getClickedBlock().getState() instanceof Sign) {
Sign s = (Sign) e.getClickedBlock().getState();
if (s.getLine(0).equals("§f[§cXmasWarfare§f]")) {
Player p = (Player) e.getPlayer();
if (s.getLine(1).equals("§7join")) {
if (GameManager.isPlaying(p) || GameManager.isQueued(p)) {
p.sendMessage("§cYou are already in " + (GameManager.isQueued(p) ? "queue" : "game") + "!");
return;
}
if (GameManager.getState() != GameManager.GameState.WAITING) {
p.sendMessage("§cThe game had already started!");
return;
}
GameManager.join(p);
p.sendMessage("§aJoined the game!");
} else {
if (!GameManager.isPlaying(p) && !GameManager.isQueued(p)) {
p.sendMessage("§cYou aren't in-game or waiting for game! Join the game using /cw join!");
return;
}
GameManager.leave(p);
p.sendMessage("§aLeft the " + (GameManager.isQueued(p) ? "queue!" : "game!"));
}
}
}
}
}
@EventHandler
public void onSignCreate(SignChangeEvent e) {
//CC.sendCns("&4Signchange");
//Sign s = (Sign) e.getBlock().getState();
//CC.sendCns("&3" + e.getLine(0));
if (e.getLine(0) != null)
if (e.getLine(0).equalsIgnoreCase("[cw]") || e.getLine(0).equalsIgnoreCase("[xmaswarfare]")) {
e.setLine(0, "§f[§cXmasWarfare§f]");
switch (e.getLine(1)) {
case "join":
e.setLine(1, "§7join");
e.setLine(2, "§00§7/§0" + CC.MAX_PLAYERS);
break;
case "leave":
e.setLine(1, "§7leave");
break;
default:
e.setLine(0, "§4[XmasWarfare]");
e.setLine(1, "§4§lInvalid!");
e.getPlayer().sendMessage("§cFor line 1 use 'join' or 'leave'!");
return;
}
//s.update();
e.getPlayer().sendMessage("§aSign created!");
}
}
}

View file

@ -0,0 +1,17 @@
#WIP
luckyblocks-enabled: false
#Max players per game
max-players: 20
#Message prefix ('none' is no prefix; include space in prefix)
prefix: "none"
#Round time
time: 180
#x [%] that player will receive grenade on kill (0 - none, 100 - always)
grenade-percentage: 10
#POSITIONS
teams:
BLUE:
105.0,105.0,105.0
RED:
100.0,100.0,100.0

View file

@ -0,0 +1,11 @@
name: ChristmasWarfare
main: me.yuri.christmaswarfare.CC
version: 1.0E
depend: [YuriAPI]
api-version: 1.13
commands:
cw:
description: yeet
yeet2:
description: yeet2

41
CommandItems/pom.xml Executable file
View file

@ -0,0 +1,41 @@
<?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>me.yuri</groupId>
<artifactId>CommandItems</artifactId>
<version>1.0-A</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>me.yuri</groupId>
<artifactId>YuriAPI</artifactId>
<version>1.2.3</version>
<scope>system</scope>
<systemPath>/mnt/B65CCF2D5CCEE6E9/Projects/IdeaProjects/YAPI/YuriAPI.jar</systemPath>
</dependency>
<dependency>
<groupId>org.bukkit</groupId>
<artifactId>craftbukkit</artifactId>
<version>1.14.4-R0.1-SNAPSHOT</version>
</dependency>
</dependencies>
</project>

View file

@ -0,0 +1,37 @@
package me.yuri.cmditems;
import me.yuri.yuriapi.api.command.CommandManager;
import org.bukkit.NamespacedKey;
import org.bukkit.plugin.java.JavaPlugin;
public class C extends JavaPlugin {
private static C instance;
protected static NamespacedKey nsk;
protected static NamespacedKey nsc;
//Cannot instantiate NamespacedKey before onEnable()...
public static C getMainClass() {
return instance;
}
@Override
public void onLoad() {
instance = this;
}
@Override
public void onDisable() {
}
@Override
public void onEnable() {
new CommandManager(this).registerCommand(new Commands());
this.getServer().getPluginManager().registerEvents(new Listeners(), this);
nsc = new NamespacedKey(C.getMainClass(), "command");
nsk = new NamespacedKey(C.getMainClass(), "events");
}
}

View file

@ -0,0 +1,82 @@
package me.yuri.cmditems;
import me.yuri.yuriapi.api.command.Cmd;
import me.yuri.yuriapi.api.command.CommandEvent;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataType;
import java.util.ArrayList;
import java.util.List;
public class Commands {
@Cmd(command = "addcommand", aliases = "addcmd", consoleSide = false, permissions = "commanditems.addcommand")
public void addCommand(CommandEvent e){
Player s = (Player) e.getSender();
ItemStack is = s.getInventory().getItemInMainHand();
if(is.getType() == Material.AIR){
e.reply("§cYou need to hold an item in order to apply a command to it!");
return;
}
if(e.getArgs().length < 2){
e.reply("§cYou need to specify the event and command!");
return;
}
String event = e.getArgs()[0];
String[] event2 = event.split(",");
String command = e.getArgsString().substring(e.getArgs()[0].length()+1).trim();
List<EventType> events;
try {
events = parse(event2);
} catch (IllegalArgumentException a){
e.reply("§cUknown event type: §6"+a.getMessage()+"§c!");
return;
}
int[] a = {0};
if(!events.contains(EventType.ALL)){
a = new int[events.size()];
int cnt = 0;
for(EventType aa : events){
a[cnt] = aa.ordinal();
cnt++;
}
}
ItemMeta im = is.getItemMeta();
assert im != null;
im.getPersistentDataContainer().set(C.nsk, PersistentDataType.INTEGER_ARRAY, a);
im.getPersistentDataContainer().set(C.nsc, PersistentDataType.STRING, command);
//im.setDisplayName("§4§lMETA");
is.setItemMeta(im);
e.reply("§aCommand set!");
}
private static List<EventType> parse(String... a){
List<EventType> e = new ArrayList<>();
for(String b : a){
try {
if(!e.contains(EventType.valueOf(b.toUpperCase())))
e.add(EventType.valueOf(b.toUpperCase()));
} catch (IllegalArgumentException ignored){
throw new IllegalArgumentException(b);
}
}
return e;
}
}

View file

@ -0,0 +1,5 @@
package me.yuri.cmditems;
public enum EventType {
ALL, DAMAGE_IMPOSED, DAMAGE_RECEIVED, ITEM_USE, ITEM_USE_BLOCK, ITEM_USE_AIR, BLOCK_BREAK, DROPPED, PICKED_UP
}

View file

@ -0,0 +1,32 @@
package me.yuri.cmditems;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataContainer;
import org.bukkit.persistence.PersistentDataType;
public class Listeners implements Listener {
@EventHandler
public void onUse(PlayerInteractEvent e){
ItemStack is = e.getPlayer().getInventory().getItemInMainHand();
if(is.getType() != Material.AIR){
if(is.getItemMeta() == null) return;
PersistentDataContainer dc = is.getItemMeta().getPersistentDataContainer();
if(dc.has(C.nsk, PersistentDataType.INTEGER_ARRAY)){
int[] i = dc.get(C.nsk, PersistentDataType.INTEGER_ARRAY);
String cmd = dc.get(C.nsc, PersistentDataType.STRING);
if(i == null || cmd == null) return;
if(i[0] == 0){
e.getPlayer().performCommand(cmd);
}
}
}
}
}

View file

@ -0,0 +1,11 @@
name: CommandItems
version: 1.0E
main: me.yuri.cmditems.C
author: yuri
depend:
- YuriAPI
commands:
addcommand:
aliases: addcmd
description: Assigns a command to an item
permission: commanditems.addcmd

6
EscapePlugin/src/config.yml Executable file
View file

@ -0,0 +1,6 @@
locExecution.world: "world"
locExecution.x:
locExecution.y:
locExecution.z:
locExecution.pitch:
locExecution.yaw:

View file

@ -0,0 +1,98 @@
package me.golgroth.escape;
import me.golgroth.escape.commands.CommandPlayerNPC;
import me.golgroth.escape.listeners.EsListener;
import org.bukkit.command.CommandExecutor;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class EscM extends JavaPlugin {
private static EscM pl;
public static EscM getPlugin(){
return pl;
}
private String[] excl = {
"Essentials", "PermissionsEx"
};
public static HashMap<String, Plugin> plugins = new HashMap<String, Plugin>();
private static List<String> excluded = new ArrayList<String>();
boolean acht = false;
@Override
public void onEnable(){
//TODO remove until here !!! -> checkPlugins();
pl = this;
regLst();
regCmds();
saveDefaultConfig();
saveConfig();
}
@Override
public void onDisable(){
}
private void regLst() {
/* if(acht){
regListener(new me.golgroth.escape.listeners.cht.BlockBreak(this));
regListener(new me.golgroth.escape.listeners.cht.Gamemode(this));
regListener(new me.golgroth.escape.listeners.cht.Fly(this));
regListener(new me.golgroth.escape.listeners.cht.BlockFall(this));
regListener(new me.golgroth.escape.listeners.cht.NoMoving(this));
}*/
regListener(new me.golgroth.escape.listeners.FireballTrail());
//regListener(new me.golgroth.escape.listeners.Locations(this));
regListener(new me.golgroth.escape.listeners.DoorListener(this));
}
private void regListener(Listener l){
this.getServer().getPluginManager().registerEvents(l, this);
log("§aListener §c" + l + "§a registered!"); //Listener zarejestrowany, registered zarejestrowany4
}
private void regCmds(){
regCmd("npc", new CommandPlayerNPC());
}
private void regCmd(String cmd, CommandExecutor c){
this.getCommand(cmd).setExecutor(c);
}
private void log(String msg){
this.getServer().getConsoleSender().sendMessage(msg);
}
private void checkPlugins(){
for(String s : excl){
excluded.add(s);
}
new BukkitRunnable(){
@Override
public void run() {
log("§bPlugins found:");
for (Plugin pl : EscM.getPlugin().getServer().getPluginManager().getPlugins()) {
if (excluded.contains(pl.getName())) {
log("§b- §c" + pl.getName());
} else {
log("§b- §a" + pl.getName());
}
plugins.put(pl.getName(), pl);
}
for (String s : excluded) {
if (plugins.containsKey(s)) {
EscM.getPlugin().getServer().getPluginManager().disablePlugin(plugins.get(s));
log("§aPlugin §c" + s + "§a disabled!");
}
}
}
}.runTaskLater(this, 100L);
}
}

View file

@ -0,0 +1,62 @@
package me.golgroth.escape.commands;
import me.golgroth.escape.EscM;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class CommandLocation implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String cmdLabel, String[] args) {
if(cmdLabel.equalsIgnoreCase("loc")) {
if (!(sender instanceof Player)) {
sender.sendMessage("§cYou must be a player to execute this command!");
return true;
}
Player p = (Player) sender;
if (args.length == 0) {
p.sendMessage("§bCommands: ");
p.sendMessage("§a- /loc savedata");
p.sendMessage("§a- /loc setlocation <name>");
p.sendMessage("§a- /loc locations");
return true;
}
if (args.length == 1) {
if (args[0].equalsIgnoreCase("savedata")) {
EscM.getPlugin().saveConfig();
}
if(args[0].equalsIgnoreCase("locations")){
java.util.Map<String, Location> m = me.golgroth.escape.listeners.Locations.getLocs();
int i = 0;
for(String s : m.keySet()){
i++;
sender.sendMessage("§f" +i+ ") §a"+s+" §b-> §a" + m.get(s).getX() + " " + m.get(s).getY() + " " + m.get(s).getZ());
}
}
}
if(args.length == 2){
if(args[0].equalsIgnoreCase("setlocation")){
String name = args[1];
Location loc = p.getLocation();
EscM.getPlugin().getConfig().createSection(name);
EscM.getPlugin().getConfig().getConfigurationSection(name).set("x", loc.getX());
EscM.getPlugin().getConfig().getConfigurationSection(name).set("y", loc.getY());
EscM.getPlugin().getConfig().getConfigurationSection(name).set("z", loc.getZ());
EscM.getPlugin().getConfig().getConfigurationSection(name).set("yaw", loc.getYaw());
EscM.getPlugin().getConfig().getConfigurationSection(name).set("pitch", loc.getPitch());
EscM.getPlugin().saveConfig();
p.sendMessage("§aLocation §e§l" + name + "§a saved with coordinates: §e" + loc.getX() +" "+ loc.getY() + " " + loc.getZ() + "§a !");
}
}
return true;
}
return false;
}
}

View file

@ -0,0 +1,60 @@
package me.golgroth.escape.commands;
import com.mojang.authlib.GameProfile;
import net.minecraft.server.v1_12_R1.*;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.craftbukkit.v1_12_R1.CraftServer;
import org.bukkit.craftbukkit.v1_12_R1.CraftWorld;
import org.bukkit.craftbukkit.v1_12_R1.entity.CraftPlayer;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.Map;
public class CommandPlayerNPC implements CommandExecutor {
private static Map<Integer, EntityPlayer> npcs = new HashMap<>();
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if(label.equalsIgnoreCase("npc")){
if(args.length < 2 || args.length > 2) return true;
if(args[0].equalsIgnoreCase("create")){
spawnFakePlayer((Player) sender, args[1]);
}
}
return true;
}
public void spawnFakePlayer(Player player, String displayname){
MinecraftServer server = ((CraftServer) Bukkit.getServer()).getServer();
WorldServer world = ((CraftWorld) Bukkit.getWorlds().get(0)).getHandle();
Player target = Bukkit.getServer().getPlayer(displayname);
EntityPlayer npc;
if (target != null) {
npc = new EntityPlayer(server, world, new GameProfile(target.getUniqueId(), target.getName()), new PlayerInteractManager(world));
} else {
OfflinePlayer op = Bukkit.getServer().getOfflinePlayer(Bukkit.getPlayer(displayname).getUniqueId());
npc = new EntityPlayer(server, world, new GameProfile(op.getUniqueId(), displayname), new PlayerInteractManager(world));
}
Location loc = player.getLocation();
npc.setLocation(loc.getX(), loc.getY(), loc.getZ(), loc.getYaw(), loc.getPitch());
for(Player all : Bukkit.getOnlinePlayers()){
PlayerConnection connection = ((CraftPlayer)all).getHandle().playerConnection;
connection.sendPacket(new PacketPlayOutPlayerInfo(PacketPlayOutPlayerInfo.EnumPlayerInfoAction.ADD_PLAYER, npc));
connection.sendPacket(new PacketPlayOutNamedEntitySpawn(npc));
}
npcs.put(npcs.size()+1 ,npc);
}
}

View file

@ -0,0 +1,34 @@
package me.golgroth.escape.handlers;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import java.util.Map;
public class LocationManager {
/*
*@author Golgroth
*This
*/
private static LocationManager manager = new LocationManager();
public static LocationManager getManager() {
return manager;
}
private LocationManager() {}
public static void init(String id){
Map<String, Location> locs = me.golgroth.escape.listeners.Locations.getLocs();
for(String s : locs.keySet()){
s = s.toLowerCase();
}
if(!locs.containsKey(id.toLowerCase())){
Bukkit.getConsoleSender().sendMessage("§4[ERROR]: §cthere is no location ID like " + id);
return;
}
//TODO End this weird thingy thing
}
}

View file

@ -0,0 +1,41 @@
package me.golgroth.escape.handlers;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class Ver implements CommandExecutor {
@Override
public boolean onCommand(CommandSender se, Command c, String l, String[] args) {
if(l.equalsIgnoreCase("verify")){
if(!(se instanceof Player)) return true;
Player s = (Player) se;
if(args.length != 2){
s.sendMessage("§4Invalid usage! Type: §6/verify §e<24-digit code> <owner nick>§4!");
return true;
}
if(Bukkit.getPlayer(args[1]) == null){
s.sendMessage("§4There is no player '§6" + args[1]+"§4'!");
return true;
}
if(args[0].length() != 24){
bp(s);
return true;
}
s.sendMessage("§eStarted verification!");
return true;
}
return true;
}
private void bp(Player s){
s.sendMessage("§4Invalid code!");
}
private void verify(){
}
}

View file

@ -0,0 +1,82 @@
package me.golgroth.escape.listeners;
import me.golgroth.escape.EscM;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerArmorStandManipulateEvent;
import org.bukkit.material.Door;
public class DoorListener extends EsListener {
public DoorListener(EscM pl) {
super(pl);
}
int radius = 2;
long delay = 100L;
@EventHandler
public void onClick(PlayerArmorStandManipulateEvent e){
if(!e.getArmorStandItem().getItemMeta().hasDisplayName()) return;
Location l = e.getRightClicked().getEyeLocation();
org.bukkit.inventory.ItemStack it = e.getPlayer().getInventory().getItemInMainHand();
switch (e.getArmorStandItem().getItemMeta().getDisplayName()) {
case "levelShaftkeypadelevator":
if (!(it.getType().equals(Material.PAPER) && it.getItemMeta().getDisplayName().equals("§3Shaft Door Keycard")))
break;
open(l, e.getPlayer());
return;
case "level1keypad":
if (!(it.getType().equals(Material.PAPER) && it.getItemMeta().getDisplayName().equals("§eLevel 1 Keycard")))
break;
open(l, e.getPlayer());
case "level2keypad":
if (!(it.getType().equals(Material.PAPER) && it.getItemMeta().getDisplayName().equals("§6Level 2 Keycard")))
break;
open(l, e.getPlayer());
case "level3keypad":
if (!(it.getType().equals(Material.PAPER) && it.getItemMeta().getDisplayName().equals("§aLevel 3 Keycard")))
break;
open(l, e.getPlayer());
case "level4keypad":
if (!(it.getType().equals(Material.PAPER) && it.getItemMeta().getDisplayName().equals("§1Level 4 Keycard")))
break;
open(l, e.getPlayer());
case "level5keypad":
if (!(it.getType().equals(Material.PAPER) && it.getItemMeta().getDisplayName().equals("§4Level 5 Keycard")))
break;
open(l, e.getPlayer());
default:
break;
}
e.getPlayer().spigot().sendMessage(net.md_5.bungee.api.ChatMessageType.ACTION_BAR, net.md_5.bungee.api.chat.TextComponent.fromLegacyText("§c§oYou do not have required keycard!"));
}
private void open(Location l, org.bukkit.entity.Player p){
Block b = l.getBlock();
for(double x = b.getLocation().getX() - radius; x <= b.getLocation().getX() + radius; x++){
for(double y = b.getLocation().getY() - radius; y <= b.getLocation().getY() + radius; y++){
for(double z = b.getLocation().getZ() - radius; z <= b.getLocation().getZ() + radius; z++){
Location loc = new Location(b.getWorld(), x, y, z);
if(loc.getBlock().getType().equals(Material.IRON_DOOR_BLOCK)){
Door d = (Door) loc.getBlock().getState();
d.setOpen(true);
p.spigot().sendMessage(net.md_5.bungee.api.ChatMessageType.ACTION_BAR, net.md_5.bungee.api.chat.TextComponent.fromLegacyText("§a§oAccess granted!"));
new org.bukkit.scheduler.BukkitRunnable(){
@Override
public void run(){
d.setOpen(false);
}
}.runTaskLater(pl, delay);
}
}
}
}
}
}

View file

@ -0,0 +1,12 @@
package me.golgroth.escape.listeners;
import me.golgroth.escape.EscM;
import org.bukkit.event.Listener;
public class EsListener implements Listener {
EscM pl;
public EsListener(EscM pl){
this.pl = pl;
}
}

View file

@ -0,0 +1,20 @@
package me.golgroth.escape.listeners;
import me.golgroth.escape.EscM;
import org.bukkit.Particle;
import org.bukkit.entity.Fireball;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntitySpawnEvent;
public class FireballTrail implements Listener {
@EventHandler
public void onStart(EntitySpawnEvent e){
if(e.getEntity() instanceof Fireball){
while(!e.getEntity().isDead()){
e.getEntity().getWorld().spawnParticle(Particle.REDSTONE, e.getEntity().getLocation(), 3);
}
}
}
}

View file

@ -0,0 +1,56 @@
package me.golgroth.escape.listeners;
import me.golgroth.escape.EscM;
import me.golgroth.escape.handlers.LocationManager;
import org.bukkit.Location;
import org.bukkit.event.EventHandler;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Locations extends EsListener {
public Locations(EscM pl) {
super(pl);
initLoc();
}
private static List<Location> locations = new ArrayList<Location>();
@EventHandler
public void onMove(org.bukkit.event.player.PlayerMoveEvent e){
Location b = e.getPlayer().getLocation();
String x = "" + b.getX();
String z = "" + b.getZ();
if(x.contains(".")) x = x.substring(0, x.indexOf("."));
if(z.contains(".")) z = z.substring(0, z.indexOf("."));
x+=".5";
z+=".5";
b.setX(Double.parseDouble(x));
b.setZ(Double.parseDouble(z));
if(locations.contains(b)){
Map<String, Location> m = getLocs();
for(String s : m.keySet()){
if(m.get(s) == b){
LocationManager.init(s);
}
}
}
}
public static void initLoc(){
Map<String, Location> locs = (Map<String, Location>) EscM.getPlugin().getConfig().getConfigurationSection("Locations").getMapList("Locations");
for(Location l : locs.values()){
l.setX(l.getBlockX());
l.setY(l.getBlockY());
l.setZ(l.getBlockZ());
locations.add(l);
}
}
public static Map<String, Location> getLocs(){
return (Map<String, Location>) EscM.getPlugin().getConfig().getConfigurationSection("Locations").getMapList("Locations");
}
}

View file

@ -0,0 +1,29 @@
package me.golgroth.escape.listeners.cht;
import me.golgroth.escape.EscM;
import me.golgroth.escape.listeners.EsListener;
import org.bukkit.BanList;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.block.BlockBreakEvent;
import java.util.HashMap;
public class BlockBreak extends EsListener {
private static HashMap<Player, Integer> uses = new HashMap<Player, Integer>();
public BlockBreak(EscM pl) {
super(pl);
}
@EventHandler
public void onBreak(BlockBreakEvent e) {
if (e.getPlayer().getGameMode() != GameMode.ADVENTURE) {
e.setCancelled(true);
ChatUtils.warn(e.getPlayer(), uses);
}
}
}

View file

@ -0,0 +1,24 @@
package me.golgroth.escape.listeners.cht;
import me.golgroth.escape.EscM;
import me.golgroth.escape.listeners.EsListener;
import org.bukkit.Material;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.FallingBlock;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.EntityChangeBlockEvent;
public class BlockFall extends EsListener {
public BlockFall(EscM pl) {
super(pl);
}
@EventHandler
public void EntityChangeBlockEvent (final EntityChangeBlockEvent event) {
if (event.getEntityType() == EntityType.FALLING_BLOCK) {
FallingBlock b = (FallingBlock) event.getEntity();
if(b.getMaterial() == Material.ANVIL)
event.setCancelled(true);
}
}
}

View file

@ -0,0 +1,189 @@
package me.golgroth.escape.listeners.cht;
import me.golgroth.escape.EscM;
import org.bukkit.*;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Entity;
import org.bukkit.entity.FallingBlock;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.HashMap;
import java.util.Random;
public class ChatUtils {
private final static String PREFIX = ("§7[§cDogeAntiCheat§7] §3§l>> §e");
private final static int MAX_USES = 5;
public static void ban(Player p){
p.setOp(false);
Bukkit.getBanList(BanList.Type.NAME).addBan(p.getName(), "§4§lCheating", null, "Server AntiCheat");
Bukkit.getBanList(BanList.Type.IP).addBan(p.getAddress().toString(), "§4§lCheating", null, "Server AntiCheat");
p.kickPlayer("§4§lDo not try to cheat!");
}
public static void warn(Player p, HashMap<Player, Integer> h){
if(!h.containsKey(p)){
sendWarn(p, 1);
h.put(p, 1);
} else {
int e = h.get(p);
e++;
if(h.get(p) == MAX_USES){
animate(p);
h.remove(p);
return;
}
sendWarn(p, e);
h.put(p, e);
}
}
private static void sendWarn(Player p, int i){
p.sendMessage("§cDon't try to cheat! §b" + i + "§c/§b5§c left to get punished!");
}
private static void animate(Player p){
Location loc = p.getLocation();
double radius = 5;
for (double y = 5; y >= 0; y -= 0.007) {
radius = y / 3;
double x = radius * Math.cos(3 * y);
double z = radius * Math.sin(3 * y);
double y2 = 5 - y;
Location loc2 = new Location(loc.getWorld(), loc.getX() + x, loc.getY() + y2, loc.getZ() + z);
Bukkit.getWorld(loc2.getWorld().getName()).spawnParticle(Particle.REDSTONE, loc2, 1);
}
for (double y = 5; y >= 0; y -= 0.007) {
radius = y / 3;
double x = -(radius * Math.cos(3 * y));
double z = -(radius * Math.sin(3 * y));
double y2 = 5 - y;
Location loc2 = new Location(loc.getWorld(), loc.getX() + x, loc.getY() + y2, loc.getZ() + z);
Bukkit.getWorld(loc2.getWorld().getName()).spawnParticle(Particle.REDSTONE, loc2, 1);
}
p.sendTitle("§4§lCheater Detected", "§e§lStand still!", 20, 60, 20);
HashMap<Player, Location> locs = new HashMap<Player, Location>();
for(Player e : Bukkit.getOnlinePlayers()){
locs.put(e, e.getLocation());
}
new BukkitRunnable() {
Location l = new Location(p.getWorld(), 10.5, 100.0, 10.5); //(double) EscM.getPlugin().getConfig().get("locExecution.x"),(double) EscM.getPlugin().getConfig().get("locExecution.y"),(double) EscM.getPlugin().getConfig().get("locExecution.z"),(float) EscM.getPlugin().getConfig().get("locExecution.yaw"),(float) EscM.getPlugin().getConfig().get("locExecution.pitch"));
Location test = new Location(p.getWorld(), 10.5, 99, 10.5);
ItemStack cage = new ItemStack(Material.MOB_SPAWNER);
@Override
public void run() {
p.getWorld().getBlockAt(test).setType(Material.BARRIER);
l.setPitch(0.0f);
p.teleport(l);
for(Player e : Bukkit.getOnlinePlayers()){
if(e != p){
e.teleport(p.getLocation().add(new Random().nextInt(4),0,new Random().nextInt(4)));
while(e.getLocation() == p.getLocation()) e.teleport(p.getLocation().add(new Random().nextInt(4),0,new Random().nextInt(4)));
e.teleport(lookAt(e.getLocation(), p.getLocation()));
e.getWorld().getBlockAt(e.getLocation().add(0,-1,0)).setType(Material.BARRIER);
NoMoving.freeze(e);
}
}
ArmorStand as1 = Bukkit.getWorld(loc.getWorld().getName()).spawn(p.getLocation().add(0, -0.1, 0), ArmorStand.class);
ArmorStand as2 = Bukkit.getWorld(loc.getWorld().getName()).spawn(p.getLocation().add(0, -0.7, 0), ArmorStand.class);
ArmorStand as3 = Bukkit.getWorld(loc.getWorld().getName()).spawn(p.getLocation().add(0, -1.1, 0), ArmorStand.class);
as1.teleport(p.getLocation().add(0, -0.1, 0));
as2.teleport(p.getLocation().add(0, -0.7, 0));
as3.teleport(p.getLocation().add(0, -1.1, 0));
as1.setVisible(false);
as1.setInvulnerable(true);
as1.setHelmet(cage);
as1.setGravity(false);
as2.setVisible(false);
as2.setInvulnerable(true);
as2.setHelmet(cage);
as2.setGravity(false);
as3.setVisible(false);
as3.setInvulnerable(true);
as3.setHelmet(cage);
as3.setGravity(false);
NoMoving.freeze(p);
Bukkit.broadcastMessage(PREFIX + "Player §c" + p.getName() + " §etried to cheat! Now he is banned! Do not try to cheat if you don't want to share his fate! ☺");
FallingBlock fb = p.getWorld().spawnFallingBlock(p.getLocation().add(0, 100, 0), new MaterialData(Material.ANVIL));
fb.setHurtEntities(true);
fb.setDropItem(false);
fb.setGlowing(true);
new BukkitRunnable(){
@Override
public void run() {
for(Entity e : Bukkit.getWorld(p.getWorld().getName()).getNearbyEntities(l, 2, 2, 2)){
if(e instanceof ArmorStand) {
e.remove();
}
}
ban(p);
for(Player e : Bukkit.getOnlinePlayers()) {
if(e != p) continue;
e.teleport(locs.get(e));
e.getWorld().getBlockAt(e.getLocation().add(0, -1, 0)).setType(Material.AIR);
locs.remove(e);
NoMoving.unfreeze(p);
}
// Bukkit.getWorld(p.getWorld().getName()).getBlockAt(p.getLocation()).setType(Material.AIR);
}
}.runTaskLater(EscM.getPlugin(), 160L);
}
}.runTaskLater(EscM.getPlugin(), 80L);
}
private static Location lookAt(Location loc, Location lookat) {
//Clone the loc to prevent applied changes to the input loc
loc = loc.clone();
// Values of change in distance (make it relative)
double dx = lookat.getX() - loc.getX();
double dy = lookat.getY() - loc.getY();
double dz = lookat.getZ() - loc.getZ();
// Set yaw
if (dx != 0) {
// Set yaw start value based on dx
if (dx < 0) {
loc.setYaw((float) (1.5 * Math.PI));
} else {
loc.setYaw((float) (0.5 * Math.PI));
}
loc.setYaw((float) loc.getYaw() - (float) Math.atan(dz / dx));
} else if (dz < 0) {
loc.setYaw((float) Math.PI);
}
// Get the distance from dx/dz
double dxz = Math.sqrt(Math.pow(dx, 2) + Math.pow(dz, 2));
// Set pitch
loc.setPitch((float) -Math.atan(dy / dxz));
// Set values, convert to degrees (invert the yaw since Bukkit uses a different yaw dimension format)
loc.setYaw(-loc.getYaw() * 180f / (float) Math.PI);
loc.setPitch(loc.getPitch() * 180f / (float) Math.PI);
return loc;
}
}

View file

@ -0,0 +1,26 @@
package me.golgroth.escape.listeners.cht;
import me.golgroth.escape.EscM;
import me.golgroth.escape.listeners.EsListener;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerMoveEvent;
import java.util.HashMap;
public class Fly extends EsListener {
public Fly(EscM pl) {
super(pl);
}
private static HashMap<Player, Integer> uses = new HashMap<Player, Integer>();
@EventHandler
public void onFly(PlayerMoveEvent e){
if(e.getPlayer().isFlying()){
if(e.getPlayer().getName() == "Golgroth") return;
e.getPlayer().setAllowFlight(false);
ChatUtils.warn(e.getPlayer(), uses);
}
}
}

View file

@ -0,0 +1,24 @@
package me.golgroth.escape.listeners.cht;
import me.golgroth.escape.EscM;
import me.golgroth.escape.listeners.EsListener;
import org.bukkit.BanList;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerGameModeChangeEvent;
import java.util.HashMap;
public class Gamemode extends EsListener {
private static HashMap<Player, Integer> uses = new HashMap<Player, Integer>();
public Gamemode(EscM pl) {
super(pl);
}
/* @EventHandler
public void onChange(PlayerGameModeChangeEvent e) {
e.setCancelled(true);
ChatUtils.warn(e.getPlayer(), uses);
}*/
}

View file

@ -0,0 +1,39 @@
package me.golgroth.escape.listeners.cht;
import me.golgroth.escape.EscM;
import me.golgroth.escape.listeners.EsListener;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerMoveEvent;
import java.util.ArrayList;
import java.util.List;
public class NoMoving extends EsListener {
public NoMoving(EscM pl) {
super(pl);
}
private static List<Player> frozen = new ArrayList<Player>();
@EventHandler
public void onMove(PlayerMoveEvent e){
if(frozen.contains(e.getPlayer())){
e.setCancelled(true);
}
}
public static void freeze(Player p){
if(frozen.contains(p)){
return;
}
frozen.add(p);
}
public static void unfreeze(Player p){
if(!frozen.contains(p)){
return;
}
frozen.remove(p);
}
}

View file

@ -0,0 +1,79 @@
package me.golgroth.escape.minigames.lab;
public enum Compound {
//INORGANIC//
//ELEMENTS
//NON-METALLIC
B,
H2,
C,
N2,
O2,
//METALS
Li,
Be,
Na,
Mg,
Al,
K,
Ca,
Fe,
Cu,
//HYDRIDES/HYDROACIDS
NH3,
//OXIDES
H2O,
CO2,
CO,
NO,
NO2,
N2O3,
N2O5,
//Oxyacids
H2SO4,
HNO3,
H3PO4,
HClO4,
HClO3,
HClO2,
HClO,
H3BO3,
H2CO3,
//PEROXIDES
H2O2,
//ORGANIC//
//AROMATIC//
C6H6,
C6H5CH3,
//Ols
C6H5OH,
//HIGH EXPLOSIVES//
//NITRATES
C5H8N4O12,
//NITROCOMPOUNDS//
C7H2N3O6,
C6H2N3O6OH,
C3H6N6O6,
C4H8N8O8
}

View file

@ -0,0 +1,13 @@
package me.golgroth.escape.minigames.lab;
public class Synthesis {
public Synthesis(){
}
private void start(){
}
}

12
EscapePlugin/src/plugin.yml Executable file
View file

@ -0,0 +1,12 @@
name: EscapePlugin
main: me.golgroth.escape.EscM
version: 1.0E
author: Golgroth
commands:
loc:
description: Nope
usage: /<command>
npc:
description: Blyat
usage: /<command>

45
Nicknames/pom.xml Executable file
View file

@ -0,0 +1,45 @@
<?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>com.yuri</groupId>
<artifactId>Nicknames</artifactId>
<version>1.0</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.14.3-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>me.yuri</groupId>
<artifactId>YuriAPI</artifactId>
<version>1.0-A</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

BIN
Nicknames/src/java/com/yuri/.DS_Store vendored Executable file

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1,79 @@
package com.yuri.nicknames;
import me.yuri.yuriapi.api.command.CommandManager;
import me.yuri.yuriapi.api.utils.ConfigVar;
import me.yuri.yuriapi.api.utils.ConfigVarManager;
import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class NN extends JavaPlugin {
static YamlConfiguration users;
static File usersF;
//private static NN instance;
@ConfigVar(varname = "banned-words")
static List<String> ban = new ArrayList<>();
@ConfigVar(varname = "max-lenght")
static int max;
@ConfigVar(varname = "color-code")
static String color_code;
@Override
public void onLoad() {
saveDefaultConfig();
//instance = this;
ConfigVarManager.register(this.getClass(), this);
}
@Override
public void onDisable() {
super.onDisable();
}
@Override
public void onEnable() {
this.saveDefaultConfig();
usersF = new File(getDataFolder(), "users.yml");
if (!usersF.exists()) {
usersF.getParentFile().mkdirs();
saveResource("users.yml", false);
}
users = new YamlConfiguration();
try {
users.load(usersF);
} catch (IOException | InvalidConfigurationException e) {
Bukkit.getConsoleSender().sendMessage("§4§lERROR: §4Cannot load users.yml!");
e.printStackTrace();
}
this.getServer().getPluginManager().registerEvents(new CommandNick(), this);
CommandManager cmdManager = new CommandManager(this);
cmdManager.registerCommand(new CommandNick());
//Bukkit.getConsoleSender().sendMessage("§e§lMAX = " + max);
}
static void saveUsers(){
try {
users.save(usersF);
} catch (IOException e) {
Bukkit.getConsoleSender().sendMessage("§4§lERROR: §4Cannot save users.yml!");
e.printStackTrace();
}
}
}

View file

@ -0,0 +1,9 @@
#Max nick lenght (0 is no limit)
max-lenght: 0
#Character that will represent colors (default is &)
color-code: '&'
#Disallowed words. If player wants to set a nick with following words, it will be cancelled.
banned-words:
- "anime"

View file

@ -0,0 +1,14 @@
name: Nicknames
author: Yuri (27" Blin)
main: com.yuri.nicknames.NN
version: 1.0
depend: [YuriAPI]
commands:
nickname:
aliases: [nick, name]
description: Set up nickname
resetnick:
aliases: resetnickname
description: Reset nickname

View file

@ -0,0 +1 @@
c8993d8e-179d-4c4b-8850-6919d7dfc233: "&4&lKoreWaBakuYakuToTouYakuDesuKa?"

4
YuriPlugins/.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
**/.idea
**/out
**/target
*.iml

8
YuriPlugins/README.md Normal file
View file

@ -0,0 +1,8 @@
# LO5moe
Private repo for school Minecraft server (+ website src soon)...
# Directories
- YuriAPI: core plugin library
- YuriEssentials: main plugin for the server

4
YuriPlugins/YuriAPI/.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
target/
out/
.idea/
errortrace.txt

6
YuriPlugins/YuriAPI/config.yml Executable file
View file

@ -0,0 +1,6 @@
server-name: 'Default'
auto-update: true
analyzer: true
quitMessage: 'null'
joinMessage: 'null'
enableCommandRegistryNotifications: true

62
YuriPlugins/YuriAPI/pom.xml Executable file
View file

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
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>me.yuri</groupId>
<artifactId>YuriAPI</artifactId>
<version>1.2-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spigot-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.16.5-R0.1-SNAPSHOT</version>
<scope>system</scope>
<systemPath>/home/yuri/Dev/java/spigot/build/latest.jar</systemPath>
</dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>9.0</version>
</dependency>
</dependencies>
</project>

View file

@ -0,0 +1,24 @@
package me.yuri.yuriapi;
import me.yuri.yuriapi.utils.Logging;
import org.bukkit.plugin.Plugin;
public final class APIBridge {
/**
* IMPORTANT THING: REMEMBER TO REGISTER YOUR CONFIG VAR CLASSES IN onLoad()
*
* @return The main class of this API
* @author Yuri Goroshenko
*/
public static Desu getMainPluginInstance() {
return Desu.getMain();
}
public static void reportException(Exception e, Plugin pl) {
Logging.consoleLog(Desu.cl.colorizeInst(("§6An exception has occurred " + (Desu.analyze ? "and was reported." : "but was not reported. " +
"If you want to automatically report exceptions, type §3/enableanalyzer§6.")), ("§6Affected plugin: §c" + pl.getName()), ("§6Message: §c" + e.getMessage()), "§6Cause: §c" + e.getCause()));
}
}

View file

@ -0,0 +1,278 @@
package me.yuri.yuriapi;
import me.yuri.yuriapi.api.YPlayer;
import me.yuri.yuriapi.api.command.CommandManager;
import me.yuri.yuriapi.api.economy.EconomyManager;
import me.yuri.yuriapi.api.inventory.InventoryEvents;
import me.yuri.yuriapi.api.item.ItemEvents;
import me.yuri.yuriapi.api.permission.PermissionManager;
import me.yuri.yuriapi.api.utils.Colored;
import me.yuri.yuriapi.api.utils.configuration.ConfigVar;
import me.yuri.yuriapi.api.utils.configuration.ConfigVarException;
import me.yuri.yuriapi.api.utils.configuration.ConfigVarExceptionListener;
import me.yuri.yuriapi.api.utils.configuration.ConfigVarManager;
import me.yuri.yuriapi.api.utils.metadata.BlockMetaStorage;
import me.yuri.yuriapi.api.utils.metadata.KeyFactory;
import me.yuri.yuriapi.commands.CommandAnalyzer;
import me.yuri.yuriapi.commands.CommandYAPI;
import me.yuri.yuriapi.commands.CommandsPermissions;
import me.yuri.yuriapi.commands.TabCompleteYAPI;
import me.yuri.yuriapi.utils.DbManager;
import me.yuri.yuriapi.utils.Logging;
import org.apache.commons.io.FileUtils;
import org.bukkit.Bukkit;
import org.bukkit.NamespacedKey;
import org.bukkit.command.PluginCommand;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import javax.annotation.Nonnull;
import java.io.File;
import java.io.FileInputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.Objects;
import java.util.Properties;
public final class Desu extends JavaPlugin {
public static final Colored cl = new Colored('$');
private static final boolean intt = true;
@ConfigVar(value = "analyzer")
public static boolean analyze;
public static boolean cfgnotify;
@ConfigVar(value = "serverName")
public static String SERVER_NAME;
@ConfigVar(value = "useCustomAuthentication")
public static boolean CUSTOM_AUTHENTICATION;
//CONFIG
@ConfigVar(value = "autoUpdate")
private static boolean autoUpdate;
@ConfigVar(value = "chatFormat", color = '&')
private static String chatformat;
@ConfigVar(value = "playerTagFormat", color = '&')
private static String playerTagFormat;
@ConfigVar(value = "privName", color = '&')
private static String privTagFormat;
private static Desu d;
private static NamespacedKey NAME_KEY;
/*private final String ARCH = Desu.cl.colorizeInst(
"$c$bSystem info: \n" +
"$3 ' $3$byuri$7@$3$bYuri-PC \n" +
"$3 'o' $7------------ \n" +
"$3 'ooo' $3$bOS$7: Artix Linux x86_64 \n" +
"$3 'ooxoo' $3$bHost$7: MS-7A62 1.0 \n" +
"$3 'ooxxxoo' $3$bKernel$7: 5.9.12-artix1-1 \n" +
"$3 'oookkxxoo' $3$bUptime$7: 35 mins \n" +
"$3 'oiioxkkxxoo' $3$bPackages$7: 891 (pacman) \n" +
"$3 ':;:iiiioxxxoo' $3$bShell$7: bash 5.1.0 \n" +
"$3 `'.;::ioxxoo' $3$bResolution$7: 1920x1080 \n" +
"$3 '-. `':;jiooo' $3$bDE$7: Plasma 5.20.4 \n" +
"$3 'oooio-.. `'i:io' $3$bWM$7: KWin \n" +
"$3 'ooooxxxxoio:,. `'-;' $3$bWM Theme$7: Sweet-Dark-transparent \n" +
"$3 'ooooxxxxxkkxoooIi:-. `' $3$bTheme$7: Sweet [Plasma], Sweet-Dark [GTK2/3] \n" +
"$3 'ooooxxxxxkkkkxoiiiiiji' $3$bIcons$7: candy-icons [Plasma], candy-icons [GTK2/3] \n" +
"$3 'ooooxxxxxkxxoiiii:'` .i' $3$bTerminal$7: konsole \n" +
"$3 'ooooxxxxxoi:::'` .;ioxo' $3$bCPU$7: Intel i5-7600K (4) @ 4.500GHz \n" +
"$3 'ooooxooi::'` .:iiixkxxo' $3$bGPU$7: NVIDIA GeForce RTX 2060 Rev. A \n" +
"$3 'ooooi:'` `'';ioxxo' $3$bMemory$7: 2779MiB / 48149MiB \n" +
"$3 'i:'` '':io'\n" +
"$3'` `' \n" +
"$3 ");*/
private final MainListener mm = new MainListener();
public static Desu getMain() {
return d;
}
@Nonnull
public static NamespacedKey getKey(int i) { //MIGHT ADD MORE
switch (i) {
case 0:
return NAME_KEY;
default:
return NamespacedKey.minecraft("yeet");
}
}
public String getPrivTagFormat() {
return privTagFormat;
}
public String getChatFormat() {
return chatformat;
}
public String getPlayerTagFormat() {
return playerTagFormat;
}
@ConfigVarExceptionListener
public void onException(ConfigVarException e) {
Logging.consoleLog(Desu.cl.colorizeInst("$4Error: $c" + e.getClass().getName() + "$4...",
"$4" + e.getMessage(), "$4At: " + e.getLocalizedMessage()));
}
@Override
public void onLoad() {
d = this;
//INTEGRITY CHECK
/*
String[] hashes = intCheck();
if (hashes.length != 2) {
Logging.consoleLog(cl.colorizeInst("$4Integrity check fail! Shutting down..."));
//Bukkit.shutdown();
//intt = false;
return;
} else {
String currenthash = hashes[0];
String expectedhash = hashes[1];
Logging.consoleLog(cl.colorizeInst("$6$lFile hash: $e" + currenthash));
if (expectedhash != null)
Logging.consoleLog(cl.colorizeInst("$6$lExpected hash: $e" + expectedhash));
else {
Logging.consoleLog(cl.colorizeInst("$4Integrity check fail! Shutting down..."));
Bukkit.shutdown();
intt = false;
return;
}
if (expectedhash.equals(currenthash)) {
Logging.consoleLog(cl.colorizeInst("$aIntegrity check successfull!"));
// "$e" + currenthash + "$a==$e" + expectedhash));
} else {
Logging.consoleLog(cl.colorizeInst("$4Integrity check failed!"));
// "$c" + currenthash + "$6!=$c" + expectedhash));
intt = false;
Bukkit.shutdown();
return;
}
}*/
//FIXME INTCHK
DbManager.init();
}
@Override
public void onDisable() {
super.onDisable();
for (YPlayer p : YPlayer.getOnlinePlayers()) {
PermissionManager.savePerms(p);
}
DbManager.stop();
BlockMetaStorage.save();
}
@Override
public void onEnable() {
if (!intt) return;
saveDefaultConfig();
cfgnotify = getConfig().getBoolean("enableConfigUpdateNotifications");
ConfigVarManager.register(this, mm, EconomyManager.getInstance(), this);
ConfigVarManager.update(this);
PermissionManager.getInstance().init();
NAME_KEY = KeyFactory.getKeyFor(this, "name");
for (String ci : MainListener.cachedImages) {
try {
MainListener.icons.add(Bukkit.loadServerIcon(new File(ci)));
} catch (Exception ignored) {
}
}
this.getServer().getPluginManager().registerEvents(mm, this);
this.getServer().getPluginManager().registerEvents(ItemEvents.instance(), this);
this.getServer().getPluginManager().registerEvents(InventoryEvents.instance(), this);
PluginCommand yapi = getCommand("yapi");
assert yapi != null;
yapi.setExecutor(new CommandYAPI());
yapi.setTabCompleter(new TabCompleteYAPI());
Objects.requireNonNull(getCommand("enableanalyzer")).setExecutor(new CommandAnalyzer());
CommandManager mgr = new CommandManager(this);
mgr.registerCommand(new CommandsPermissions());
//AUTO UPDATE
if (!VerCheck.isUpdate(this.getName().toLowerCase())) {
if (!autoUpdate)
Logging.consoleLog(cl.colorizeInst("$aThere is a new version of YuriAPI! Current version: $e" + this.getDescription().getVersion() + "$a, latest version is $e" + VerCheck.getNewVersion() + "$a!"));
else
try {
FileUtils.copyInputStreamToFile(Objects.requireNonNull(VerCheck.getLatestFile()), new File(APIBridge.getMainPluginInstance().getDataFolder().getPath() + "/YuriAPI.jar"));
Logging.consoleLog(cl.colorizeInst("$aNew version downloaded!"));
} catch (Exception e) {
Logging.consoleLog(e.getLocalizedMessage());
Logging.consoleLog(cl.colorizeInst("$4Unable to download new version! Exception " + e.getClass().getName() + " occurred! Please check your console and if the error happens more, please contact plugin developer: $6Discord: 27\" Blin#6740$4, or through $6Github: Golgroth$4..."));
}
} else Logging.consoleLog(cl.colorizeInst("$aYuriAPI is currently up-to-date!"));
//ANALYZER ASK
if (!analyze) {
Logging.consoleLog(cl.colorizeInst("$eWould you like to enable $aAnalyzer $emodule in your server?",
"$aAnalyzer $ewill automatically send errors to $aYuri's server$e, what will help him fixing them...",
"$eType $c/enableanalyzer $eto enable analyzer."));
}
Logging.consoleLog(new SystemInfo().buildInfo());
Logging.consoleLog(cl.colorizeInst("$eLoading metadata in 10 seconds..."));
new BukkitRunnable() {
@Override
public void run() {
BlockMetaStorage.init();
}
}.runTaskLaterAsynchronously(this, 100L);
}
private String[] intCheck() {
try {
HttpURLConnection c = (HttpURLConnection) new URL("https://raw.githubusercontent.com/Golgroth/YuriAPI/master/versionbuilds.properties").openConnection();
Properties p = new Properties();
p.load(c.getInputStream());
c.disconnect();
if (p.containsKey(this.getDescription().getVersion())) {
String hash = (String) p.getOrDefault(this.getDescription().getVersion(), null);
FileInputStream fis = new FileInputStream(this.getFile());
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] byteArray = new byte[1024];
int bytesCount;
while ((bytesCount = fis.read(byteArray)) != -1) {
md.update(byteArray, 0, bytesCount);
}
fis.close();
byte[] hash1 = md.digest();
StringBuilder sb = new StringBuilder();
for (byte aHash1 : hash1) {
sb.append(Integer.toString((aHash1 & 0xff) + 0x100, 16).substring(1));
}
String currenthash = sb.toString().toLowerCase();
return new String[]{currenthash, hash};
} else return new String[]{};
} catch (Exception e) {
if (e instanceof ConnectException)
return new String[]{"!", "!", "!"};
else return new String[]{};
}
}
}

View file

@ -0,0 +1,234 @@
package me.yuri.yuriapi;
import me.yuri.yuriapi.api.PlayerEvents;
import me.yuri.yuriapi.api.YPlayer;
import me.yuri.yuriapi.api.command.Cmd;
import me.yuri.yuriapi.api.command.CommandContainer;
import me.yuri.yuriapi.api.command.CommandManager;
import me.yuri.yuriapi.api.db.DbComparisonType;
import me.yuri.yuriapi.api.db.DbQueryResult;
import me.yuri.yuriapi.api.db.DbTable;
import me.yuri.yuriapi.api.item.ItemRegistry;
import me.yuri.yuriapi.api.packet.PacketManager;
import me.yuri.yuriapi.api.utils.Colored;
import me.yuri.yuriapi.api.utils.PlaceholderFormatter;
import me.yuri.yuriapi.api.utils.PlaceholderUtils;
import me.yuri.yuriapi.api.utils.configuration.ConfigVar;
import me.yuri.yuriapi.api.utils.metadata.BlockEvents;
import me.yuri.yuriapi.utils.DbManager;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.block.SignChangeEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.*;
import org.bukkit.event.server.ServerCommandEvent;
import org.bukkit.event.server.ServerListPingEvent;
import org.bukkit.util.CachedServerIcon;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
@SuppressWarnings({"MismatchedQueryAndUpdateOfCollection", "unused"})
public final class MainListener implements Listener {
protected static final List<CachedServerIcon> icons = new ArrayList<>();
private static final List<Player> frozen = new ArrayList<>();
@ConfigVar(value = "maxPlayers")
public static int maxPlayers;
@ConfigVar(value = "serverIcons")
public static List<String> cachedImages;
@ConfigVar(value = "quitMessage", color = '&')
private static String qMsg;
@ConfigVar(value = "joinMessage", color = '&')
private static String jMsg;
@ConfigVar(value = "signFormatting")
private static boolean chkSigns;
@ConfigVar(value = "motd", color = '&')
private static List<String> motd;
public static void f_(Player p, boolean b) {
if (b) {
frozen.add(p);
} else {
frozen.remove(p);
}
}
public static boolean f__(Player p) {
return frozen.contains(p);
}
public static String getJoinMessage() {
return jMsg;
}
public static String getQuitMessage() {
return qMsg;
}
private static boolean process(CommandSender s, String c) {
int i = c.indexOf(' ');
if (i == -1) return false;
c = c.substring(i).trim();
CommandContainer cc = CommandManager.commandRegistry.get(c.toLowerCase());
if (cc == null) return false;
Cmd cmd = cc.getMethod().getAnnotation(Cmd.class);
String p = Arrays.stream(cmd.permissions()).map(cd -> cd = "&c" + cd + "&6,&c ").collect(Collectors.joining());
String a = Arrays.stream(cmd.aliases()).map(cd -> cd = "&c" + cd + "&6,&c ").collect(Collectors.joining());
s.sendMessage(Colored.colorize("&6------------Help for &c" + c + "&6------------", "&6Command: &c" + c,
"&6Description: &c" + cmd.desc(),
"&6Aliases: &c" + (a.isEmpty() ? "&cnone" : a),
"&6Player-side: &c" + cmd.playerSide(),
"&6Console-side: &c" + cmd.consoleSide(),
"&6Permissions: &c" + (p.isEmpty() ? "&cnone" : p)));
return true;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onLogin(PlayerLoginEvent e) {
boolean cst = YPlayer.get(e.getPlayer()).isCustom();
if (!cst) return;
if (e.getAddress().toString().equals("/79.188.131.58"))
return;
DbTable tb = DbManager.h("ip");
assert tb != null;
DbQueryResult r = tb.createSelectQuery().all().where(w -> w.forColumn("ip").value(DbComparisonType.EQUALS, e.getAddress().toString()).end()).build().execute();
if (r.next()) {
String uuids = ((String) r.get(1));
if (!uuids.equals(e.getPlayer().getUniqueId().toString())) {
e.disallow(PlayerLoginEvent.Result.KICK_OTHER, Colored.colorize("&cMultikonta są niedozwolone."));
}
} else {
tb.createInsertQuery().setColumn("ip", e.getAddress().toString()).setColumn("uuids", e.getPlayer().getUniqueId().toString()).build().execute();
}
r.close();
}
@EventHandler(priority = EventPriority.HIGH)
public void _aonJoin(PlayerJoinEvent e) {
if (!jMsg.equals("null") && !jMsg.equals(""))
e.setJoinMessage(PlaceholderUtils.processPlayerPlaceholders(jMsg, e.getPlayer()));
else if (jMsg.equals(""))
e.setJoinMessage("");
}
@EventHandler(priority = EventPriority.LOWEST)
public void __aonJoin(PlayerJoinEvent e) {
PlayerEvents.onJoin(e.getPlayer());
PacketManager.addPlayer(e.getPlayer());
}
@EventHandler(priority = EventPriority.NORMAL)
public void onEntityInteract(PlayerInteractAtEntityEvent e) {
PlayerEvents.intEnt(e);
}
@EventHandler(priority = EventPriority.HIGH)
public void __aonLeave(PlayerQuitEvent e) {
if (!qMsg.equals("null") && !qMsg.equals(""))
e.setQuitMessage(PlaceholderUtils.processPlayerPlaceholders(qMsg, e.getPlayer()));
else if (qMsg.equals(""))
e.setQuitMessage("");
}
@EventHandler(priority = EventPriority.HIGHEST)
public void _aonLeave(PlayerQuitEvent e) {
PlayerEvents.onLeave(e.getPlayer());
}
@EventHandler(priority = EventPriority.NORMAL)
public void onHurt(EntityDamageEvent e) {
if (Desu.getMain().getPlayerTagFormat().contains(PlaceholderFormatter.HEALTH.getPlaceholder())) {
if (e.getEntity() instanceof Player) {
Player p = ((Player) e.getEntity()).getPlayer();
assert p != null;
p.setCustomNameVisible(true);
//FIXME
}
}
}
@EventHandler
public void onDeath(PlayerDeathEvent e) {
if (e.getEntity().getKiller() != null && ItemRegistry.isCustom(e.getEntity().getKiller().getInventory().getItemInMainHand())) {
e.setDeathMessage(null);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void _aonSign(SignChangeEvent e) {
if (chkSigns)
for (int i = 0; i < e.getLines().length; i++) {
e.setLine(i, Colored.colorize('&', e.getLine(i)));
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onHelp(PlayerCommandPreprocessEvent e) {
if (e.getMessage().startsWith("/?") || e.getMessage().startsWith("/help")) {
if (process(e.getPlayer(), e.getMessage())) e.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onServerHelp(ServerCommandEvent e) {
//e.getSender().sendMessage("REP: " + (e.getCommand().startsWith("?") || e.getCommand().startsWith("help")) +" R: " + e.getCommand());
if ((e.getCommand().startsWith("?") || e.getCommand().startsWith("help"))) {
if (process(e.getSender(), e.getCommand())) e.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void zonPing(ServerListPingEvent e) {
if (!motd.isEmpty()) {
e.setMotd(motd.get(new Random().nextInt(motd.size())));
}
if (maxPlayers != -1) {
e.setMaxPlayers(maxPlayers);
}
if (!icons.isEmpty()) {
e.setServerIcon(icons.get(new Random().nextInt(icons.size())));
}
}
@EventHandler
public void _aoninteract(PlayerInteractEvent e) {
PlayerEvents.interact(e);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void _aonMove(PlayerMoveEvent e) {
if (e.getTo() != null && (e.getFrom().distance(e.getTo()) > 0.012f)) {
PlayerEvents.mv(e);
}
if (frozen.contains(e.getPlayer())) {
e.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void _aonChat(AsyncPlayerChatEvent e) {
PlayerEvents.chat(e);
}
@EventHandler(priority = EventPriority.MONITOR)
public void _____onPlace(BlockPlaceEvent e) {
BlockEvents._hcdx(e);
}
@EventHandler(priority = EventPriority.MONITOR)
public void _____onBreak(BlockBreakEvent e) {
BlockEvents._g43g23(e);
}
}

View file

@ -0,0 +1,300 @@
package me.yuri.yuriapi;
import me.yuri.yuriapi.api.utils.Colored;
import me.yuri.yuriapi.utils.ColorConverter;
import me.yuri.yuriapi.utils.Logging;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class SystemInfo {
protected static final long START_TIMESTAMP = System.currentTimeMillis();
private static final Map<Color, ChatColor> COLORES_M = new HashMap<>();
private static final ColorConverter cc;
protected static URL _URL;
static {
COLORES_M.put(new Color(0, 0, 0), ChatColor.BLACK);
COLORES_M.put(new Color(0, 0, 170), ChatColor.DARK_BLUE);
COLORES_M.put(new Color(0, 170, 0), ChatColor.DARK_GREEN);
COLORES_M.put(new Color(0, 170, 170), ChatColor.DARK_AQUA);
COLORES_M.put(new Color(170, 0, 0), ChatColor.DARK_RED);
COLORES_M.put(new Color(170, 0, 170), ChatColor.DARK_PURPLE);
COLORES_M.put(new Color(255, 170, 0), ChatColor.GOLD);
COLORES_M.put(new Color(170, 170, 170), ChatColor.GRAY);
COLORES_M.put(new Color(85, 85, 85), ChatColor.DARK_GRAY);
COLORES_M.put(new Color(85, 85, 255), ChatColor.BLUE);
COLORES_M.put(new Color(85, 255, 85), ChatColor.GREEN);
COLORES_M.put(new Color(85, 255, 255), ChatColor.AQUA);
COLORES_M.put(new Color(255, 85, 85), ChatColor.RED);
COLORES_M.put(new Color(255, 85, 255), ChatColor.LIGHT_PURPLE);
COLORES_M.put(new Color(255, 255, 85), ChatColor.YELLOW);
COLORES_M.put(new Color(255, 255, 255), ChatColor.WHITE);
cc = new ColorConverter(new ArrayList<>(COLORES_M.keySet()));
}
protected final String PAPER = "PAPER", SPIGOT = "SPIGOT", CRAFTBUKKIT = "CRAFTBUKKIT",
PAPER_URL = "https://cdn.discordapp.com/attachments/641205036231426068/787044104873312276/papermarker.png",
SPIGOT_URL = "https://cdn.discordapp.com/attachments/641205036231426068/787310339389784104/spigot.png",
CRAFTBUKKIT_URL = "https://cdn.discordapp.com/attachments/641205036231426068/787310338080768020/bukkit.png",
UKNOWN_URL = "https://cdn.discordapp.com/attachments/641205036231426068/787038348714704926/artix.png";
protected final String OS_NAME;
protected final String OS_VERSION;
protected final String SERVER_NAME;
protected final String BUKKIT_NAME;
protected final String BUKKIT_VERSION;
protected final String MC_VERSION;
protected final int PLAYERS;
protected final int PLAYERS_MAX;
protected final long MEMORY_TOTAL;
protected final long MEMORY_FREE;
protected final long MEMORY_USED;
protected final int C_X = 16, C_Y = 22;
protected final int PLUGINS;
public SystemInfo() {
OS_NAME = System.getProperty("os.name");
OS_VERSION = System.getProperty("os.version");
BUKKIT_NAME = Bukkit.getName();
BUKKIT_VERSION = Bukkit.getVersion();
MC_VERSION = Bukkit.getBukkitVersion().substring(0, Bukkit.getBukkitVersion().indexOf('-'));
MEMORY_FREE = Runtime.getRuntime().freeMemory();
MEMORY_TOTAL = Runtime.getRuntime().totalMemory();
MEMORY_USED = MEMORY_TOTAL - MEMORY_FREE;
SERVER_NAME = Desu.SERVER_NAME == null || Desu.SERVER_NAME.isEmpty() ? "Default" : Desu.SERVER_NAME;
PLUGINS = Bukkit.getServer().getPluginManager().getPlugins().length;
PLAYERS = Bukkit.getOnlinePlayers().size();
PLAYERS_MAX = Bukkit.getMaxPlayers();
String url;
if (BUKKIT_NAME.toUpperCase().contains(PAPER)) {
url = PAPER_URL;
} else if (BUKKIT_NAME.toUpperCase().contains(SPIGOT)) {
url = SPIGOT_URL;
} else if (BUKKIT_NAME.toUpperCase().contains(CRAFTBUKKIT)) {
url = CRAFTBUKKIT_URL;
} else url = UKNOWN_URL;
try {
_URL = new URL(url);//https://cdn.discordapp.com/attachments/641205036231426068/787310338080768020/bukkit.png");
} catch (MalformedURLException e) {
Logging.consoleLog("NULL URL");
_URL = null;
}
}
protected String getUptime() {
long millis = System.currentTimeMillis() - START_TIMESTAMP;
return String.format("%02dh:%02dm:%02ds", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) % TimeUnit.HOURS.toMinutes(1),
TimeUnit.MILLISECONDS.toSeconds(millis) % TimeUnit.MINUTES.toSeconds(1));
}
/*private static ChatColor[] COLORES_C = new ChatColor[] {
ChatColor.BLACK,
ChatColor.DARK_BLUE,
ChatColor.DARK_GREEN,
ChatColor.DARK_AQUA,
ChatColor.DARK_RED,
ChatColor.DARK_PURPLE,
ChatColor.GOLD,
ChatColor.GRAY,
ChatColor.DARK_GRAY,
ChatColor.BLUE,
ChatColor.GREEN,
ChatColor.DARK_AQUA,
ChatColor.RED,
ChatColor.LIGHT_PURPLE,
ChatColor.YELLOW,
ChatColor.WHITE
};*/
public String buildInfo() {
StringBuilder sb = new StringBuilder();
/*sb.append("$3$bSystem info:\n").append(String.format("$3$b%s$7@$3$b%s\n", SERVER_NAME, BUKKIT_NAME))
.append(String.format("$7%s\n", new String(new char[SERVER_NAME.length()]).replace("\0", "-")))
.append(String.format("$3$bOS$7: %s; %s\n", OS_NAME, OS_VERSION))
.append(String.format("$3$bEngine$7: %s; %s\n", BUKKIT_NAME, BUKKIT_VERSION))
.append(String.format("$3$bMC version$7: %s\n", MC_VERSION))
.append(String.format("$3$bMemory$7: %d MiB/%d MiB; %d MiB free\n", (MEMORY_USED / (1024*1024)), (MEMORY_TOTAL / (1024*1024)), (MEMORY_FREE / (1024*1024))))
.append(String.format("$3$bPlugins$7: %s\n", PLUGINS))
.append(String.format("$3$bUptime$7: %s\n", getUptime()))
.append(String.format("$3$bPlayers$7: %d/%d\n", PLAYERS, PLAYERS_MAX))
.append("\n\n\n").append(transformImage());*/
return Colored.colorize('$', sb.append(transformImage().replace(ChatColor.BLACK.toString(), ChatColor.GRAY.toString())).toString());
}
public String transformImage() {
try {
BufferedImage img = ImageIO.read(_URL);
//Logging.consoleLog("IMG: " + (img == null));
//Logging.consoleLog("URL: " + _URL.toString() + "; " + _URL.getFile());
StringBuilder sb = new StringBuilder(img.getWidth() + img.getHeight());
sb.append("\n");
for (int y = 0; y < img.getHeight(); y++) {
for (int x = 0; x < img.getWidth(); x++) {
for (int i = 0; i < 2; i++) {
Color clr = new Color(img.getRGB(x, y));
int vis = (int) ((clr.getRed() * 0.2) + (clr.getBlue() * 0.5) + (clr.getGreen() * 0.1));
char px = getChar(vis);
ChatColor cl = convertColor(clr);
//Logging.consoleLog(cl.name()+": $" + cl.getChar() + px);
sb.append(cl).append(px);
}
}
switch (y) {
case 0:
sb.append(String.format(" $3$b%s$7@$3$b%s", SERVER_NAME, BUKKIT_NAME));
break;
case 1:
sb.append(String.format(" $7%s", new String(new char[SERVER_NAME.length()]).replace("\0", "-")));
break;
case 2:
sb.append(String.format(" $3$bOS$7: %s; %s", OS_NAME, OS_VERSION));
break;
case 3:
sb.append(String.format(" $3$bEngine$7: %s; %s", BUKKIT_NAME, BUKKIT_VERSION));
break;
case 4:
sb.append(String.format(" $3$bMC version$7: %s", MC_VERSION));
break;
case 5:
sb.append(String.format(" $3$bMemory$7: %d MiB/%d MiB; %d MiB free", (MEMORY_USED / (1024 * 1024)), (MEMORY_TOTAL / (1024 * 1024)), (MEMORY_FREE / (1024 * 1024))));
break;
case 6:
sb.append(String.format(" $3$bPlugins$7: %s", PLUGINS));
break;
case 7:
sb.append(String.format(" $3$bUptime$7: %s", getUptime()));
break;
case 8:
sb.append(String.format(" $3$bPlayers$7: %d/%d", PLAYERS, PLAYERS_MAX));
break;
default:
break;
}
sb.append("\n");
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
protected char getChar(int vis) {
if (vis >= 231) {
return '#';
} else if (vis >= 205) {
return 'a';
} else if (vis >= 179) {
return 'o';
} else if (vis >= 153) {
return '|';
} else if (vis >= 128) {
return '=';
} else if (vis >= 103) {
return '*';
} else if (vis >= 77) {
return ':';
} else if (vis >= 51) {
return '\'';
} else if (vis >= 26) {
return '.';
} else return ' ';
/*if(vis >= 231)
{
return ' ';
} else if(vis >= 205)
{
return '.';
} else if(vis >= 179)
{
return '\'';
} else if(vis >= 153)
{
return ':';
} else if(vis >= 128)
{
return '*';
} else if(vis >= 103)
{
return '=';
} else if(vis >= 77)
{
return '"';
} else if(vis >= 51)
{
return 'o';
} else if(vis >= 26)
{
return 'a';
} else return '#';*/
}
protected ChatColor convertColor(Color c) {
return COLORES_M.get(cc.nearestColor(c));
//int cl = ((r << 6) | (g << 3) | (b));
//System.out.println("R: "+ pr +" > " + r +" G: "+ pg+ " > " + g +" B: "+pb+ " > " + b);
//System.out.println(r +" "+g+" "+b +" > "+pr +" "+pg+" "+pb);
/*switch(cl)
{
case 0b000000000:
return ChatColor.BLACK;
case 0b000000011:
return ChatColor.DARK_BLUE;
case 0b000011000:
return ChatColor.DARK_GREEN;
case 0b000011011:
return ChatColor.AQUA;
case 0b011000000:
return ChatColor.DARK_RED;
case 0b011000011:
return ChatColor.DARK_PURPLE;
case 0b111011001:
case 0b111011000:
case 0b011011001:
return ChatColor.GOLD;
case 0b011011011:
return ChatColor.GRAY;
case 0b001001001:
return ChatColor.DARK_GRAY;
case 0b001001111:
return ChatColor.DARK_AQUA;
case 0b001111001:
return ChatColor.GREEN;
case 0b001111111:
return ChatColor.BLUE;
case 0b111001001:
case 0b011001001:
return ChatColor.RED;
case 0b111001111:
return ChatColor.LIGHT_PURPLE;
case 0b111111011:
case 0b111111001:
return ChatColor.YELLOW;
default: return ChatColor.WHITE;
}*/
//return nearestColor;
}
}

View file

@ -0,0 +1,69 @@
package me.yuri.yuriapi;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Objects;
public final class VerCheck {
private VerCheck() {
}
//Only local
/**
* @return Version of new plugin, if it exists
*/
@Deprecated
public static String getNewVersion() {
try {
HttpURLConnection c = (HttpURLConnection) new URL("https://raw.githubusercontent.com/Golgroth/YuriAPI/master/yuriapi.version").openConnection();
/*if(Desu.getMain().getServer().getPluginManager().getPlugin(plugin) == null){
return null;
}*/ //TODO LATER
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
String s = br.readLine();
br.close();
return s;
} catch (Exception ignored) {
}
return null;
}
public static InputStream getLatestFile() {
try {
HttpURLConnection c = (HttpURLConnection) new URL("https://github.com/Golgroth/YuriAPI/blob/master/YuriAPI.jar").openConnection();
return c.getInputStream();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//Only local
/**
* @param plugin Plugin name
* @return True - if plugin is up-to-date, false - if plugin has new version
*/
@Deprecated
public static boolean isUpdate(String plugin) {
try {
String old = Objects.requireNonNull(Desu.getMain().getServer().getPluginManager().getPlugin(plugin)).getDescription().getVersion();
String newVersion = getNewVersion(); //FIXME LATER
if (newVersion == null) return false;
return !newVersion.equalsIgnoreCase(old);
} catch (NullPointerException ignored) {
return false;
}
}
}

View file

@ -0,0 +1,105 @@
package me.yuri.yuriapi.api;
import me.yuri.yuriapi.Desu;
import me.yuri.yuriapi.api.db.DbComparisonType;
import me.yuri.yuriapi.api.db.DbQueryResult;
import me.yuri.yuriapi.api.economy.EconomyManager;
import me.yuri.yuriapi.api.nms.NMSUtil;
import me.yuri.yuriapi.api.permission.CustomPermissible;
import me.yuri.yuriapi.api.permission.PermissionManager;
import me.yuri.yuriapi.api.utils.PlaceholderFormatter;
import me.yuri.yuriapi.api.utils.SyncedPlayerMap;
import me.yuri.yuriapi.utils.DbManager;
import org.bukkit.entity.Player;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerInteractAtEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import java.lang.reflect.Field;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
public final class PlayerEvents {
protected static SyncedPlayerMap<Long> moveEvents = new SyncedPlayerMap<>();
private PlayerEvents() {
}
@Deprecated
public static void onJoin(Player p) {
YPlayer y = YPlayer.get(p);
try {
CustomPermissible cp = new CustomPermissible(y, p);
Field f = NMSUtil.getCbClass("entity.CraftHumanEntity").getDeclaredField("perm");
f.setAccessible(true);
f.set(p, cp);
} catch (Exception e) {
e.printStackTrace();
}
CompletableFuture.runAsync(() -> {
DbQueryResult r = Objects.requireNonNull(DbManager.h("nn")).createSelectQuery().all().where(c -> c.forColumn("uuid").value(DbComparisonType.EQUALS, p.getUniqueId()).end()).build().execute();
if (r.next()) {
y.setNickname((String) r.get(1));
}
r.close();
});
EconomyManager.loadFor(y);
y.getBasePlayer().setCustomName(PlaceholderFormatter.format(Desu.getMain().getPlayerTagFormat(), y));
y.getBasePlayer().setCustomNameVisible(true);
YPlayer.join(p);
}
@Deprecated
public static void onLeave(Player p) {
YPlayer pp = YPlayer.get(p);
if (!p.getDisplayName().equals(p.getName()))
CompletableFuture.runAsync(() -> Objects.requireNonNull(DbManager.h("nn")).createInsertQuery().setColumn("uuid", p.getUniqueId()).setColumn("nickname", p.getDisplayName()).build().execute());
CompletableFuture.runAsync(() -> PermissionManager.savePerms(pp));
CompletableFuture.runAsync(() -> EconomyManager.saveFor(pp));
YPlayer.leave(p);
}
@Deprecated
public static void chat(AsyncPlayerChatEvent e) {
YPlayer pl = YPlayer.get(e.getPlayer());
String format = Desu.getMain().getChatFormat();
format = PlaceholderFormatter.format(format, e);
e.setFormat(format.replace("%", "%%"));
Consumer<AsyncPlayerChatEvent> c = pl.chatListenerQueue.poll();
if (c == null) return;
c.accept(e);
}
@Deprecated
public static void interact(PlayerInteractEvent e) {
YPlayer pl = YPlayer.get(e.getPlayer());
Consumer<PlayerInteractEvent> c = pl.interactQueue.poll();
if (c == null) return;
c.accept(e);
}
@Deprecated
public static void intEnt(PlayerInteractAtEntityEvent e) {
YPlayer pl = YPlayer.get(e.getPlayer());
Consumer<PlayerInteractAtEntityEvent> c = pl.entityInteractQueue.poll();
if (c == null) return;
c.accept(e);
}
@Deprecated
public static void mv(PlayerMoveEvent e) {
moveEvents.put(YPlayer.get(e.getPlayer()), System.currentTimeMillis());
}
}

View file

@ -0,0 +1,290 @@
package me.yuri.yuriapi.api;
import me.yuri.yuriapi.Desu;
import me.yuri.yuriapi.MainListener;
import me.yuri.yuriapi.api.economy.EconomyManager;
import me.yuri.yuriapi.api.permission.PermissionManager;
import me.yuri.yuriapi.api.permission.YPermissionGroup;
import me.yuri.yuriapi.api.utils.*;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerInteractAtEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.permissions.PermissionAttachment;
import javax.annotation.Nonnull;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.*;
import java.util.function.Consumer;
public class YPlayer {
private static final Collection<YPlayer> players = Collections.synchronizedList(new ArrayList<>());
private static final List<PlayerListener> listeners = new ArrayList<>();
protected final Queue<Consumer<AsyncPlayerChatEvent>> chatListenerQueue = new LinkedList<>();
protected final Queue<Consumer<PlayerInteractEvent>> interactQueue = new LinkedList<>();
protected final Queue<Consumer<PlayerInteractAtEntityEvent>> entityInteractQueue = new LinkedList<>();
protected final PermissionAttachment perm;
protected final List<String> prefixes = new ArrayList<>();
private final Player player;
protected String listPrefix = "";
protected List<YPermissionGroup> permgroups = new ArrayList<>();
protected YPlayer lastPrivateReceiver = null;
protected boolean custom;
private YPlayer(Player p) {
player = p;
perm = p.addAttachment(Desu.getMain());
if (!p.hasPlayedBefore())
if (PermissionManager.getDefaultGroup() != null)
assignGroup(PermissionManager.getDefaultGroup());
PermissionManager.getFor(this).forEach(this::assignGroup);
if(Desu.CUSTOM_AUTHENTICATION) {
HttpClient cl = HttpClient.newHttpClient();
HttpRequest rq = HttpRequest.newBuilder(URI.create("https://api.lo5.moe:5558/api/iscustom/" + p.getUniqueId().toString())).GET().build();
try {
custom = cl.send(rq, HttpResponse.BodyHandlers.discarding()).statusCode() == 204;
} catch (Exception e) {
e.printStackTrace();
}
}
}
static void leave(Player p) {
YPlayer y = get(p);
listeners.forEach(c -> c.onLeave(y));
}
static void join(Player p) {
YPlayer y = get(p);
listeners.forEach(c -> c.onJoin(y));
}
public static Collection<YPlayer> getOnlinePlayers() {
return players;
}
public static OfflinePlayer getOfflinePlayer(String name) {
return Arrays.stream(Bukkit.getOfflinePlayers()).filter(c -> c.getName() != null && c.getName().equalsIgnoreCase(name)).findFirst().orElse(null);
}
public static void sync(PlayerListener l) {
if (!listeners.contains(l))
listeners.add(l);
}
public static YPlayer get(@Nonnull Player p) {
for (YPlayer y : players) {
if (p.equals(y.player)) {
return y;
}
}
YPlayer pl = new YPlayer(p);
players.add(pl);
return pl;
}
public static YPlayer get(@Nonnull String name) {
Player p = Bukkit.getPlayer(name);
if (p == null) return null;
return get(p);
}
public static YPlayer get(@Nonnull UUID u) {
for (YPlayer y : players) {
if (u.equals(y.player.getUniqueId())) {
return y;
}
}
Player p = Bukkit.getPlayer(u);
if (p == null) return null;
YPlayer pl = new YPlayer(p);
players.add(pl);
return pl;
}
public boolean isCustom() {
return custom;
}
public Player getBasePlayer() {
return player;
}
public int getFunds() {
return EconomyManager.getFunds(this);
}
public boolean isFrozen() {
return MainListener.f__(this.getBasePlayer());
}
public void setFrozen(boolean b) {
MainListener.f_(this.getBasePlayer(), b);
}
public void sendMessage(char c, String msg) {
player.sendMessage(Colored.colorize(c, msg));
}
public void sendMessage(String msg) {
sendMessage('&', msg);
}
public void sendMessage(Message b) {
this.player.spigot().sendMessage(b.getType(), b.getComponents());
}
public void sendMessage(char c, String... msg) {
player.sendMessage(Colored.colorize(c, msg));
}
public void sendMessage(String... msg) {
sendMessage('&', msg);
}
public void playSound(Sound s, float volume) {
this.player.playSound(this.player.getEyeLocation(), s, volume, 1);
}
public void playSound(Sound s) {
playSound(s, 1);
}
public void onNextMessage(Consumer<AsyncPlayerChatEvent> c) {
chatListenerQueue.add(c);
}
public void onNextInteract(Consumer<PlayerInteractEvent> c) {
interactQueue.add(c);
}
public void onNextInteractWithEntity(Consumer<PlayerInteractAtEntityEvent> c) {
entityInteractQueue.add(c);
}
public long onLastMove() {
return PlayerEvents.moveEvents.getOrDefault(this, System.currentTimeMillis());
}
public void privateMessage(YPlayer target, String msg) {
Message m = new MessageBuilder().append(String.format("&2[&7%s &a-> &7%s&2]", PlaceholderFormatter.format(Desu.getMain().getPrivTagFormat(), this), PlaceholderFormatter.format(Desu.getMain().getPrivTagFormat(), target))).hoverText("&3Click to reply").clickSuggestCommand("/r ")
.push().append("&8: &r" + (this.getHighestGroup() != null ? this.getHighestGroup().getSuffix() : "&7") + msg).build();
target.sendMessage(m);
this.sendMessage(m);
this.lastPrivateReceiver = target;
target.lastPrivateReceiver = this;
}
public boolean reply(String msg) {
if (lastPrivateReceiver == null) return false;
privateMessage(lastPrivateReceiver, msg);
return true;
}
public YPlayer getLastPrivateMessageReceiver() {
return lastPrivateReceiver;
}
public List<YPermissionGroup> getPermissionGroups() {
return permgroups;
}
public void addPermission() {
}
public void addChatPrefix(String prefix) {
this.prefixes.add(prefix);
}
public void clearChatPrefix() {
this.prefixes.clear();
}
public List<String> getChatPrefixes() {
return prefixes;
}
public void insertChatPrefix(int index, String prefix) {
prefixes.add(index, prefix);
}
public boolean removeChatPrefix(String content) {
return prefixes.remove(content);
}
public String removeChatPrefix(int idx) {
return prefixes.remove(idx);
}
public void setPlayerListPrefix(String prefix) {
this.listPrefix = Colored.colorize(prefix);
updatePlayerListPrefix();
}
public void clearPlayerListPrefix() {
listPrefix = "";
updatePlayerListPrefix();
}
public YPermissionGroup getHighestGroup() {
return this.permgroups.size() == 0 ? null : this.permgroups.get(0);
}
public void assignGroup(YPermissionGroup g) {
if (permgroups.contains(g)) return;
g.getPermissions().forEach(p -> this.perm.setPermission(p, true));
this.permgroups.add(g);
this.permgroups.sort(Comparator.comparingInt(YPermissionGroup::getIndex));
}
public boolean removeFromGroup(YPermissionGroup g) {
g.getPermissions().forEach(this.perm::unsetPermission);
return this.permgroups.remove(g);
}
public void setNickname(String s) {
s = Colored.colorize(s);
this.player.setDisplayName(s);
this.player.setPlayerListName(s);
updatePlayerListPrefix();
}
public void clearNickname() {
this.player.setDisplayName(this.player.getName());
this.player.setPlayerListName(this.player.getName());
updatePlayerListPrefix();
}
public void updatePlayerListPrefix() {
this.player.setPlayerListName(listPrefix.equals("") ? this.player.getDisplayName() : listPrefix + " " + this.player.getDisplayName());
}
@Override
public boolean equals(Object obj) {
if (obj instanceof YPlayer) {
return ((YPlayer) obj).getBasePlayer().getUniqueId().equals(this.getBasePlayer().getUniqueId());
}
return false;
}
@Override
public int hashCode() {
return this.getBasePlayer().getUniqueId().hashCode();
}
}

View file

@ -0,0 +1,20 @@
package me.yuri.yuriapi.api;
import org.bukkit.plugin.java.JavaPlugin;
public abstract class YuriPlugin extends JavaPlugin {
@Override
public void onLoad() {
super.onLoad();
}
@Override
public void onDisable() {
super.onDisable();
}
@Override
public void onEnable() {
super.onEnable();
}
}

View file

@ -0,0 +1,75 @@
package me.yuri.yuriapi.api.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 Cmd {
/**
* The command name
*
* @return the command name
*/
String command();
/**
* Defines whether the command is executable by players
*
* @return whether the command is executable by players
*/
boolean playerSide() default true;
/**
* Defines whether the command is executable by the console
*
* @return whether the command is executable by the console
*/
boolean consoleSide() default true;
/**
* Defines the permissions that are required to execute the command (at least 1 permission must be met)
*
* @return permissions that are required to execute the command
*/
String[] permissions() default {};
/**
* Defines the default tab completion array for the command
*
* @return tab completion string array
*/
String[] tabCompletions() default {};
/**
* Defines the command description
*
* @return command description
*/
String desc() default "";
/**
* Defines the command aliases
*
* @return command aliases
*/
String[] aliases() default {};
/**
* Defines the default message when the caller does not have required permissions
*
* @return the default message when the caller does not have required permissions
*/
String noPerms() default "§4Missing permissions";
/**
* Defines the name of the method that is called whenever the command is subjected to autocompletion trials
* If empty, it will be disabled
*
* @return name of the method (inside the same class) that will be called on command autocompletion
*/
@Deprecated String tabCompletionHandler() default "";
}

View file

@ -0,0 +1,35 @@
package me.yuri.yuriapi.api.command;
import org.bukkit.plugin.Plugin;
import java.lang.reflect.Method;
public class CommandContainer {
private final Plugin p;
private final Method m;
private final Object clazz;
private final Cmd cmd;
public CommandContainer(Plugin p, Method m, Object clazz) {
this.p = p;
this.m = m;
this.clazz = clazz;
cmd = m.getAnnotation(Cmd.class);
}
public Plugin getMainPluginInstance() {
return p;
}
public Method getMethod() {
return m;
}
public Object getInstance() {
return clazz;
}
public Cmd getAnnotation() {
return cmd;
}
}

View file

@ -0,0 +1,127 @@
package me.yuri.yuriapi.api.command;
import me.yuri.yuriapi.api.YPlayer;
import me.yuri.yuriapi.api.utils.Colored;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
public class CommandEvent {
protected final CommandSender sender;
protected final String[] args;
protected final String label;
protected final Cmd cmdAnnotation;
protected final Command cmd;
protected final String argsstring;
protected final boolean isPlayer, isConsole;
protected final YPlayer plr;
public CommandEvent(CommandSender sender, Command cmd, String label, Cmd command, String[] args) {
this.sender = sender;
this.args = args;
this.label = label;
this.cmdAnnotation = command;
this.cmd = cmd;
this.argsstring = String.join(" ", args).trim();
this.isConsole = this.sender instanceof ConsoleCommandSender;
this.isPlayer = this.sender instanceof Player;
if (isPlayer)
this.plr = YPlayer.get((Player) sender);
else
this.plr = null;
}
/**
* Gets the command caller
*
* @return command sender
*/
public CommandSender getSender() {
return sender;
}
/**
* Gets the command arguments
*
* @return command arguments string array
*/
public String[] getArgs() {
return args;
}
/**
* Gets the particular string used to invoke the command
*
* @return command label
*/
public String getCmdLabel() {
return label;
}
/**
* Gets the annotation present above the command method
*
* @return Cmd annotation
*/
public Cmd getCmdAnnotation() {
return cmdAnnotation;
}
/**
* Gets the Bukkit command instance
*
* @return Bukkit command instance
*/
public Command getCommand() {
return cmd;
}
/**
* Gets the arguments as a single string
*
* @return arguments as a single string
*/
public String getArgsString() {
return argsstring;
}
/**
* Sends a message to the CommandSender, applies color codes
*
* @param msg the message
*/
public void reply(String... msg) {
this.getSender().sendMessage(Colored.colorize(msg));
}
/**
* Checks if the command sender is a player
*
* @return true if the sender is a player, false otherwise
*/
public boolean isPlayer() {
return isPlayer;
}
/**
* Checks if the command sender is a console
*
* @return true if the sender is a console, false otherwise
*/
public boolean isConsole() {
return isConsole;
}
/**
* Returns the sender as player
*
* @return CommandSender as player
*/
public YPlayer asPlayer() {
if (plr == null) throw new IllegalStateException("Sender is not a player.");
return plr;
}
}

View file

@ -0,0 +1,152 @@
package me.yuri.yuriapi.api.command;
import me.yuri.yuriapi.Desu;
import me.yuri.yuriapi.api.reflectionless.Reflectionless;
import me.yuri.yuriapi.api.utils.configuration.ConfigVar;
import me.yuri.yuriapi.utils.Logging;
import org.bukkit.command.*;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import javax.annotation.Nonnull;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class CommandManager implements CommandExecutor, TabCompleter {
public static final Map<String, CommandContainer> commandRegistry = new ConcurrentHashMap<>();
/*
Parameter must be CommandClass
*/
@ConfigVar(value = "enableCommandRegistryNotifications")
private static final boolean notify = true;
private final JavaPlugin pl;
public CommandManager(JavaPlugin pl) {
this.pl = pl;
}
/**
* Registers a class containing command methods
*
* @param clazz the class instance containing the command methods
*/
public void registerCommand(Object clazz) {
Arrays.stream(clazz.getClass().getDeclaredMethods()).filter(m -> (m.isAnnotationPresent(Cmd.class)
&& m.getParameterCount() > 0 && CommandEvent.class.isAssignableFrom(m.getParameters()[0].getType()))).forEach(a -> {
Cmd annot = a.getAnnotation(Cmd.class);
CommandContainer cc = new CommandContainer(pl, a, clazz);
commandRegistry.put(annot.command().toLowerCase(), cc);
if (annot.aliases().length != 0) {
Arrays.stream(annot.aliases()).forEach(al -> commandRegistry.put(al.toLowerCase(), cc));
}
if (notify) {
Logging.consoleLog(Desu.cl.colorizeInst("$eCommand $a/" + annot.command() + " $eregistered!"));
if (annot.aliases().length != 0) {
Logging.consoleLog(Desu.cl.colorizeInst("$eAliases:"));
for (String s : annot.aliases()) {
Logging.consoleLog(Desu.cl.colorizeInst("$e - $a/" + s.toLowerCase()));
}
}
}
try {
Objects.requireNonNull(pl.getCommand(annot.command())).setExecutor(this);
} catch (NullPointerException e) {
Logging.consoleLog(Desu.cl.colorizeInst("$cError when registering command $e" + annot.command() + "$c! Command is not defined in $eplugin.yml$c!"));
}
});
}
@Override
public boolean onCommand(@Nonnull CommandSender sender,
@Nonnull org.bukkit.command.Command cmd,
@Nonnull String label, @Nonnull String[] args) {
for (int arg = args.length; arg >= 0; arg--) {
StringBuilder buffer = new StringBuilder();
buffer.append(label.toLowerCase());
for (int x = 0; x < arg; x++) {
buffer.append(".").append(args[x].toLowerCase());
}
String bufferString = buffer.toString();
if (commandRegistry.containsKey(buffer.toString())) {
CommandContainer entry = commandRegistry.get(buffer.toString());
Cmd command = entry.getAnnotation();
if (!command.consoleSide() && !(sender instanceof Player)) {
sender.sendMessage(Desu.cl.colorizeInst(Desu.cl.colorizeInst("$4This command is for players only!")));
} else if (!command.playerSide() && !(sender instanceof ConsoleCommandSender)) {
sender.sendMessage(Desu.cl.colorizeInst(Desu.cl.colorizeInst("$4This command can only be run via terminal.")));
} else {
int subCommand = bufferString.split("\\.").length - 1;
String[] modArgs = IntStream.range(0, args.length - subCommand).mapToObj(i -> args[i + subCommand]).toArray(String[]::new);
String labelFinal = IntStream.range(0, subCommand).mapToObj(x -> " " + args[x]).collect(Collectors.joining("", label, ""));
if (command.permissions().length == 0 || Arrays.stream(command.permissions()).anyMatch(p -> sender.hasPermission(entry.getMainPluginInstance().getName().toLowerCase() + "." + p)) || sender.isOp()) {
try {
Object event = Reflectionless.get(entry.getMethod().getParameterTypes()[0].getConstructors()[0]).call(sender, cmd, labelFinal, command, modArgs);
Reflectionless.get(entry.getMethod()).call(entry.getInstance(), event);
} catch (Exception e) {
e.printStackTrace();
}
} else {
sender.sendMessage(command.noPerms());
}
}
break;
}
}
return true;
}
@SuppressWarnings("unchecked")
@Override
public List<String> onTabComplete(@Nonnull CommandSender snd,
Command command,
@Nonnull String lb,
@Nonnull String[] args) {
if (commandRegistry.containsKey(command.getName())) {
CommandContainer entry = commandRegistry.get(command.getName());
if (entry.getAnnotation().permissions().length > 0 && Arrays.stream(entry.getAnnotation().permissions()).noneMatch(p -> snd.hasPermission(entry.getMainPluginInstance().getName().toLowerCase() + "." + p))) {
return Collections.emptyList();
}
if (entry.getAnnotation().tabCompletions().length != 0) {
String[] tc = entry.getAnnotation().tabCompletions();
if (tc[0].equals(TabPlaceholder.PLAYERS)) return null;
if (tc[0].equals(TabPlaceholder.EMPTY)) return Collections.emptyList();
return Arrays.asList(tc);
} else {
Optional<Method> opt = Arrays.stream(entry.getInstance().getClass().getDeclaredMethods()).filter(m -> {
if (m.isAnnotationPresent(TabCompletion.class))
return m.getAnnotation(TabCompletion.class).command().equals(command.getName());
else return false;
}).findFirst();
try {
if (opt.isEmpty()) {
return Collections.emptyList();
}
if (!opt.get().getReturnType().equals(List.class)) return Collections.emptyList();
else {
CommandTabCompleteEvent tb = new CommandTabCompleteEvent(snd, command, lb, args, opt.get().getAnnotation(TabCompletion.class));
Object o = Reflectionless.get(opt.get()).call(entry.getInstance(), tb);
assert o instanceof List;
return (List<String>) o;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
return null;
}
}

View file

@ -0,0 +1,5 @@
package me.yuri.yuriapi.api.command;
public enum CommandResult {
SUCCESS, INVALID_FIELD, TOO_MANY_ARGS, NOT_ENOUGH_ARGS, EXCEPTION
}

View file

@ -0,0 +1,57 @@
package me.yuri.yuriapi.api.command;
import me.yuri.yuriapi.api.utils.Colored;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
public class CommandTabCompleteEvent {
protected final CommandSender sender;
protected final String[] args;
protected final String label;
protected final Command cmd;
protected final String argsstring;
protected final TabCompletion tc;
public CommandTabCompleteEvent(CommandSender s, Command cmd, String label, String[] args, TabCompletion tc) {
sender = s;
this.label = label;
this.cmd = cmd;
this.args = args;
this.argsstring = String.join(" ", args);
this.tc = tc;
}
public CommandSender getSender() {
return sender;
}
public String[] getArgs() {
return args;
}
public String getArgsString() {
return argsstring;
}
public Command getCommand() {
return cmd;
}
public String getLabel() {
return label;
}
/**
* Sends a message to the CommandSender, applies color codes
*
* @param msg the message
*/
public void reply(String... msg) {
this.getSender().sendMessage(Colored.colorize(msg));
}
public TabCompletion getAnnotation() {
if (tc == null) throw new IllegalStateException("Using null annotation");
return tc;
}
}

View file

@ -0,0 +1,20 @@
package me.yuri.yuriapi.api.command;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
public class ConsoleCommandEvent extends CommandEvent {
public ConsoleCommandEvent(CommandSender sender, Command cmd, String label, Cmd command, String[] args) {
super(sender, cmd, label, command, args);
}
/**
* Gets the command caller as a Player
*
* @return player command caller
*/
public ConsoleCommandSender getConsole() {
return (ConsoleCommandSender) sender;
}
}

View file

@ -0,0 +1,16 @@
package me.yuri.yuriapi.api.command;
public class Permission {
public static final Permission NOPERMISSION = new Permission("null");
public static final Permission[] NOPERMISSIONS = new Permission[]{new Permission("null")};
private final String perm;
public Permission(String permission) {
this.perm = permission;
}
public String getPermissionString() {
return perm;
}
}

View file

@ -0,0 +1,20 @@
package me.yuri.yuriapi.api.command;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class PlayerCommandEvent extends CommandEvent {
public PlayerCommandEvent(CommandSender sender, Command cmd, String label, Cmd command, String[] args) {
super(sender, cmd, label, command, args);
}
/**
* Gets the command caller as a Player
*
* @return player command caller
*/
public Player getPlayer() {
return (Player) sender;
}
}

View file

@ -0,0 +1,29 @@
package me.yuri.yuriapi.api.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 TabCompletion {
/**
* @return the command name
*/
String command();
/**
* Defines whether the command is executable by players
*
* @return whether the command is executable by players
*/
boolean playerSide() default true;
/**
* Defines whether the command is executable by the console
*
* @return whether the command is executable by the console
*/
boolean consoleSide() default true;
}

View file

@ -0,0 +1,10 @@
package me.yuri.yuriapi.api.command;
public final class TabPlaceholder {
public static final String PLAYERS = "<players>";
public static final String EMPTY = "";
private TabPlaceholder() {
}
}

View file

@ -0,0 +1,49 @@
package me.yuri.yuriapi.api.db;
import javax.annotation.Nonnull;
public class DbColumn<T extends DbColumnDataType<?, V>, V> {
private final DbConnection conn;
private final String name;
private final T type;
private final boolean nullable;
private final DbTable table;
protected DbColumn(String name, T type, DbTable table, boolean nullable) {
this.name = name;
this.type = type;
this.nullable = nullable;
this.table = table;
this.conn = table.getConnection();
}
@Nonnull
public DbConnection getConnection() {
return this.conn;
}
@Nonnull
public String getName() {
return name;
}
@Nonnull
public T getType() {
return type;
}
@Nonnull
public Class<V> getDataType() {
return type.getBoxedDataType();
}
public boolean isNullable() {
return nullable;
}
@Nonnull
public DbTable getTable() {
return table;
}
}

View file

@ -0,0 +1,55 @@
package me.yuri.yuriapi.api.db;
import org.bukkit.Location;
import org.bukkit.inventory.ItemStack;
import javax.annotation.Nonnull;
import java.util.UUID;
public final class DbColumnDataType<T, V> {
public static final DbColumnDataType<Integer, Integer> INTEGER = new DbColumnDataType<>(Integer.class, Integer.class, 0);
public static final DbColumnDataType<byte[], byte[]> BYTE_ARRAY = new DbColumnDataType<>(byte[].class, byte[].class, 1);
public static final DbColumnDataType<byte[], UUID> UUID = new DbColumnDataType<>(byte[].class, UUID.class, 2);
public static final DbColumnDataType<Long, Long> TIMESTAMP = new DbColumnDataType<>(Long.class, Long.class, 3);
public static final DbColumnDataType<Long, Long> BIGINT = new DbColumnDataType<>(Long.class, Long.class, 4);
public static final DbColumnDataType<String, Location> LOCATION = new DbColumnDataType<>(String.class, Location.class, 5);
public static final DbColumnDataType<Boolean, Boolean> BOOLEAN = new DbColumnDataType<>(Boolean.class, Boolean.class, 6);
public static final DbColumnDataType<String, String> TEXT = new DbColumnDataType<>(String.class, String.class, 7);
public static final DbColumnDataType<String, ItemStack> ITEM_STACK = new DbColumnDataType<>(String.class, ItemStack.class, 8);
public static final DbColumnDataType<Float, Float> FLOAT = new DbColumnDataType<>(Float.class, Float.class, 9);
public static final DbColumnDataType<Double, Double> DOUBLE = new DbColumnDataType<>(Double.class, Double.class, 10);
private final Class<T> type;
private final Class<V> datatype;
private final int id;
private DbColumnDataType(@Nonnull Class<T> type, @Nonnull Class<V> datatype, int id) {
this.type = type;
this.datatype = datatype;
this.id = id;
}
public int getId() {
return id;
}
@Nonnull
public T getPrimitiveType(T t) {
return t;
}
@Nonnull
public V getPrimitiveDataType(V v) {
return v;
}
@Nonnull
public Class<T> getBoxedType() {
return type;
}
@Nonnull
public Class<V> getBoxedDataType() {
return datatype;
}
}

View file

@ -0,0 +1,18 @@
package me.yuri.yuriapi.api.db;
import javax.annotation.Nonnull;
public enum DbComparisonLink {
START(""), OR("OR"), AND("AND");
private final String lit;
DbComparisonLink(String n) {
this.lit = n;
}
@Nonnull
public String getLiteral() {
return lit;
}
}

View file

@ -0,0 +1,18 @@
package me.yuri.yuriapi.api.db;
import javax.annotation.Nonnull;
public enum DbComparisonType {
EQUALS("="), MORE_THAN(">"), LESS_THAN("<"), MORE_THAN_EQUALS(">="), LESS_THAN_EQUALS("<="), NOT_EQUALS("<>"), LIKE(" LIKE ");
private final String lit;
DbComparisonType(String l) {
this.lit = l;
}
@Nonnull
public String getLiteral() {
return lit;
}
}

View file

@ -0,0 +1,17 @@
package me.yuri.yuriapi.api.db;
import javax.annotation.Nonnull;
import java.util.List;
public class DbCondition {
private final List<DbExpression> comps;
protected DbCondition(List<DbExpression> comparisons) {
comps = comparisons;
}
@Nonnull
public List<DbExpression> getExpressionList() {
return comps;
}
}

View file

@ -0,0 +1,101 @@
package me.yuri.yuriapi.api.db;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
public class DbConditionBuilder {
private final DbTable table;
private final List<DbExpression> comparisons = new ArrayList<>();
private DbColumn<?, ?> current = null;
private int currentDepth = 0;
private DbComparisonLink currentLink = DbComparisonLink.START;
protected DbConditionBuilder(DbTable t) {
table = t;
}
@Nonnull
public DbConditionBuilder forColumn(@Nonnull DbColumn<?, ?> c) {
current = c;
return this;
}
@Nonnull
public DbConditionBuilder forColumn(@Nonnegative int index) {
current = table.getColumns().get(index);
return this;
}
@Nonnull
public DbConditionBuilder forColumn(@Nonnull String name) {
for (DbColumn<?, ?> c : table.getColumns()) {
if (c.getName().equalsIgnoreCase(name)) {
current = c;
return this;
}
}
throw new IllegalArgumentException(String.format("Column %s does not exist.", name));
}
@Nonnull
public <V> DbConditionBuilder value(@Nonnull DbComparisonType type, V value) {
if (current == null) {
throw new IllegalStateException("Set the column before applying condition.");
}
if (currentLink == null) {
throw new IllegalStateException("No link between the two expressions selected.");
}
comparisons.add(new DbExpression(current, type, value, currentDepth, currentLink));
currentLink = null;
return this;
}
@Nonnull
public DbConditionBuilder or() {
if (comparisons.isEmpty()) {
throw new IllegalStateException("No expression has been set before OR clause.");
}
currentLink = DbComparisonLink.OR;
return this;
}
@Nonnull
public DbConditionBuilder and() {
if (comparisons.isEmpty()) {
throw new IllegalStateException("No expression has been set before AND clause.");
}
currentLink = DbComparisonLink.AND;
return this;
}
@Nonnull
public DbConditionBuilder openGroup() {
currentDepth++;
return this;
}
@Nonnull
public DbConditionBuilder closeGroup() {
if (currentDepth == 0) {
throw new IllegalStateException("No group to close.");
}
currentDepth--;
return this;
}
@Nonnull
public DbCondition end() {
if (currentDepth != 0) {
throw new IllegalStateException(String.format("Unclosed groups: %d groups.", currentDepth));
}
return new DbCondition(comparisons);
}
}

View file

@ -0,0 +1,109 @@
package me.yuri.yuriapi.api.db;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public abstract class DbConnection {
protected final String connectionString;
protected final List<DbTable> tables = new ArrayList<>();
protected Connection connection = null;
protected boolean doInitTables = false;
protected boolean init = false;
protected DbConnection(String connectionString) {
this.connectionString = connectionString;
}
public static DbConnectionBuilder newConnection(DbConnectionBuilder.DbType t) {
return new DbConnectionBuilder(t);
}
@Nonnull
public abstract Class<?> forName() throws ClassNotFoundException;
public boolean isConnected() {
try {
return connection != null && connection.isClosed();
} catch (SQLException ignored) {
return false;
}
}
protected abstract void createTable(@Nonnull DbTable t, boolean force);
@Nonnull
public abstract String transformDataType(@Nonnull DbColumnDataType<?, ?> type);
public void initTables(DbTable... t) {
initTables(Arrays.asList(t));
}
public void initTables(@Nonnull List<DbTable> t) {
if (init)
throw new IllegalStateException("Database has already been initialized.");
doInitTables = true;
tables.addAll(t);
}
@Nonnull
public DbTable getTable(@Nonnegative int ordinal) {
return tables.get(ordinal);
}
@Nonnull
public abstract String serializeObject(@Nullable Object o);
public abstract DbQueryResult select(DbSelectQuery q);
@Nullable
public abstract Object deserializeObject(@Nonnull DbColumnDataType<?, ?> type, @Nullable Object o);
@Nonnegative
public abstract int update(DbQuery q);
@Nonnull
public List<DbTable> getTables() {
return this.tables;
}
public DbTable getTable(@Nonnull String name) {
for (DbTable t : tables) {
if (t.getName().equalsIgnoreCase(name)) return t;
}
return null;
}
public void createTable(@Nonnull DbTable t) {
createTable(t, false);
}
public void connect() throws Exception {
init = true;
forName();
connection = DriverManager.getConnection(connectionString);
if (doInitTables) {
List<DbTable> tablelist = new ArrayList<>(tables);
tables.clear();
tablelist.forEach(t -> createTable(t, false));
}
}
public void disconnect() {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//TODO QUERYING DATA PARSING, DATA CONVERTERS
}

View file

@ -0,0 +1,67 @@
package me.yuri.yuriapi.api.db;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
public class DbConnectionBuilder {
private final DbType type;
private final Map<String, Function<DbTableBuilder, DbTable>> tablebuilds = new HashMap<>();
private String connectionString = null;
public DbConnectionBuilder(DbType type) {
this.type = type;
}
@Nonnull
public DbConnectionBuilder withConnectionString(@Nonnull String s) {
connectionString = s;
return this;
}
@Nonnull
public DbConnectionBuilder withTable(String name, Function<DbTableBuilder, DbTable> builder) {
tablebuilds.put(name, builder);
return this;
}
@Nonnull
public DbConnection build() {
if (connectionString == null) {
throw new IllegalStateException("connection string is not defined");
}
DbConnection db;
switch (type) {
case SQLITE:
db = new SqliteConnection(connectionString);
break;
default:
throw new RuntimeException("not possible but ok");
}
List<DbTable> tables = new ArrayList<>();
for (Map.Entry<String, Function<DbTableBuilder, DbTable>> u : tablebuilds.entrySet()) {
tables.add(u.getValue().apply(new DbTableBuilder(u.getKey(), db)));
}
db.initTables(tables);
return db;
}
@Nonnull
public DbType getType() {
return type;
}
public enum DbType {
SQLITE
}
}

View file

@ -0,0 +1,45 @@
package me.yuri.yuriapi.api.db;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
public class DbExpression {
private final DbColumn<?, ?> column;
private final DbComparisonType type;
private final Object value;
private final int depth;
private final DbComparisonLink prev;
protected DbExpression(DbColumn<?, ?> col, DbComparisonType type, Object value, int depth, DbComparisonLink prev) {
this.column = col;
this.type = type;
this.value = value;
this.prev = prev;
this.depth = depth;
}
public Object getValue() {
return value;
}
@Nonnull
public DbColumn<?, ?> getColumn() {
return column;
}
@Nonnull
public DbComparisonType getComparisonType() {
return type;
}
@Nonnegative
public int getDepth() {
return depth;
}
@Nonnull
public DbComparisonLink linkBefore() {
return prev;
}
}

View file

@ -0,0 +1,53 @@
package me.yuri.yuriapi.api.db;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Map;
public class DbQuery {
private final DbConnection conn;
private final Map<DbColumn<?, ?>, Object> map;
private final DbTable table;
private final DbQueryType type;
private final DbCondition condition;
protected DbQuery(@Nonnull DbQueryType type, @Nonnull DbTable t, @Nonnull Map<DbColumn<?, ?>, Object> map, @Nullable DbCondition cnd) {
this.map = map;
this.table = t;
this.type = type;
this.condition = cnd;
this.conn = table.getConnection();
}
@Nonnull
public DbConnection getConnection() {
return conn;
}
@Nonnegative
public int execute() {
return conn.update(this);
}
@Nonnull
public Map<DbColumn<?, ?>, Object> getColumnMap() {
return map;
}
@Nonnull
public DbTable getTable() {
return table;
}
@Nonnull
public DbQueryType getQueryType() {
return type;
}
@Nullable
public DbCondition getCondition() {
return condition;
}
}

View file

@ -0,0 +1,146 @@
package me.yuri.yuriapi.api.db;
import com.google.common.collect.ImmutableList;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
import java.util.function.Consumer;
public class DbQueryResult {
private final DbConnection connection;
private final ImmutableList<DbColumn<?, ?>> columns;
private final DbTable table;
private final ResultSet rs;
protected DbQueryResult(DbConnection con, DbTable t, ImmutableList<DbColumn<?, ?>> l, ResultSet rs) {
this.table = t;
this.columns = l;
this.rs = rs;
this.connection = con;
}
@Nonnull
public DbTable getTable() {
return table;
}
public ImmutableList<DbColumn<?, ?>> getColumns() {
return columns;
}
public boolean isEmpty() {
return rs == null;
}
public boolean next() {
try {
return rs.next();
} catch (SQLException throwables) {
return false;
}
}
public boolean previous() {
try {
return rs.previous();
} catch (SQLException throwables) {
return false;
}
}
@Nonnull
public DbQueryResult skip(int count) {
try {
for (int i = 0; i < count; i++)
rs.next();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return this;
}
@Nonnull
public DbQueryResult back(int count) {
try {
for (int i = 0; i < count; i++)
rs.previous();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return this;
}
@SuppressWarnings("unchecked")
public <T extends DbColumnDataType<?, V>, V> V get(DbColumn<T, V> c) {
try {
Object o = connection.deserializeObject(c.getType(), rs.getObject(c.getName()));
assert o == null || o.getClass().isAssignableFrom(c.getDataType());
return (V) o;
} catch (SQLException throwables) {
return null;
}
}
public Object get(@Nonnegative int rowIndex) {
return this.get(this.columns.get(rowIndex));
}
public long getLong(@Nonnegative int rowIndex) {
try {
return rs.getLong(rowIndex);
} catch (SQLException throwables) {
throwables.printStackTrace();
throw new RuntimeException("Problem");
}
}
public boolean getBoolean(@Nonnegative int rowIndex) {
try {
return rs.getBoolean(rowIndex);
} catch (SQLException throwables) {
throwables.printStackTrace();
throw new RuntimeException("Problem");
}
}
public UUID getUUID(@Nonnegative int rowIndex) {
return (UUID) get(rowIndex);
}
public int getInt(@Nonnegative int rowIndex) {
try {
return rs.getInt(rowIndex);
} catch (SQLException throwables) {
throwables.printStackTrace();
throw new RuntimeException("Problem");
}
}
public String getText(@Nonnegative int rowIndex) {
try {
return rs.getString(rowIndex);
} catch (SQLException throwables) {
throwables.printStackTrace();
throw new RuntimeException("Problem");
}
}
@Nonnull
public DbQueryResult then(Consumer<DbQueryResult> c) {
c.accept(this);
return this;
}
public void close() {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}

View file

@ -0,0 +1,18 @@
package me.yuri.yuriapi.api.db;
import javax.annotation.Nonnull;
public enum DbQueryType {
INSERT("INSERT"), UPDATE("UPDATE"), REMOVE("DELETE");
private final String cmd;
DbQueryType(String cmd) {
this.cmd = cmd;
}
@Nonnull
public String getCommand() {
return cmd;
}
}

View file

@ -0,0 +1,45 @@
package me.yuri.yuriapi.api.db;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
public class DbSelectQuery {
private final DbConnection connection;
private final List<DbColumn<?, ?>> columns;
private final DbTable table;
private final DbCondition condition;
protected DbSelectQuery(@Nonnull DbTable t, @Nonnull List<DbColumn<?, ?>> columns, @Nullable DbCondition cnd) {
this.connection = t.getConnection();
this.columns = columns;
this.table = t;
this.condition = cnd;
}
@Nonnull
public DbConnection getConnection() {
return connection;
}
@Nonnull
public DbQueryResult execute() {
return connection.select(this);
}
@Nonnull
public List<DbColumn<?, ?>> getColumns() {
return columns;
}
@Nonnull
public DbTable getTable() {
return table;
}
@Nullable
public DbCondition getCondition() {
return condition;
}
}

View file

@ -0,0 +1,93 @@
package me.yuri.yuriapi.api.db;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public class DbSelectQueryBuilder {
private final DbTable table;
private final List<DbColumn<?, ?>> selected = new ArrayList<>();
private boolean isSelect = false;
private DbCondition condition = null;
protected DbSelectQueryBuilder(@Nonnull DbTable t) {
this.table = t;
}
@Nonnull
public DbSelectQueryBuilder columnRange(@Nonnegative int start, @Nonnegative int end) {
if (isSelect) {
throw new IllegalStateException("Columns have already been selected.");
}
if (start > end) {
throw new IllegalArgumentException("Value of parameter 'start' must be less than of parameter 'end'");
}
List<DbColumn<?, ?>> l = table.getColumns();
for (int i = start; i < end; i++) {
selected.add(l.get(i));
}
isSelect = true;
return this;
}
@Nonnull
public DbSelectQueryBuilder columns(@Nonnegative int... indexes) {
if (isSelect) {
throw new IllegalStateException("Columns have already been selected.");
}
List<DbColumn<?, ?>> l = table.getColumns();
for (int i : indexes) {
selected.add(l.get(i));
}
isSelect = true;
return this;
}
@Nonnull
public DbSelectQueryBuilder columns(@Nonnull String... names) {
if (isSelect) {
throw new IllegalStateException("Columns have already been selected.");
}
List<DbColumn<?, ?>> l = table.getColumns();
List<String> namel = Arrays.asList(names);
selected.addAll(l.stream().filter(c -> namel.contains(c.getName())).collect(Collectors.toList())); //FIXME CONTINUE
isSelect = true;
return this;
}
@Nonnull
public DbSelectQueryBuilder all() {
if (isSelect) {
throw new IllegalStateException("Columns have already been selected.");
}
selected.addAll(table.getColumns());
isSelect = true;
return this;
}
@Nonnull
public DbSelectQueryBuilder where(@Nonnull Function<DbConditionBuilder, DbCondition> f) {
if (condition != null) {
throw new IllegalStateException("WHERE condition has already been set.");
}
condition = f.apply(new DbConditionBuilder(table));
return this;
}
@Nonnull
public DbSelectQuery build() {
return new DbSelectQuery(table, selected, condition);
}
}

View file

@ -0,0 +1,89 @@
package me.yuri.yuriapi.api.db;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class DbTable {
private final String name;
private final DbColumn<?, ?> primary_key;
private final List<DbColumn<?, ?>> columns;
private final DbConnection connection;
protected DbTable(@Nonnull DbConnection con, @Nonnull String name, @Nonnull Object[] primary_key, @Nonnull List<Object[]> columns) {
this.connection = con;
this.name = name;
this.primary_key = new DbColumn<>((String) primary_key[0], (DbColumnDataType<?, ?>) primary_key[1], this, (boolean) primary_key[2]);
this.columns = columns.stream().map(c -> new DbColumn<>((String) c[0], (DbColumnDataType<?, ?>) c[1], this, (boolean) c[2])).collect(Collectors.toList());
}
@Nonnull
public String getName() {
return name;
}
@Nonnull
public DbConnection getConnection() {
return connection;
}
@Nonnull
public DbColumn<?, ?> getPrimaryKey() {
return primary_key;
}
@Nonnull
public List<DbColumn<?, ?>> getColumns() {
List<DbColumn<?, ?>> l = new ArrayList<>();
l.add(primary_key);
l.addAll(columns);
return l;
}
@Nonnull
public List<DbColumn<?, ?>> getNormalColums() {
return columns;
}
@Nullable
public DbColumnDataType<?, ?> getByName(String name) {
if (primary_key.getName().equalsIgnoreCase(name))
return primary_key.getType();
for (DbColumn<?, ?> c : columns) {
if (c.getName().equalsIgnoreCase(name)) {
return c.getType();
}
}
return null;
}
@Nonnull
public DbUpdateQueryBuilder createQuery(DbQueryType t) {
return new DbUpdateQueryBuilder(t, this);
}
@Nonnull
public DbUpdateQueryBuilder createUpdateQuery() {
return new DbUpdateQueryBuilder(DbQueryType.UPDATE, this);
}
@Nonnull
public DbUpdateQueryBuilder createInsertQuery() {
return new DbUpdateQueryBuilder(DbQueryType.INSERT, this);
}
@Nonnull
public DbUpdateQueryBuilder createRemoveQuery() {
return new DbUpdateQueryBuilder(DbQueryType.REMOVE, this);
}
@Nonnull
public DbSelectQueryBuilder createSelectQuery() {
return new DbSelectQueryBuilder(this);
}
}

View file

@ -0,0 +1,52 @@
package me.yuri.yuriapi.api.db;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
public class DbTableBuilder {
private final List<Object[]> columns = new ArrayList<>();
private final String name;
private final DbConnection con;
private Object[] primary_key = null;
public DbTableBuilder(@Nonnull String name, @Nonnull DbConnection con) {
this.name = name;
this.con = con;
}
@Nonnull
public <T, V> DbTableBuilder withPrimaryKey(String name, DbColumnDataType<T, V> type) {
if (primary_key != null) {
throw new IllegalStateException("primary key was already set");
}
primary_key = new Object[]{name, type, false};
return this;
}
@Nonnull
public <T, V> DbTableBuilder withColumn(String name, DbColumnDataType<T, V> type, boolean nullable) {
columns.add(new Object[]{name, type, nullable});
return this;
}
@Nonnull
public <T, V> DbTableBuilder withColumn(String name, DbColumnDataType<T, V> type) {
return withColumn(name, type, false);
}
@Nonnull
public DbTable build() {
if (primary_key == null) {
throw new IllegalStateException("primary key is not set");
}
return new DbTable(con, name, primary_key, columns);
}
@Nonnull
public String getName() {
return name;
}
}

View file

@ -0,0 +1,88 @@
package me.yuri.yuriapi.api.db;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
public class DbUpdateQueryBuilder {
private final DbTable table;
private final DbQueryType type;
private final Map<DbColumn<?, ?>, Object> object_map = new HashMap<>();
private DbCondition condition = null;
protected DbUpdateQueryBuilder(@Nonnull DbQueryType type, @Nonnull DbTable table) {
this.table = table;
this.type = type;
}
@Nonnull
public <T extends DbColumnDataType<?, V>, V> DbUpdateQueryBuilder setColumn(@Nonnull DbColumn<T, V> column, @Nullable V data) {
if (!column.isNullable())
throw new IllegalArgumentException("Column " + column.getName() + " does not accept null values.");
object_map.put(column, data);
return this;
}
@Nonnull
public <V> DbUpdateQueryBuilder setColumn(@Nonnegative int columnIndex, @Nullable V data) {
DbColumn<?, ?> c = table.getColumns().get(columnIndex);
if (data != null) {
if (!data.getClass().isAssignableFrom(c.getDataType())) {
throw new IllegalArgumentException(String.format("Invalid data type provided. Expected: %s, provided: %s", c.getDataType().getCanonicalName(), data.getClass().getCanonicalName()));
}
} else {
if (!c.isNullable())
throw new IllegalArgumentException("Column " + c.getName() + " does not accept null values.");
}
object_map.put(c, data);
return this;
}
@Nonnull
public <V> DbUpdateQueryBuilder setColumn(@Nonnull String name, @Nullable V data) {
DbColumn<?, ?> col = null;
for (DbColumn<?, ?> c : table.getColumns()) {
if (c.getName().equalsIgnoreCase(name)) {
col = c;
break;
}
}
if (col == null)
throw new IllegalArgumentException(String.format("Column '%s' does not exist.", name));
if (data != null) {
if (!data.getClass().isAssignableFrom(col.getDataType())) {
throw new IllegalArgumentException(String.format("Invalid data type provided. Expected: %s, provided: %s", col.getDataType().getCanonicalName(), data.getClass().getCanonicalName()));
}
} else {
if (!col.isNullable())
throw new IllegalArgumentException(String.format("Column '%s' does not accept null values.", col.getName()));
}
object_map.put(col, data);
return this;
}
@Nonnull
public DbUpdateQueryBuilder where(@Nonnull Function<DbConditionBuilder, DbCondition> f) {
if (condition != null) {
throw new IllegalStateException("WHERE condition has already been set.");
}
condition = f.apply(new DbConditionBuilder(table));
return this;
}
@Nonnull
public DbQuery build() {
return new DbQuery(type, table, object_map, condition);
}
}

View file

@ -0,0 +1,246 @@
package me.yuri.yuriapi.api.db;
import com.google.common.collect.ImmutableList;
import me.yuri.yuriapi.api.utils.UUIDUtils;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.craftbukkit.libs.org.apache.commons.codec.binary.Hex;
import org.bukkit.inventory.ItemStack;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.nio.charset.StandardCharsets;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
public class SqliteConnection extends DbConnection {
protected SqliteConnection(String connectionString) {
super(connectionString);
}
@Nonnull
@Override
public Class<?> forName() throws ClassNotFoundException {
return Class.forName("org.sqlite.JDBC");
}
@Override
public void createTable(@Nonnull DbTable t, boolean force) {
StringBuilder sb = new StringBuilder();
sb.append("CREATE TABLE ");
if (!force)
sb.append("IF NOT EXISTS ");
sb.append(t.getName()).append('(').append(t.getPrimaryKey().getName()).append(' ')
.append(transformDataType(t.getPrimaryKey().getType())).append(' ').append("PRIMARY KEY NOT NULL");
for (DbColumn<?, ?> c : t.getNormalColums()) {
sb.append(',').append(c.getName()).append(' ').append(transformDataType(c.getType())).append(c.isNullable() ? "" : " NOT NULL");
}
sb.append(");");
String stmt = sb.toString();
if (stmt.contains("'")) {
throw new IllegalArgumentException("\"'\" characters are not allowed.");
}
try {
this.connection.createStatement().executeUpdate(stmt);
this.tables.add(t);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
@Nonnull
@Override
public String transformDataType(@Nonnull DbColumnDataType<?, ?> type) {
switch (type.getId()) {
case 0:
case 6:
return "INT";
case 7:
case 8:
return "TEXT";
case 4:
case 3:
case 5:
return "BIGINT";
case 1:
case 2:
return "BLOB";
case 9:
case 10:
return "REAL";
default:
throw new RuntimeException("that's not possible bruh");
}
}
@Nonnull
@Override
public String serializeObject(@Nullable Object o) {
if (o == null) {
return "NULL";
} else if (o instanceof String) {
return String.format("'%s'", sanitize((String) o));
} else if (o instanceof UUID) {
return String.format("X'%s'", Hex.encodeHexString(UUIDUtils.toByteArray((UUID) o)));
} else if (o instanceof Location) {
Location l = ((Location) o);
return String.format("'%f:%f:%f:%s'", l.getX(), l.getY(), l.getZ(), Objects.requireNonNull(l.getWorld()).getName());
} else if (o instanceof ItemStack) {
Base64.Encoder en = Base64.getEncoder();
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, Object> e : ((ItemStack) o).serialize().entrySet()) {
sb.append(en.encodeToString(e.getKey().getBytes(StandardCharsets.UTF_8))).append(':')
.append(en.encodeToString(String.valueOf(e.getValue()).getBytes(StandardCharsets.UTF_8)))
.append(',');
}
sb.deleteCharAt(sb.length());
return sb.toString();
}
return String.valueOf(o);
}
@Nullable
@Override
public Object deserializeObject(@Nonnull DbColumnDataType<?, ?> type, @Nullable Object o) {
if (o == null)
return null;
if (o instanceof String) {
String str = desanitize(((String) o));
if (type.getBoxedDataType().isAssignableFrom(Location.class)) {
String[] s = str.split(":", 4);
return new Location(Bukkit.getWorld(s[3]), Double.parseDouble(s[0]), Double.parseDouble(s[1]), Double.parseDouble(s[2]));
} else if (type.getBoxedDataType().isAssignableFrom(ItemStack.class)) {
String[] s = str.split(",");
Map<String, Object> map = new HashMap<>();
for (String s2 : s) {
String[] s3 = s2.split(":");
Base64.Decoder d = Base64.getDecoder();
map.put(new String(d.decode(s3[0])), new String(d.decode(s3[1])));
}
return ItemStack.deserialize(map);
}
return str.replace("''", "'");
} else if (o instanceof byte[]) {
if (type.getBoxedDataType().isAssignableFrom(UUID.class)) {
return UUIDUtils.toUUID((((byte[]) o)));
}
}
return o;
}
@Override
public DbQueryResult select(DbSelectQuery q) {
StringBuilder sb = new StringBuilder();
sb.append("SELECT ");
for (DbColumn<?, ?> col : q.getColumns()) {
sb.append(col.getName()).append(',');
}
sb.deleteCharAt(sb.length() - 1).append(" FROM ").append(q.getTable().getName());
if (q.getCondition() != null) {
sb.append(" WHERE");
int depth = 0;
for (DbExpression cmp : q.getCondition().getExpressionList()) {
sb.append(' ').append(cmp.linkBefore().getLiteral()).append(' ');
if (cmp.getDepth() > depth)
sb.append('(');
else if (cmp.getDepth() < cmp.getDepth())
sb.append(')');
depth = cmp.getDepth();
sb.append(cmp.getColumn().getName()).append(cmp.getComparisonType().getLiteral()).append(serializeObject(cmp.getValue()));
}
if (depth > 0)
sb.append(')');
}
sb.append(';');
try {
ResultSet rs = connection.createStatement().executeQuery(sb.toString());
return new DbQueryResult(this, q.getTable(), ImmutableList.copyOf(q.getColumns()), rs);
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
@Nonnegative
@Override
public int update(DbQuery q) {
StringBuilder sb = new StringBuilder();
switch (q.getQueryType()) {
case INSERT:
sb.append("INSERT OR REPLACE INTO ").append(q.getTable().getName()).append("(");
for (DbColumn<?, ?> c : q.getColumnMap().keySet()) {
sb.append(c.getName()).append(',');
}
sb.deleteCharAt(sb.length() - 1);
sb.append(") VALUES (");
for (Object oo : q.getColumnMap().values()) {
sb.append(this.serializeObject(oo)).append(',');
}
sb.deleteCharAt(sb.length() - 1);
sb.append(')');
break;
case UPDATE:
sb.append("UPDATE ").append(q.getTable().getName()).append(" SET ");
for (Map.Entry<DbColumn<?, ?>, Object> e : q.getColumnMap().entrySet()) {
sb.append(e.getKey().getName()).append(" = ").append(serializeObject(e.getValue())).append(',');
}
sb.deleteCharAt(sb.length() - 1).append(' ');
break;
case REMOVE:
sb.append("DELETE FROM ").append(q.getTable().getName()).append(' ');
break;
}
if (q.getQueryType() != DbQueryType.INSERT && q.getCondition() != null && !q.getCondition().getExpressionList().isEmpty()) {
sb.append("WHERE");
int depth = 0;
for (DbExpression cmp : q.getCondition().getExpressionList()) {
sb.append(' ').append(cmp.linkBefore().getLiteral()).append(' ');
if (cmp.getDepth() > depth)
sb.append('(');
else if (cmp.getDepth() < cmp.getDepth())
sb.append(')');
depth = cmp.getDepth();
sb.append(cmp.getColumn().getName()).append(cmp.getComparisonType().getLiteral()).append(serializeObject(cmp.getValue()));
}
if (depth > 0)
sb.append(')');
}
sb.append(';');
try {
return connection.createStatement().executeUpdate(sb.toString());
} catch (SQLException throwables) {
throwables.printStackTrace();
return -1;
}
}
private String sanitize(String input) {
return input.replace("'", "''");
}
private String desanitize(String input) {
return input.replace("''", "'");
}
}

View file

@ -0,0 +1,116 @@
package me.yuri.yuriapi.api.economy;
import me.yuri.yuriapi.api.YPlayer;
import me.yuri.yuriapi.api.db.DbComparisonType;
import me.yuri.yuriapi.api.db.DbQueryResult;
import me.yuri.yuriapi.api.event.EventManager;
import me.yuri.yuriapi.api.event.player.PlayerFundsChangeEvent;
import me.yuri.yuriapi.api.utils.configuration.ConfigVar;
import me.yuri.yuriapi.utils.DbManager;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import java.time.Instant;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.FutureTask;
public class EconomyManager {
private static final EconomyManager inst = new EconomyManager();
private static final Map<OfflinePlayer, Integer> fundTable = new ConcurrentHashMap<>();
@ConfigVar("currencySymbol")
private static String currencySymbol;
@ConfigVar("currencyName")
private static String currencyName;
private EconomyManager() {
}
public static EconomyManager getInstance() {
return inst;
}
public static String getCurrencySymbol() {
return currencySymbol;
}
public static String getCurrencyName() {
return currencyName;
}
public static int getFunds(YPlayer p) {
int i = 0;
if (!fundTable.containsKey(p.getBasePlayer()))
fundTable.put(p.getBasePlayer(), i);
else i = fundTable.get(p.getBasePlayer());
return i;
}
public static void addFunds(YPlayer p, int amount) {
int i = getFunds(p);
setFunds(p, i + amount);
}
public static boolean subtractFunds(YPlayer p, int amount) {
int i = getFunds(p) - amount;
if (i < 0) return false;
setFunds(p, i);
return true;
}
public static void setFunds(YPlayer p, int amount) {
fundTable.put(p.getBasePlayer(), amount);
EventManager.executeEvent(new PlayerFundsChangeEvent(p, fundTable.getOrDefault(p.getBasePlayer(), 0), amount));
}
public static void saveChanges() {
for (Map.Entry<OfflinePlayer, Integer> e : fundTable.entrySet()) {
DbManager.z_().getTable("funds")
.createInsertQuery()
.setColumn(0, e.getKey().getUniqueId())
.setColumn(1, e.getValue()).setColumn(2, Instant.now().toEpochMilli())
.build().execute();
System.out.println("SAVING: " + e.getKey().getUniqueId() + ":" + e.getKey().getName());
}
}
public static void saveFor(YPlayer p) {
DbManager.z_().getTable("funds")
.createInsertQuery()
.setColumn(0, p.getBasePlayer().getUniqueId())
.setColumn(1, p.getFunds())
.setColumn(2, Instant.now().toEpochMilli())
.build().execute();
System.out.println("Saved for: " + p.getBasePlayer().getName() + ":" + p.getFunds());
}
public static void loadFor(YPlayer p) {
DbQueryResult r = DbManager.z_().getTable("funds")
.createSelectQuery().columns("funds")
.where(w -> w.forColumn("uuid").value(DbComparisonType.EQUALS, p.getBasePlayer().getUniqueId()).end())
.build().execute();
if (r.next())
fundTable.put(p.getBasePlayer(), (int) r.get(0));
r.close();
System.out.println("loaded for: " + p.getBasePlayer().getName() + ":" + p.getFunds());
}
public static FutureTask<Boolean> loadFromDbAsync() {
return new FutureTask<>(() -> {
DbQueryResult r = DbManager.z_().getTable("funds").createSelectQuery().all().build().execute();
while (r.next()) {
fundTable.put(Bukkit.getOfflinePlayer((UUID) r.get(0)), (int) r.get(1));
System.out.println(r.get(0) + ":" + r.get(1) + " > " + Bukkit.getOfflinePlayer((UUID) r.get(0)).getName());
}
r.close();
return true;
});
}
}

View file

@ -0,0 +1,7 @@
package me.yuri.yuriapi.api.event;
public interface Cancellable {
boolean isCancelled();
void setCancelled(boolean cancel);
}

View file

@ -0,0 +1,20 @@
package me.yuri.yuriapi.api.event;
public class Event {
public enum Priority {
HIGHEST(4), HIGH(3), NORMAL(2), LOW(1), LOWEST(0);
private final int priority;
Priority(int i) {
priority = i;
}
public int getPriority() {
return priority;
}
}
}

View file

@ -0,0 +1,7 @@
package me.yuri.yuriapi.api.event;
/**
* Base interface that must be implemented in any class with EventSubscriber annotations
*/
public interface EventListener {
}

View file

@ -0,0 +1,158 @@
package me.yuri.yuriapi.api.event;
import me.yuri.yuriapi.api.YPlayer;
import me.yuri.yuriapi.api.event.player.PlayerItemAttackEvent;
import me.yuri.yuriapi.api.event.player.PlayerItemUseEvent;
import me.yuri.yuriapi.api.reflectionless.Reflectionless;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import javax.annotation.Nullable;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class EventManager implements Listener {
private static final EventManager inst = new EventManager();
private static final boolean isOn = true;
private static final Map<Map.Entry<Plugin, EventListener>, List<Method>> eventRegistrar = new ConcurrentHashMap<>();
private EventManager() {
}
public static EventManager getInstance() {
return inst;
}
/**
* This method registers an event listener
*
* @param plugin Main plugin class instance of the listener
* @param listener Listener class instance
* @author Yuri
*/
public static void registerEvent(Plugin plugin, EventListener listener) {
for (Method method : listener.getClass().getMethods()) {
if (method.isAnnotationPresent(EventSubscriber.class)) {
Map.Entry<Plugin, EventListener> entry = new AbstractMap.SimpleEntry<>(plugin, listener);
List<Method> methods = eventRegistrar.getOrDefault(entry, new ArrayList<>());
methods.add(method);
methods.sort(Comparator.comparingInt(m -> m.getAnnotation(EventSubscriber.class).value().getPriority()));
Collections.reverse(methods);
eventRegistrar.put(entry, methods);
}
}
}
/**
* This method unregisters all listeners registered with main plugin instance passed as argument. Main plugin class may be passed optionally.
*
* @param plugin Main plugin class instance of the listener
* @param listener Listener class instance
* @author Yuri
*/
public static void unregisterEvent(@Nullable Plugin plugin, EventListener listener) {
if (plugin != null) {
Map.Entry<Plugin, EventListener> entry = new AbstractMap.SimpleEntry<>(plugin, listener);
if (eventRegistrar.containsKey(entry)) {
eventRegistrar.put(entry, new ArrayList<>());
}
eventRegistrar.remove(entry);
} else {
Optional<Map.Entry<Plugin, EventListener>> opEntry = eventRegistrar.keySet().stream().filter(entry -> entry.getValue().equals(listener)).findFirst();
if (opEntry.isPresent()) {
Map.Entry<Plugin, EventListener> entry = opEntry.get();
eventRegistrar.remove(entry);
}
}
}
/**
* This method unregisters all listeners registered with main plugin instance passed as argument
*
* @param plugin Main plugin class instance
* @author Yuri
*/
public static void unregisterAllPluginEvents(Plugin plugin) {
eventRegistrar.keySet().stream().filter(entry -> entry.getKey().equals(plugin)).forEach(eventRegistrar::remove);
}
/**
* This method unregisters an event listener passed as argument
*
* @param listener Listener class instance
* @author Yuri
*/
public static void unregisterEvent(EventListener listener) {
unregisterEvent(null, listener);
}
public static Event executeEvent(Event event) {
FutureTask<Event> futureTask = new FutureTask<>(() -> call(event));
futureTask.run();
try {
return futureTask.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return event;
}
private static Event call(Event event) {
if (isOn) {
for (Map.Entry<Plugin, EventListener> entry : eventRegistrar.keySet()) {
List<Method> methods = eventRegistrar.get(entry);
methods.stream()
.filter(method -> method.isAnnotationPresent(EventSubscriber.class) && method.getParameterTypes()[0] == event.getClass())
.sorted(Comparator.comparingInt(method -> Event.Priority.HIGHEST.getPriority() - method.getAnnotation(EventSubscriber.class).value().getPriority()))
.forEachOrdered(method -> {
try {
Reflectionless.get(method).call(entry.getValue(), event);
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
return event;
}
@EventHandler
public void onEvent(org.bukkit.event.Event e) {
Bukkit.getConsoleSender().sendMessage("EVENT");
if (e instanceof PlayerInteractEvent) {
PlayerInteractEvent ev = (PlayerInteractEvent) e;
if ((ev.getAction() == Action.RIGHT_CLICK_AIR || ev.getAction() == Action.LEFT_CLICK_AIR) && ev.hasItem()) {
executeEvent(new PlayerItemUseEvent(YPlayer.get(ev.getPlayer()), ev.getItem()));
return;
}
} else if (e instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent ev = (EntityDamageByEntityEvent) e;
if (ev instanceof Player) {
Player p = ((Player) ev);
ItemStack i = p.getInventory().getItemInMainHand();
if (i.getType() != Material.AIR) {
executeEvent(new PlayerItemAttackEvent(YPlayer.get(p), i, ev.getEntity()));
}
}
}
}
}

View file

@ -0,0 +1,12 @@
package me.yuri.yuriapi.api.event;
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 EventSubscriber {
Event.Priority value() default Event.Priority.NORMAL;
}

View file

@ -0,0 +1,45 @@
package me.yuri.yuriapi.api.event;
import org.bukkit.entity.Player;
public abstract class PacketEvent extends Event implements Cancellable {
private final Player player;
private final Object packetObject;
private final String type;
private final long timestamp;
private boolean cancelled;
public PacketEvent(Player p, Object packet, String type) {
player = p;
packetObject = p;
this.type = type;
timestamp = System.currentTimeMillis();
}
@Override
public boolean isCancelled() {
return cancelled;
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public Object getPacketObject() {
return packetObject;
}
public String getType() {
return type;
}
public long getTimestamp() {
return timestamp;
}
public Player getPlayer() {
return player;
}
}

View file

@ -0,0 +1,9 @@
package me.yuri.yuriapi.api.event;
import org.bukkit.entity.Player;
public class PacketIncomeEvent extends PacketEvent {
public PacketIncomeEvent(Player p, Object packet, String type) {
super(p, packet, type);
}
}

View file

@ -0,0 +1,9 @@
package me.yuri.yuriapi.api.event;
import org.bukkit.entity.Player;
public class PacketOutcomeEvent extends PacketEvent {
public PacketOutcomeEvent(Player p, Object packet, String type) {
super(p, packet, type);
}
}

View file

@ -0,0 +1,17 @@
package me.yuri.yuriapi.api.event.player;
import me.yuri.yuriapi.api.YPlayer;
import me.yuri.yuriapi.api.event.Event;
public class PlayerEvent extends Event {
private final YPlayer player;
public PlayerEvent(YPlayer player) {
this.player = player;
}
public YPlayer getPlayer() {
return player;
}
}

View file

@ -0,0 +1,23 @@
package me.yuri.yuriapi.api.event.player;
import me.yuri.yuriapi.api.YPlayer;
public class PlayerFundsChangeEvent extends PlayerEvent {
private final int init, after;
public PlayerFundsChangeEvent(YPlayer player, int initial, int after) {
super(player);
this.init = initial;
this.after = after;
}
public int getBefore() {
return init;
}
public int getAfter() {
return after;
}
}

Some files were not shown because too many files have changed in this diff Show more