Compare commits

...

39 Commits

Author SHA1 Message Date
GeorgH93 c2972c56ef
Add experimental paper 1.20.6 support 2024-06-01 16:40:32 +02:00
GeorgH93 b2221b26eb
Mark paper experimental 2024-05-19 16:37:11 +02:00
GeorgH93 0e53b1f41d
Fix paper not supported message 2024-05-15 10:38:22 +02:00
GeorgH93 41644b2ac9
Add warning about not supported paper version 2024-05-14 08:56:57 +02:00
GeorgH93 0811e56b26
Fix crash on Paper 2024-05-09 13:57:23 +02:00
GeorgH93 212e1b207d
Merge pull request #313 from GeorgH93/snyk-upgrade-2b07f74124e3589e620139b077fde222
[Snyk] Upgrade org.projectlombok:lombok from 1.18.30 to 1.18.32
2024-05-04 22:08:51 +02:00
GeorgH93 48157c0d8e
Update to v2.4.28 2024-04-22 20:58:11 +02:00
snyk-bot 02e7e42dbd
fix: upgrade org.projectlombok:lombok from 1.18.30 to 1.18.32
Snyk has created this PR to upgrade org.projectlombok:lombok from 1.18.30 to 1.18.32.

See this package in Maven Repository:
https://mvnrepository.com/artifact/org.projectlombok/lombok/

See this project in Snyk:
https://app.snyk.io/org/georgh93/project/8593930e-9ac6-4553-a9e1-18fe8f17f83e?utm_source=github&utm_medium=referral&page=upgrade-pr
2024-04-14 22:39:30 +00:00
GeorgH93 c3ac9b63d9
Build with Java 21 2024-02-08 22:45:11 +01:00
GeorgH93 0b9ec74747
Alert player about shrunken backpack (Fixes #284) 2024-01-30 00:01:02 +01:00
GeorgH93 f759a4b799
Cleanup Files handler 2024-01-29 01:36:15 +01:00
GeorgH93 1d3e3fa464
Fix issue with database cleanup of old cooldowns 2024-01-28 18:18:18 +01:00
GeorgH93 582ada4657
Refactor OpenCommand 2024-01-27 19:18:17 +01:00
GeorgH93 e4ecb9919c
Cleanup logging 2024-01-26 14:36:32 +01:00
GeorgH93 2fdb20b464
Replace switch with if 2024-01-25 11:22:33 +01:00
GeorgH93 a4148d5772
Remove useless curly braces 2024-01-23 22:11:33 +01:00
GeorgH93 9528030055
Fix warning about missing translation for Command.Description.Shortcut 2024-01-22 00:56:11 +01:00
GeorgH93 5604b1b5ee
Build API with current version of PluginLib 2024-01-19 00:45:23 +01:00
GeorgH93 12c0892419
Replace printStackTrace with logger 2024-01-18 00:41:53 +01:00
GeorgH93 e50c92f603
Replace printStackTrace with logger 2024-01-17 00:37:11 +01:00
GeorgH93 6d0022e413
Allow playername placeholder in own title. 2024-01-16 13:39:34 +01:00
GeorgH93 5f3b80308d
Update to v2.4.25 2024-01-03 15:05:11 +01:00
GeorgH93 70e7414e9f
Change visibilitys 2023-12-20 15:01:53 +01:00
GeorgH93 6f6106fe62
Remove unnecessary replaceAll 2023-12-19 14:56:32 +01:00
GeorgH93 ad22323fce
Remove unused imports 2023-12-18 14:49:22 +01:00
GeorgH93 d2609e44b0
Cleanup RestoreCommand 2023-12-17 14:47:22 +01:00
GeorgH93 c08454d45d
Cleanup main class 2023-12-16 14:40:11 +01:00
GeorgH93 9df3df69b0
Cleanup config class 2023-12-15 17:17:17 +01:00
GeorgH93 b238a17467
Cleanup backpack callback code 2023-12-14 14:12:08 +01:00
GeorgH93 222e122eda
Refactor debug command 2023-12-13 15:21:33 +01:00
GeorgH93 032f22a3df
Cleanup MinepacksCommand 2023-12-12 14:02:44 +01:00
GeorgH93 0bacf05204
Reorder modifiers 2023-12-11 17:53:33 +01:00
GeorgH93 8c2e25a75e
Update javadoc 2023-12-10 14:14:14 +01:00
GeorgH93 1e1b16bb07
Update sonarcloud config to java 17 2023-12-09 15:16:17 +01:00
GeorgH93 26abcf31e4
Remove backpack item if user does not have the permission to use it 2023-12-08 11:13:15 +01:00
GeorgH93 d11f959ead
Fix formatting 2023-12-07 13:51:06 +01:00
GeorgH93 0c9ef35e36
Update to 2.4.24 2023-12-04 02:21:11 +01:00
GeorgH93 bb7776b065
Allow to spawn backpack for others 2023-10-24 21:57:11 +02:00
GeorgH93 0fc18aca2b
Add ShortcutCommand 2023-10-23 21:50:11 +02:00
29 changed files with 354 additions and 263 deletions

View File

@ -10,7 +10,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
java-version: [ 8, 11, 17 ]
java-version: [ 8, 11, 17, 21 ]
steps:
- name: Checkout
uses: actions/checkout@v3

View File

@ -13,10 +13,10 @@ jobs:
steps:
- uses: actions/checkout@v3
- name: Set up JDK 17
- name: Set up JDK 21
uses: actions/setup-java@v3
with:
java-version: 17
java-version: 21
distribution: temurin
server-id: github
settings-path: ${{ github.workspace }} # location for the settings.xml file

View File

@ -14,10 +14,10 @@ jobs:
- uses: actions/checkout@v3
with:
fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis
- name: Set up JDK 11
- name: Set up JDK 21
uses: actions/setup-java@v3
with:
java-version: 11
java-version: 21
distribution: temurin
- name: Cache SonarCloud packages
uses: actions/cache@v3

View File

@ -18,7 +18,7 @@
<dependency>
<groupId>at.pcgamingfreaks</groupId>
<artifactId>PluginLib</artifactId>
<version>1.0.17-SNAPSHOT</version>
<version>${pcgfPluginLibVersion}</version>
<scope>provided</scope>
</dependency>
</dependencies>

View File

@ -36,6 +36,7 @@ public interface Backpack extends InventoryHolder
* Gets the owner of the backpack.
*
* @return The owner of the backpack;
* @deprecated Use the {@link Backpack#getOwnerId()} function instead.
*/
@Deprecated
@NotNull OfflinePlayer getOwner();

View File

@ -21,5 +21,5 @@ public interface Callback<T>
{
void onResult(T done);
void onFail();
default void onFail() { /* In most cases this can be ignored since it will not happen with most db queries used */ }
}

View File

@ -35,12 +35,12 @@ public class InventoryClearEvent extends Event implements Cancellable
/**
* The player whose inventory should be cleared.
*/
@Getter final private Player player;
@Getter private final Player player;
/**
* The command sender who has requested the inventory to be cleared.
*/
@Getter final private CommandSender sender;
@Getter private final CommandSender sender;
// Bukkit handler stuff
private static final HandlerList handlers = new HandlerList();

View File

@ -31,12 +31,12 @@ public class InventoryClearedEvent extends Event
/**
* The player whose inventory has been cleared.
*/
@Getter final private Player player;
@Getter private final Player player;
/**
* The command sender who has requested the inventory to be cleared.
*/
@Getter final private CommandSender sender;
@Getter private final CommandSender sender;
// Bukkit handler stuff
private static final HandlerList handlers = new HandlerList();

View File

@ -30,15 +30,20 @@ import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
/**
* Only available if the plugin is not running in standalone mode!
*/
public abstract class MinepacksCommand extends SubCommand
{
private static MinepacksPlugin minepacksPlugin = null;
private static Method showHelp = null;
@SuppressWarnings("FieldMayBeFinal")
private static MinepacksPlugin minepacksPlugin = null; // Will be set by reflection
@SuppressWarnings("FieldMayBeFinal")
private static Method showHelp = null; // Will be set by reflection
@SuppressWarnings("FieldMayBeFinal") // Will be overwritten by reflection
private static Message messageNoPermission = new Message(ChatColor.RED + "You don't have the permission to do that.");
@SuppressWarnings("FieldMayBeFinal") // Will be overwritten by reflection
private static Message messageNotFromConsole = new Message(ChatColor.RED + "This command can't be used from console!");
protected final JavaPlugin plugin;
private final boolean playerOnly;
@ -52,7 +57,7 @@ public abstract class MinepacksCommand extends SubCommand
* @param description The description of the command.
* @param aliases List of aliases for that command.
*/
public MinepacksCommand(@NotNull JavaPlugin plugin, @NotNull String name, @NotNull String description, @Nullable String... aliases)
protected MinepacksCommand(@NotNull JavaPlugin plugin, @NotNull String name, @NotNull String description, @Nullable String... aliases)
{
this(plugin, name, description, null, aliases);
}
@ -66,7 +71,7 @@ public abstract class MinepacksCommand extends SubCommand
* @param permission The permission to be checked for this command. Players without the permission neither can use the command nor will they see it in help.
* @param aliases List of aliases for that command.
*/
public MinepacksCommand(@NotNull JavaPlugin plugin, @NotNull String name, @NotNull String description, @Nullable String permission, @Nullable String... aliases)
protected MinepacksCommand(@NotNull JavaPlugin plugin, @NotNull String name, @NotNull String description, @Nullable String permission, @Nullable String... aliases)
{
this(plugin, name, description, permission, false, aliases);
}
@ -81,7 +86,7 @@ public abstract class MinepacksCommand extends SubCommand
* @param playerOnly Limits the command to players, console can't use and can't see the command.
* @param aliases List of aliases for that command.
*/
public MinepacksCommand(@NotNull JavaPlugin plugin, @NotNull String name, @NotNull String description, @Nullable String permission, boolean playerOnly, @Nullable String... aliases)
protected MinepacksCommand(@NotNull JavaPlugin plugin, @NotNull String name, @NotNull String description, @Nullable String permission, boolean playerOnly, @Nullable String... aliases)
{
super(name, description, permission, aliases);
this.plugin = plugin;
@ -173,7 +178,7 @@ public abstract class MinepacksCommand extends SubCommand
* @param usedMainCommandAlias The used backpack alias to replace the /backpack with the used alias.
*/
@Override
public void showHelp(@NotNull CommandSender sendTo, @NotNull String usedMainCommandAlias)
public void showHelp(final @NotNull CommandSender sendTo, final @NotNull String usedMainCommandAlias)
{
try
{
@ -181,7 +186,7 @@ public abstract class MinepacksCommand extends SubCommand
}
catch(Exception e)
{
e.printStackTrace();
plugin.getLogger().log(Level.SEVERE, e, () -> "Failed to execute command " + usedMainCommandAlias);
}
}

View File

@ -16,6 +16,7 @@ Language:
NotAllowedInBackpack_SendMethod: "action_bar"
DontRemoveShortcut: "&cYou must not remove the backpack shortcut from your inventory!"
DontRemoveShortcut_SendMethod: "action_bar"
BackpackShrunk: "&cYour backpack shrunk! Some items fell to the ground!"
Open:
#Parameter: {TimeLeft} time in seconds till the backpack can be reopened, {TimeSpanLeft} time formatted as string till the backpack can be reopened
Cooldown: "[{\"text\":\"Please wait \",\"color\":\"dark_green\"},{\"text\":\"{TimeSpanLeft}\",\"hoverEvent\":{\"action\":\"show_text\",\"value\":\"{TimeLeft} seconds\"}},{\"text\":\" till you reopen your backpack.\"}]"

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2020 GeorgH93
* Copyright (C) 2024 GeorgH93
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -12,18 +12,17 @@
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package at.pcgamingfreaks.Minepacks.Bukkit;
import at.pcgamingfreaks.Bukkit.MCVersion;
import at.pcgamingfreaks.Bukkit.Message.Message;
import at.pcgamingfreaks.Bukkit.Util.InventoryUtils;
import at.pcgamingfreaks.Minepacks.Bukkit.Database.Helper.InventoryCompressor;
import at.pcgamingfreaks.Util.StringUtils;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
@ -33,6 +32,10 @@ import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@ -42,8 +45,10 @@ import java.util.concurrent.ConcurrentHashMap;
public class Backpack implements at.pcgamingfreaks.Minepacks.Bukkit.API.Backpack
{
@Setter(AccessLevel.PACKAGE) private static ShrinkApproach shrinkApproach = ShrinkApproach.COMPRESS;
private static Object titleOwn;
private static String titleOtherFormat;
@Setter(AccessLevel.PACKAGE) private static Message messageBackpackShrunk = new Message("Backpack shrunk!");
private static Object titleOwnGlobal;
private static String titleFormat, titleOtherFormat;
private final Object titleOwn;
private final String titleOther;
@Getter private final UUID ownerId;
private final Map<Player, Boolean> opened = new ConcurrentHashMap<>(); //Thanks Minecraft 1.14
@ -54,7 +59,8 @@ public class Backpack implements at.pcgamingfreaks.Minepacks.Bukkit.API.Backpack
public static void setTitle(final @NotNull String title, final @NotNull String titleOther)
{
titleOwn = InventoryUtils.prepareTitleForOpenInventoryWithCustomTitle(title);
titleOwnGlobal = title.contains("%s") ? null : InventoryUtils.prepareTitleForOpenInventoryWithCustomTitle(title);
titleFormat = title;
titleOtherFormat = titleOther;
}
@ -80,6 +86,9 @@ public class Backpack implements at.pcgamingfreaks.Minepacks.Bukkit.API.Backpack
bp = Bukkit.createInventory(this, size, titleOther);
this.size = size;
ownerDatabaseId = ID;
if (titleOwnGlobal != null) titleOwn = titleOwnGlobal;
else titleOwn = InventoryUtils.prepareTitleForOpenInventoryWithCustomTitle(String.format(titleFormat, owner.getName()));
}
public Backpack(final OfflinePlayer owner, ItemStack[] backpack, final int ID)
@ -135,14 +144,20 @@ public class Backpack implements at.pcgamingfreaks.Minepacks.Bukkit.API.Backpack
int size = Minepacks.getInstance().getBackpackPermSize(owner);
if(size != bp.getSize())
{
boolean dropped = false;
List<ItemStack> items = setSize(size);
for(ItemStack i : items)
{
if(i != null)
{
owner.getWorld().dropItemNaturally(owner.getLocation(), i);
dropped = true;
}
}
if (dropped)
{
messageBackpackShrunk.send(owner);
}
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2023 GeorgH93
* Copyright (C) 2024 GeorgH93
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -37,6 +37,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
public class CommandManager extends CommandExecutorWithSubCommandsGeneric<MinepacksCommand> /*if_not[STANDALONE]*/ implements MinepacksCommandManager /*end[STANDALONE]*/
{
@ -67,8 +68,7 @@ public class CommandManager extends CommandExecutorWithSubCommandsGeneric<Minepa
}
catch(Exception e)
{
plugin.getLogger().warning(ConsoleColor.RED + "Unable to set the help format. Default format will be used.\nMore details:" + ConsoleColor.RESET);
e.printStackTrace();
plugin.getLogger().log(Level.SEVERE, e, () -> ConsoleColor.RED + "Unable to set the help format. Default format will be used.\nMore details:" + ConsoleColor.RESET);
}
// Init backpack commands
@ -126,11 +126,8 @@ public class CommandManager extends CommandExecutorWithSubCommandsGeneric<Minepa
WorldBlacklistMode disabled = plugin.isDisabled((Player) sender);
if(disabled != WorldBlacklistMode.None)
{
switch(disabled)
{
case Message: plugin.messageWorldDisabled.send(sender); break;
case MissingPermission: plugin.messageNoPermission.send(sender); break;
}
if (disabled == WorldBlacklistMode.Message) plugin.messageWorldDisabled.send(sender);
else if (disabled == WorldBlacklistMode.MissingPermission) plugin.messageNoPermission.send(sender);
return null;
}
}

View File

@ -70,7 +70,7 @@ public class DebugCommand extends MinepacksCommand
builder = new MessageBuilder("All data has been collected!", MessageColor.GREEN, MessageFormat.BOLD).appendNewLine();
builder.append("You can now interact with your game again.").appendNewLine();
builder.append("The collected data can be found in your plugins directory inside the 'debug.txt' file.").appendNewLine();
builder.append("Please upload this fiel to ");
builder.append("Please upload this file to ");
builder.append("https://pastebin.com/", MessageColor.YELLOW, MessageFormat.UNDERLINE).onClick(MessageClickEvent.ClickEventAction.OPEN_URL, "https://pastebin.com/");
builder.append(" and send the link to the developer.");
messageDone = builder.getMessage();
@ -157,48 +157,55 @@ public class DebugCommand extends MinepacksCommand
}
else if (args.length == 2 && args[0].equals("size"))
{
Player player = Bukkit.getServer().getPlayer(args[1]);
if (player == null)
{
commandSender.sendMessage("Player " + args[1] + " is offline.");
return;
}
Backpack bp = Minepacks.getInstance().getBackpackCachedOnly(player);
int bpSize = -1, bpInvSize = -1, sizeShouldBe = Minepacks.getInstance().getBackpackPermSize(player);
String actualSize = "backpack not loaded", actualSizeInventory = "backpack not loaded";
if (bp != null)
{
bpSize = bp.getSize();
bpInvSize = bp.getInventory().getSize();
actualSize = String.valueOf(bpSize);
actualSizeInventory = String.valueOf(bpInvSize);
}
commandSender.sendMessage("### Backpack size for " + player.getName() + " ###");
commandSender.sendMessage("Size: " + actualSize);
commandSender.sendMessage("Inventory Size: " + actualSizeInventory);
commandSender.sendMessage("Should be: " + sizeShouldBe);
if (bpSize != sizeShouldBe)
{
commandSender.sendMessage("Size missmatch detected, attempt resize ...");
((at.pcgamingfreaks.Minepacks.Bukkit.Backpack) bp).checkResize();
if (bp.getSize() != sizeShouldBe)
{
commandSender.sendMessage("Failed to resize backpack.");
}
else
{
commandSender.sendMessage("Resized backpack successfully.");
}
}
if (bp != null && bp.getSize() != bp.getInventory().getSize())
{
commandSender.sendMessage("Inventory size does not match backpack size!");
}
commandSender.sendMessage("Player class: " + player.getClass().getName());
commandSender.sendMessage("###############################");
executeSize(commandSender, args[1]);
}
else
{
debugSystem(commandSender);
}
}
void executeSize(final @NotNull CommandSender commandSender, final @NotNull String playerName)
{
Player player = Bukkit.getServer().getPlayer(playerName);
if (player == null)
{
commandSender.sendMessage("Player " + playerName + " is offline.");
return;
}
Backpack bp = Minepacks.getInstance().getBackpackCachedOnly(player);
int bpSize = -1, bpInvSize = -1, sizeShouldBe = Minepacks.getInstance().getBackpackPermSize(player);
String actualSize = "backpack not loaded", actualSizeInventory = "backpack not loaded";
if (bp != null)
{
bpSize = bp.getSize();
bpInvSize = bp.getInventory().getSize();
actualSize = String.valueOf(bpSize);
actualSizeInventory = String.valueOf(bpInvSize);
}
commandSender.sendMessage("### Backpack size for " + player.getName() + " ###");
commandSender.sendMessage("Size: " + actualSize);
commandSender.sendMessage("Inventory Size: " + actualSizeInventory);
commandSender.sendMessage("Should be: " + sizeShouldBe);
if (bpSize != sizeShouldBe && bp != null)
{
commandSender.sendMessage("Size mismatch detected, attempt resize ...");
((at.pcgamingfreaks.Minepacks.Bukkit.Backpack) bp).checkResize();
if (bp.getSize() != sizeShouldBe)
{
commandSender.sendMessage("Failed to resize backpack.");
}
else
{
commandSender.sendMessage("Resized backpack successfully.");
}
}
if (bp != null && bp.getSize() != bp.getInventory().getSize())
{
commandSender.sendMessage("Inventory size does not match backpack size!");
}
commandSender.sendMessage("Player class: " + player.getClass().getName());
commandSender.sendMessage("###############################");
}
@Override

View File

@ -64,42 +64,52 @@ public class OpenCommand extends MinepacksCommand
Player player = (Player) sender;
if(args.length == 0)
{
if(getMinepacksPlugin().isPlayerGameModeAllowed(player))
{
if(plugin.getCooldownManager() != null && !player.hasPermission(Permissions.NO_COOLDOWN))
{
long cd = plugin.getCooldownManager().getRemainingCooldown(player);
if(cd > 0)
{
TimeSpan ts = TimeSpan.fromMilliseconds(cd);
messageCooldown.send(sender, cd / 1000f, ts.toString());
return;
}
plugin.getCooldownManager().setCooldown(player);
}
plugin.openBackpack(player, player, true);
}
else
{
messageWrongGameMode.send(player, player.getGameMode());
}
executeSelf(player);
}
else
{
if(player.hasPermission(Permissions.OTHERS))
executeOther(player, args[0]);
}
}
void executeSelf(Player player)
{
if(getMinepacksPlugin().isPlayerGameModeAllowed(player))
{
if(plugin.getCooldownManager() != null && !player.hasPermission(Permissions.NO_COOLDOWN))
{
OfflinePlayer target = Bukkit.getPlayer(args[0]);
if(target == null)
long cd = plugin.getCooldownManager().getRemainingCooldown(player);
if(cd > 0)
{
//noinspection deprecation
target = Bukkit.getOfflinePlayer(args[0]);
TimeSpan ts = TimeSpan.fromMilliseconds(cd);
messageCooldown.send(player, cd / 1000f, ts.toString());
return;
}
plugin.openBackpack(player, target, player.hasPermission(Permissions.OTHERS_EDIT));
plugin.getCooldownManager().setCooldown(player);
}
else
plugin.openBackpack(player, player, true);
}
else
{
messageWrongGameMode.send(player, player.getGameMode());
}
}
void executeOther(Player player, String name)
{
if(player.hasPermission(Permissions.OTHERS))
{
OfflinePlayer target = Bukkit.getPlayer(name);
if(target == null)
{
plugin.messageNoPermission.send(player);
//noinspection deprecation
target = Bukkit.getOfflinePlayer(name);
}
plugin.openBackpack(player, target, player.hasPermission(Permissions.OTHERS_EDIT));
}
else
{
plugin.messageNoPermission.send(player);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2020 GeorgH93
* Copyright (C) 2023 GeorgH93
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -20,8 +20,6 @@ package at.pcgamingfreaks.Minepacks.Bukkit.Command;
import at.pcgamingfreaks.Bukkit.Message.Message;
import at.pcgamingfreaks.Command.HelpData;
import at.pcgamingfreaks.Message.MessageClickEvent;
import at.pcgamingfreaks.Minepacks.Bukkit.API.Backpack;
import at.pcgamingfreaks.Minepacks.Bukkit.API.Callback;
import at.pcgamingfreaks.Minepacks.Bukkit.API.MinepacksCommand;
import at.pcgamingfreaks.Minepacks.Bukkit.Minepacks;
import at.pcgamingfreaks.Minepacks.Bukkit.Permissions;
@ -114,17 +112,10 @@ public class RestoreCommand extends MinepacksCommand
messageNoUserFound.send(sender);
return;
}
getMinepacksPlugin().getBackpack(target, new Callback<Backpack>() {
@Override
public void onResult(Backpack backpack)
{
backpack.getInventory().setContents(items);
backpack.setChanged();
messageRestored.send(sender);
}
@Override
public void onFail() {}
getMinepacksPlugin().getBackpack(target, backpack -> {
backpack.getInventory().setContents(items);
backpack.setChanged();
messageRestored.send(sender);
});
}
else
@ -133,21 +124,32 @@ public class RestoreCommand extends MinepacksCommand
}
}
private void listBackups(final @NotNull CommandSender sender, final @NotNull String mainCommandAlias, final @NotNull String alias, final @NotNull String[] args)
private int parsePageNr(final @NotNull CommandSender sender, final @NotNull String[] args)
{
int page = 0;
if(args.length == 2)
{
try
{
page = StringUtils.parsePageNumber(args[1]);
return StringUtils.parsePageNumber(args[1]);
}
catch(NumberFormatException ignored)
{
((Minepacks) getMinepacksPlugin()).messageNotANumber.send(sender);
return;
}
}
return 0;
}
private String formatUUID(final @NotNull String uuidString)
{
if (uuidString.contains("-")) return uuidString;
return uuidString.replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5");
}
private void listBackups(final @NotNull CommandSender sender, final @NotNull String mainCommandAlias, final @NotNull String alias, final @NotNull String[] args)
{
int page = parsePageNr(sender, args);
ArrayList<String> backups = ((Minepacks) getMinepacksPlugin()).getDatabase().getBackups();
int pages = backups.size() / elementsPerPage + 1;
page = Math.min(page, pages - 1);
@ -158,7 +160,7 @@ public class RestoreCommand extends MinepacksCommand
{
String backup = backups.get(offset++), uuid = "No UUID", date = "Unknown";
String[] components = backup.split("_");
if(components.length == 3) uuid = (components[1].contains("-")) ? components[1] : components[1].replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5");
if(components.length == 3) uuid = formatUUID(components[1]);
if(dateFormat != null && (components.length == 2 || components.length == 3))
{
try

View File

@ -0,0 +1,68 @@
/*
* Copyright (C) 2023 GeorgH93
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package at.pcgamingfreaks.Minepacks.Bukkit.Command;
import at.pcgamingfreaks.Command.HelpData;
import at.pcgamingfreaks.Minepacks.Bukkit.API.MinepacksCommand;
import at.pcgamingfreaks.Minepacks.Bukkit.Listener.ItemShortcut;
import at.pcgamingfreaks.Minepacks.Bukkit.Minepacks;
import at.pcgamingfreaks.Minepacks.Bukkit.Permissions;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
public class ShortcutCommand extends MinepacksCommand
{
private final ItemShortcut itemShortcut;
public ShortcutCommand(Minepacks plugin, final @NotNull ItemShortcut itemShortcut)
{
super(plugin, "shortcut", ""/*plugin.getLanguage().getTranslated("Commands.Description.Shortcut")*/, Permissions.USE, true, plugin.getLanguage().getCommandAliases("Shortcut"));
this.itemShortcut = itemShortcut;
}
@Override
public void execute(@NotNull CommandSender sender, @NotNull String mainCommandAlias, @NotNull String alias, @NotNull String[] args)
{
if (args.length == 1 && sender.hasPermission(Permissions.OTHERS))
{
Player p = Bukkit.getPlayer(args[0]);
if (p != null && p.hasPermission(Permissions.USE)) itemShortcut.addItem(p);
}
else
{
itemShortcut.addItem((Player) sender);
}
}
@Override
public List<String> tabComplete(@NotNull CommandSender sender, @NotNull String mainCommandAlias, @NotNull String alias, @NotNull String[] args)
{
return null;
}
@Override
public @Nullable List<HelpData> getHelp(@NotNull CommandSender requester)
{
return null;
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2020 GeorgH93
* Copyright (C) 2023 GeorgH93
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -18,8 +18,6 @@
package at.pcgamingfreaks.Minepacks.Bukkit.Command;
import at.pcgamingfreaks.Bukkit.Message.Message;
import at.pcgamingfreaks.Minepacks.Bukkit.API.Backpack;
import at.pcgamingfreaks.Minepacks.Bukkit.API.Callback;
import at.pcgamingfreaks.Minepacks.Bukkit.API.MinepacksCommand;
import at.pcgamingfreaks.Minepacks.Bukkit.Database.Helper.InventoryCompressor;
import at.pcgamingfreaks.Minepacks.Bukkit.Minepacks;
@ -44,24 +42,16 @@ public class SortCommand extends MinepacksCommand
public void execute(final @NotNull CommandSender commandSender, @NotNull String mainCommandAlias, @NotNull String alias, @NotNull String[] args)
{
final Player player = (Player) commandSender;
getMinepacksPlugin().getBackpack(player, new Callback<Backpack>()
{
@Override
public void onResult(Backpack backpack)
getMinepacksPlugin().getBackpack(player, backpack -> {
InventoryCompressor compressor = new InventoryCompressor(backpack.getInventory().getContents());
if(!compressor.sort().isEmpty())
{
InventoryCompressor compressor = new InventoryCompressor(backpack.getInventory().getContents());
if(!compressor.sort().isEmpty())
{
plugin.getLogger().warning("Failed to sort backpack!"); //this should not happen
return;
}
backpack.getInventory().setContents(compressor.getTargetStacks());
backpack.setChanged();
messageSorted.send(player);
plugin.getLogger().warning("Failed to sort backpack!"); //this should not happen
return;
}
@Override
public void onFail() {} // This should not happen
backpack.getInventory().setContents(compressor.getTargetStacks());
backpack.setChanged();
messageSorted.send(player);
});
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2019 GeorgH93
* Copyright (C) 2023 GeorgH93
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -17,7 +17,6 @@
package at.pcgamingfreaks.Minepacks.Bukkit;
import at.pcgamingfreaks.Minepacks.Bukkit.API.Callback;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
@ -91,16 +90,7 @@ public class CooldownManager extends BukkitRunnable implements Listener
{
final UUID uuid = event.getPlayer().getUniqueId();
cooldowns.put(uuid, System.currentTimeMillis() + cooldown); // Temporary cooldown till the data is loaded from the database
plugin.getDatabase().getCooldown(event.getPlayer(), new Callback<Long>() {
@Override
public void onResult(Long dbCooldownTime)
{
cooldowns.put(uuid, dbCooldownTime);
}
@Override
public void onFail() {}
});
plugin.getDatabase().getCooldown(event.getPlayer(), dbCooldownTime -> cooldowns.put(uuid, dbCooldownTime));
}
else if(addOnJoin)
{

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2023 GeorgH93
* Copyright (C) 2024 GeorgH93
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -12,7 +12,7 @@
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package at.pcgamingfreaks.Minepacks.Bukkit.Database;
@ -31,11 +31,13 @@ import at.pcgamingfreaks.Minepacks.Bukkit.Minepacks;
import at.pcgamingfreaks.Minepacks.Bukkit.ShrinkApproach;
import at.pcgamingfreaks.Minepacks.MagicValues;
import at.pcgamingfreaks.Version;
import org.bukkit.*;
import org.jetbrains.annotations.NotNull;
import java.io.FileNotFoundException;
import java.util.*;
import java.util.logging.Level;
public class Config extends Configuration implements DatabaseConnectionConfiguration, ILanguageConfiguration
{
@ -97,7 +99,7 @@ public class Config extends Configuration implements DatabaseConnectionConfigura
}
catch(FileNotFoundException e)
{
e.printStackTrace();
logger.log(Level.SEVERE, "Failed to set database type", e);
}
}
@ -131,7 +133,7 @@ public class Config extends Configuration implements DatabaseConnectionConfigura
Boolean detectedOnlineMode = Utils.getBungeeOrVelocityOnlineMode();
if (detectedOnlineMode != null)
{
logger.info("Detected online mode in paper config: " + detectedOnlineMode);
logger.log(Level.INFO, "Detected online mode in paper config: {0}", detectedOnlineMode);
return detectedOnlineMode;
}
logger.warning("When using BungeeCord please make sure to set the UUID_Type config option explicitly!");
@ -169,12 +171,12 @@ public class Config extends Configuration implements DatabaseConnectionConfigura
public String getBPTitleOther()
{
return ChatColor.translateAlternateColorCodes('&', getConfigE().getString("BackpackTitleOther", "{OwnerName} Backpack").replaceAll("%", "%%").replaceAll("\\{OwnerName}", "%s"));
return ChatColor.translateAlternateColorCodes('&', getConfigE().getString("BackpackTitleOther", "{OwnerName} Backpack").replace("%", "%%").replace("{OwnerName}", "%s"));
}
public String getBPTitle()
{
return ChatColor.translateAlternateColorCodes('&', getConfigE().getString("BackpackTitle", "Backpack"));
return ChatColor.translateAlternateColorCodes('&', getConfigE().getString("BackpackTitle", "Backpack").replace("%", "%%").replace("{OwnerName}", "%s"));
}
public boolean getDropOnDeath()
@ -208,7 +210,7 @@ public class Config extends Configuration implements DatabaseConnectionConfigura
}
catch(IllegalArgumentException ignored)
{
logger.warning("Unknown ShrinkApproach \"" + approach + "\"!");
logger.log(Level.WARNING, "Unknown ShrinkApproach \"{0}\"!", approach);
return ShrinkApproach.SORT;
}
}
@ -226,7 +228,7 @@ public class Config extends Configuration implements DatabaseConnectionConfigura
{
return channel;
}
else logger.info("Unknown update Channel: " + channel);
else logger.log(Level.INFO, "Unknown update Channel: {0}", channel);
return null;
}
@ -305,7 +307,7 @@ public class Config extends Configuration implements DatabaseConnectionConfigura
gameModes.add(gm);
}
}
if(gameModes.size() < 1)
if(gameModes.isEmpty())
{
logger.info("No game-mode's allowed, allowing: " + GameMode.SURVIVAL.name());
gameModes.add(GameMode.SURVIVAL);
@ -329,11 +331,13 @@ public class Config extends Configuration implements DatabaseConnectionConfigura
return getConfigE().getDouble("FullInventory.CollectRadius", 1.5); // in blocks
}
public boolean isFullInvToggleAllowed() {
public boolean isFullInvToggleAllowed()
{
return getConfigE().getBoolean("FullInventory.IsToggleAllowed", false);
}
public boolean isFullInvEnabledOnJoin() {
public boolean isFullInvEnabledOnJoin()
{
return getFullInvCollect();
}
//endregion
@ -514,14 +518,17 @@ public class Config extends Configuration implements DatabaseConnectionConfigura
return null;
}
private static final @NotNull String DEFAULT_SOUND_OPEN = MCVersion.isNewerOrEqualThan(MCVersion.MC_1_11) ? "BLOCK_SHULKER_BOX_OPEN" : (MCVersion.isNewerOrEqualThan(MCVersion.MC_1_9_2) ? "BLOCK_CHEST_OPEN" : "CHEST_OPEN");
private static final @NotNull String DEFAULT_SOUND_CLOSE = MCVersion.isNewerOrEqualThan(MCVersion.MC_1_11) ? "BLOCK_SHULKER_BOX_CLOSE" : (MCVersion.isNewerOrEqualThan(MCVersion.MC_1_9_2) ? "BLOCK_CHEST_CLOSE" : "CHEST_CLOSE");
public Sound getOpenSound()
{
return getSound("OpenSound", MCVersion.isNewerOrEqualThan(MCVersion.MC_1_11) ? "BLOCK_SHULKER_BOX_OPEN" : (MCVersion.isNewerOrEqualThan(MCVersion.MC_1_9_2) ? "BLOCK_CHEST_OPEN" : "CHEST_OPEN"));
return getSound("OpenSound", DEFAULT_SOUND_OPEN);
}
public Sound getCloseSound()
{
return getSound("CloseSound", MCVersion.isNewerOrEqualThan(MCVersion.MC_1_11) ? "BLOCK_SHULKER_BOX_CLOSE" : (MCVersion.isNewerOrEqualThan(MCVersion.MC_1_9_2) ? "BLOCK_CHEST_CLOSE" : "CHEST_CLOSE"));
return getSound("CloseSound", DEFAULT_SOUND_CLOSE);
}
//endregion

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2020 GeorgH93
* Copyright (C) 2024 GeorgH93
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -12,7 +12,7 @@
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package at.pcgamingfreaks.Minepacks.Bukkit.Database;
@ -20,7 +20,8 @@ package at.pcgamingfreaks.Minepacks.Bukkit.Database;
import at.pcgamingfreaks.Minepacks.Bukkit.API.Callback;
import at.pcgamingfreaks.Minepacks.Bukkit.Backpack;
import at.pcgamingfreaks.Minepacks.Bukkit.Minepacks;
import at.pcgamingfreaks.UUIDConverter;
import at.pcgamingfreaks.UUID.UuidConverter;
import org.bukkit.OfflinePlayer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
@ -39,10 +40,12 @@ public class Files extends Database
public static final String EXT = ".backpack", EXT_REGEX = "\\.backpack", FOLDER_NAME = "backpacks";
private final File saveFolder;
private final UuidConverter converter;
public Files(Minepacks plugin)
{
super(plugin);
converter = new UuidConverter(plugin.getLogger());
maxAge *= 24 * 3600000L;
saveFolder = new File(this.plugin.getDataFolder(), FOLDER_NAME);
if(!saveFolder.exists())
@ -64,6 +67,21 @@ public class Files extends Database
// Files are stored with the users name or the uuid, there is no reason to update anything
}
private String getUuidFromFileName(String fileName)
{
String name = fileName.substring(0, fileName.length() - EXT.length());
UUID uuid = (onlineUUIDs) ? converter.getUUID(name, true) : UuidConverter.getOfflineModeUUID(name);
return getPlayerFormattedUUID(uuid);
}
private void tryRename(File file, File newFileName)
{
if (!file.renameTo(newFileName))
{
plugin.getLogger().log(Level.WARNING, () -> "Failed to rename file (" + file.getAbsolutePath() + " to " + newFileName.getAbsolutePath() + ").");
}
}
private void checkFiles()
{
File[] allFiles = saveFolder.listFiles((dir, name) -> name.endsWith(EXT));
@ -81,32 +99,20 @@ public class Files extends Database
int len = file.getName().length() - EXT.length();
if(len <= 16) // It's a player name
{
if(!file.renameTo(new File(saveFolder, UUIDConverter.getUUIDFromName(file.getName().substring(0, len), onlineUUIDs, useUUIDSeparators) + EXT)))
{
plugin.getLogger().warning("Failed to rename file (" + file.getAbsolutePath() + ").");
}
tryRename(file, new File(saveFolder, getUuidFromFileName(file.getName()) + EXT));
}
else // It's an UUID
else // It's a UUID
{
if(file.getName().contains("-"))
{
if(!useUUIDSeparators)
{
if(!file.renameTo(new File(saveFolder, file.getName().replaceAll("-", ""))))
{
plugin.getLogger().warning("Failed to rename file (" + file.getAbsolutePath() + ").");
}
tryRename(file, new File(saveFolder, file.getName().replaceAll("-", "")));
}
}
else
else if(useUUIDSeparators)
{
if(useUUIDSeparators)
{
if(!file.renameTo(new File(saveFolder, file.getName().replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})" + EXT_REGEX, "$1-$2-$3-$4-$5" + EXT))))
{
plugin.getLogger().warning("Failed to rename file (" + file.getAbsolutePath() + ").");
}
}
tryRename(file, new File(saveFolder, file.getName().replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})" + EXT_REGEX, "$1-$2-$3-$4-$5" + EXT)));
}
}
}

View File

@ -20,10 +20,12 @@ package at.pcgamingfreaks.Minepacks.Bukkit.Database;
import at.pcgamingfreaks.Bukkit.ItemStackSerializer.ItemStackSerializer;
import at.pcgamingfreaks.Bukkit.MCVersion;
import at.pcgamingfreaks.ConsoleColor;
import lombok.Getter;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import java.util.logging.Level;
import java.util.logging.Logger;
public class InventorySerializer
@ -49,13 +51,16 @@ public class InventorySerializer
}
catch(Exception e)
{
e.printStackTrace();
logger.log(Level.SEVERE, "Failed to produce serializer!", e);
}
if(serializer == null)
{
logger.severe("NBTItemStackSerializer does not support your Minecraft version!\nFalling back to BukkitItemStackSerializer! This most likely is wrong!");
usedSerializer = 0;
serializer = BUKKIT_ITEM_STACK_SERIALIZER;
if (MCVersion.isOlderThan(MCVersion.MC_NMS_1_8_R1))
{
usedSerializer = 0;
serializer = BUKKIT_ITEM_STACK_SERIALIZER;
}
}
this.serializer = serializer;
this.usedSerializer = usedSerializer;

View File

@ -38,7 +38,7 @@ public class MySQL extends SQL
protected void updateQueriesForDialect()
{
queryDeleteOldBackpacks = "DELETE FROM {TableBackpacks} WHERE {FieldBPLastUpdate} + INTERVAL {VarMaxAge} day < NOW()";
queryUpdateBp = queryUpdateBp.replaceAll("\\{NOW}", "NOW()");
queryUpdateBp = queryUpdateBp.replace("{NOW}", "NOW()");
}
@Override

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2023 GeorgH93
* Copyright (C) 2024 GeorgH93
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -32,6 +32,7 @@ import org.intellij.lang.annotations.Language;
import org.jetbrains.annotations.NotNull;
import java.sql.*;
import java.util.logging.Level;
public abstract class SQL extends Database
{
@ -64,7 +65,7 @@ public abstract class SQL extends Database
}
catch(SQLException e)
{
e.printStackTrace();
plugin.getLogger().log(Level.SEVERE, "Failed to delete old backpacks! Error: {0}", e.getMessage());
}
}
// Delete old cooldowns
@ -72,11 +73,11 @@ public abstract class SQL extends Database
{
try(Connection connection = getConnection())
{
DBTools.runStatement(connection, queryDeleteOldCooldowns, System.currentTimeMillis());
DBTools.runStatement(connection, queryDeleteOldCooldowns, new Timestamp(System.currentTimeMillis()));
}
catch(SQLException e)
{
e.printStackTrace();
plugin.getLogger().log(Level.SEVERE, "Failed to delete cooldowns! Error: {0}", e.getMessage());
}
}
}
@ -115,7 +116,7 @@ public abstract class SQL extends Database
}
catch(SQLException e)
{
e.printStackTrace();
plugin.getLogger().log(Level.SEVERE, "Failed to check UUIDs! Error: {0}", e.getMessage());
}
}
@ -163,10 +164,10 @@ public abstract class SQL extends Database
protected String replacePlaceholders(@Language("SQL") String query)
{
return query.replaceAll("(\\{\\w+})", "`$1`").replaceAll("`(\\{\\w+})`_(\\w+)", "`$1_$2`").replaceAll("fk_`(\\{\\w+})`_`(\\{\\w+})`_`(\\{\\w+})`", "`fk_$1_$2_$3`") // Fix name formatting
.replaceAll("\\{TablePlayers}", tablePlayers).replaceAll("\\{FieldName}", fieldPlayerName).replaceAll("\\{FieldUUID}", fieldPlayerUUID).replaceAll("\\{FieldPlayerID}", fieldPlayerID) // Players
.replaceAll("\\{TableBackpacks}", tableBackpacks).replaceAll("\\{FieldBPOwner}", fieldBpOwner).replaceAll("\\{FieldBPITS}", fieldBpIts) // Backpacks
.replaceAll("\\{FieldBPVersion}", fieldBpVersion).replaceAll("\\{FieldBPLastUpdate}", fieldBpLastUpdate) // Backpacks
.replaceAll("\\{TableCooldowns}", tableCooldowns).replaceAll("\\{FieldCDPlayer}", fieldCdPlayer).replaceAll("\\{FieldCDTime}", fieldCdTime); // Cooldowns
.replace("{TablePlayers}", tablePlayers).replace("{FieldName}", fieldPlayerName).replace("{FieldUUID}", fieldPlayerUUID).replace("{FieldPlayerID}", fieldPlayerID) // Players
.replace("{TableBackpacks}", tableBackpacks).replace("{FieldBPOwner}", fieldBpOwner).replace("{FieldBPITS}", fieldBpIts) // Backpacks
.replace("{FieldBPVersion}", fieldBpVersion).replace("{FieldBPLastUpdate}", fieldBpLastUpdate) // Backpacks
.replace("{TableCooldowns}", tableCooldowns).replace("{FieldCDPlayer}", fieldCdPlayer).replace("{FieldCDTime}", fieldCdTime); // Cooldowns
}
protected void runStatementAsync(final String query, final Object... args)
@ -186,8 +187,7 @@ public abstract class SQL extends Database
}
catch(SQLException e)
{
plugin.getLogger().severe("Query: " + query);
e.printStackTrace();
plugin.getLogger().log(Level.SEVERE, e, () -> "Query: " + query);
}
}
@ -236,8 +236,7 @@ public abstract class SQL extends Database
}
catch(SQLException e)
{
plugin.getLogger().warning("Failed to save backpack in database! Error: " + e.getMessage());
e.printStackTrace();
plugin.getLogger().log(Level.SEVERE, "Failed to save backpack in database! Error: {0}", e.getMessage());
writeBackup(name, nameOrUUID, usedSerializer, data);
}
};
@ -289,7 +288,7 @@ public abstract class SQL extends Database
}
catch(SQLException e)
{
e.printStackTrace();
plugin.getLogger().log(Level.SEVERE, "Failed to load backpack! Error: {0}", e.getMessage());
plugin.getServer().getScheduler().runTask(plugin, callback::onFail);
}
});
@ -317,7 +316,7 @@ public abstract class SQL extends Database
}
catch(SQLException e)
{
e.printStackTrace();
plugin.getLogger().log(Level.SEVERE, "Failed to load cooldown! Error: {0}", e.getMessage());
plugin.getServer().getScheduler().runTask(plugin, () -> callback.onResult(0L));
}
});

View File

@ -24,7 +24,7 @@ public abstract class UnCacheStrategy
{
protected Database cache;
public UnCacheStrategy(Database cache)
protected UnCacheStrategy(Database cache)
{
this.cache = cache;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2022 GeorgH93
* Copyright (C) 2023 GeorgH93
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -17,8 +17,6 @@
package at.pcgamingfreaks.Minepacks.Bukkit.Listener;
import at.pcgamingfreaks.Minepacks.Bukkit.API.Backpack;
import at.pcgamingfreaks.Minepacks.Bukkit.API.Callback;
import at.pcgamingfreaks.Minepacks.Bukkit.API.Events.BackpackDropOnDeathEvent;
import at.pcgamingfreaks.Minepacks.Bukkit.API.WorldBlacklistMode;
import at.pcgamingfreaks.Minepacks.Bukkit.Minepacks;
@ -48,21 +46,13 @@ public class DropOnDeath extends MinepacksListener
if (!player.hasPermission(Permissions.KEEP_ON_DEATH))
{
final Location location = player.getLocation();
plugin.getBackpack(player, new Callback<Backpack>()
{
@Override
public void onResult(Backpack backpack)
plugin.getBackpack(player, backpack -> {
BackpackDropOnDeathEvent event1 = new BackpackDropOnDeathEvent(player, backpack);
plugin.getServer().getPluginManager().callEvent(event1);
if(!event1.isCancelled())
{
BackpackDropOnDeathEvent event = new BackpackDropOnDeathEvent(player, backpack);
plugin.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled())
{
backpack.drop(location);
}
backpack.drop(location);
}
@Override
public void onFail() {}
});
}
}

View File

@ -91,7 +91,7 @@ public class ItemShortcut extends MinepacksListener
return itemDisplayName != null && itemNameNoReset.equals(itemDisplayName.replace(ChatColor.RESET.toString(), ""));
}
private void addItem(Player player)
public void addItem(Player player)
{
if(player.hasPermission(Permissions.USE))
{
@ -120,6 +120,17 @@ public class ItemShortcut extends MinepacksListener
player.getInventory().addItem(HeadUtils.fromBase64(value, itemName, MINEPACKS_UUID));
}
}
else
{
for(ItemStack itemStack : player.getInventory())
{
if(isItemShortcut(itemStack))
{
player.getInventory().remove(itemStack);
return;
}
}
}
}
private void removeItem(Player player)

View File

@ -1,5 +1,5 @@
/*
* Copyright (C) 2023 GeorgH93
* Copyright (C) 2024 GeorgH93
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -27,6 +27,7 @@ import at.pcgamingfreaks.Minepacks.Bukkit.API.Backpack;
import at.pcgamingfreaks.Minepacks.Bukkit.API.*;
import at.pcgamingfreaks.Minepacks.Bukkit.Command.CommandManager;
import at.pcgamingfreaks.Minepacks.Bukkit.Command.InventoryClearCommand;
import at.pcgamingfreaks.Minepacks.Bukkit.Command.ShortcutCommand;
import at.pcgamingfreaks.Minepacks.Bukkit.Database.Config;
import at.pcgamingfreaks.Minepacks.Bukkit.Database.Database;
import at.pcgamingfreaks.Minepacks.Bukkit.Database.Language;
@ -37,10 +38,10 @@ import at.pcgamingfreaks.Minepacks.Bukkit.SpecialInfoWorker.NoDatabaseWorker;
import at.pcgamingfreaks.Minepacks.MagicValues;
import at.pcgamingfreaks.Plugin.IPlugin;
import at.pcgamingfreaks.ServerType;
import at.pcgamingfreaks.Util.StringUtils;
import at.pcgamingfreaks.Updater.UpdateResponseCallback;
import at.pcgamingfreaks.Util.StringUtils;
import at.pcgamingfreaks.Version;
import lombok.Getter;
import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.OfflinePlayer;
@ -53,6 +54,8 @@ import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import lombok.Getter;
import java.io.File;
import java.util.Collection;
import java.util.Locale;
@ -60,12 +63,12 @@ import java.util.Set;
public class Minepacks extends JavaPlugin implements MinepacksPlugin, IPlugin
{
private static Minepacks instance = null;
@Getter private static Minepacks instance = null;
private ManagedUpdater updater = null;
private Config config;
private Language lang;
private Database database;
@Getter private Database database;
public Message messageNoPermission, messageInvalidBackpack, messageWorldDisabled, messageNotFromConsole, messageNotANumber;
@ -82,11 +85,6 @@ public class Minepacks extends JavaPlugin implements MinepacksPlugin, IPlugin
private ItemShortcut shortcut = null;
@Getter private PlaceholderManager placeholderManager = null;
public static Minepacks getInstance()
{
return instance;
}
@Override
public boolean isRunningInStandaloneMode()
{
@ -125,7 +123,12 @@ public class Minepacks extends JavaPlugin implements MinepacksPlugin, IPlugin
private boolean checkMcVersion()
{
if(MCVersion.is(MCVersion.UNKNOWN) || !MCVersion.isUUIDsSupportAvailable() || MCVersion.isNewerThan(MCVersion.MC_NMS_1_20_R2))
if (MCVersion.isNewerThan(MCVersion.MC_NMS_1_20_R3) && ServerType.isPaperCompatible())
{
getLogger().warning("Paper support is experimental! Use at your own risk!");
getLogger().warning("No guarantee for data integrity! Backup constantly!");
}
if (MCVersion.is(MCVersion.UNKNOWN) || !MCVersion.isUUIDsSupportAvailable() || MCVersion.isNewerThan(MCVersion.MC_NMS_1_20_R4))
{
this.warnOnVersionIncompatibility();
this.setEnabled(false);
@ -197,6 +200,7 @@ public class Minepacks extends JavaPlugin implements MinepacksPlugin, IPlugin
maxSize = config.getBackpackMaxSize();
at.pcgamingfreaks.Minepacks.Bukkit.Backpack.setShrinkApproach(config.getShrinkApproach());
at.pcgamingfreaks.Minepacks.Bukkit.Backpack.setTitle(config.getBPTitle(), config.getBPTitleOther());
at.pcgamingfreaks.Minepacks.Bukkit.Backpack.setMessageBackpackShrunk(lang.getMessage("Ingame.BackpackShrunk"));
messageNotFromConsole = lang.getMessage("NotFromConsole");
messageNoPermission = lang.getMessage("Ingame.NoPermission");
messageInvalidBackpack = lang.getMessage("Ingame.InvalidBackpack");
@ -220,13 +224,14 @@ public class Minepacks extends JavaPlugin implements MinepacksPlugin, IPlugin
{
shortcut = new ItemShortcut(this);
pluginManager.registerEvents(shortcut, this);
commandManager.registerSubCommand(new ShortcutCommand(this, shortcut));
}
else shortcut = null;
if(config.isWorldWhitelistMode()) pluginManager.registerEvents(new WorldBlacklistUpdater(this), this);
//endregion
if(config.getFullInvCollect() || config.isFullInvToggleAllowed()) collector = new ItemsCollector(this);
worldBlacklist = config.getWorldBlacklist();
worldBlacklistMode = (worldBlacklist.size() == 0) ? WorldBlacklistMode.None : config.getWorldBlockMode();
worldBlacklistMode = (worldBlacklist.isEmpty()) ? WorldBlacklistMode.None : config.getWorldBlockMode();
gameModes = config.getAllowedGameModes();
if(config.getCommandCooldown() > 0) cooldownManager = new CooldownManager(this);
@ -265,11 +270,9 @@ public class Minepacks extends JavaPlugin implements MinepacksPlugin, IPlugin
public void warnOnVersionIncompatibility()
{
String name = Bukkit.getServer().getClass().getPackage().getName();
String[] version = name.substring(name.lastIndexOf('.') + 2).split("_");
getLogger().warning(ConsoleColor.RED + "################################" + ConsoleColor.RESET);
getLogger().warning(ConsoleColor.RED + String.format("Your minecraft version (MC %1$s) is currently not compatible with this plugins version (%2$s). " +
"Please check for updates!", version[0] + "." + version[1], getDescription().getVersion()) + ConsoleColor.RESET);
"Please check for updates!", Bukkit.getServer().getVersion(), getDescription().getVersion()) + ConsoleColor.RESET);
getLogger().warning(ConsoleColor.RED + "################################" + ConsoleColor.RESET);
Utils.blockThread(5);
}
@ -284,11 +287,6 @@ public class Minepacks extends JavaPlugin implements MinepacksPlugin, IPlugin
return lang;
}
public Database getDatabase()
{
return database;
}
@Override
public void openBackpack(@NotNull final Player opener, @NotNull final OfflinePlayer owner, final boolean editable)
{
@ -304,17 +302,7 @@ public class Minepacks extends JavaPlugin implements MinepacksPlugin, IPlugin
@Override
public void openBackpack(@NotNull Player opener, @NotNull OfflinePlayer owner, boolean editable, @Nullable String title)
{
database.getBackpack(owner, new Callback<Backpack>()
{
@Override
public void onResult(Backpack backpack)
{
openBackpack(opener, backpack, editable, title);
}
@Override
public void onFail() {}
});
database.getBackpack(owner, backpack -> openBackpack(opener, backpack, editable, title));
}
@Override
@ -323,11 +311,8 @@ public class Minepacks extends JavaPlugin implements MinepacksPlugin, IPlugin
WorldBlacklistMode disabled = isDisabled(opener);
if(disabled != WorldBlacklistMode.None)
{
switch(disabled)
{
case Message: messageWorldDisabled.send(opener); break;
case MissingPermission: messageNoPermission.send(opener); break;
}
if (disabled == WorldBlacklistMode.Message) messageWorldDisabled.send(opener);
else if (disabled == WorldBlacklistMode.MissingPermission) messageNoPermission.send(opener);
return;
}
if(backpack == null)
@ -382,7 +367,7 @@ public class Minepacks extends JavaPlugin implements MinepacksPlugin, IPlugin
}
@Override
public WorldBlacklistMode isDisabled(Player player)
public @NotNull WorldBlacklistMode isDisabled(final @NotNull Player player)
{
if(worldBlacklistMode == WorldBlacklistMode.None || (worldBlacklistMode != WorldBlacklistMode.NoPlugin && player.hasPermission(Permissions.IGNORE_WORLD_BLACKLIST))) return WorldBlacklistMode.None;
if(worldBlacklist.contains(player.getWorld().getName().toLowerCase(Locale.ROOT))) return worldBlacklistMode;

View File

@ -71,4 +71,6 @@ public class Permissions
}
return permissions;
}
private Permissions() {}
}

10
pom.xml
View File

@ -7,16 +7,16 @@
<packaging>pom</packaging>
<properties>
<revision>2.4.23</revision>
<revision>2.4.30</revision>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<configFileVersion>34</configFileVersion>
<languageFileVersion>20</languageFileVersion>
<pcgfPluginLibVersion>1.0.39.2-SNAPSHOT</pcgfPluginLibVersion>
<languageFileVersion>21</languageFileVersion>
<pcgfPluginLibVersion>1.0.39.6-SNAPSHOT</pcgfPluginLibVersion>
<bukkitVersion>1.15.2-R0.1-SNAPSHOT</bukkitVersion>
<mavenShade.version>3.4.1</mavenShade.version>
<mavenShade.version>3.5.3</mavenShade.version>
<author>GeorgH93</author>
<maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format>
@ -81,7 +81,7 @@
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
<version>1.18.32</version>
<scope>provided</scope>
</dependency>
</dependencies>