Skip to content

Commit

Permalink
Fix ParcelListGUI and refactor code
Browse files Browse the repository at this point in the history
  • Loading branch information
Jakubk15 committed Jan 13, 2024
1 parent 9323b9f commit 548775d
Show file tree
Hide file tree
Showing 11 changed files with 111 additions and 73 deletions.
32 changes: 19 additions & 13 deletions src/main/java/com/eternalcode/parcellockers/ParcelLockers.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.eternalcode.parcellockers;

import com.eternalcode.parcellockers.command.argument.PlayerArgument;
import com.eternalcode.parcellockers.command.argument.UUIDArgument;
import com.eternalcode.parcellockers.command.handler.InvalidUsageImpl;
import com.eternalcode.parcellockers.command.handler.PermissionMessage;
import com.eternalcode.parcellockers.configuration.ConfigurationManager;
Expand All @@ -24,6 +25,7 @@
import com.google.common.base.Stopwatch;
import com.zaxxer.hikari.HikariDataSource;
import dev.rollczi.litecommands.LiteCommands;
import dev.rollczi.litecommands.adventure.LiteAdventureExtension;
import dev.rollczi.litecommands.annotations.LiteCommandsAnnotations;
import dev.rollczi.litecommands.bukkit.LiteBukkitMessages;
import dev.rollczi.litecommands.bukkit.LiteCommandsBukkit;
Expand All @@ -41,6 +43,7 @@
import org.bukkit.plugin.java.JavaPlugin;

import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
Expand Down Expand Up @@ -95,27 +98,30 @@ public void onEnable() {

MainGUI mainGUI = new MainGUI(this, server, miniMessage, config, parcelRepository, parcelLockerRepositoryImpl);
ParcelListGUI parcelListGUI = new ParcelListGUI(this, server, miniMessage, config, parcelRepository, parcelLockerRepositoryImpl, mainGUI);

this.liteCommands = LiteCommandsBukkit.builder("parcellockers", this)
.argument(Parcel.class, new ParcelArgument(parcelRepository))
.argument(Player.class, new PlayerArgument(server, config))
.message(LiteBukkitMessages.PLAYER_ONLY, config.messages.onlyForPlayers)
.commands(LiteCommandsAnnotations.of(
new ParcelCommand(server, parcelLockerRepositoryImpl, announcer, config, mainGUI, parcelListGUI, parcelManager),
new ParcelLockersCommand(configManager, config, announcer, miniMessage)
))
.invalidUsage(new InvalidUsageImpl(announcer, config))
.missingPermission(new PermissionMessage(announcer, config))
.build();
.argument(Parcel.class, new ParcelArgument(parcelRepository))
.argument(Player.class, new PlayerArgument(server, config))
.argument(UUID.class, new UUIDArgument(parcelRepository))
.extension(new LiteAdventureExtension<>())
.message(LiteBukkitMessages.PLAYER_ONLY, config.messages.onlyForPlayers)
.commands(LiteCommandsAnnotations.of(
new ParcelCommand(server, parcelLockerRepositoryImpl, announcer, config, mainGUI, parcelListGUI, parcelManager),
new ParcelLockersCommand(configManager, config, announcer)
))
.invalidUsage(new InvalidUsageImpl(announcer, config))
.missingPermission(new PermissionMessage(announcer, config))
.build();

if (!this.setupEconomy()) {
this.getLogger().severe("Disabling due to no Vault dependency found!");
this.getLogger().severe("Disabling due to no Vault dependency or its implementator(s) found!");
server.getPluginManager().disablePlugin(this);
return;
}

Stream.of(
new LockerInteractionController(this, parcelLockerRepositoryImpl, itemStorageRepository, miniMessage, config),
new LockerPlaceController(config, miniMessage, this, parcelLockerRepositoryImpl, announcer),
new LockerPlaceController(config, this, parcelLockerRepositoryImpl, announcer),
new LockerBreakController(parcelLockerRepositoryImpl, announcer, config.messages)
).forEach(controller -> server.getPluginManager().registerEvents(controller, this));

Expand Down Expand Up @@ -164,7 +170,7 @@ private boolean setupEconomy() {

RegisteredServiceProvider<Economy> rsp = this.getServer().getServicesManager().getRegistration(Economy.class);
if (rsp == null) {
return false; // !!!MAJK!!! Vault is installed but no economy plugin is registered (e.g. EssentialsX)
return false; // Vault is installed but no economy plugin is registered (e.g. EssentialsX) - majk
}

this.economy = rsp.getProvider();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import dev.rollczi.litecommands.annotations.context.Context;
import dev.rollczi.litecommands.annotations.execute.Execute;
import dev.rollczi.litecommands.annotations.permission.Permission;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
Expand All @@ -20,13 +19,11 @@ public class ParcelLockersCommand {
private final ConfigurationManager configManager;
private final PluginConfiguration config;
private final NotificationAnnouncer announcer;
private final MiniMessage miniMessage;

public ParcelLockersCommand(ConfigurationManager configManager, PluginConfiguration config, NotificationAnnouncer announcer, MiniMessage miniMessage) {
public ParcelLockersCommand(ConfigurationManager configManager, PluginConfiguration config, NotificationAnnouncer announcer) {
this.configManager = configManager;
this.config = config;
this.announcer = announcer;
this.miniMessage = miniMessage;
}

@Async
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.eternalcode.parcellockers.command.argument;

import com.eternalcode.parcellockers.parcel.repository.ParcelRepositoryImpl;
import dev.rollczi.litecommands.argument.Argument;
import dev.rollczi.litecommands.argument.parser.ParseResult;
import dev.rollczi.litecommands.argument.resolver.ArgumentResolver;
import dev.rollczi.litecommands.invocation.Invocation;
import dev.rollczi.litecommands.suggestion.SuggestionContext;
import dev.rollczi.litecommands.suggestion.SuggestionResult;
import dev.rollczi.litecommands.suggestion.SuggestionStream;
import org.bukkit.command.CommandSender;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.IntStream;

public class UUIDArgument extends ArgumentResolver<CommandSender, UUID> {

private final ParcelRepositoryImpl parcelRepository;

public UUIDArgument(ParcelRepositoryImpl parcelRepository) {
this.parcelRepository = parcelRepository;
}

@Override
protected ParseResult<UUID> parse(Invocation<CommandSender> invocation, Argument<UUID> context, String argument) {
return ParseResult.success(UUID.fromString(argument));
}

@Override
public SuggestionResult suggest(Invocation<CommandSender> invocation, Argument<UUID> argument, SuggestionContext context) {
if (!this.parcelRepository.cache().isEmpty()) {
return SuggestionStream.of(this.parcelRepository.cache().keySet())
.map(UUID::toString)
.collect(s -> s);
}
List<UUID> uuids = new ArrayList<>();
IntStream.rangeClosed(1, 10).forEach(i -> uuids.add(UUID.randomUUID()));
return SuggestionStream.of(uuids)
.map(UUID::toString)
.collect(s -> s);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public static class Messages {
public String onlyForPlayers = "&7» &cThis command is only available to players!";
public String noPermission = "&7» &cYou don't have permission to perform this command! &c(&7{PERMISSION}&c)";
public String cantFindPlayer = "&7» &cThe specified player could not be found!";
public String invalidUsage = "&7» &bCorrect usage: &e{USAGE}";
public String invalidUsage = "&7» &3Correct usage: &b{USAGE}";
public String reload = "&7» &bConfiguration has been successfully reloaded!";
public String parcelCommandUsage = "&7» &3/parcel &b<list|info|send|cancel> [parcel]";
public String parcelSuccessfullyCreated = "&7» &aParcel created successfully.";
Expand All @@ -91,7 +91,7 @@ public static class Messages {
public String enterDescriptionPrompt = "&7» &6Enter a description for the parcel locker:";
public String cannotBreakParcelLocker = "&7» &cYou have no permission to break the parcel locker.";
public String parcelLockerSuccessfullyDeleted = "&7» &aParcel locker deleted successfully.";
public String broadcastParcelLockerRemoved = "&7» &a&lWARNING! &r&4The parcel locker at &c{X} {Y} {Z} in world {WORLD} &4has been removed by &4{PLAYER}!";
public String broadcastParcelLockerRemoved = "&7» &cThe parcel locker at &6{X} {Y} {Z} in world {WORLD} &chas been removed by &c{PLAYER}!";
@Description({" ", "# The parcel info message."})
public List<String> parcelInfoMessages = List.of(
"&7» &6Parcel info:",
Expand All @@ -118,9 +118,6 @@ public static class GuiSettings {
@Description({" ", "# The item of the sent parcels GUI"})
public String sentParcelsTitle = "&6Sent parcels";

@Description({" ", "# The item of the parcel locker main GUI"})
public String parcelLockerMainGuiTitle = "&3Parcel locker";

@Description({" ", "# The item of the parcel locker sending GUI"})
public String parcelLockerSendingGuiTitle = "&3Parcel sending";

Expand Down Expand Up @@ -171,10 +168,10 @@ public static class GuiSettings {

@Description({" ", "# The item of the selected priority button"})
public ConfigItem selectedPriorityItem = new ConfigItem()
.setName("&aPriority")
.setLore(List.of("&aCurrently selected!", "&c&oClick to unselect."))
.setGlow(true)
.setType(Material.REDSTONE_BLOCK);
.setName("&aPriority")
.setLore(List.of("&aCurrently selected!", "&c&oClick to unselect."))
.setType(Material.REDSTONE_BLOCK)
.setGlow(true);

@Description({" ", "# The close button item"})
public ConfigItem closeItem = new ConfigItem()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import org.bukkit.conversations.Prompt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import panda.utilities.StringUtils;

public class ParcelLockerPlacePrompt implements Prompt {

Expand All @@ -29,7 +28,7 @@ public Prompt acceptInput(@NotNull ConversationContext context, @Nullable String
@Override
public String getPromptText(@NotNull ConversationContext context) {
this.announcer.sendMessage((CommandSender) context.getForWhom(), this.config.messages.enterDescriptionPrompt);
return StringUtils.EMPTY;
return null;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import com.eternalcode.parcellockers.locker.repository.LockerRepositoryImpl;
import com.eternalcode.parcellockers.notification.NotificationAnnouncer;
import com.eternalcode.parcellockers.shared.PositionAdapter;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.Location;
import org.bukkit.conversations.ConversationFactory;
import org.bukkit.conversations.NullConversationPrefix;
Expand All @@ -25,14 +24,12 @@
public class LockerPlaceController implements Listener {

private final PluginConfiguration config;
private final MiniMessage miniMessage;
private final Plugin plugin;
private final LockerRepositoryImpl databaseService;
private final NotificationAnnouncer announcer;

public LockerPlaceController(PluginConfiguration config, MiniMessage miniMessage, Plugin plugin, LockerRepositoryImpl databaseService, NotificationAnnouncer announcer) {
public LockerPlaceController(PluginConfiguration config, Plugin plugin, LockerRepositoryImpl databaseService, NotificationAnnouncer announcer) {
this.config = config;
this.miniMessage = miniMessage;
this.plugin = plugin;
this.databaseService = databaseService;
this.announcer = announcer;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public CompletableFuture<Void> save(Locker locker) {

@Override
public CompletableFuture<List<Locker>> findAll() {
return this.supplyExecute("SELECT * FROM `lockers`;", this::extractParcelLockers);
return this.supplyExecute("SELECT * FROM `lockers`;", this::extractLockers);
}


Expand Down Expand Up @@ -105,7 +105,7 @@ public CompletableFuture<LockerPageResult> findPage(Page page) {
statement.setInt(1, page.getLimit() + 1);
statement.setInt(2, page.getOffset());

List<Locker> lockers = this.extractParcelLockers(statement);
List<Locker> lockers = this.extractLockers(statement);

boolean hasNext = lockers.size() > page.getLimit();
if (hasNext) {
Expand All @@ -115,7 +115,7 @@ public CompletableFuture<LockerPageResult> findPage(Page page) {
});
}

private List<Locker> extractParcelLockers(PreparedStatement statement) throws SQLException {
private List<Locker> extractLockers(PreparedStatement statement) throws SQLException {
List<Locker> list = new ArrayList<>();
ResultSet rs = statement.executeQuery();

Expand All @@ -138,7 +138,7 @@ public Optional<Locker> findLocker(UUID uuid) {
if (this.isInCache(uuid)) {
return Optional.ofNullable(this.cache.get(uuid));
}
return this.findByUUID(uuid).join();
return this.findByUUID(uuid).orTimeout(2, TimeUnit.SECONDS).join();
}

private void addToCache(Locker locker) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,16 +58,16 @@ void info(@Context Player player, @Arg Parcel parcel) {
}

@Execute(name = "send", aliases = "create") // similar create, add
void create(@Context Player player, @Arg String name, @Arg boolean priority, @Arg ParcelSize size, @Arg String entryLocker, @Arg String destinationLocker) {
void create(@Context Player player, @Arg String name, @Arg boolean priority, @Arg ParcelSize size, @Arg UUID entryLocker, @Arg UUID destinationLocker) {
Parcel parcel = Parcel.builder()
.uuid(UUID.randomUUID())
.name(name)
.sender(player.getUniqueId())
.receiver(player.getUniqueId())
.priority(priority)
.size(size)
.entryLocker(UUID.fromString(entryLocker))
.destinationLocker(UUID.fromString(destinationLocker))
.entryLocker(entryLocker)
.destinationLocker(destinationLocker)
.build();

this.parcelManager.createParcel(player, parcel);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,7 @@
import org.bukkit.plugin.Plugin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.IntStream;

public class ParcelItemStorageGUI {
Expand All @@ -30,9 +27,6 @@ public class ParcelItemStorageGUI {
private final PluginConfiguration config;
private final MiniMessage miniMessage;
private final ItemStorageRepositoryImpl itemStorageRepository;
private final Map<UUID, List<ItemStack>> lastInserted = new HashMap<>();

private boolean confirmed;

public ParcelItemStorageGUI(Plugin plugin, PluginConfiguration config, MiniMessage miniMessage, ItemStorageRepositoryImpl itemStorageRepository) {
this.plugin = plugin;
Expand All @@ -48,7 +42,6 @@ void show(Player player, ParcelSize size) {
GuiItem backgroundItem = guiSettings.mainGuiBackgroundItem.toGuiItem(event -> event.setCancelled(true));

GuiItem confirmItem = guiSettings.confirmItemsItem.toGuiItem(event -> {
this.confirmed = true;
new ParcelSendingGUI(plugin, this.config, this.miniMessage, itemStorageRepository).show(player);
});

Expand Down Expand Up @@ -94,7 +87,6 @@ void show(Player player, ParcelSize size) {
}

items.add(item);
this.lastInserted.put(player.getUniqueId(), items);
}

this.itemStorageRepository.remove(player.getUniqueId()).whenComplete((unused, throwable) -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import dev.triumphteam.gui.guis.Gui;
import dev.triumphteam.gui.guis.GuiItem;
import dev.triumphteam.gui.guis.PaginatedGui;
import io.sentry.Sentry;
import net.kyori.adventure.text.minimessage.MiniMessage;
import org.bukkit.Server;
import org.bukkit.entity.Player;
Expand Down Expand Up @@ -74,31 +75,29 @@ private void show(Player player, Page page) {
}

this.parcelRepository.findPage(page).whenComplete((result, throwable) -> {
if (throwable != null) {
Sentry.captureException(throwable);
throwable.printStackTrace();
return;
}

if (result.parcels().isEmpty() && page.hasPrevious()) {
this.show(player, page.previous());
return;
}

for (Parcel parcel : result.parcels()) {
if (!player.hasPermission("parcellockers.admin.debug.seeOthersParcels")) {
continue;
}

if (!parcel.sender().equals(player.getUniqueId())) {
continue;
}

if (!parcel.recipients().contains(player.getUniqueId())) {
/*if (!parcel.recipients().contains(player.getUniqueId())) {
continue;
}
}*/

ItemMeta parcelItemMeta = parcelItem.getItemStack().getItemMeta();

List<String> newLore = this.replaceParcelPlaceholders(parcel, parcelItemMeta.getLore());

parcelItemMeta.setLore(newLore);
if (parcelItemMeta != null) {
List<String> newLore = this.replaceParcelPlaceholders(parcel, parcelItemMeta.getLore());
parcelItemMeta.setLore(newLore);
}
gui.addItem(parcelItem);

}

gui.setItem(49, closeItem);
Expand All @@ -112,6 +111,11 @@ private void show(Player player, Page page) {
}

this.server.getScheduler().runTask(this.plugin, () -> gui.open(player));
}).whenComplete((unused, throwable) -> {
if (throwable != null) {
Sentry.captureException(throwable);
throwable.printStackTrace();
}
});

}
Expand All @@ -128,7 +132,7 @@ private List<String> replaceParcelPlaceholders(Parcel parcel, List<String> lore)
.register("{RECEIVER}", this.server.getPlayer(parcel.receiver()).getName())
.register("{SIZE}", parcel.size().toString())
.register("{PRIORITY}", parcel.priority() ? this.miniMessage.deserialize("&aYes") : this.miniMessage.deserialize("&cNo"))
.register("{DESCRIPTION}", parcel.description())
//.register("{DESCRIPTION}", parcel.description())
.register("{RECIPIENTS}", parcel.recipients().stream()
.map(this.server::getPlayer)
.filter(Objects::nonNull)
Expand Down
Loading

0 comments on commit 548775d

Please sign in to comment.