Merge branch 'development'

This commit is contained in:
Brianna 2019-10-09 11:26:16 -04:00
commit aba0b68762
41 changed files with 884 additions and 1399 deletions

3
.gitignore vendored
View File

@ -1,3 +1,4 @@
\.idea
\target
EpicVouchers.iml
EpicVouchers.iml
dependency-reduced-pom.xml

View File

@ -4,7 +4,7 @@ stages:
variables:
name: "EpicVouchers"
path: "/builds/$CI_PROJECT_PATH"
version: "2.1.7"
version: "2.1.11"
build:
stage: build

51
pom.xml
View File

@ -32,7 +32,7 @@
<createDependencyReducedPom>false</createDependencyReducedPom>
<artifactSet>
<includes>
<include>com.songoda:songodaupdater</include>
<include>com.songoda:SongodaCore</include>
</includes>
</artifactSet>
<filters>
@ -45,26 +45,10 @@
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<minimizeJar>true</minimizeJar>
<relocations>
<relocation>
<pattern>org.bstats</pattern>
<shadedPattern>com.songoda.epicvouchers</shadedPattern>
<pattern>com.songoda.core</pattern>
<shadedPattern>${project.groupId}.epicvouchers.core</shadedPattern>
</relocation>
</relocations>
</configuration>
@ -83,15 +67,7 @@
<repositories>
<repository>
<id>private</id>
<url>http://repo.songoda.com/artifactory/private</url>
</repository>
<repository>
<id>aikar</id>
<url>https://repo.aikar.co/content/groups/aikar/</url>
</repository>
<repository>
<id>CodeMC</id>
<url>https://repo.codemc.org/repository/maven-public</url>
<url>https://repo.songoda.com/artifactory/private/</url>
</repository>
</repositories>
@ -99,13 +75,14 @@
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot</artifactId>
<version>1.14</version>
<version>1.14.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.songoda</groupId>
<artifactId>songodaupdater</artifactId>
<version>1</version>
<artifactId>SongodaCore</artifactId>
<version>LATEST</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
@ -113,17 +90,5 @@
<version>1.18.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>co.aikar</groupId>
<artifactId>acf-bukkit</artifactId>
<version>0.5.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.bstats</groupId>
<artifactId>bstats-bukkit</artifactId>
<version>1.4</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>

View File

@ -1,45 +1,42 @@
package com.songoda.epicvouchers;
import com.songoda.epicvouchers.command.CommandManager;
import com.songoda.core.SongodaCore;
import com.songoda.core.SongodaPlugin;
import com.songoda.core.commands.CommandManager;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.configuration.Config;
import com.songoda.core.gui.GuiManager;
import com.songoda.epicvouchers.commands.*;
import com.songoda.epicvouchers.handlers.Connections;
import com.songoda.epicvouchers.libraries.BountifulAPI;
import com.songoda.epicvouchers.libraries.inventory.FastInv;
import com.songoda.epicvouchers.libraries.inventory.IconInv;
import com.songoda.epicvouchers.listeners.PlayerCommandListener;
import com.songoda.epicvouchers.listeners.PlayerInteractListener;
import com.songoda.epicvouchers.utils.ConfigWrapper;
import com.songoda.epicvouchers.utils.Methods;
import com.songoda.epicvouchers.utils.ServerVersion;
import com.songoda.epicvouchers.utils.SettingsManager;
import com.songoda.epicvouchers.utils.locale.Locale;
import com.songoda.epicvouchers.utils.updateModules.LocaleModule;
import com.songoda.epicvouchers.settings.Settings;
import com.songoda.epicvouchers.voucher.CoolDownManager;
import com.songoda.epicvouchers.voucher.Voucher;
import com.songoda.epicvouchers.voucher.VoucherExecutor;
import com.songoda.update.Plugin;
import com.songoda.update.SongodaUpdate;
import org.bstats.bukkit.Metrics;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
public class EpicVouchers extends JavaPlugin {
public class EpicVouchers extends SongodaPlugin {
private static EpicVouchers INSTANCE;
private final ServerVersion serverVersion = ServerVersion.fromPackageName(Bukkit.getServer().getClass().getPackage().getName());
private CommandManager commandManager;
private final GuiManager guiManager = new GuiManager(this);
private Connections connections;
private CoolDownManager coolDowns;
private Locale locale;
private SettingsManager settingsManager;
private VoucherExecutor voucherExecutor;
private ConfigWrapper vouchersFile = new ConfigWrapper(this, "", "vouchers.yml");
private CommandManager commandManager;
private Config vouchersConfig = new Config(this, "vouchers.yml");
private LinkedHashMap<String, Voucher> vouchers;
public static EpicVouchers getInstance() {
@ -47,33 +44,43 @@ public class EpicVouchers extends JavaPlugin {
}
@Override
public void onEnable() {
public void onPluginLoad() {
INSTANCE = this;
Bukkit.getConsoleSender().sendMessage(Methods.format("&a============================="));
Bukkit.getConsoleSender().sendMessage(Methods.format("&7EpicVouchers " + this.getDescription().getVersion() + " by &5Songoda <3&7!"));
Bukkit.getConsoleSender().sendMessage(Methods.format("&7Action: &aEnabling&7..."));
}
// Setup language
new Locale(this, "en_US");
this.locale = Locale.getLocale(getConfig().getString("System.Language Mode"));
@Override
public void onPluginDisable() {
connections.closeMySQL();
}
//Running Songoda Updater
Plugin plugin = new Plugin(this, 25);
plugin.addModule(new LocaleModule());
SongodaUpdate.load(plugin);
@Override
public void onPluginEnable() {
// Run Songoda Updater
SongodaCore.registerPlugin(this, 25, CompatibleMaterial.EMERALD);
// Setup Config
Settings.setupConfig();
this.setLocale(Settings.LANGUGE_MODE.getString(), false);
// Register commands
this.commandManager = new CommandManager(this);
this.commandManager.addCommand(new CommandEpicVouchers(this))
.addSubCommands(
new CommandEditor(this),
new CommandForce(this),
new CommandForceAll(this),
new CommandGive(this),
new CommandGiveAll(this),
new CommandList(this),
new CommandReload(this)
);
FastInv.init(this);
IconInv.init(this);
BountifulAPI.init(this);
this.settingsManager = new SettingsManager(this);
this.settingsManager.updateSettings();
this.vouchers = new LinkedHashMap<>();
getConfig().options().copyDefaults(true);
saveConfig();
this.commandManager = new CommandManager(this);
this.connections = new Connections(this);
this.coolDowns = new CoolDownManager(this);
this.voucherExecutor = new VoucherExecutor(this);
@ -92,22 +99,26 @@ public class EpicVouchers extends JavaPlugin {
loadVouchersFromFile();
connections.openMySQL();
new Metrics(this);
Bukkit.getConsoleSender().sendMessage(Methods.format("&a============================="));
}
private void loadVouchersFromFile() {
vouchers.clear();
if (vouchersFile.getConfig().contains("vouchers")) {
for (String key : vouchersFile.getConfig().getConfigurationSection("vouchers").getKeys(false)) {
if (vouchersConfig.contains("vouchers")) {
for (String key : vouchersConfig.getConfigurationSection("vouchers").getKeys(false)) {
key = key.toLowerCase();
Voucher voucher = new Voucher(key, this);
ConfigurationSection cs = vouchersFile.getConfig().getConfigurationSection("vouchers." + key);
Material material = cs.getString("material") == null || cs.getString("material").equals("") ? Material.PAPER :
Material.matchMaterial(cs.getString("material")) == null ? Material.PAPER : Material.matchMaterial(cs.getString("material"));
ConfigurationSection cs = vouchersConfig.getConfigurationSection("vouchers." + key);
Material material;
String stringMaterial = cs.getString("material");
if (stringMaterial == null || stringMaterial.isEmpty()) {
material = Material.PAPER;
} else {
material = Material.matchMaterial(stringMaterial);
if (material == null) material = Material.PAPER;
}
voucher.setPermission(cs.getString("permission", ""));
voucher.setMaterial(material);
@ -144,30 +155,17 @@ public class EpicVouchers extends JavaPlugin {
}
}
public void reload() {
vouchersFile.reloadConfig();
@Override
public void onConfigReload() {
vouchersConfig.load();
loadVouchersFromFile();
reloadConfig();
saveConfig();
this.locale = Locale.getLocale(getConfig().getString("System.Language Mode"));
this.setLocale(getConfig().getString("System.Language Mode"), true);
this.locale.reloadMessages();
}
@Override
public void onDisable() {
connections.closeMySQL();
Bukkit.getConsoleSender().sendMessage(Methods.format("&a============================="));
Bukkit.getConsoleSender().sendMessage(Methods.format("&7EpicVouchers " + this.getDescription().getVersion() + " by &5Songoda <3&7!"));
Bukkit.getConsoleSender().sendMessage(Methods.format("&7Action: &cDisabling&7..."));
Bukkit.getConsoleSender().sendMessage(Methods.format("&a============================="));
}
public ServerVersion getServerVersion() {
return this.serverVersion;
}
public CommandManager getCommandManager() {
return this.commandManager;
public List<Config> getExtraConfig() {
return Collections.singletonList(vouchersConfig);
}
public Connections getConnections() {
@ -178,23 +176,23 @@ public class EpicVouchers extends JavaPlugin {
return this.coolDowns;
}
public Locale getLocale() {
return this.locale;
}
public SettingsManager getSettingsManager() {
return this.settingsManager;
}
public VoucherExecutor getVoucherExecutor() {
return this.voucherExecutor;
}
public ConfigWrapper getVouchersFile() {
return this.vouchersFile;
public Config getVouchersConfig() {
return this.vouchersConfig;
}
public LinkedHashMap<String, Voucher> getVouchers() {
return this.vouchers;
}
public CommandManager getCommandManager() {
return commandManager;
}
public GuiManager getGuiManager() {
return guiManager;
}
}

View File

@ -1,30 +0,0 @@
package com.songoda.epicvouchers.command;
import co.aikar.commands.BukkitCommandManager;
import co.aikar.commands.InvalidCommandArgument;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.epicvouchers.voucher.Voucher;
import java.util.Optional;
public class CommandManager extends BukkitCommandManager {
private EpicVouchers instance;
public CommandManager(EpicVouchers instance) {
super(instance);
this.instance = instance;
registerDependency(EpicVouchers.class, "instance", instance);
getCommandContexts().registerContext(Voucher.class, c ->
Optional.ofNullable(instance.getVouchers().get(c.popFirstArg().toLowerCase())).orElseThrow(() ->
new InvalidCommandArgument("Unknown voucher.")));
getCommandCompletions().registerCompletion("vouchers", c -> instance.getVouchers().keySet());
registerCommand(new EfCommand());
enableUnstableAPI("help");
}
}

View File

@ -1,92 +0,0 @@
package com.songoda.epicvouchers.command;
import co.aikar.commands.BaseCommand;
import co.aikar.commands.CommandHelp;
import co.aikar.commands.annotation.*;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.epicvouchers.menus.VoucherMenu;
import com.songoda.epicvouchers.voucher.Voucher;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Collections;
@CommandAlias("epicvouchers|ev")
public class EfCommand extends BaseCommand {
@Dependency
private EpicVouchers instance;
@Subcommand("reload")
@CommandPermission("epicvouchers.admin")
@Description("Reload all configuration files.")
public void onReload(CommandSender sender) {
instance.reload();
instance.getLocale().getMessage("command.reload.success").sendPrefixedMessage(sender);
}
@Subcommand("list")
@CommandPermission("epicvouchers.admin")
@Description("List all available vouchers.")
public void onList(CommandSender sender) {
instance.getLocale().getMessage("command.list.list")
.processPlaceholder("%list%", String.join(", ", instance.getVouchers().keySet()))
.sendPrefixedMessage(sender);
}
@Subcommand("give")
@CommandPermission("epicvouchers.admin")
@CommandCompletion("@players @vouchers @range:1-10")
@Description("Give a voucher to a player.")
public void onGivePlayer(CommandSender sender, @Flags("other") Player player, Voucher voucher, int amount) {
voucher.give(sender, Collections.singletonList(player), amount);
}
@Subcommand("giveall")
@CommandPermission("epicvouchers.admin")
@CommandCompletion("@vouchers @range:1-10")
@Description("Give everyone online a voucher.")
public void onGiveAll(CommandSender sender, Voucher voucher, int amount) {
voucher.giveAll(sender, amount);
}
@Subcommand("force")
@CommandPermission("epicvouchers.admin")
@CommandCompletion("@players @vouchers @range:1-10")
@Description("Force user to redeem voucher.")
public void onForce(CommandSender sender, @Flags("other") Player player, Voucher voucher, int amount) {
voucher.forceRedeem(sender, Collections.singletonList(player), amount);
instance.getLocale().getMessage("command.force.send")
.processPlaceholder("player", player.getName())
.processPlaceholder("voucher", voucher.getName(true))
.processPlaceholder("amount", String.valueOf(amount))
.sendPrefixedMessage(sender);
}
@Subcommand("forceall")
@CommandPermission("epicvouchers.admin")
@CommandCompletion("@vouchers @range:1-10")
@Description("Force all online users to redeem voucher.")
public void onForceAll(CommandSender sender, Voucher voucher, int amount) {
voucher.forceRedeem(sender, new ArrayList<>(Bukkit.getOnlinePlayers()), amount);
instance.getLocale().getMessage("command.force.send")
.processPlaceholder("player", "everyone")
.processPlaceholder("voucher", voucher.getName(true))
.processPlaceholder("amount", String.valueOf(amount))
.sendPrefixedMessage(sender);
}
@Subcommand("editor")
@CommandPermission("epicvouchers.admin")
@Description("Opens the voucher editor.")
public void onEditor(Player player) {
new VoucherMenu(instance).open(player);
}
@HelpCommand
public void onHelp(CommandSender sender, CommandHelp help) {
help.showHelp();
}
}

View File

@ -0,0 +1,45 @@
package com.songoda.epicvouchers.commands;
import com.songoda.core.commands.AbstractCommand;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.epicvouchers.menus.VoucherMenu;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class CommandEditor extends AbstractCommand {
final EpicVouchers instance;
public CommandEditor(EpicVouchers instance) {
super(true, "editor");
this.instance = instance;
}
@Override
protected ReturnType runCommand(CommandSender sender, String... args) {
new VoucherMenu(instance).open((Player) sender);
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(CommandSender sender, String... args) {
return null;
}
@Override
public String getPermissionNode() {
return "epicvouchers.admin";
}
@Override
public String getSyntax() {
return "/ev editor";
}
@Override
public String getDescription() {
return "Opens the voucher editor.";
}
}

View File

@ -0,0 +1,54 @@
package com.songoda.epicvouchers.commands;
import com.songoda.core.commands.AbstractCommand;
import com.songoda.epicvouchers.EpicVouchers;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import java.util.List;
public class CommandEpicVouchers extends AbstractCommand {
final EpicVouchers instance;
public CommandEpicVouchers(EpicVouchers instance) {
super(false, "EpicVouchers");
this.instance = instance;
}
@Override
protected ReturnType runCommand(CommandSender sender, String... args) {
sender.sendMessage("");
instance.getLocale().newMessage("&7Version " + instance.getDescription().getVersion()
+ " Created with <3 by &5&l&oSongoda").sendPrefixedMessage(sender);
for (AbstractCommand command : instance.getCommandManager().getAllCommands()) {
if (command.getPermissionNode() == null || sender.hasPermission(command.getPermissionNode())) {
sender.sendMessage(ChatColor.translateAlternateColorCodes('&', "&8 - &a" + command.getSyntax() + "&7 - " + command.getDescription()));
}
}
sender.sendMessage("");
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(CommandSender sender, String... args) {
return null;
}
@Override
public String getPermissionNode() {
return null;
}
@Override
public String getSyntax() {
return "/EpicVouchers";
}
@Override
public String getDescription() {
return "Displays this page.";
}
}

View File

@ -0,0 +1,78 @@
package com.songoda.epicvouchers.commands;
import com.songoda.core.commands.AbstractCommand;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.epicvouchers.voucher.Voucher;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class CommandForce extends AbstractCommand {
final EpicVouchers instance;
public CommandForce(EpicVouchers instance) {
super(false, "force");
this.instance = instance;
}
@Override
protected ReturnType runCommand(CommandSender sender, String... args) {
if (args.length != 3)
return ReturnType.SYNTAX_ERROR;
Player player = Bukkit.getPlayer(args[0]);
if (Bukkit.getPlayer(args[0]) == null) {
instance.getLocale().newMessage("&cThat player does not exist or is currently offline.").sendPrefixedMessage(sender);
return ReturnType.FAILURE;
}
Voucher voucher = instance.getVouchers().get(args[1]);
if (voucher == null) {
sender.sendMessage("Unknown voucher...");
return ReturnType.FAILURE;
}
voucher.forceRedeem(sender, Collections.singletonList(player), Integer.parseInt(args[2]));
instance.getLocale().getMessage("command.force.send")
.processPlaceholder("player", player.getName())
.processPlaceholder("voucher", voucher.getName(true))
.processPlaceholder("amount", args[2].trim())
.sendPrefixedMessage(sender);
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(CommandSender sender, String... args) {
if (args.length == 1) {
return Bukkit.getOnlinePlayers().stream().map(HumanEntity::getName).collect(Collectors.toList());
} else if (args.length == 2) {
return new ArrayList<>(instance.getVouchers().keySet());
} else if (args.length == 3) {
return Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9", "10");
}
return null;
}
@Override
public String getPermissionNode() {
return "epicvouchers.admin";
}
@Override
public String getSyntax() {
return "/ev force <player> <voucher> <amount>";
}
@Override
public String getDescription() {
return "Force user to redeem voucher.";
}
}

View File

@ -0,0 +1,66 @@
package com.songoda.epicvouchers.commands;
import com.songoda.core.commands.AbstractCommand;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.epicvouchers.voucher.Voucher;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class CommandForceAll extends AbstractCommand {
final EpicVouchers instance;
public CommandForceAll(EpicVouchers instance) {
super(false, "forceall");
this.instance = instance;
}
@Override
protected ReturnType runCommand(CommandSender sender, String... args) {
if (args.length != 2)
return ReturnType.SYNTAX_ERROR;
Voucher voucher = instance.getVouchers().get(args[0]);
if (voucher == null) {
sender.sendMessage("Unknown voucher...");
return ReturnType.FAILURE;
}
voucher.forceRedeem(sender, new ArrayList<>(Bukkit.getOnlinePlayers()), Integer.parseInt(args[1]));
instance.getLocale().getMessage("command.force.send")
.processPlaceholder("player", "everyone")
.processPlaceholder("voucher", voucher.getName(true))
.processPlaceholder("amount", args[1].trim())
.sendPrefixedMessage(sender);
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(CommandSender sender, String... args) {
if (args.length == 1) {
return new ArrayList<>(instance.getVouchers().keySet());
} else if (args.length == 2) {
return Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9", "10");
}
return null;
}
@Override
public String getPermissionNode() {
return "epicvouchers.admin";
}
@Override
public String getSyntax() {
return "/ev forceall <voucher> <amount>";
}
@Override
public String getDescription() {
return "Force all online users to redeem voucher.";
}
}

View File

@ -0,0 +1,74 @@
package com.songoda.epicvouchers.commands;
import com.songoda.core.commands.AbstractCommand;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.epicvouchers.menus.VoucherMenu;
import com.songoda.epicvouchers.voucher.Voucher;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class CommandGive extends AbstractCommand {
final EpicVouchers instance;
public CommandGive(EpicVouchers instance) {
super(false, "give");
this.instance = instance;
}
@Override
protected ReturnType runCommand(CommandSender sender, String... args) {
if (args.length != 3)
return ReturnType.SYNTAX_ERROR;
Player player = Bukkit.getPlayer(args[0]);
if (Bukkit.getPlayer(args[0]) == null) {
instance.getLocale().newMessage("&cThat player does not exist or is currently offline.").sendPrefixedMessage(sender);
return ReturnType.FAILURE;
}
Voucher voucher = instance.getVouchers().get(args[1]);
if (voucher == null) {
sender.sendMessage("Unknown voucher...");
return ReturnType.FAILURE;
}
voucher.give(sender, Collections.singletonList(player), Integer.parseInt(args[2]));
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(CommandSender sender, String... args) {
if (args.length == 1) {
return Bukkit.getOnlinePlayers().stream().map(HumanEntity::getName).collect(Collectors.toList());
} else if (args.length == 2) {
return new ArrayList<>(instance.getVouchers().keySet());
} else if (args.length == 3) {
return Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9", "10");
}
return null;
}
@Override
public String getPermissionNode() {
return "epicvouchers.admin";
}
@Override
public String getSyntax() {
return "/ev give <player> <voucher> <amount>";
}
@Override
public String getDescription() {
return "Give a voucher to a player.";
}
}

View File

@ -0,0 +1,65 @@
package com.songoda.epicvouchers.commands;
import com.songoda.core.commands.AbstractCommand;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.epicvouchers.voucher.Voucher;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class CommandGiveAll extends AbstractCommand {
final EpicVouchers instance;
public CommandGiveAll(EpicVouchers instance) {
super(false, "giveall");
this.instance = instance;
}
@Override
protected ReturnType runCommand(CommandSender sender, String... args) {
if (args.length != 2)
return ReturnType.SYNTAX_ERROR;
Voucher voucher = instance.getVouchers().get(args[0]);
if (voucher == null) {
sender.sendMessage("Unknown voucher...");
return ReturnType.FAILURE;
}
voucher.giveAll(sender, Integer.parseInt(args[1]));
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(CommandSender sender, String... args) {
if (args.length == 1) {
return new ArrayList<>(instance.getVouchers().keySet());
} else if (args.length == 2) {
return Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9", "10");
}
return null;
}
@Override
public String getPermissionNode() {
return "epicvouchers.admin";
}
@Override
public String getSyntax() {
return "/ev giveall <voucher> <amount>";
}
@Override
public String getDescription() {
return "Give everyone online a voucher.";
}
}

View File

@ -0,0 +1,47 @@
package com.songoda.epicvouchers.commands;
import com.songoda.core.commands.AbstractCommand;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.epicvouchers.menus.VoucherMenu;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.List;
public class CommandList extends AbstractCommand {
final EpicVouchers instance;
public CommandList(EpicVouchers instance) {
super(false, "list");
this.instance = instance;
}
@Override
protected ReturnType runCommand(CommandSender sender, String... args) {
instance.getLocale().getMessage("command.list.list")
.processPlaceholder("list", String.join(", ", instance.getVouchers().keySet()))
.sendPrefixedMessage(sender);
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(CommandSender sender, String... args) {
return null;
}
@Override
public String getPermissionNode() {
return "epicvouchers.admin";
}
@Override
public String getSyntax() {
return "/ev list";
}
@Override
public String getDescription() {
return "List all available vouchers.";
}
}

View File

@ -0,0 +1,44 @@
package com.songoda.epicvouchers.commands;
import com.songoda.core.commands.AbstractCommand;
import com.songoda.epicvouchers.EpicVouchers;
import org.bukkit.command.CommandSender;
import java.util.List;
public class CommandReload extends AbstractCommand {
final EpicVouchers instance;
public CommandReload(EpicVouchers instance) {
super(false, "reload");
this.instance = instance;
}
@Override
protected ReturnType runCommand(CommandSender sender, String... args) {
instance.reloadConfig();
instance.getLocale().getMessage("&7Configuration and Language files reloaded.").sendPrefixedMessage(sender);
return ReturnType.SUCCESS;
}
@Override
protected List<String> onTab(CommandSender sender, String... args) {
return null;
}
@Override
public String getPermissionNode() {
return "epicvouchers.admin";
}
@Override
public String getSyntax() {
return "/ev reload";
}
@Override
public String getDescription() {
return "Reload the Configuration and Language files.";
}
}

View File

@ -8,48 +8,52 @@ import org.bukkit.event.HandlerList;
public class ForceRedeemEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private static final HandlerList handlers = new HandlerList();
private final Player player;
private final String voucher;
private final int amount;
private final CommandSender sender;
private boolean cancelled;
private final Player player;
private final String voucher;
private final int amount;
private final CommandSender sender;
private boolean cancelled;
public ForceRedeemEvent(Player player, String voucher, int amount, CommandSender sender) {
this.player = player;
this.voucher = voucher;
this.amount = amount;
this.sender = sender;
this.cancelled = false;
}
public ForceRedeemEvent(Player player, String voucher, int amount, CommandSender sender) {
this.player = player;
this.voucher = voucher;
this.amount = amount;
this.sender = sender;
this.cancelled = false;
}
public Player getPlayer() {
return player;
}
public Player getPlayer() {
return player;
}
public String getVoucher() {
return voucher;
}
public String getVoucher() {
return voucher;
}
public int getAmount() {
return amount;
}
public int getAmount() {
return amount;
}
public CommandSender getSender() {
return sender;
}
public CommandSender getSender() {
return sender;
}
public boolean isCancelled() {
return cancelled;
}
public boolean isCancelled() {
return cancelled;
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public HandlerList getHandlers() {
return handlers;
}
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}

View File

@ -9,54 +9,58 @@ import org.bukkit.inventory.ItemStack;
public class VoucherReceiveEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private static final HandlerList handlers = new HandlerList();
private final Player player;
private final String voucher;
private final ItemStack item;
private final int amount;
private final CommandSender sender;
private boolean cancelled;
private final Player player;
private final String voucher;
private final ItemStack item;
private final int amount;
private final CommandSender sender;
private boolean cancelled;
public VoucherReceiveEvent(Player player, String voucher, ItemStack item, int amount, CommandSender sender) {
this.player = player;
this.voucher = voucher;
this.item = item;
this.amount = amount;
this.sender = sender;
this.cancelled = false;
}
public VoucherReceiveEvent(Player player, String voucher, ItemStack item, int amount, CommandSender sender) {
this.player = player;
this.voucher = voucher;
this.item = item;
this.amount = amount;
this.sender = sender;
this.cancelled = false;
}
public Player getPlayer() {
return player;
}
public Player getPlayer() {
return player;
}
public String getVoucher() {
return voucher;
}
public String getVoucher() {
return voucher;
}
public ItemStack getItem() {
return item;
}
public ItemStack getItem() {
return item;
}
public int getAmount() {
return amount;
}
public int getAmount() {
return amount;
}
public CommandSender getSender() {
return sender;
}
public CommandSender getSender() {
return sender;
}
public boolean isCancelled() {
return cancelled;
}
public boolean isCancelled() {
return cancelled;
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public HandlerList getHandlers() {
return handlers;
}
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}

View File

@ -8,48 +8,52 @@ import org.bukkit.inventory.ItemStack;
public class VoucherRedeemEvent extends Event implements Cancellable {
private static final HandlerList handlers = new HandlerList();
private static final HandlerList handlers = new HandlerList();
private final Player player;
private final String voucher;
private final ItemStack item;
private final boolean manual;
private boolean cancelled;
private final Player player;
private final String voucher;
private final ItemStack item;
private final boolean manual;
private boolean cancelled;
public VoucherRedeemEvent(Player player, String voucher, ItemStack item, boolean manual) {
this.player = player;
this.voucher = voucher;
this.item = item;
this.manual = manual;
this.cancelled = false;
}
public VoucherRedeemEvent(Player player, String voucher, ItemStack item, boolean manual) {
this.player = player;
this.voucher = voucher;
this.item = item;
this.manual = manual;
this.cancelled = false;
}
public Player getPlayer() {
return player;
}
public Player getPlayer() {
return player;
}
public String getVoucher() {
return voucher;
}
public String getVoucher() {
return voucher;
}
public ItemStack getItem() {
return item;
}
public ItemStack getItem() {
return item;
}
public boolean getManual() {
return manual;
}
public boolean getManual() {
return manual;
}
public boolean isCancelled() {
return cancelled;
}
public boolean isCancelled() {
return cancelled;
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public HandlerList getHandlers() {
return handlers;
}
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
}

View File

@ -1,7 +1,7 @@
package com.songoda.epicvouchers.handlers;
import com.songoda.core.utils.TextUtils;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.epicvouchers.utils.Methods;
import org.bukkit.entity.Player;
import java.sql.*;
@ -28,9 +28,9 @@ public class Connections {
connection = DriverManager.getConnection("jdbc:mysql://" + mysqlIP + ":" + mysqlPort + "/" + mysqlDatabase + "?useSSL=true?autoReconnect=true", mysqlUsername, mysqlPassword);
System.out.println(Methods.format("&fSuccessfully created a connection with MySQL."));
System.out.println(TextUtils.formatText("&fSuccessfully created a connection with MySQL."));
} catch (Exception error) {
System.out.println(Methods.format("&cFailed to create a connection with MySQL."));
System.out.println(TextUtils.formatText("&cFailed to create a connection with MySQL."));
error.printStackTrace();
}
}
@ -41,9 +41,9 @@ public class Connections {
}
try {
connection.close();
System.out.println(Methods.format("&fSuccessfully closed the MySQL connection."));
System.out.println(TextUtils.formatText("&fSuccessfully closed the MySQL connection."));
} catch (Exception error) {
System.out.println(Methods.format("&cFailed to close the MySQL connection."));
System.out.println(TextUtils.formatText("&cFailed to close the MySQL connection."));
error.printStackTrace();
}
}
@ -60,9 +60,9 @@ public class Connections {
statement.execute("CREATE TABLE IF NOT EXISTS redeems (id INT NOT NULL AUTO_INCREMENT, player varchar(120) NOT NULL, voucher varchar(120) NOT NULL, timestamp varchar(120) NOT NULL, PRIMARY KEY (ID));");
statement.execute("INSERT INTO redeems VALUES (default, '" + player.getName() + "', '" + voucher + "', '" + time + "');");
statement.close();
System.out.println(Methods.format("&fSuccessfully saved the redeem in the MySQL database."));
System.out.println(TextUtils.formatText("&fSuccessfully saved the redeem in the MySQL database."));
} catch (Exception error) {
System.out.println(Methods.format("&cFailed to save the redeem data in the MySQL database."));
System.out.println(TextUtils.formatText("&cFailed to save the redeem data in the MySQL database."));
error.printStackTrace();
}
}

View File

@ -1,282 +0,0 @@
package com.songoda.epicvouchers.libraries;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.epicvouchers.utils.NMSUtil;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class AbstractAnvilGUI {
private static Class<?> BlockPositionClass;
private static Class<?> PacketPlayOutOpenWindowClass;
private static Class<?> IChatBaseComponentClass;
private static Class<?> ICraftingClass;
private static Class<?> ContainerAnvilClass;
private static Class<?> ChatMessageClass;
private static Class<?> EntityHumanClass;
private static Class<?> ContainerClass;
private static Class<?> ContainerAccessClass;
private static Class<?> WorldClass;
private static Class<?> PlayerInventoryClass;
private static Class<?> ContainersClass;
private Player player;
private Map<AnvilSlot, ItemStack> items = new HashMap<>();
private Inventory inv;
private Listener listener;
static {
BlockPositionClass = NMSUtil.getNMSClass("BlockPosition");
PacketPlayOutOpenWindowClass = NMSUtil.getNMSClass("PacketPlayOutOpenWindow");
IChatBaseComponentClass = NMSUtil.getNMSClass("IChatBaseComponent");
ICraftingClass = NMSUtil.getNMSClass("ICrafting");
ContainerAnvilClass = NMSUtil.getNMSClass("ContainerAnvil");
EntityHumanClass = NMSUtil.getNMSClass("EntityHuman");
ChatMessageClass = NMSUtil.getNMSClass("ChatMessage");
ContainerClass = NMSUtil.getNMSClass("Container");
WorldClass = NMSUtil.getNMSClass("World");
PlayerInventoryClass = NMSUtil.getNMSClass("PlayerInventory");
if (NMSUtil.getVersionNumber() > 13) {
ContainerAccessClass = NMSUtil.getNMSClass("ContainerAccess");
ContainersClass = NMSUtil.getNMSClass("Containers");
}
}
public AbstractAnvilGUI(EpicVouchers instance, final Player player, final AnvilClickEventHandler handler) {
this.player = player;
this.listener = new Listener() {
@EventHandler(priority = EventPriority.LOWEST)
public void onInventoryClick(InventoryClickEvent event) {
if (event.getWhoClicked() instanceof Player) {
if (event.getInventory().equals(inv)) {
event.setCancelled(true);
ItemStack item = event.getCurrentItem();
int slot = event.getRawSlot();
String name = "";
if (item != null) {
if (item.hasItemMeta()) {
ItemMeta meta = item.getItemMeta();
if (meta != null && meta.hasDisplayName()) {
name = meta.getDisplayName();
}
}
}
AnvilClickEvent clickEvent = new AnvilClickEvent(AnvilSlot.bySlot(slot), name);
handler.onAnvilClick(clickEvent);
if (clickEvent.getWillClose()) {
event.getWhoClicked().closeInventory();
}
if (clickEvent.getWillDestroy()) {
destroy();
}
}
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onInventoryClose(InventoryCloseEvent event) {
if (event.getPlayer() instanceof Player) {
Inventory inv = event.getInventory();
player.setLevel(player.getLevel() - 1);
if (inv.equals(inv)) {
inv.clear();
destroy();
}
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerQuit(PlayerQuitEvent event) {
if (event.getPlayer().equals(getPlayer())) {
player.setLevel(player.getLevel() - 1);
destroy();
}
}
};
Bukkit.getPluginManager().registerEvents(listener, instance);
}
public Player getPlayer() {
return player;
}
public void setSlot(AnvilSlot slot, ItemStack item) {
items.put(slot, item);
}
public void open() {
player.setLevel(player.getLevel() + 1);
try {
Object craftPlayer = NMSUtil.getCraftClass("entity.CraftPlayer").cast(player);
Method getHandleMethod = craftPlayer.getClass().getMethod("getHandle");
Object entityPlayer = getHandleMethod.invoke(craftPlayer);
Object playerInventory = NMSUtil.getFieldObject(entityPlayer, NMSUtil.getField(entityPlayer.getClass(), "inventory", false));
Object world = NMSUtil.getFieldObject(entityPlayer, NMSUtil.getField(entityPlayer.getClass(), "world", false));
Object blockPosition = BlockPositionClass.getConstructor(int.class, int.class, int.class).newInstance(0, 0, 0);
Object container;
if (NMSUtil.getVersionNumber() > 13) {
container = ContainerAnvilClass
.getConstructor(int.class, PlayerInventoryClass, ContainerAccessClass)
.newInstance(7, playerInventory, ContainerAccessClass.getMethod("at", WorldClass, BlockPositionClass).invoke(null, world, blockPosition));
} else {
container = ContainerAnvilClass
.getConstructor(PlayerInventoryClass, WorldClass, BlockPositionClass, EntityHumanClass)
.newInstance(playerInventory, world, blockPosition, entityPlayer);
}
NMSUtil.getField(ContainerClass, "checkReachable", true).set(container, false);
Method getBukkitViewMethod = container.getClass().getMethod("getBukkitView");
Object bukkitView = getBukkitViewMethod.invoke(container);
Method getTopInventoryMethod = bukkitView.getClass().getMethod("getTopInventory");
inv = (Inventory) getTopInventoryMethod.invoke(bukkitView);
for (AnvilSlot slot : items.keySet()) {
inv.setItem(slot.getSlot(), items.get(slot));
}
Method nextContainerCounterMethod = entityPlayer.getClass().getMethod("nextContainerCounter");
int c = (int) nextContainerCounterMethod.invoke(entityPlayer);
Constructor<?> chatMessageConstructor = ChatMessageClass.getConstructor(String.class, Object[].class);
Object inventoryTitle = chatMessageConstructor.newInstance("Repairing", new Object[]{});
Object packet;
if (NMSUtil.getVersionNumber() > 13) {
packet = PacketPlayOutOpenWindowClass
.getConstructor(int.class, ContainersClass, IChatBaseComponentClass)
.newInstance(c, ContainersClass.getField("ANVIL").get(null), inventoryTitle);
} else {
packet = PacketPlayOutOpenWindowClass
.getConstructor(int.class, String.class, IChatBaseComponentClass, int.class)
.newInstance(c, "minecraft:anvil", inventoryTitle, 0);
}
NMSUtil.sendPacket(player, packet);
Field activeContainerField = NMSUtil.getField(EntityHumanClass, "activeContainer", true);
if (activeContainerField != null) {
activeContainerField.set(entityPlayer, container);
NMSUtil.getField(ContainerClass, "windowId", true).set(activeContainerField.get(entityPlayer), c);
Method addSlotListenerMethod = activeContainerField.get(entityPlayer).getClass().getMethod("addSlotListener", ICraftingClass);
addSlotListenerMethod.invoke(activeContainerField.get(entityPlayer), entityPlayer);
if (NMSUtil.getVersionNumber() > 13) {
ContainerClass.getMethod("setTitle", IChatBaseComponentClass).invoke(container, inventoryTitle);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void destroy() {
player = null;
items = null;
HandlerList.unregisterAll(listener);
listener = null;
}
public enum AnvilSlot {
INPUT_LEFT(0),
INPUT_RIGHT(1),
OUTPUT(2);
private int slot;
AnvilSlot(int slot) {
this.slot = slot;
}
public static AnvilSlot bySlot(int slot) {
for (AnvilSlot anvilSlot : values()) {
if (anvilSlot.getSlot() == slot) {
return anvilSlot;
}
}
return null;
}
public int getSlot() {
return slot;
}
}
@FunctionalInterface
public interface AnvilClickEventHandler {
void onAnvilClick(AnvilClickEvent event);
}
public class AnvilClickEvent {
private AnvilSlot slot;
private String name;
private boolean close = true;
private boolean destroy = true;
public AnvilClickEvent(AnvilSlot slot, String name) {
this.slot = slot;
this.name = name;
}
public AnvilSlot getSlot() {
return slot;
}
public String getName() {
return name;
}
public boolean getWillClose() {
return close;
}
public void setWillClose(boolean close) {
this.close = close;
}
public boolean getWillDestroy() {
return destroy;
}
public void setWillDestroy(boolean destroy) {
this.destroy = destroy;
}
}
}

View File

@ -1,13 +1,11 @@
package com.songoda.epicvouchers.libraries.inventory;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.epicvouchers.libraries.ItemBuilder;
import com.songoda.epicvouchers.menus.ActionMenu;
import com.songoda.epicvouchers.utils.NMSUtil;
import com.songoda.epicvouchers.utils.ServerVersion;
import com.songoda.epicvouchers.voucher.Voucher;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
@ -19,7 +17,8 @@ import java.util.stream.IntStream;
import static org.bukkit.ChatColor.GRAY;
import static org.bukkit.ChatColor.YELLOW;
import static org.bukkit.Material.*;
import static org.bukkit.Material.ARROW;
import static org.bukkit.Material.BARRIER;
public abstract class PlayersMenu extends FastInv {
private final int SLOTS = 17;
@ -53,7 +52,7 @@ public abstract class PlayersMenu extends FastInv {
Player player = players.get(index);
ItemStack itemStack = new ItemStack(NMSUtil.getVersionNumber() > 12 ? PLAYER_HEAD : Material.valueOf("SKULL_ITEM"));
ItemStack itemStack = CompatibleMaterial.PLAYER_HEAD.getItem();
SkullMeta skullMeta = (SkullMeta) itemStack.getItemMeta();
@ -96,8 +95,7 @@ public abstract class PlayersMenu extends FastInv {
}
if (instance.getConfig().getBoolean("Interface.Fill Interfaces With Glass")) {
ItemStack fillItem = instance.getServerVersion().isServerVersionAtLeast(ServerVersion.V1_13) ? new ItemStack(Material.valueOf("GRAY_STAINED_GLASS_PANE")) :
new ItemStack(Material.valueOf("STAINED_GLASS_PANE"), 1, (short) 7);
ItemStack fillItem = CompatibleMaterial.GRAY_STAINED_GLASS_PANE.getItem();
IntStream.rangeClosed(SLOTS + 1, 26).forEach(slot -> {
if (getInventory().getItem(slot) == null)

View File

@ -1,7 +1,7 @@
package com.songoda.epicvouchers.libraries.inventory.icons;
import com.songoda.core.gui.AnvilGui;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.epicvouchers.libraries.AbstractAnvilGUI;
import com.songoda.epicvouchers.libraries.ItemBuilder;
import com.songoda.epicvouchers.utils.Pair;
import org.bukkit.entity.Player;
@ -9,7 +9,6 @@ import org.bukkit.event.inventory.ClickType;
import java.util.function.BiConsumer;
import static com.songoda.epicvouchers.libraries.AbstractAnvilGUI.AnvilSlot.INPUT_LEFT;
import static org.bukkit.ChatColor.GRAY;
import static org.bukkit.ChatColor.YELLOW;
import static org.bukkit.Material.PAPER;
@ -23,12 +22,12 @@ public class ListEntryIcon extends Icon {
return;
}
AbstractAnvilGUI anvilGUI = new AbstractAnvilGUI(instance, event.getPlayer(), anvilEvent -> onEdit.accept(event.getPlayer(), new Pair<String, String>(entry, anvilEvent.getName())));
anvilGUI.setSlot(INPUT_LEFT, new ItemBuilder(PAPER).name(entry).build());
anvilGUI.open();
});
AnvilGui gui = new AnvilGui(event.getPlayer());
gui.setTitle("Current: " + entry);
gui.setAction(aevent -> onEdit.accept(event.getPlayer(), new Pair<>(entry, gui.getInputText().trim())));
instance.getGuiManager().showGUI(event.getPlayer(), gui);
});
}
}
}

View File

@ -1,9 +1,10 @@
package com.songoda.epicvouchers.libraries.inventory.icons;
import com.songoda.core.compatibility.ServerVersion;
import com.songoda.core.gui.AnvilGui;
import com.songoda.core.utils.TextUtils;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.epicvouchers.libraries.AbstractAnvilGUI;
import com.songoda.epicvouchers.libraries.ItemBuilder;
import com.songoda.epicvouchers.utils.ServerVersion;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
@ -13,8 +14,6 @@ import org.bukkit.inventory.ItemStack;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
import static com.songoda.epicvouchers.libraries.AbstractAnvilGUI.AnvilSlot.INPUT_LEFT;
import static com.songoda.epicvouchers.utils.Methods.format;
import static org.bukkit.ChatColor.GRAY;
import static org.bukkit.ChatColor.WHITE;
@ -30,12 +29,12 @@ public class StringIcon extends Icon {
}
public StringIcon(EpicVouchers instance, String string, String current, BiConsumer<Player, String> consumer, Predicate<String> predicate) {
this(instance, new ItemBuilder(instance.getServerVersion().isServerVersionAtLeast(ServerVersion.V1_14) ? Material.OAK_SIGN : Material.valueOf("SIGN")).name(ChatColor.YELLOW + string)
this(instance, new ItemBuilder(ServerVersion.isServerVersionAtLeast(ServerVersion.V1_14) ? Material.OAK_SIGN : Material.valueOf("SIGN")).name(ChatColor.YELLOW + string)
.lore(GRAY + "Current: " + WHITE + current, GRAY + "Right click to edit", GRAY + "Left click to clear").build(), current, consumer, predicate, false);
}
public StringIcon(EpicVouchers instance, String string, String current, BiConsumer<Player, String> consumer, Predicate<String> predicate, boolean noLeft) {
this(instance, new ItemBuilder(instance.getServerVersion().isServerVersionAtLeast(ServerVersion.V1_14) ? Material.OAK_SIGN : Material.valueOf("SIGN")).name(ChatColor.YELLOW + string)
this(instance, new ItemBuilder(ServerVersion.isServerVersionAtLeast(ServerVersion.V1_14) ? Material.OAK_SIGN : Material.valueOf("SIGN")).name(ChatColor.YELLOW + string)
.lore(GRAY + "Current: " + WHITE + current, GRAY + "Right click to edit", GRAY + "Left click to clear").build(), current, consumer, predicate, noLeft);
}
@ -47,18 +46,20 @@ public class StringIcon extends Icon {
super(itemStack, event -> {
if (!noLeft && event.getClickType() == ClickType.LEFT) {
consumer.accept(event.getPlayer(), "");
event.getPlayer().sendMessage(format("&7Successfully cleared&7."));
event.getPlayer().sendMessage(TextUtils.formatText("&7Successfully cleared&7."));
} else {
AbstractAnvilGUI anvilGUI = new AbstractAnvilGUI(instance, event.getPlayer(), anvilEvent -> {
if (!predicate.test(anvilEvent.getName())) {
event.getPlayer().sendMessage(format("&cFailed to set value to: " + anvilEvent.getName()));
AnvilGui gui = new AnvilGui(event.getPlayer());
gui.setTitle("current:" + current);
gui.setAction(aevent -> {
final String msg = gui.getInputText().trim();
if (!predicate.test(msg)) {
event.getPlayer().sendMessage(TextUtils.formatText("&cFailed to set value to: " + msg));
return;
}
consumer.accept(event.getPlayer(), anvilEvent.getName());
event.getPlayer().sendMessage(format("&7Successfully set to &r{changed}&7.", "{changed}", anvilEvent.getName()));
consumer.accept(event.getPlayer(), msg);
event.getPlayer().sendMessage(TextUtils.formatText("&7Successfully set to &r" + msg + "&7."));
});
anvilGUI.setSlot(INPUT_LEFT, new ItemBuilder(instance.getServerVersion().isServerVersionAtLeast(ServerVersion.V1_14) ? Material.OAK_SIGN : Material.valueOf("SIGN")).name(current).build());
anvilGUI.open();
instance.getGuiManager().showGUI(event.getPlayer(), gui);
}
});

View File

@ -3,6 +3,8 @@ package com.songoda.epicvouchers.listeners;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.epicvouchers.menus.ConfirmMenu;
import com.songoda.epicvouchers.voucher.Voucher;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
@ -29,17 +31,17 @@ public class PlayerInteractListener implements Listener {
final Player player = event.getPlayer();
for (Voucher voucher : instance.getVouchers().values()) {
final ItemStack voucherItem = voucher.getItemStack();
final ItemStack voucherItem = voucher.toItemStack();
// does the item they're holding match this voucher?
if (voucherItem != null && !voucher.getItemStack().isSimilar(item))
continue;
else if (item.getType() != voucher.getMaterial() || item.getDurability() != voucher.getData())
continue;
if (voucherItem != null && !voucherItem.isSimilar(item)) continue;
else if (item.getType() != voucher.getMaterial() || item.getDurability() != voucher.getData()) continue;
else {
// material matches - verify the name + lore
final ItemMeta meta = item.getItemMeta();
if (meta == null || !meta.hasDisplayName() || !meta.hasLore() || !meta.getDisplayName().equals(voucher.getName(true)) || !meta.getLore().equals(voucher.getLore(true)))
if (meta == null || !meta.hasDisplayName()
|| !ChatColor.stripColor(meta.getDisplayName()).equals(ChatColor.stripColor(voucher.getName(true)))
|| (meta.hasLore() && !meta.getLore().equals(voucher.getLore(true))))
continue;
}

View File

@ -1,11 +1,12 @@
package com.songoda.epicvouchers.menus;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.utils.TextUtils;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.epicvouchers.libraries.ItemBuilder;
import com.songoda.epicvouchers.libraries.inventory.FastInv;
import com.songoda.epicvouchers.menus.sub.action.ForceMenu;
import com.songoda.epicvouchers.menus.sub.action.GiveMenu;
import com.songoda.epicvouchers.utils.ServerVersion;
import com.songoda.epicvouchers.voucher.Voucher;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
@ -14,7 +15,6 @@ import org.bukkit.inventory.ItemStack;
import java.util.ArrayList;
import static com.songoda.epicvouchers.utils.Methods.format;
import static org.bukkit.ChatColor.GRAY;
import static org.bukkit.ChatColor.YELLOW;
import static org.bukkit.Material.BARRIER;
@ -25,21 +25,21 @@ public class ActionMenu extends FastInv {
super(27, "Give menu");
addItem(10, new ItemBuilder(Material.FEATHER)
.name(format("&6Give voucher"))
.lore(format("&eGive the voucher to a"),
format("&especific player."))
.name(TextUtils.formatText("&6Give voucher"))
.lore(TextUtils.formatText("&eGive the voucher to a"),
TextUtils.formatText("&especific player."))
.build(), event -> new GiveMenu(instance, voucher).open(event.getPlayer()));
addItem(14, new ItemBuilder(Material.ANVIL)
.name(format("&6Force voucher"))
.lore(format("&eForce the redeeming of the"),
format("&evoucher on a specific player."))
.name(TextUtils.formatText("&6Force voucher"))
.lore(TextUtils.formatText("&eForce the redeeming of the"),
TextUtils.formatText("&evoucher on a specific player."))
.build(), event -> new ForceMenu(instance, voucher).open(event.getPlayer()));
addItem(12, new ItemBuilder(Material.FEATHER)
.name(format("&6Give all voucher"))
.lore(format("&eGive the voucher to all"),
format("&eonline players."))
.name(TextUtils.formatText("&6Give all voucher"))
.lore(TextUtils.formatText("&eGive the voucher to all"),
TextUtils.formatText("&eonline players."))
.build(), event -> new ConfirmMenu(instance,
() -> {
voucher.giveAll(event.getPlayer(), 1);
@ -47,9 +47,9 @@ public class ActionMenu extends FastInv {
}, () -> open(event.getPlayer())).open(event.getPlayer()));
addItem(16, new ItemBuilder(Material.ANVIL)
.name(format("&6Force all voucher"))
.lore(format("&eForce the redeeming of the"),
format("&evoucher on all online players."))
.name(TextUtils.formatText("&6Force all voucher"))
.lore(TextUtils.formatText("&eForce the redeeming of the"),
TextUtils.formatText("&evoucher on all online players."))
.build(), event -> new ConfirmMenu(instance,
() -> {
voucher.forceRedeem(event.getPlayer(), new ArrayList<>(Bukkit.getOnlinePlayers()), 1);
@ -62,8 +62,7 @@ public class ActionMenu extends FastInv {
.addGlow().build(), event -> new VoucherMenu(instance).open(event.getPlayer()));
if (instance.getConfig().getBoolean("Interface.Fill Interfaces With Glass")) {
ItemStack fillItem = instance.getServerVersion().isServerVersionAtLeast(ServerVersion.V1_13) ? new ItemStack(Material.valueOf("GRAY_STAINED_GLASS_PANE")) :
new ItemStack(Material.valueOf("STAINED_GLASS_PANE"), 1, (short) 7);
ItemStack fillItem = CompatibleMaterial.GRAY_STAINED_GLASS_PANE.getItem();
fill(new ItemBuilder(fillItem).name(ChatColor.RESET.toString()).build());
}

View File

@ -1,9 +1,10 @@
package com.songoda.epicvouchers.menus;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.compatibility.ServerVersion;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.epicvouchers.libraries.ItemBuilder;
import com.songoda.epicvouchers.libraries.inventory.FastInv;
import com.songoda.epicvouchers.utils.ServerVersion;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
@ -12,6 +13,7 @@ import static org.bukkit.enchantments.Enchantment.DURABILITY;
import static org.bukkit.inventory.ItemFlag.HIDE_ENCHANTS;
public class ConfirmMenu extends FastInv {
public ConfirmMenu(EpicVouchers instance, Runnable success, Runnable failure) {
super(27, instance.getLocale().getMessage("interface.confirmsettings.title").getMessage());
@ -34,8 +36,7 @@ public class ConfirmMenu extends FastInv {
});
if (instance.getConfig().getBoolean("Interface.Fill Interfaces With Glass")) {
ItemStack fillItem = instance.getServerVersion().isServerVersionAtLeast(ServerVersion.V1_13) ? new ItemStack(Material.valueOf("GRAY_STAINED_GLASS_PANE")) :
new ItemStack(Material.valueOf("STAINED_GLASS_PANE"), 1, (short) 7);
ItemStack fillItem = CompatibleMaterial.GRAY_STAINED_GLASS_PANE.getItem();
fill(new ItemBuilder(fillItem).name(ChatColor.RESET.toString()).build());
}

View File

@ -1,15 +1,16 @@
package com.songoda.epicvouchers.menus;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.core.compatibility.ServerVersion;
import com.songoda.core.utils.TextUtils;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.epicvouchers.libraries.ItemBuilder;
import com.songoda.epicvouchers.libraries.inventory.FastInv;
import com.songoda.epicvouchers.menus.sub.editor.SetItemMenu;
import com.songoda.epicvouchers.utils.ServerVersion;
import com.songoda.epicvouchers.voucher.Voucher;
import org.bukkit.ChatColor;
import org.bukkit.inventory.ItemStack;
import static com.songoda.epicvouchers.utils.Methods.format;
import static org.bukkit.ChatColor.GRAY;
import static org.bukkit.ChatColor.YELLOW;
import static org.bukkit.Material.*;
@ -19,7 +20,7 @@ public class OptionMenu extends FastInv {
public OptionMenu(EpicVouchers instance, Voucher voucher) {
super(27, "Options: " + voucher.getKey());
addItem(13, new ItemBuilder(voucher.toItemStack()).name(format(voucher.getName(true))).build());
addItem(13, new ItemBuilder(voucher.toItemStack()).name(TextUtils.formatText(voucher.getName(true))).build());
addItem(18, new ItemBuilder(BARRIER)
.name(YELLOW + "Return")
@ -27,24 +28,22 @@ public class OptionMenu extends FastInv {
.addGlow().build(), event -> new VoucherMenu(instance).open(event.getPlayer()));
addItem(0, new ItemBuilder(FEATHER)
.name(format("&6Voucher actions"))
.lore(format("&eGive or redeem your voucher"))
.name(TextUtils.formatText("&6Voucher actions"))
.lore(TextUtils.formatText("&eGive or redeem your voucher"))
.addGlow()
.build(), event -> new ActionMenu(instance, voucher).open(event.getPlayer()));
addItem(26, new ItemBuilder(STONE)
.name(format("&6Set item"))
.lore(format("&eSet the item of your voucher."))
.name(TextUtils.formatText("&6Set item"))
.lore(TextUtils.formatText("&eSet the item of your voucher."))
.addGlow().build(), event -> new SetItemMenu(instance, voucher).open(event.getPlayer()));
addItem(8, new ItemBuilder(BOOK)
.name(format("&6Change all options"))
.lore(format("&eSet the options of your voucher."))
.name(TextUtils.formatText("&6Change all options"))
.lore(TextUtils.formatText("&eSet the options of your voucher."))
.build(), event -> new VoucherEditorMenu(instance, voucher).open(event.getPlayer()));
fill(new ItemBuilder(instance.getServerVersion().isServerVersionAtLeast(ServerVersion.V1_13) ?
new ItemStack(valueOf("GRAY_STAINED_GLASS_PANE")) :
new ItemStack(valueOf("STAINED_GLASS_PANE"), 1, (short) 7)).name(ChatColor.RESET.toString()).build());
fill(new ItemBuilder(CompatibleMaterial.GRAY_STAINED_GLASS_PANE.getItem()).name(ChatColor.RESET.toString()).build());
}
}

View File

@ -1,24 +1,23 @@
package com.songoda.epicvouchers.menus;
import com.songoda.core.compatibility.ServerVersion;
import com.songoda.core.gui.AnvilGui;
import com.songoda.core.utils.TextUtils;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.epicvouchers.libraries.AbstractAnvilGUI;
import com.songoda.epicvouchers.libraries.ItemBuilder;
import com.songoda.epicvouchers.libraries.inventory.IconInv;
import com.songoda.epicvouchers.libraries.inventory.icons.Icon;
import com.songoda.epicvouchers.utils.ServerVersion;
import com.songoda.epicvouchers.voucher.Voucher;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import static com.songoda.epicvouchers.libraries.AbstractAnvilGUI.AnvilSlot.INPUT_LEFT;
import static com.songoda.epicvouchers.utils.Methods.format;
import static org.bukkit.Material.PAPER;
public class VoucherMenu extends IconInv {
public VoucherMenu(EpicVouchers instance) {
super((int) (Math.ceil(instance.getVouchers().size() / 9.0) * 9 + (instance.getVouchers().size() % 9 == 0 ? 9 : 0)), "Vouchers");
super((int) (Math.ceil(instance.getVouchers().size() / 9.0) * 9 + (instance.getVouchers().size() % 9 == 0 ? 9 : 0)), "Vouchers");
for (Voucher voucher : instance.getVouchers().values()) {
if (getInventory().firstEmpty() != -1) {
@ -27,31 +26,33 @@ public class VoucherMenu extends IconInv {
}
addIcon(getInventory().getSize() - 1, new Icon(new ItemBuilder(PAPER)
.name(format("&6New voucher"))
.lore(format("&eCreate a new voucher with set id.")).build(), event -> {
AbstractAnvilGUI anvilGUI = new AbstractAnvilGUI(instance, event.getPlayer(), anvilEvent -> {
if (instance.getVouchers().containsKey(anvilEvent.getName())) {
event.getPlayer().sendMessage(format("&cAlready a voucher registered with the id: " + anvilEvent.getName()));
.name(TextUtils.formatText("&6New voucher"))
.lore(TextUtils.formatText("&eCreate a new voucher with set id.")).build(), event -> {
AnvilGui gui = new AnvilGui(event.getPlayer());
gui.setTitle("Insert id");
gui.setAction(aevent -> {
final String msg = gui.getInputText().trim();
if (instance.getVouchers().containsKey(msg)) {
event.getPlayer().sendMessage(TextUtils.formatText("&cAlready a voucher registered with the id: " + msg));
new VoucherMenu(instance).open(event.getPlayer());
return;
}
Voucher voucher = new Voucher(anvilEvent.getName(), instance);
Voucher voucher = new Voucher(msg, instance);
voucher.setMaterial(PAPER);
voucher.setName("&f" + anvilEvent.getName());
voucher.setName("&f" + msg);
instance.getVouchers().put(anvilEvent.getName(), voucher);
instance.getVouchersFile().getConfig().set("vouchers." + anvilEvent.getName() + ".material", voucher.getMaterial().toString());
instance.getVouchersFile().getConfig().set("vouchers." + anvilEvent.getName() + ".name", voucher.getName(false));
instance.getVouchersFile().saveConfig();
event.getPlayer().sendMessage(format("&7Successfully created voucher with id &r{id}&7.", "{id}", anvilEvent.getName()));
instance.getVouchers().put(msg, voucher);
instance.getConfig().set("vouchers." + msg + ".material", voucher.getMaterial().toString());
instance.getConfig().set("vouchers." + msg + ".name", voucher.getName(false));
instance.getVouchersConfig().save();
event.getPlayer().sendMessage(TextUtils.formatText("&7Successfully created voucher with id &r" + msg + "&7."));
new VoucherMenu(instance).open(event.getPlayer());
});
anvilGUI.setSlot(INPUT_LEFT, new ItemBuilder(PAPER).name("Insert id").build());
anvilGUI.open();
instance.getGuiManager().showGUI(event.getPlayer(), gui);
}));
fill(new Icon(new ItemBuilder(instance.getServerVersion().isServerVersionAtLeast(ServerVersion.V1_13) ?
fill(new Icon(new ItemBuilder(ServerVersion.isServerVersionAtLeast(ServerVersion.V1_13) ?
new ItemStack(Material.valueOf("GRAY_STAINED_GLASS_PANE")) :
new ItemStack(Material.valueOf("STAINED_GLASS_PANE"), 1, (short) 7)).name(ChatColor.RESET.toString()).build()));
}

View File

@ -1,10 +1,10 @@
package com.songoda.epicvouchers.menus.sub.editor;
import com.songoda.core.compatibility.CompatibleMaterial;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.epicvouchers.libraries.ItemBuilder;
import com.songoda.epicvouchers.libraries.inventory.FastInv;
import com.songoda.epicvouchers.menus.OptionMenu;
import com.songoda.epicvouchers.utils.ServerVersion;
import com.songoda.epicvouchers.voucher.Voucher;
import org.bukkit.ChatColor;
import org.bukkit.Material;
@ -21,9 +21,7 @@ public class SetItemMenu extends FastInv {
setDefaultCancel(false);
fill(new ItemBuilder(instance.getServerVersion().isServerVersionAtLeast(ServerVersion.V1_13) ?
new ItemStack(Material.valueOf("GRAY_STAINED_GLASS_PANE")) :
new ItemStack(Material.valueOf("STAINED_GLASS_PANE"), 1, (short) 7))
fill(new ItemBuilder(CompatibleMaterial.GRAY_STAINED_GLASS_PANE.getItem())
.name(ChatColor.RESET.toString()).build(), event -> event.setCancelled(true));
addItem(13, null);
@ -48,7 +46,7 @@ public class SetItemMenu extends FastInv {
ItemStack itemStack = event.getInventory().getInventory().getItem(13);
if(event.getClickType() == ClickType.RIGHT) {
if (event.getClickType() == ClickType.RIGHT) {
new OptionMenu(instance, voucher).open(event.getPlayer());
voucher.setName("");
voucher.setLore(null);

View File

@ -1,19 +1,17 @@
package com.songoda.epicvouchers.menus.sub.editor;
import com.songoda.core.gui.AnvilGui;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.epicvouchers.libraries.AbstractAnvilGUI;
import com.songoda.epicvouchers.libraries.ItemBuilder;
import com.songoda.epicvouchers.libraries.inventory.IconInv;
import com.songoda.epicvouchers.libraries.inventory.icons.ListEntryIcon;
import com.songoda.epicvouchers.menus.VoucherEditorMenu;
import com.songoda.epicvouchers.voucher.Voucher;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import java.util.List;
import java.util.stream.Collectors;
import static com.songoda.epicvouchers.libraries.AbstractAnvilGUI.AnvilSlot.INPUT_LEFT;
import static org.bukkit.ChatColor.*;
import static org.bukkit.Material.PAPER;
@ -34,14 +32,13 @@ public class StringListMenu extends IconInv {
.build());
addIcon(size - 1, new ItemBuilder(PAPER).name(GREEN + "Add to list").build(), event -> {
AbstractAnvilGUI anvilGUI = new AbstractAnvilGUI(instance, event.getPlayer(), anvilEvent -> {
list.add(anvilEvent.getName());
AnvilGui gui = new AnvilGui(event.getPlayer());
gui.setAction(aevent -> {
list.add(gui.getInputText().trim());
voucher.saveSetting(key.toLowerCase(), list);
new StringListMenu(instance, key, list, toEdit, voucher).open(event.getPlayer());
});
anvilGUI.setSlot(INPUT_LEFT, new ItemStack(PAPER));
anvilGUI.open();
instance.getGuiManager().showGUI(event.getPlayer(), gui);
});
for (int i = 0; i < list.size(); i++) {

View File

@ -0,0 +1,34 @@
package com.songoda.epicvouchers.settings;
import com.songoda.core.configuration.Config;
import com.songoda.core.configuration.ConfigSetting;
import com.songoda.epicvouchers.EpicVouchers;
import org.bukkit.event.Listener;
/**
* Created by songo on 6/4/2017.
*/
public class Settings implements Listener {
static final Config config = EpicVouchers.getInstance().getCoreConfig();
public static final ConfigSetting FILL_GLASS = new ConfigSetting(config, "Interface.Fill Interfaces With Glass", true);
public static final ConfigSetting COOLDOWN_DELAY = new ConfigSetting(config, "Main.Cooldown Delay", 10);
public static final ConfigSetting DATABASE_SUPPORT = new ConfigSetting(config, "Database.Activate Mysql Support", false);
public static final ConfigSetting DATABASE_IP = new ConfigSetting(config, "Database.IP", "127.0.0.1");
public static final ConfigSetting DATABASE_PORT = new ConfigSetting(config, "Database.Port", 3306);
public static final ConfigSetting DATABASE_NAME = new ConfigSetting(config, "Database.Database Name", "EpicVouchers");
public static final ConfigSetting DATABASE_USERNAME = new ConfigSetting(config, "Database.Username", "PUT_USERNAME_HERE");
public static final ConfigSetting DATABASE_PASSWORD = new ConfigSetting(config, "Database.Password", "PUT_PASSWORD_HERE");
public static final ConfigSetting LANGUGE_MODE = new ConfigSetting(config, "System.Language Mode", "en_US",
"The enabled language file.",
"More language files (if available) can be found in the plugins data folder.");
public static void setupConfig() {
config.load();
config.setAutoremove(true).setAutosave(true);
config.saveChanges();
}
}

View File

@ -1,67 +0,0 @@
package com.songoda.epicvouchers.utils;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
/**
* ConfigWrapper made by @clip
*/
public class ConfigWrapper {
private final JavaPlugin plugin;
private FileConfiguration config;
private File configFile;
private final String folderName, fileName;
public ConfigWrapper(final JavaPlugin instance, final String folderName, final String fileName) {
this.plugin = instance;
this.folderName = folderName;
this.fileName = fileName;
}
public void createNewFile(final String message, final String header) {
reloadConfig();
saveConfig();
loadConfig(header);
if (message != null) {
plugin.getLogger().info(message);
}
}
public FileConfiguration getConfig() {
if (config == null) {
reloadConfig();
}
return config;
}
public void loadConfig(final String header) {
config.options().header(header);
config.options().copyDefaults(true);
saveConfig();
}
public void reloadConfig() {
if (configFile == null) {
configFile = new File(plugin.getDataFolder() + folderName, fileName);
}
config = YamlConfiguration.loadConfiguration(configFile);
}
public void saveConfig() {
if (config == null || configFile == null) {
return;
}
try {
getConfig().save(configFile);
} catch (final IOException ex) {
plugin.getLogger().log(Level.SEVERE, "Could not save config to " + configFile, ex);
}
}
}

View File

@ -1,19 +0,0 @@
package com.songoda.epicvouchers.utils;
import org.bukkit.ChatColor;
import javax.annotation.Nullable;
public class Methods {
public static String format(String text) {
if (text == null || text.equals(""))
return "";
return format(text, "", null);
}
public static String format(String text, String toReplace, @Nullable Object object) {
return ChatColor.translateAlternateColorCodes('&', text).replace(toReplace, object == null ? "" : object.toString());
}
}

View File

@ -1,41 +0,0 @@
package com.songoda.epicvouchers.utils;
import org.apache.commons.lang.ArrayUtils;
public enum ServerVersion {
UNKNOWN("unknown_server_version"),
V1_7("org.bukkit.craftbukkit.v1_7"),
V1_8("org.bukkit.craftbukkit.v1_8"),
V1_9("org.bukkit.craftbukkit.v1_9"),
V1_10("org.bukkit.craftbukkit.v1_10"),
V1_11("org.bukkit.craftbukkit.v1_11"),
V1_12("org.bukkit.craftbukkit.v1_12"),
V1_13("org.bukkit.craftbukkit.v1_13"),
V1_14("org.bukkit.craftbukkit.v1_14");
private final String packagePrefix;
ServerVersion(String packagePrefix) {
this.packagePrefix = packagePrefix;
}
public static ServerVersion fromPackageName(String packageName) {
for (ServerVersion version : values())
if (packageName.startsWith(version.packagePrefix)) return version;
return ServerVersion.UNKNOWN;
}
public boolean isServerVersion(ServerVersion version) {
return this == version;
}
public boolean isServerVersion(ServerVersion... versions) {
return ArrayUtils.contains(versions, this);
}
public boolean isServerVersionAtLeast(ServerVersion version) {
return this.ordinal() >= version.ordinal();
}
}

View File

@ -1,48 +0,0 @@
package com.songoda.epicvouchers.utils;
import com.songoda.epicvouchers.EpicVouchers;
import org.bukkit.event.Listener;
/**
* Created by songo on 6/4/2017.
*/
public class SettingsManager implements Listener {
private final EpicVouchers instance;
public SettingsManager(EpicVouchers instance) {
this.instance = instance;
instance.getServer().getPluginManager().registerEvents(this, instance);
}
public void updateSettings() {
for (Settings s : Settings.values()) {
instance.getConfig().addDefault(s.setting, s.option);
}
}
public enum Settings {
CONFIRM_FILL_GLASS("Interface.Fill Interfaces With Glass", true),
COOLDOWN_DELAY("Main.Cooldown Delay", 10),
DATABASE_SUPPORT("Database.Activate Mysql Support", false),
DATABASE_IP("Database.IP", "127.0.0.1"),
DATABASE_PORT("Database.Port", 3306),
DATABASE_NAME("Database.Database Name", "EpicVouchers"),
DATABASE_USERNAME("Database.Username", "PUT_USERNAME_HERE"),
DATABASE_PASSWORD("Database.Password", "PUT_PASSWORD_HERE"),
LANGUGE_MODE("System.Language Mode", "en_US"),
DEBUGGER_ENABLED("System.Debugger Enabled", false);
private final String setting;
private final Object option;
Settings(String setting, Object option) {
this.setting = setting;
this.option = option;
}
}
}

View File

@ -1,302 +0,0 @@
package com.songoda.epicvouchers.utils.locale;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* Assists in the utilization of localization files.
* Created to be used by the Songoda Team.
*
* @author Brianna O'Keefe - Songoda
*/
public class Locale {
private static final List<Locale> LOCALES = new ArrayList<>();
private static final Pattern NODE_PATTERN = Pattern.compile("(\\w+(?:\\.{1}\\w+)*)\\s*=\\s*\"(.*)\"");
private static final String FILE_EXTENSION = ".lang";
private static JavaPlugin plugin;
private static File localeFolder;
private final Map<String, String> nodes = new HashMap<>();
private static String defaultLocale;
private File file;
private String name;
/**
* Instantiate the Locale class for future use
*
* @param name the name of the instantiated language
*/
private Locale(String name) {
if (plugin == null)
return;
this.name = name;
String fileName = name + FILE_EXTENSION;
this.file = new File(localeFolder, fileName);
if (!this.reloadMessages()) return;
plugin.getLogger().info("Loaded locale \"" + fileName + "\"");
}
/**
* Initialize the class to load all existing language files and update them.
* This must be called before any other methods in this class as otherwise
* the methods will fail to invoke
*
* @param plugin the plugin instance
* @param defaultLocale the default language
*/
public Locale(JavaPlugin plugin, String defaultLocale) {
Locale.plugin = plugin;
Locale.localeFolder = new File(plugin.getDataFolder(), "locales/");
if (!localeFolder.exists()) localeFolder.mkdirs();
//Save the default locale file.
Locale.defaultLocale = defaultLocale;
saveLocale(defaultLocale);
for (File file : localeFolder.listFiles()) {
String fileName = file.getName();
if (!fileName.endsWith(FILE_EXTENSION)) continue;
String name = fileName.substring(0, fileName.lastIndexOf('.'));
if (name.split("_").length != 2) continue;
if (localeLoaded(name)) continue;
LOCALES.add(new Locale(name));
}
}
/**
* Save a locale file from the InputStream, to the locale folder
*
* @param fileName the name of the file to save
* @return true if the operation was successful, false otherwise
*/
public static boolean saveLocale(String fileName) {
return saveLocale(plugin.getResource(defaultLocale + FILE_EXTENSION), fileName);
}
/**
* Save a locale file from the InputStream, to the locale folder
*
* @param in file to save
* @param fileName the name of the file to save
* @return true if the operation was successful, false otherwise
*/
public static boolean saveLocale(InputStream in, String fileName) {
if (!localeFolder.exists()) localeFolder.mkdirs();
if (!fileName.endsWith(FILE_EXTENSION))
fileName = (fileName.lastIndexOf(".") == -1 ? fileName : fileName.substring(0, fileName.lastIndexOf('.'))) + FILE_EXTENSION;
File destinationFile = new File(localeFolder, fileName);
if (destinationFile.exists())
return compareFiles(in, destinationFile);
try (OutputStream outputStream = new FileOutputStream(destinationFile)) {
copy(in, outputStream);
fileName = fileName.substring(0, fileName.lastIndexOf('.'));
if (fileName.split("_").length != 2) return false;
LOCALES.add(new Locale(fileName));
if (defaultLocale == null) defaultLocale = fileName;
return true;
} catch (IOException e) {
return false;
}
}
// Write new changes to existing files, if any at all
private static boolean compareFiles(InputStream in, File existingFile) {
InputStream defaultFile =
in == null ? plugin.getResource((defaultLocale != null ? defaultLocale : "en_US") + FILE_EXTENSION) : in;
boolean changed = false;
List<String> defaultLines, existingLines;
try (BufferedReader defaultReader = new BufferedReader(new InputStreamReader(defaultFile));
BufferedReader existingReader = new BufferedReader(new FileReader(existingFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(existingFile, true))) {
defaultLines = defaultReader.lines().collect(Collectors.toList());
existingLines = existingReader.lines().map(s -> s.split("\\s*=")[0]).collect(Collectors.toList());
for (String defaultValue : defaultLines) {
if (defaultValue.isEmpty() || defaultValue.startsWith("#")) continue;
String key = defaultValue.split("\\s*=")[0];
if (!existingLines.contains(key)) {
if (!changed) {
writer.newLine();
writer.newLine();
// Leave a note alerting the user of the newly added messages.
writer.write("# New messages for " + plugin.getName() + " v" + plugin.getDescription().getVersion() + ".");
// If changes were found outside of the default file leave a note explaining that.
if (in == null) {
writer.newLine();
writer.write("# These translations were found untranslated, join");
writer.newLine();
writer.write("# our translation Discord https://discord.gg/f7fpZEf");
writer.newLine();
writer.write("# to request an official update!");
}
}
writer.newLine();
writer.write(defaultValue);
changed = true;
}
}
if (in != null && !changed) compareFiles(null, existingFile);
} catch (IOException e) {
return false;
}
return changed;
}
/**
* Check whether a locale exists and is registered or not
*
* @param name the whole language tag (i.e. "en_US")
* @return true if it exists
*/
public static boolean localeLoaded(String name) {
for (Locale locale : LOCALES)
if (locale.getName().equals(name)) return true;
return false;
}
/**
* Get a locale by its entire proper name (i.e. "en_US")
*
* @param name the full name of the locale
* @return locale of the specified name
*/
public static Locale getLocale(String name) {
for (Locale locale : LOCALES)
if (locale.getName().equalsIgnoreCase(name)) return locale;
return null;
}
/**
* Clear the previous message cache and load new messages directly from file
*
* @return reload messages from file
*/
public boolean reloadMessages() {
if (!this.file.exists()) {
plugin.getLogger().warning("Could not find file for locale \"" + this.name + "\"");
return false;
}
this.nodes.clear(); // Clear previous data (if any)
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
for (int lineNumber = 0; (line = reader.readLine()) != null; lineNumber++) {
if (line.trim().isEmpty() || line.startsWith("#") /* Comment */) continue;
Matcher matcher = NODE_PATTERN.matcher(line);
if (!matcher.find()) {
System.err.println("Invalid locale syntax at (line=" + lineNumber + ")");
continue;
}
nodes.put(matcher.group(1), matcher.group(2));
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* Supply the Message object with the plugins prefix.
*
* @param message message to be applied
* @return applied message
*/
private Message supplyPrefix(Message message) {
return message.setPrefix(this.nodes.getOrDefault("general.nametag.prefix", "[Plugin]"));
}
/**
* Create a new unsaved Message
*
* @param message the message to create
* @return the created message
*/
public Message newMessage(String message) {
return supplyPrefix(new Message(message));
}
/**
* Get a message set for a specific node.
*
* @param node the node to get
* @return the message for the specified node
*/
public Message getMessage(String node) {
return this.getMessageOrDefault(node, node);
}
/**
* Get a message set for a specific node
*
* @param node the node to get
* @param defaultValue the default value given that a value for the node was not found
* @return the message for the specified node. Default if none found
*/
public Message getMessageOrDefault(String node, String defaultValue) {
return supplyPrefix(new Message(this.nodes.getOrDefault(node, defaultValue)));
}
/**
* Return the locale name (i.e. "en_US")
*
* @return the locale name
*/
public String getName() {
return name;
}
private static void copy(InputStream input, OutputStream output) {
int n;
byte[] buffer = new byte[1024 * 4];
try {
while ((n = input.read(buffer)) != -1) {
output.write(buffer, 0, n);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -1,115 +0,0 @@
package com.songoda.epicvouchers.utils.locale;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
* The Message object. This holds the message to be sent
* as well as the plugins prefix so that they can both be
* easily manipulated then deployed
*/
public class Message {
private String prefix = null;
private String message;
/**
* create a new message
*
* @param message the message text
*/
public Message(String message) {
this.message = message;
}
/**
* Format and send the held message to a player
*
* @param player player to send the message to
*/
public void sendMessage(Player player) {
player.sendMessage(this.getMessage());
}
/**
* Format and send the held message with the
* appended plugin prefix to a player
*
* @param player player to send the message to
*/
public void sendPrefixedMessage(Player player) {
player.sendMessage(this.getPrefixedMessage());
}
/**
* Format and send the held message to a player
*
* @param sender command sender to send the message to
*/
public void sendMessage(CommandSender sender) {
sender.sendMessage(this.getMessage());
}
/**
* Format and send the held message with the
* appended plugin prefix to a command sender
*
* @param sender command sender to send the message to
*/
public void sendPrefixedMessage(CommandSender sender) {
sender.sendMessage(this.getPrefixedMessage());
}
/**
* Format the held message and append the plugins
* prefix
*
* @return the prefixed message
*/
public String getPrefixedMessage() {
return ChatColor.translateAlternateColorCodes('&',(prefix == null ? "" : this.prefix)
+ " " + this.message);
}
/**
* Get and format the held message
*
* @return the message
*/
public String getMessage() {
return ChatColor.translateAlternateColorCodes('&', this.message);
}
/**
* Get the held message
*
* @return the message
*/
public String getUnformattedMessage() {
return this.message;
}
/**
* Replace the provided placeholder with the
* provided object
*
* @param placeholder the placeholder to replace
* @param replacement the replacement object
* @return the modified Message
*/
public Message processPlaceholder(String placeholder, Object replacement) {
this.message = message.replace("%" + placeholder + "%", replacement.toString());
return this;
}
Message setPrefix(String prefix) {
this.prefix = prefix;
return this;
}
@Override
public String toString() {
return this.message;
}
}

View File

@ -1,32 +0,0 @@
package com.songoda.epicvouchers.utils.updateModules;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.update.Module;
import com.songoda.update.Plugin;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class LocaleModule implements Module {
@Override
public void run(Plugin plugin) {
JSONObject json = plugin.getJson();
try {
JSONArray files = (JSONArray) json.get("neededFiles");
for (Object o : files) {
JSONObject file = (JSONObject) o;
if (file.get("type").equals("locale")) {
InputStream in = new URL((String) file.get("link")).openStream();
EpicVouchers.getInstance().getLocale().saveLocale(in, (String) file.get("name"));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -28,11 +28,13 @@ public class CoolDownManager {
}
public boolean isOnCoolDown(UUID uuid) {
if(!entries.containsKey(uuid)) {
Long time = entries.get(uuid);
if (time == null) {
return false;
}
if(entries.get(uuid) >= System.currentTimeMillis()) {
if (time >= System.currentTimeMillis()) {
return true;
}
@ -41,10 +43,12 @@ public class CoolDownManager {
}
public long getTime(UUID uuid) {
if(!entries.containsKey(uuid)) {
Long time = entries.get(uuid);
if (time == null) {
return 0L;
}
return (entries.get(uuid) - System.currentTimeMillis()) / 1000;
return (time - System.currentTimeMillis()) / 1000;
}
}

View File

@ -1,9 +1,9 @@
package com.songoda.epicvouchers.voucher;
import com.songoda.core.utils.TextUtils;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.epicvouchers.events.ForceRedeemEvent;
import com.songoda.epicvouchers.events.VoucherReceiveEvent;
import com.songoda.epicvouchers.utils.Methods;
import lombok.experimental.Accessors;
import org.bukkit.Bukkit;
import org.bukkit.Material;
@ -17,10 +17,8 @@ import org.bukkit.inventory.meta.ItemMeta;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.stream.Collectors;
import static com.songoda.epicvouchers.utils.Methods.format;
import static org.bukkit.Material.PAPER;
@Accessors(chain = true)
@ -85,7 +83,7 @@ public class Voucher {
}
if (!name.isEmpty()) {
meta.setDisplayName(format(name));
meta.setDisplayName(TextUtils.formatText(name));
}
if (lore != null) {
@ -110,25 +108,25 @@ public class Voucher {
}
public String getName(boolean applyFormatting) {
return applyFormatting ? format(name) : name;
return applyFormatting ? TextUtils.formatText(name) : name;
}
public List<String> getLore(boolean applyFormatting) {
return applyFormatting ? lore.stream().map(Methods::format).collect(Collectors.toList()) : lore;
return applyFormatting ? lore.stream().map(TextUtils::formatText).collect(Collectors.toList()) : lore;
}
public List<String> getBroadcasts(boolean applyFormatting) {
return applyFormatting ? broadcasts.stream().map(Methods::format).collect(Collectors.toList()) : broadcasts;
return applyFormatting ? broadcasts.stream().map(TextUtils::formatText).collect(Collectors.toList()) : broadcasts;
}
public List<String> getMessages(boolean applyFormatting) {
return applyFormatting ? messages.stream().map(Methods::format).collect(Collectors.toList()) : messages;
return applyFormatting ? messages.stream().map(TextUtils::formatText).collect(Collectors.toList()) : messages;
}
public void saveSetting(String key, Object value) {
ConfigurationSection cs = instance.getVouchersFile().getConfig().getConfigurationSection("vouchers." + getKey());
ConfigurationSection cs = instance.getConfig().getConfigurationSection("vouchers." + getKey());
cs.set(key, value);
instance.getVouchersFile().saveConfig();
instance.getVouchersConfig().save();
}
@Override
@ -141,17 +139,16 @@ public class Voucher {
}
public void give(CommandSender sender, List<Player> players, int amount) {
String giveMessage = instance.getLocale().getMessage("command.give.send")
.processPlaceholder("%player%", players.size() == 1 ? players.get(0).getName() : "everyone")
.processPlaceholder("%voucher%", Matcher.quoteReplacement(getName(true)))
.processPlaceholder("%amount%", String.valueOf(amount)).getPrefixedMessage();
.processPlaceholder("player", players.size() == 1 ? players.get(0).getName() : "everyone")
.processPlaceholder("voucher", getName(true))
.processPlaceholder("amount", String.valueOf(amount)).getPrefixedMessage();
for (Player player : players) {
String receiveMessage = instance.getLocale().getMessage("command.give.receive")
.processPlaceholder("%voucher%", Matcher.quoteReplacement(getName(true)))
.processPlaceholder("%player%", player.getName())
.processPlaceholder("%amount%", String.valueOf(amount)).getPrefixedMessage();
.processPlaceholder("voucher", getName(true))
.processPlaceholder("player", player.getName())
.processPlaceholder("amount", String.valueOf(amount)).getPrefixedMessage();
VoucherReceiveEvent event = new VoucherReceiveEvent(player, getName(true), toItemStack(amount), amount, sender);
Bukkit.getServer().getPluginManager().callEvent(event);
@ -184,15 +181,15 @@ public class Voucher {
}
public String getActionBar() {
return format(actionBar);
return TextUtils.formatText(actionBar);
}
public String getSubTitle() {
return format(subTitle);
return TextUtils.formatText(subTitle);
}
public String getTitle() {
return format(title);
return TextUtils.formatText(title);
}
public String getKey() {

View File

@ -1,20 +1,20 @@
package com.songoda.epicvouchers.voucher;
import com.songoda.core.utils.TextUtils;
import com.songoda.epicvouchers.EpicVouchers;
import com.songoda.epicvouchers.events.VoucherRedeemEvent;
import com.songoda.epicvouchers.libraries.BountifulAPI;
import com.songoda.epicvouchers.listeners.PlayerCommandListener;
import com.songoda.epicvouchers.utils.Methods;
import org.bukkit.Bukkit;
import org.bukkit.Effect;
import org.bukkit.Sound;
import org.bukkit.craftbukkit.libs.org.apache.commons.lang3.StringUtils;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.jetbrains.annotations.Nullable;
import java.util.logging.Level;
@ -25,7 +25,7 @@ public class VoucherExecutor {
this.instance = instance;
}
public void redeemVoucher(Player player, Voucher voucher, ItemStack item, boolean manual, @Nullable PlayerInteractEvent event) {
public void redeemVoucher(Player player, Voucher voucher, ItemStack item, boolean manual, PlayerInteractEvent event) {
try {
VoucherRedeemEvent redeemEvent = new VoucherRedeemEvent(player, voucher.getName(true), item, manual);
Bukkit.getServer().getPluginManager().callEvent(redeemEvent);
@ -45,7 +45,7 @@ public class VoucherExecutor {
} catch (Exception | Error ignore) {
}
if (player.getInventory().getItem(slot) != null && !player.getInventory().getItem(slot).isSimilar(item)) {
if (!item.isSimilar(player.getInventory().getItem(slot))) {
duplication = true;
}
}
@ -54,13 +54,12 @@ public class VoucherExecutor {
if (manual) {
instance.getCoolDowns().addCoolDown(player.getUniqueId(), voucher);
if (voucher.isRemoveItem()) {
ItemStack clone = item.clone();
if (clone.getAmount() <= 1) {
clone = null;
if (item.getAmount() <= 1) {
item = null;
} else {
clone.setAmount(clone.getAmount() - 1);
item.setAmount(item.getAmount() - 1);
}
player.getInventory().setItem(slot, clone);
player.getInventory().setItem(slot, item);
player.updateInventory();
}
}
@ -114,9 +113,14 @@ public class VoucherExecutor {
} else if (command.startsWith("[chat]")) {
command = command.replace("[chat]", "");
player.chat(command);
} else if (command.startsWith("[delay]")) {
//command = command.replace("[delay]", "");
throw new UnsupportedOperationException("delay is not supported yet");
} else if (command.startsWith("[delay")) {
String delayCommand = StringUtils.substringBetween(command, "[", "]");
int delay = Integer.parseInt(delayCommand.split("-", 2)[1]);
final String finalCommand = command.replace("[" + delayCommand + "]", "");
final ItemStack heldItem = item;
Bukkit.getScheduler().scheduleSyncDelayedTask(instance, () -> {
runCommand(finalCommand, player);
}, 20 * delay);
} else {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command);
}
@ -155,15 +159,39 @@ public class VoucherExecutor {
player.addPotionEffect(new PotionEffect(PotionEffectType.getByName(effect), duration, amplifier));
}
instance.getLogger().log(Level.INFO, Methods.format("&f" + player.getName() + " has successfully redeemed the voucher " + voucher.getKey() + "."));
instance.getLogger().log(Level.INFO, TextUtils.formatText("&f" + player.getName() + " has successfully redeemed the voucher " + voucher.getKey() + "."));
instance.getConnections().saveRedeem(player, voucher.getName(true));
} else {
instance.getLogger().log(Level.WARNING, Methods.format("&c" + player.getName() + " has failed to duplicate the voucher " + voucher.getKey() + "."));
instance.getLogger().log(Level.WARNING, TextUtils.formatText("&c" + player.getName() + " has failed to duplicate the voucher " + voucher.getKey() + "."));
}
} catch (Exception error) {
instance.getLogger().log(Level.SEVERE, Methods.format("&cFailed to redeem the voucher " + voucher.getKey() + " for the player " + player.getName() + "."));
instance.getLogger().log(Level.SEVERE, TextUtils.formatText("&cFailed to redeem the voucher " + voucher.getKey() + " for the player " + player.getName() + "."));
instance.getLogger().log(Level.SEVERE, error.getMessage());
error.printStackTrace();
}
}
private void runCommand(String command, Player player) {
if (command.startsWith("[player]")) {
command = command.replace("[player]", "");
player.performCommand(command);
} else if (command.startsWith("[op]")) {
command = command.replace("[op]", "");
boolean wasOp = player.isOp();
PlayerCommandListener.addCommand(player.getUniqueId(), command);
player.setOp(true);
player.performCommand(command);
if (!wasOp) {
player.setOp(false);
}
PlayerCommandListener.removeCommand(player.getUniqueId());
} else if (command.startsWith("[chat]")) {
command = command.replace("[chat]", "");
player.chat(command);
} else {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command);
}
}
}

View File

@ -4,4 +4,10 @@ version: maven-version-number
author: Songoda
website: https://songoda.host/epicvouchers
description: Enhance your server with awesome customizable vouchers with a lot of features.
api-version: 1.13
api-version: 1.13
commands:
epicvouchers:
description: View information on this plugin.
default: true
aliases: [ev]
usage: /ev